content
stringlengths
42
6.51k
def bubble_sort(input_list): """ Compare each element with each other element to provide a sorted array. :param input_list A list of objects to be reversed. :return A sorted version/copy of the list. """ for i in range(0, len(input_list)): for j in range(i + 1, len(input_list)): ...
def map_range(x, in_min, in_max, out_min, out_max): """ Maps a number from one range to another. :return: Returns value mapped to new range :rtype: float """ mapped = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min if out_min <= out_max: return max(min(mapped, out_ma...
def compare_dictionaries(reference, comparee, ignore=None): """ Compares two dictionary objects and displays the differences in a useful fashion. """ if not isinstance(reference, dict): raise Exception("reference was %s, not dictionary" % type(reference)) if not isinstance(comparee, dict): ...
def __renumber(dictionary): """Renumber the values of the dictionary from 0 to n """ count = 0 ret = dictionary.copy() new_values = dict([]) for key in dictionary.keys(): value = dictionary[key] new_value = new_values.get(value, -1) if new_value == -1: new_va...
def end_of_chunk(prev_tag, tag, prev_type, type_): """Checks if a chunk ended between the previous and current word. Args: prev_tag: previous chunk tag. tag: current chunk tag. prev_type: previous type. type_: current type. Returns: chunk_end: boolean. """ c...
def get_session_value(key_string, prefix='', rconn=None): """If key_string is not found, return None""" if not key_string: return if rconn is None: return keystring = prefix+key_string if not rconn.exists(key_string): # no value exists return binvalues = rconn...
def bitreversed_decimal(dec_input, maxbits): """Description: Compute bit-reversed value of a decimal number Parameters ---------- dec_input Decimal input whose bit-reversed value must be computed maxbits Total number of bits in binary used to represent 'in' and 'out'. Return...
def calculate_income_range(income): """ if income < 25000: return 0 elif income < 50000: return 1 elif income < 75000: return 2 else: return 3 """ return int(income/10000)
def config_to_kvmap(config_data, config_data_map): """ """ return dict([ (k, config_data[config_data_map[k]][2]) for k in config_data_map ])
def literal(c, code): """literal value 0x00-0x1F (literal)""" v = "0x%04X" % (code - 0x20) return v
def tryint(x, sub=-1): """Tries to convert object to integer. Like ``COALESCE(CAST(x as int), -1)`` but won't fail on `'1.23'` :Returns: int(x), ``sub`` value if fails (default: -1) """ try: return int(x) except: return sub
def create_figure(path, caption=None, align=None, alt=None, width=None): """ This method is available within ``.. exec::``. It allows someone to create a figure with a caption. """ rst = [".. figure:: {}".format(path)] if align: rst += [" :align: {}".format(align)] if alt: ...
def findall(root, tag, namespace=None): """ Get all nodes by tag and namespace under Node root. """ if root is None: return [] if namespace is None: return root.getElementsByTagName(tag) else: return root.getElementsByTagNameNS(namespace, tag)
def parse_bool(data): """Parse a string value to bool""" if data.lower() in ('yes', 'true',): return True elif data.lower() in ('no', 'false',): return False else: err = f'"{data}" could not be interpreted as a boolean' raise TypeError(err)
def YFrequencyList_to_HFrequencyList(y_frequency_list): """ Converts Y parameters into h-parameters. ABCD-parameters should be in the form [[f,Y11,Y12,Y21,Y22],...] Returns data in the form [[f,h11,h12,h21,h22],...] """ h_frequency_list=[] for row in y_frequency_list[:]: [frequency,Y11,Y...
def get_args(text: str) -> str: """Return the part of message following the command.""" splitted = text.split(" ", 1) if not len(splitted) == 2: splitted = text.split("\n", 1) if not len(splitted) == 2: return "" prefix, args = splitted print(prefix) args = args.str...
def get_hashtags(tweet: dict) -> list: """ The tweet argument is a dict. So get 'entities' key or return a empty dict. This is required for the second .get() to not throw a error where we try to get 'hashtags' """ entities = tweet.get('entities', {}) hashtags = entities.get('hashtags', []) ...
def params_deepTools_plotHeatmap_xAxisLabel(wildcards): """ Created: 2017-05-07 18:51:43 Aim: what to show take argument with spaces which is not very good with paths. xAxisLabel-tss/xAxisLabel-peak-center """ tmp = str(wildcards['deepTools_plotHeatmap_xAxisLabel_id']); ...
def eqiv(values): """Recursive function that does eqivalent boolean operations Example: Input: [True, True, False, False] (((True == True) == False) == False)) is True """ try: values = list(values) except TypeError: return values try: outcome = values[0] ...
def project_to_2D(xyz): """Projection to (0, X, Z) plane.""" return xyz[0], xyz[2]
def _is_leap(year): """year -> 1 if leap year, else 0.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def swapxy(v:list) -> list: """Swaps the first two values in a list Args: list[x, y] Returns: list[y, x] """ return [v[1], v[0]]
def kwargs_nonempty(**kwargs): """Returns any keyword arguments with non-empty values as a dict.""" return {x: y for x, y in kwargs.items() if y}
def bestrelpath(path, relto=None): """Return a relative path only if it's under $PWD (or `relto`)""" if relto is None: from os import getcwd relto = getcwd() from os.path import relpath relpath = relpath(path, relto) if relpath.startswith('.'): return path else: r...
def create_response(bot_reply, end_of_session=False): """Base reply for Alexa""" response = { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": bot_reply, }, "reprompt": { "outputSpeech": { "type": "PlainText", "te...
def _join_matchers(matcher, *matchers): """Joins matchers of lists correctly.""" output = {k: [e for e in v] for k, v in matcher.items()} for matcher_to_join in matchers: has_default = False for key, value in matcher_to_join.items(): if key == "default": # Default has a special...
def _find_imports(*args): """ Helper sorting the named modules into existing and not existing. """ import importlib exists = { True: [], False: [], } for name in args: name = name.replace('-', '_') try: importlib.import_module(name) exists[True].append(name) except ImportE...
def heuristic(parent, switch): """ rules: ? """ k, i, f = switch if (k, f, i) in parent: return False for kk, ii, ff in parent: if kk > k and ii == i and ff == f: return False return True
def keywithmaxval(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d.values()) k=list(d.keys()) return k[v.index(max(v))]
def _join_description_strs(strs): """Join lines to a single string while removing empty lines.""" strs = [str_i for str_i in strs if len(str_i) > 0] return "\n".join(strs)
def to_real(real, x): """ Helper function to convert a value x to a type real. This exists because not every type has a direct conversion, but maybe we can help it? """ try: # the obvious way return real(x) except TypeError as exc: # well seems like that won't work ...
def desnake(text): """Turns underscores into spaces""" return text.strip().replace("_", " ")
def make_operator(_operator, _double_pipe_c): """Handles concatenation operators.""" if _operator == 'C': if _double_pipe_c: return '||' else: return '+' else: return _operator
def interp(val, array_value, array_ref): """ Interpolate the array_value from the array_ref with val. The array_ref must be in an increasing order! """ if val <= array_ref[0]: return array_value[0] elif val > array_ref[len(array_ref)-1]: return array_value[len(array_ref)-...
def getUntilCRLF(str): """text section ends on CRLF """ return str.split("\r\n", 1)[0]
def filter_dict(dict, keywords): """ Returns only the keywords that are part of a dictionary Parameters ---------- dictionary : dict Dictionary for filtering keywords : list of str Keywords that will be filtered Returns ------- keywords : list of str List co...
def add_to_dict_of_levels(dict_levels, c, cur_level, index): """ Function returns the dict of positions according to the level of space or comma Example: {'1_,': [14], '2_,': [9], '0_ ': [3], '1_ ': [12]} comma of level 1: position 14 comma of level 2: position 9 space of level 0: po...
def leftlimit(minpoint, ds, tau): """ Find left limit. Args: minpoint (int): x coordinate of the local minimum ds (list): list of numbers representing derivative of the time-series signal s tau (int): threshold to determine a slope 'too sharp' Returns: minpoint (int): x coord...
def maybe_job_id(value: str) -> bool: """Check whether the string looks like a job id""" return value.startswith("job-")
def split_sentence(sentence: str, length: int=100): """ :param sentence: :param length: :return: """ result = [] start = 0 while start < len(sentence): result.append(sentence[start: start + length]) start += length return result
def parse_properties(properties): """ Return a dictionary of attributes based on properties. Convert properties of form "property1=value1,property2=value2, ..." to {'property1': value1, 'property2': value2, ...}. """ pairs = [ (k.strip(), eval(v.strip())) for k, v in [pro...
def divide(dividend, divisor): """ :param dividend: a numerical value :param divisor: a numerical :return: a numerical value if division is possible. Otherwise, None """ quotient = None if divisor is not None : if divisor != 0: quotient = dividend / divisor return qu...
def rle_len( rle ): """ Return the number of characters covered by a run length encoded attribute list. """ run = 0 for v in rle: assert type(v) == tuple, repr(rle) a, r = v run += r return run
def set_image_paras(no_data, min_size, min_depth, interval, resolution): """Sets the input image parameters for level-set method. Args: no_data (float): The no_data value of the input DEM. min_size (int): The minimum nuber of pixels to be considered as a depressioin. min_depth (float): ...
def _recursive_guid(input_key, input_value, indicators): """ """ results = [] if input_key in indicators: results.append(input_value) return results elif isinstance(input_value, list): for v in input_value: results.extend(_recursive_guid(None, v, indicators)) ...
def quick_doctext(doctext, indicator, value, unit=''): """ Convenience function to standardize the output format of a string. """ unitspace = ' ' if unit == '%': unitspace = '' return str('{0}\n{1} {2}{3}{4}'.format(doctext, indicator, value, unitspace, unit))
def get_int_for_unk_type(dtype): """ Returns the int for an unknown type from Sonar. The DNS type is the integer at the end of the "unk_in_{num}" string. """ return int(dtype[7:])
def postprocess_data(data: str): """ Example of a task provided by a workflow library. Task-specific details such as the Docker image and memory needs are defined here on the task. However, it is left to the user to define the executor 'utils_executor', so that user can customize project-specific d...
def do_stuff(num): """Adds 5 to passed int""" try: return int(num) + 5 except ValueError as err: return err
def pulse_train(time, start, duration, repeat_time, end): """ Implements vensim's PULSE TRAIN function. Parameters ---------- time: function Function that returns the current time. start: float Starting time of the pulse. duration: float Duration of the pulse. re...
def get_factors(num): """Returns a list Factors of the number passed as argument """ factors = [] inc_value = 1 while inc_value * inc_value <= num: if num % inc_value == 0: if num//inc_value == inc_value: factors.append(inc_value) else: ...
def anagrams(word, words): """Return list of words that are anagrams.""" final_list = [] to_match = ''.join(sorted(word)) for i in words: if ''.join(sorted(i)) == to_match: final_list.append(i) return final_list
def df_variant_id(row): """Get variant ID from pyvcf in DataFrame""" if row['ID'] != '.': return row['ID'] else: return row['CHROM'] + ':' + str(row['POS'])
def _pick_access(parameters_json: dict) -> str: """ return permissions_use if it exists, else "creator_administrative_unit, else none """ part_of = parameters_json.get('partOf', '') while isinstance(part_of, list): part_of = part_of[0] if "zp38w953h0s" in part_of or parameters_json.get('id', '')...
def compute_files_to_download(client_hashes, server_hashes): """Given a dictionary of file hashes from the client and the server, specify which files should be downloaded from the server Params: client_hashes- a dictionary where the filenames are keys and the values are md5 hashes as strings ...
def _concat(*lists): """Concatenates the items in `lists`, ignoring `None` arguments.""" concatenated = [] for list in lists: if list: concatenated += list return concatenated
def read_paragraph_element(element): """Returns the text in the given ParagraphElement. Args: element: a ParagraphElement from a Google Doc. """ text_run = element.get('textRun') if not text_run: return '' if text_run.get('textStyle', {}).get('weightedFontFamily', {}).ge...
def isBoxed(binary): """Determines if a bit array contains the marker border box.""" for bit in binary[0]: if bit != 0: return False for bit in binary[7]: if bit != 0: return False c = 1 while c < 7: if binary[c][0] != 0 or binary[c][7] != 0: ...
def num_same_chars(w1: str, w2: str)->int: """Compute the similarity of two strings based on the number of matching characters""" sim = 0 for ch in w1: if ch in w2: sim += 1 return sim
def removeDocstringAndImports(src): """ Remove the docstring and import statements from the given code. We return the source code, minus the initial docstring (if any) and any import statements. """ if src.startswith('"""'): # We have a docstring. Search for the ending docstring, a...
def get_status(node): """ Builds a dict of status from a workflow manifest. Parameters ---------- node : dict Returns ------- str """ # check if pipeline was interrupted if "message" in node and str(node["message"]) == "terminated": status = "Terminated" else: ...
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations" f"/api/v1.0/tobs <br>" f"/api/v1.0/start_date <br> " f"/api/v1.0/end_date <br> " )
def get_new_filename(artist: str, title: str) -> str: """ Get new filename for the track. Remove all symbols, replace spaces with underscores :param artist: :param title: :return: """ tmp_data = [] for data in [artist, title]: tmp_data.append(''.join([i.lower() if i != ' ' else...
def solar_panels(area): """ Given area, this function outputs a list containing the largest perfect squares that can be extracted from what remains from area. Example: If area = 12, then 9 is the largest square, and 3 remains from where 1 is the largest perfect square, and 2 remain...
def convertToStepUpCDF(x, y): """Convert to a "stepped" data format by duplicating all but the last elt. Step goes up, rather than to the right. """ newx = [] newy = [] for i, d in enumerate(x): newx.append(d) newy.append(y[i]) if i != len(x) - 1: newx.append...
def validate_users_input(users_input, word): """ Function validate_users_input - validate the user's input --------------------------------------------------------- Author : Arthur Molia - <moliaarthu@eisti.eu> Parameters : users_input : user's input word : game's solu...
def detectFormat(fileName): """Get the extension of a file""" ext = fileName.split(".")[1] return ext
def minimum_format_ensurer(products): """ This is a function to ensure that there is at least 2 digits to each input. It adds a leading or an ending zero to each single-digit entry, all values will be turned to str or tuples containing str to maintain the format. Any item not of int or float will ...
def rgb_to_hex(red: int, green: int, blue: int) -> str: """Converts RGB into hext string. Examples: >>> assert rgb_to_hex(1, 2, 3) == "010203" """ def to_hex(number: int) -> str: if number > 255: return "FF" if number < 0: return "00" return f"{n...
def t_any(cls): """ Verifies if input is of same class """ class AnyClass(cls): def __eq__(self, other): return True return AnyClass()
def _get_item_properties(item, fields): """Return a tuple containing the item properties.""" row = [] for field in fields: row.append(item.get(field, '')) return tuple(row)
def time_to_iso(time_struct): """ time to iso format """ #return '%(hour)s:%(minute)s' % time_struct hour = int(time_struct['hour']) if not hour: hour = '00' return '%s:%s' % (hour, time_struct['minute'])
def parse_non_lang_item_with_subkey(key: str, item: dict): """ Given a single item, in a list of XML values, which does not contain a language key, but does contain a hidden "sub label" e.g. {'$': 'geoscanid:123456'} create the key:value mapping for the associated column, adding the subkey t...
def enable_checking(flag = True): """Convenience function to set the checking_enabled flag. Intended for use in an assert statement, so the call depends on -o flag. """ global checking_enabled checking_enabled = flag return checking_enabled
def _count(n, word): """format word according to n""" if n == 1: return "%d %s" % (n, word) else: return "%d %ss" % (n, word)
def lorenz(num_points=15000, start=[0.10, 0.10, 0.10], scaling_factor=20, delta=0.008, a=0.1, b=4.0, c=14.0, d=0.08): """ Generates Lorenz strange attractor. """ verts = [] x = start[0] y = start[1] z = start[2] for i in range(0, num_points): # calculate delta values dx...
def _format_links(link_x): """ Format links part :param link_x: list, which has several dicts in it :return: formatted string """ try: pairs = "" for _dict in link_x: pairs += _dict['rel'] + '-> ' + _dict['href'] + '\n' return pairs[:-1] except Exception:...
def calculate_slpercentage_base_price_long(sl_price, base_price): """Calculate the SL percentage of the base price for a long deal""" return round( 100.0 - ((sl_price / base_price) * 100.0), 2 )
def calibrate_magnitude(instr_mag, airmass, ref_color, zero, extinct, color, instr=None): """ Calibrate instrumental magnitude to a standard photometric system. This assumes that ref_color has already been adjusted for any non-linearities between the instrumental magnitudes and the photome...
def u2u3(u2): """ inch to feet&inch, all strings u3 is a tuple of (feet, inch) """ u2 = float(u2) f = u2//12 i = u2%12 inch_int = int(i//1) inch_frac = i%1 # 1/4" accuracy test = round(inch_frac/0.25) if test == 0: i = str(inch_int) elif test == 4: i = str(inch_int+1) elif test == 2: i = str(inch_in...
def is_boolean(value): """ Checks if `value` is a boolean value. Args: value (mixed): Value to check. Returns: bool: Whether `value` is a boolean. Example: >>> is_boolean(True) True >>> is_boolean(False) True >>> is_boolean(0) False...
def __stretch__(p,s1,f1): """ If a point has coordinate p when the steep/flat points are at s0/f0, this returns its coordinates when the steep/flat points are at s1/f1. This is necessary to preserve the colourmap features. """ s0 = 0.3125 f0 = 0.75 dsf = f0 - s0 if p <= s0: ...
def drop_key_safely(dictionary, key): """Drop a key from a dict if it exists and return that change""" if key in dictionary: del dictionary[key] return dictionary
def search_linearf(a, x): """ Returns the index of x in a if present, None elsewhere. """ for i in range(len(a)): if a[i] == x: return i return None
def enterprise_format_numbers( unparsed_int # type: int ): """Unpack and parse [enterprise,format] numbers""" sample_type_binary = '{0:032b}'.format(unparsed_int) # Break out the binary enterprise_num = int(sample_type_binary[:20],2) # Enterprise number first 20 bits sample_data_format = int(sample_type_binary[20...
def smart_truncate(value, max_length=0, word_boundaries=False, separator=' '): """ Truncate a string """ value = value.strip(separator) if not max_length: return value if len(value) < max_length: return value if not word_boundaries: return value[:max_length].strip(separat...
def remove_first1(alist,k): """Removes the first occurrence of k from alist. It is not efficient; even it removes one occurrence, it goes on processing the input.""" retval = [] removed = False for x in alist: if x == k and not removed: removed = True else: retval.append(x) return retval
def cross(a: complex, b: complex) -> complex: """2D cross product (a.k.a. wedge product) of two vectors. Args: a (complex): First vector. b (complex): Second vector. Returns: complex: 2D cross product: a.x * b.y - a.y * b.x """ return (a.conjugate() * b).imag
def is_change_applicable_for_power_state(current_power_state, apply_power_state): """ checks if changes are applicable or not for current system state :param current_power_state: Current power state :type current_power_state: str :param apply_power_state: Required power state :type a...
def list_startswith(_list, lstart): """ Check if a list (_list) starts with all the items from another list (lstart) :param _list: list :param lstart: list :return: bool, True if _list starts with all the items of lstart. """ if _list is None: return False lenlist = len(_list) ...
def assign_labels(sentences): """ Assigns the majority class label to each sentence for each task. Returns two lists: predicted AC and predicted SP """ predictions_category = [] predictions_sentiment = [] for sentence in sentences: prediction_cat = 'NA' predictions_catego...
def _is_line_empty(line: str) -> bool: """Return true if the given string is empty or only whitespace""" return len(line.strip()) == 0
def parse_assigned_variable_name(stack_frames, constructor_name): """Analyses the provided stack frames and parses Python assignment expressions like some.namespace.variable_name = some.module.name.`constructor_name`(...) from the caller's call site and returns the name of the variable being assign...
def _process_line(group, flag, value, is_fixed, dict_): """ This function processes most parts of the initialization file. """ # This aligns the label from the initialization file with the label # inside the RESPY logic. if flag == 'coeff': flag = 'coeffs' # Prepare container for inform...
def CLng(num): """Return the closest long of a value""" return int(round(float(num)))
def partition(arr, left, right, pivot_index): """ Partition the array into three groups: less that pivot, equal to it and more than pivot Args: input_list(list): Input List left(int): start index right(int): end index pivot_index(int): index of the pivot element Returns: ...
def rshift(val, n): """ Python equivalent to TypeScripts >>> operator. @see https://stackoverflow.com/questions/5832982/how-to-get-the-logical-right-binary-shift-in-python """ return (val % 0x100000000) >> n
def summarise_app(app): """Return a string the summarises the important information about the app""" state = app["state"] if state != "Installed": state = state.upper() pin_status = "Pinned" if app["is_pinned"] else "NOT PINNED" known_status = "UNKNOWN" if app["application_version"]["is_un...
def search_trie(trie, token, token_i=0): """ Search the given character-trie for paths that match the `token` string. """ if "*" in trie: return trie["*"] if "$" in trie and token_i == len(token): return trie["$"] if token_i < len(token): char = token[token_i] if ...
def find_min_recursive(array, left, right): """ Find the minimum in rotated array in O(log n) time. >>> find_min_recursive([1,2,3,4,5,6], 0, 5) 1 >>> find_min_recursive([6, 5, 4, 3, 2, 1], 0, 5) 1 >>> find_min_recursive([6, 5, 1, 4, 3, 2], 0, 5) 1 """ if array[left] <= array[right]: ...