content
stringlengths
42
6.51k
def unique_ordered_union(x, y): """ Returns a list containing the union of 'x' and 'y', preserving order and removing duplicates. """ return list(dict.fromkeys(list(x) + list(y)).keys())
def safe_int(str_value: str, base: int=10): """Always returns integer value from string/None argument. Returns 0 if argument is None. """ if str_value: return int(str_value, base) else: return 0
def epoch_to_timestamp(records): """ Convert epoch timestamps to ISO 8601 (2015-01-04T09:30:21Z) :param records: List (of dictionaries) :return: List (of dictionaries) """ from datetime import datetime for record in records: timestamp_keys = ["time_first", "time_last"] for key in timestamp_keys: if key in record: record[key] = datetime.fromtimestamp(record[key]).isoformat() + "Z" return records
def jsonize_phrase_dict(phrase_dict, val_string='frequency', term_to_str_fn=lambda tpl: ' '.join(tpl)): """Input: a dictionary of string tuples to values. Val: a dictionary of strings to values, where tuples have been separated by spaces""" return [{'term':term_to_str_fn(term), val_string:val} for (term, val) in phrase_dict.items()]
def get_quote_style(str): """find which quote is the outer one, ' or ".""" quote_char = None at = None found = str.find("'") found2 = str.find('"') # If found == found2, both must be -1, so nothing was found. if found != found2: # If a quote was found if found >= 0 and found2 >= 0: # If both were found, invalidate the later one if found < found2: found2 = -1 else: found = -1 # See which one remains. if found >= 0: at = found + 1 quote_char = "'" elif found2 >= 0: at = found2 + 1 quote_char = '"' return quote_char, at
def is_list_of_str_or_int(value): """ Check if an object is a string or an integer :param value: :return: """ return bool(value) and isinstance(value, list) and all(isinstance(elem, (int, str)) for elem in value)
def extract_spreadsheet_id(string): """Extracts the sprreadsheet id from an url.""" if "/edit" in string: string = string.split("/edit")[0] if "/" in string: string = string.rstrip("/") string = string.split("/")[-1] string = string.split("&")[0] string = string.split("#")[0] return string
def LowerCamelCase(value): """Turns some_string or SOME_STRING into someString.""" split_value = value.lower().split('_') result = [split_value[0]] + [part.capitalize() for part in split_value[1:]] return ''.join(result)
def get_features_for_type(column_type): """ Get features to be generated for a type """ # First get the look up table lookup_table = dict() # Features for type str_eq_1w lookup_table['STR_EQ_1W'] = [('lev_dist'), ('lev_sim'), ('jaro'), ('jaro_winkler'), ('exact_match'), ('jaccard', 'qgm_3', 'qgm_3')] # Features for type str_bt_1w_5w lookup_table['STR_BT_1W_5W'] = [('jaccard', 'qgm_3', 'qgm_3'), ('cosine', 'dlm_dc0', 'dlm_dc0'), ('jaccard', 'dlm_dc0', 'dlm_dc0'), ('monge_elkan'), ('lev_dist'), ('lev_sim'), ('needleman_wunsch'), ('smith_waterman')] # dlm_dc0 is the concrete space tokenizer # Features for type str_bt_5w_10w lookup_table['STR_BT_5W_10W'] = [('jaccard', 'qgm_3', 'qgm_3'), ('cosine', 'dlm_dc0', 'dlm_dc0'), ('monge_elkan'), ('lev_dist'), ('lev_sim')] # Features for type str_gt_10w lookup_table['STR_GT_10W'] = [('jaccard', 'qgm_3', 'qgm_3'), ('cosine', 'dlm_dc0', 'dlm_dc0')] # Features for NUMERIC type lookup_table['NUM'] = [('exact_match'), ('abs_norm'), ('lev_dist'), ('lev_sim')] # Features for BOOLEAN type lookup_table['BOOL'] = [('exact_match')] # Features for un determined type lookup_table['UN_DETERMINED'] = [] # Based on the column type, return the feature functions that should be # generated. if column_type is 'str_eq_1w': features = lookup_table['STR_EQ_1W'] elif column_type is 'str_bt_1w_5w': features = lookup_table['STR_BT_1W_5W'] elif column_type is 'str_bt_5w_10w': features = lookup_table['STR_BT_5W_10W'] elif column_type is 'str_gt_10w': features = lookup_table['STR_GT_10W'] elif column_type is 'numeric': features = lookup_table['NUM'] elif column_type is 'boolean': features = lookup_table['BOOL'] elif column_type is 'un_determined': features = lookup_table['UN_DETERMINED'] else: raise TypeError('Unknown type') return features
def get_message(data): """ Method to extract message id from telegram request. """ message_text = data['message']['text'] return message_text
def int_or_none(s): """ >>> int_or_none('') None >>> int_or_none('10') 10 """ return None if not s else int(s)
def space_newline_fix(text): """Replace "space-newline" with "newline". Args: text (str): The string to work with Returns: The text with the appropriate fix. """ space_newline = ' \n' fix = '\n' while space_newline in text: text = text.replace(space_newline, fix) return text
def _extended_gcd(a, b): """ Division in integers modulus p means finding the inverse of the denominator modulo p and then multiplying the numerator by this inverse (Note: inverse of A is B such that A*B % p == 1) this can be computed via extended Euclidean algorithm http://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Computation """ x = 0 last_x = 1 y = 1 last_y = 0 while b != 0: quot = a // b a, b = b, a % b x, last_x = last_x - quot * x, x y, last_y = last_y - quot * y, y return last_x, last_y
def CTAMARS_radii(camera_name): """Radii of the cameras as defined in CTA-MARS. These values are defined in the code of CTA-MARS. They correspond to the radius of an equivalent FOV covering the same solid angle. Parameters ---------- camera_name : str Name of the camera. Returns ------- average_camera_radii_deg : dict Dictionary containing the hard-coded values. """ average_camera_radii_deg = { "ASTRICam": 4.67, "CHEC": 3.93, "DigiCam": 4.56, "FlashCam": 3.95, "NectarCam": 4.05, "LSTCam": 2.31, "SCTCam": 4.0, # dummy value } return average_camera_radii_deg[camera_name]
def find_dividend_by_unit(time): """Finds whether time best corresponds to a value in days, hours, minutes, or seconds. """ for dividend in [86400, 3600, 60]: div = time / dividend if round(div) == div: return dividend return 1
def is_valid_ssn(x): """Validates that the field is 3 digits, a hyphen, 2 digits, a hyphen, and 4 final digits only.""" return True # speed up testing valid_ssn=re.compile(r'^\d{3}-\d{2}-\d{4}$') if not bool(re.match(valid_ssn,x)): validation_error("Write the Social Security Number like this: XXX-XX-XXXX") return True
def merge(line): """ Function that merges a single row or column in 2048. """ new_line = [x for x in line if x !=0] while len(new_line) < len(line): new_line.append(0) for ind in range(len(new_line)-1): if new_line[ind] == new_line[ind+1]: new_line[ind] *= 2 new_line.pop(ind+1) new_line.append(0) return new_line
def get_bigram_data(bigram_dict, combinations_list): """ Transforms a count dictionary in an ordered feature vector. Parameters: bigram_dict : dict with a combinations count combinations : list of tuples, where each tuple is a combination of two contact types (strings) Returns: ordered count list (feature vector) """ return [bigram_dict.get(combi, 0) for combi in combinations_list]
def is_color_similar(color1, color2, overlap=0.05): """Checks if colors are similar. :param tuple[int, int, int] color1: original color. :param tuple[int, int, int] color2: color to check. :param float overlap: overlap parameter. If colors similarity > overlap then colors are similar. :rtype: bool """ r1, g1, b1 = color1 r2, g2, b2 = color2 d = ((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2) ** (1 / 2.0) return d / 510 <= overlap
def uniq(a): """ Removes duplicates from a list. Elements are ordered by the original order of their first occurrences. In terms of Python 2.4 and later, this is equivalent to list(set(a)). """ if len(a) == 0: return [] else: return [a[0]] + uniq([x for x in a if x != a[0]])
def is_valid_run_name(run_name): """ Checks the validity of the run_name. run_name cannot have spaces or colons. :param run_name: <class str> provided run_name. :return: <bool> True if valid False if not. """ return run_name and not (' ' in run_name or ':' in run_name)
def paginate(page): """ Render a pagination block with appropriate links, based on the given Django Page object. """ context = { 'page': page } return context
def min_ten_neg(x, thresh, fallback): """Returns 10**-x, or `fallback` if it doesn't meet the threshold. Note, if you want to turn a hyper "off" below, set it to "outside the threshold", rather than 0. """ x = 10**-x return x if (x and x > thresh) else fallback
def find_area(coords): """Find area of a box when given the box corners in a tuple""" return (coords[1] - coords[0]) * (coords[3] - coords[2])
def to_n_grams(message): """ Break the text into 5-character chunks.""" # Pad the message in case its length isn't a multiple of 5. message += " " # Create the 5-character chunks. result = "" for i in range(0, len(message) - 5, 5): result += message[i: i + 5] + " " # Remove trailing spaces. return result.rstrip()
def like(matchlist: list, array: list, andop=False): """Returns a list of matches in the given array by doing a comparison of each object with the values given to the matchlist parameter. Examples: >>> subdir_list = ['get_random.py', ... 'day6_15_payload-by-port.py', ... 'worksheet_get_exif.py', ... 'worksheet_get_random.py', ... 'day6_19_browser-snob.py', ... 'day6_12_letterpassword.py', ... 'day6_21_exif-tag.py', ... 'day6_17_subprocess_ssh.py', ... 'day6_16._just_use_split.py'] >>> like('day', subdir_list)\n ['day6_15_payload-by-port.py', 'day6_19_browser-snob.py', 'day6_12_letterpassword.py', 'day6_21_exif-tag.py', 'day6_17_subprocess_ssh.py', 'day6_16._just_use_split.py'] >>> like(['get','exif'], subdir_list)\n ['get_random.py', 'worksheet_get_exif.py', 'worksheet_get_random.py', 'day6_21_exif-tag.py'] >>> like(['get','exif'], subdir_list, andop=True)\n ['worksheet_get_exif.py'] Args: matchlist (list): Submit one or many substrings to match against array (list): This is the list that we want to filter andop (bool, optional): This will determine if the matchlist criteria is an "And Operation" or an "Or Operation. Defaults to False (which is the "Or Operation"). Only applies when multiple arguments are used for the "matchlist" parameter Returns: list: Returns a list of matches References: https://stackoverflow.com/questions/469913/regular-expressions-is-there-an-and-operator https://stackoverflow.com/questions/3041320/regex-and-operator https://stackoverflow.com/questions/717644/regular-expression-that-doesnt-contain-certain-string """ import re if isinstance(matchlist, str): # matchlist is a single string object thecompile = re.compile(rf"^(?=.*{matchlist}).*$") result_list = [x for x in array if re.findall(thecompile, x)] return result_list else: if andop: # We will be doing an "AND" match or an "And" "Operation" match_string = r"(?=.*?" + r".*?)(?=.*?".join(matchlist) + r".*?)" # e.g. for the above... ['6_19','6_21','6_24'] turns to: '(?=.*?6_19.*?)(?=.*?6_21.*?)(?=.*?6_24.*?)' thecompile = re.compile(rf"^{match_string}.*$") # equivalent to: '^(?=.*?6_19.*?)(?=.*?6_21.*?)(?=.*?6_24.*?).*$' result_list = [x for x in array if re.findall(thecompile, x)] return result_list else: # We will be doing an "OR" match match_string = r"(?=.*" + r"|.*".join(matchlist) + ")" # e.g. for the above... ['6_19','6_21','6_24'] turns to: '(?=.*6_19|.*6_21|.*6_24)' thecompile = re.compile(rf"^{match_string}.*$") # equivalent to: '^(?=.*6_19|.*6_21|.*6_24).*$' result_list = [x for x in array if re.findall(thecompile, x)] return result_list
def getminby2index(inputlist,index1,index2): """can get PIF calcs using flox data and crossvals note that cross ref of indexlist with Ti vs Te timestamps is needed for segregation of the data """ minbyindexlist=[min( inputlist[index1[i]:index2[i]] ) for i in range(len(index1))] return minbyindexlist
def get_transfer_dict_cmd(server_from_str, server_to_str, folders_str): """ Convert command line options to transfer dictionary Args: server_from_str (str): counter to iterate over environment variables server_to_str (str): Environment variables from os.environ folders_str (str) Returns: dict: transfer dictionary """ server_from_lst = server_from_str.split(";") server_to_lst = server_to_str.split(";") folders_dict = { el[0]: el[1] for el in [s.split(":") for s in folders_str.split(";")] } return { "server_from": { "host": server_from_lst[0], "username": server_from_lst[1], "password": server_from_lst[2], }, "server_to": { "host": server_to_lst[0], "username": server_to_lst[1], "password": server_to_lst[2], }, "dirs": folders_dict, }
def extractdate(id): """Pulls date in form YYYMMDD from id""" date = id[1:9] return int(date)
def running(demo_mode, step, max_step): """ Returns whether the demo should continue to run or not. If demo_mode is set to true, the demo should run indefinitely, so the function returns true. Otherwise, the function returns true only if step <= max_step :param demo_mode: true if running in demo mode :param step: current simulation step :param max_step: maximum simulation step :return: true if the simulation should continue """ if demo_mode: return True else: return step <= max_step
def even(text) -> str: """ Get Even-numbered characters. :param str text: String to convert. :rtype: str :return: String combining even-numbered characters. """ return text[1::2]
def convert_default(*args, **kwargs): """ Handle converter type "default" :param args: :param kwargs: :return: return schema dict """ schema = {'type': 'string'} return schema
def rgb_to_rgba(rgb): """ Convert a tuple or list containing an rgb value to a tuple containing an rgba value. rgb : tuple or list of ints or floats ([r, g, b]) """ r = rgb[0] / 255 g = rgb[1] / 255 b = rgb[2] / 255 return r, g, b
def get_bits(n, start, end): """Return value of bits [<start>:<end>] of <n>""" return (int(n) & ((1 << end) - 1)) >> start
def subscribers(object_type: str) -> str: """Key for list of subscribers to specified object type.""" return 'events:{}:subscribers'.format(object_type)
def ipv4_mask_to_net_prefix(mask): """Convert an ipv4 netmask into a network prefix length. If the input is already an integer or a string representation of an integer, then int(mask) will be returned. "255.255.255.0" => 24 str(24) => 24 "24" => 24 """ if isinstance(mask, int): return mask if isinstance(mask, str): try: return int(mask) except ValueError: pass else: raise TypeError("mask '%s' is not a string or int" % mask) if '.' not in mask: raise ValueError("netmask '%s' does not contain a '.'" % mask) toks = mask.split(".") if len(toks) != 4: raise ValueError("netmask '%s' had only %d parts" % (mask, len(toks))) return sum([bin(int(x)).count('1') for x in toks])
def commafy( number ): ############################################################ """commafy(number) - add commas to a number""" import re return re.sub(r'(\d{3})(?=\d)',r'\1,' ,str(number)[::-1])[::-1]
def chunkIt(seq, num): """ **Chunks a list into a partition of specified size.** + param **seq**: sequence to be chunked, dtype `list`. + param **num**: number of chunks, dtype `int`. + return **out**: chunked list, dtype `list`. """ out = [] last = 0.0 while last < len(seq): if int(last + num) > len(seq): break else: out.append(seq[int(last) : int(last + num)]) last += num return out
def get_ages_at_death(employees): """ Calculate approximate age at death for employees Assumes that they have a birth year and death year filled """ return list(map(lambda x: x.age_at_death(), employees))
def make_experiment_dir_name(max_model_size, experiment_name): """Return name of directory for results of given settings (only depends on model size) and experiment name""" if experiment_name is not None: return f"Experiment={experiment_name}-max_model_size={max_model_size}" else: return f"max_model_size={max_model_size}"
def is_archived(filename, suffixes): """ """ return any(filename.endswith(s) for s in suffixes)
def _inters(orig, new): """Make the interaction of two sets. If the original is a None value, a new set will be created with elements from the new set. When both operands are None, the result is None. """ if orig is None: return new elif new is None: return orig else: orig &= new return orig
def calc_new_value(old_measure, new_measure, count): """ Factor the total count in to the difference of the new value. E.g. for a value of 100ms with 50 measurements, a new measure of 150ms would add 1 ms to the total """ return (old_measure + (old_measure + (new_measure - old_measure) * (1.0 / count))) / 2.0
def join_models(model1, model2): """ Concatenate two SDD models. Assumes that both dictionaries do not share keys. """ model = model1.copy() model.update(model2) return model
def filter_out_black(list_of_pixels): """ Takes a 1-d list of pixels and filters out the very dark pixels. Returns the list of non-dark pixels """ return [pixel for pixel in list_of_pixels if max(pixel) > 0.1]
def _nd4j_datatype_from_np(np_datatype_name): """ :param np_datatype_name: a numpy data type name. 1 of: float64 float32 float16 :return: the equivalent nd4j data type name (double,float,half) """ if np_datatype_name == 'float64': return 'double' elif np_datatype_name == 'float32': return 'float' elif np_datatype_name == 'float16': return 'half' return None
def lower_words(iterable): """ turn all words in `iterable` to lower """ return [w.lower() for w in iterable]
def call_aside(f, *args, **kwargs): """ Call a function for its side effect after initialization. >>> @call_aside ... def func(): print("called") called >>> func() called Use functools.partial to pass parameters to the initial call >>> @functools.partial(call_aside, name='bingo') ... def func(name): print("called with", name) called with bingo """ f(*args, **kwargs) return f
def distance(a, b): """ distance computes the Manhattan distance between a and b where a and b are either tuples (x,y) or dicts {'x':_, 'y':_} """ if not isinstance(a, tuple): a = (a['x'], a['y']) if not isinstance(b, tuple): b = (b['x'], b['y']) return abs(a[0] - b[0]) + abs(a[1] - b[1])
def file_exists (filename): """ Determine if a file with the given name exists in the current directory and can be opened for reading. Returns: True iff it exists and can be opened, False otherwise. :param filename: Filename to check. :return True if file exists. """ try: f = open (filename, 'r') f.close () return True except IOError: return False
def remove_dup2(a): """ remove dup in sorted array without using another array """ n = len(a) j = 0 print("before removing -- ", a ) for i in range(0, n-1): if a[i] != a[i+1]: a[j] = a[i] j = j+ 1 a[j] = a[n-1] print("after removing -- ", a ) return a[0: j+1]
def detokenize(sent): """ Roughly detokenizes (mainly undoes wordpiece) """ new_sent = [] for i, tok in enumerate(sent): if tok.startswith("##"): new_sent[len(new_sent) - 1] = new_sent[len(new_sent) - 1] + tok[2:] else: new_sent.append(tok) return new_sent
def box_lengths(dimensions): """Return list of dimension ints""" return sorted([int(i) for i in dimensions.split('x')])
def get_snr(snr_min, emission_line, default=3): """Convenience function to get the minimum SNR for a certain emission line. If ``snr_min`` is a dictionary and ``emision_line`` is one of the keys, returns that value. If the emission line is not included in the dictionary, returns ``default``. If ``snr_min`` is a float, returns that value regardless of the ``emission_line``. """ if not isinstance(snr_min, dict): return snr_min if emission_line in snr_min: return snr_min[emission_line] else: return default
def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest common subsequence between the two strings Note: my_lcs only gives length of the longest common subsequence, not the actual LCS """ if (len(string) < len(sub)): sub, string = string, sub lengths = [[0 for i in range(0, len(sub) + 1)] for j in range(0, len(string) + 1)] for j in range(1, len(sub) + 1): for i in range(1, len(string) + 1): if (string[i - 1] == sub[j - 1]): lengths[i][j] = lengths[i - 1][j - 1] + 1 else: lengths[i][j] = max(lengths[i - 1][j], lengths[i][j - 1]) return lengths[len(string)][len(sub)]
def _multihex (blob): """Prepare a hex dump of binary data, given in any common form including [[str]], [[list]], [[bytes]], or [[bytearray]].""" return ' '.join(['%02X' % b for b in bytearray(blob)])
def zeroOut(data): """ """ # Convert empty strings to zeros. cols = len(data[0]) data = [0 if col == '' else col for row in data for col in row] data = [data[y : y + cols] for y in range(0, len(data), cols)] return data
def capitalizeEachWord(original_str): """ ORIGINAL_STR of type string, will return each word of string with the first letter of each word capitalized """ result = "" # Split the string and get all words in a list list_of_words = original_str.split() # Iterate over all elements in list for elem in list_of_words: # capitalize first letter of each word and add to a string if len(result) > 0: result = result + " " + elem.strip().capitalize() else: result = elem.capitalize() # If result is still empty then return original string else returned capitalized. if not result: return original_str else: return result
def getNameIndex(name): """For Cylinder.001 returns int 1""" try: location = len(name) - "".join(reversed(name)).index(".") index = int(name[location:]) except Exception: index = 0 return index
def get_r_list(area1, area2, max_area, tol=0.02): """ returns a list of r1 and r2 values that satisfies: r1/r2 = area2/area1 with the constraints: r1 <= Area_max/area1 and r2 <= Area_max/area2 r1 and r2 corresponds to the supercell sizes of the 2 interfaces that align them """ r_list = [] rmax1 = int(max_area / area1) rmax2 = int(max_area / area2) print('rmax1, rmax2: {0}, {1}\n'.format(rmax1, rmax2)) for r1 in range(1, rmax1 + 1): for r2 in range(1, rmax2 + 1): if abs(float(r1) * area1 - float(r2) * area2) / max_area <= tol: r_list.append([r1, r2]) return r_list
def escape_birdiescript(s): """Escape a Birdiescript string.""" return s.replace('\\', '\\\\').replace('`', '\\`')
def takeInputAsList(molecule_name): """ This function converts the user given molecule names separated by semicolon into a list of string INPUT: molecule_name(Molecule names in semicolon separated format. Example: Methane;Methanol;Ethane) OUTPUT: molecule_names(Molecule names in list of string format. Example: ['Methane','Methanol','Ethane']) """ molecule_names = [] molecule_name = molecule_name.split(';') for name in molecule_name: molecule_names.append(name) return molecule_names
def serialize(obj): """JSON serializer for objects not serializable by default json code """ if getattr(obj, '__dict__', False): return obj.__dict__ return str(obj)
def get_edges_by_source_id(edges, source_id): """ Get the edges from the specified source. :param edges: Input edges. :param source_id: Id of the source. :return: List of edges """ res = [] for edge in edges: if edge.source == source_id: res.append(edge) return res
def convert_repr_number (number): """ Helper function to convert a string representation back to a number. Assumptions: * It may have a thousand separator * It may have a decimal point * If it has a thousand separator then it will have a decimal point It will return false is the number doesn't look valid """ sep = "" dec = "" part_one = "0" part_two = "" for digit in number: if digit.isdigit(): if sep == "": part_one += digit else: part_two += digit else: if digit == "-" and part_one == "0": part_one = "-0" elif sep == "" and sep != digit: sep = digit elif dec == "": dec = digit part_two += "." else: # Doesn't look like a valid number repr so return return False if dec == "": return float("%s.%s" % (part_one, part_two)) else: return float("%s%s" % (part_one, part_two))
def least_significan_bit(n): """Least significant bit of a number num AND -num = LSB Args: n ([type]): [description] Raises: TypeError: [description] Returns: [type]: [description] """ if type(n) != int: raise TypeError("Number must be Integer.") if n > 0 : return (n&-n)
def toTableFormat(filteredStatDict): """ Format the filtered statistic dict into list that can be displayed into QT table arg : - filteredStatDict (dict): the dict to format return : list """ tableFormat = [] totalOccur = sum(occur for word, occur in filteredStatDict["wordcount"]) # Filtered result holds data if len(filteredStatDict["wordcount"]) > 0: for word, occur in filteredStatDict["wordcount"]: currentRow = [word, occur, round(float(occur * 100)/totalOccur, 2)] tableFormat.append(currentRow) tableFormat.append([" ", " ", " "]) tableFormat.append(["Number of lines", filteredStatDict["nbLines"], ""]) tableFormat.append(["Number of words", filteredStatDict["nbWords"], ""]) tableFormat.append(["Number of characters", filteredStatDict["nbChars"], ""]) return tableFormat
def are_islands_sorted(island_list): """ Check if sorted in ascending order. input is a list of BED with chrom, start, end and value. output: sorted =1 or 0 """ sorted = 1; for index in range(0, len(island_list)-1): if island_list[index].start> island_list[index+1].start: sorted = 0; return sorted;
def identify_significant_pairs(list_pairs): """Takes in a a list of lists, which include the pairs and the third element of each list is L.O.S. Args: list_pairs (list of lists): First element is crypto pair 1, second element crypto pair 2 and third element is L.O.S. """ return [x for x in list_pairs if x[2] <= 0.05]
def split(n): """Splits a positive integer into all but its last digit and its last digit.""" return n // 10, n % 10
def content_type(content_type="application/json"): """Construct header with content type declaration for the server API calls. Returned dict can be added to the 'request' object. """ return {'Content-type': content_type}
def decode_bytes(obj): """If the argument is bytes, decode it. :param Object obj: A string or byte object :return: A string representation of obj :rtype: str """ if isinstance(obj, bytes): return obj.decode('utf-8') elif isinstance(obj, str): return obj else: raise ValueError("ERROR: {} is not bytes or a string.".format(obj))
def value_to_HSL(value): """ Convert a value ranging from 0 to 100 into a color ranging from red to green using the HSL colorspace. Args: value (int): integer betwee 0-100 to be converted. Returns: Tuple[int]: hue, saturation and lightnes corresponding to the converted value. """ # max(value) = 100 hue = int(value * 1.2) # 1.2 = green, 0 = red saturation = 90 lightness = 40 return (hue, saturation, lightness)
def check_games(games): """Check that every player does not come in 1st and does not come in last at least once each.""" pc = dict() for game in games: max_rank = 0 max_user = None for user, rank in game.items(): if rank > 1: pc.setdefault(user, [1, 1])[1] = 0 if rank > max_rank: if max_user: pc.setdefault(max_user, [1, 1])[0] = 0 max_rank = rank max_user = user elif rank < max_rank: pc.setdefault(user, [1, 1])[0] = 0 missing_wl = sum(w+l for w, l in pc.values()) if missing_wl > 0: winners = list() losers = list() for player, (win, loss) in pc.items(): if not win and not loss: continue if win and loss: # This should never happen. raise Exception("Player with neither win or loss %s" % (player,)) if win: losers.append(player) else: winners.append(player) print("Player %s has no %s" % (player, "win" if win else "loss")) return winners, losers return None, None
def fix_image_ids(data): """ LabelBox uses strings for image ids which don't work with the coco API (which is used inside of torchvision CocoDetection dataset class """ img_ids = dict() for i, img_data in enumerate(data['images']): id = img_data['id'] # Create lookup table img_ids[id] = i # Set image id to new integer id img_data['id'] = i for ann in data['annotations']: # Set image id to new integer id for each annotation ann['image_id'] = img_ids[ann['image_id']] return data
def _conv_year(s): """Interpret a two-digit year string.""" if isinstance(s, int): return s y = int(s) return y + (1900 if y >= 57 else 2000)
def multiple_split(source_string, separators, split_by = '\n'): """ This function allows the user to split a string by using different separators. Note: This version is faster than using the (s)re.split method (I tested it with timeit). Parameters: * source_string: string to be splitted * separators: string containing the characters used to split the source string. * split_by: all the ocurrences of the separators will be replaced by this character, then the split will be done. It defaults to '|' (pipe) """ translate_to = split_by * len(separators) translation = str.maketrans(separators, translate_to) return source_string.translate(translation).split(split_by)
def is_num_present(word): """ Check if any number present in Given String params: word - string returns: 0 or 1 """ check = any(letter.isdigit() for letter in word) return 1 if check else 0
def message(operation, type, resource, raw_resource, execution_time, status): """ :summary: Concats the supplied parameters and returns them in trace format :param operation: Operation (MySQL/ Mongo/ ES/ API/ etc) :param type: Type of the Operation (SELECT/ GET/ POST/ etc) :param resource: URL / Query / Function name :param raw_resource: URL / Query / Function name :param execution_time: Time taken to perform that operation :param status: Success or Failure :return: Concatinated string """ return "%s|%s|%s|%s|%s|%s" % (operation, type, resource, raw_resource, execution_time, status)
def commonMember(a, b): """ Return True if two list have at least an element in common, False otherwise """ a_set = set(a) b_set = set(b) if (a_set & b_set): return True else: return False
def search_active_words(subject, active_words): """ This method looks for active_words in subject in a case-insensitive fashion Parameters ---------- subject: string, required email subject active_words: string, required active words represented in a comma delimited fashion Returns ------- True If any active words were found in subject or, No active words are configured False If no active words were found in subject """ if not active_words: return True else: # Convert to lower case words by splitting active_words. For example: 'Hello , World,' is generated as ('hello','world'). lower_words = [word.strip().lower() for word in filter(None, active_words.split(','))] # Convert subject to lower case in order to do a case insensitive lookup. subject_lower = subject.lower() for word in lower_words: if word in subject_lower: return True return False
def test_for_long_cell(raw_python_source: str) -> bool: """ Returns True if the text "# Long" is in the first line of `raw_python_source`. False otherwise. """ first_element = raw_python_source.split("\n")[0] if "#" in first_element and "long" in first_element.lower(): return True return False
def qual_stat(qstr): """ Modified to calculate average quality score of a sequence """ q30_sum = 0 q30_seq = 0 # q30 = 0 for q in qstr: # qual = ord(q) - 33 qual = q - 33 q30_sum += qual # if qual >= 30: # q30 += 1 q30_seq = q30_sum/len(qstr) return q30_seq
def guess_game_name_from_clone_arg(clone_arg: str) -> str: """Guess the name of the game from the --clone argument. :arg clone_arg: The str given by the user for the clone argument. Usually a git link as `https://github.com/ScienceGamez/world-3.git`.. """ if "/" in clone_arg: # If url, probably the last value is used as game name last_value = clone_arg.split("/")[-1] # The last value might have a . inside return last_value.split('.')[0] else: return clone_arg
def experience_boost_determination(ability_scores, prime_ability): """ This function determines any applicable experience boost. Assumes abilities is a list of tuples (ability as str, stat as int) Assumes prime_ability is a string. Returns a percentage as a str. """ abilities = ['Strength', 'Intelligence', 'Wisdom', 'Dexterity', 'Constitution', 'Charisma'] stats = ability_scores prime = abilities.index(prime_ability) if stats[prime][1] == 13 or stats[prime][1] == 14: experience_boost = '5%' elif stats[prime][1] >= 15: experience_boost = '10%' else: experience_boost = '0%' return experience_boost
def clean_uid(uid): """ Return a uid with all unacceptable characters replaced with underscores """ if not hasattr(uid, 'replace'): return clean_uid(str(uid.astype('S'))) try: return uid.decode('utf-8').replace(u"/", u"_").replace(u":", u"_") except AttributeError: return uid.replace("/", "_").replace(":", "_")
def get_indent(line): """Helper function for getting length of indent for line. Args: line (str): The line to check. Returns: int: The length of the indent """ for idx, char in enumerate(line): if not char.isspace(): return idx return len(line)
def default_params(fun_kwargs, default_dict=None, **kwargs): """Add to kwargs and/or default_dict the values of fun_kwargs. This function allows the user to overwrite default values of some parameters. For example, in the next example the user cannot give a value to the param `a` because you will be passing the param `a` twice to the function `another_fun`:: >>> def fun(**kwargs): ... return another_fun(a="a", **kwargs) You can solve this in two ways. The fist one:: >>> def fun(a="a", **kwargs): ... return another_fun(a=a, **kwargs) Or using default_params:: >>> def fun(**kwargs): ... kwargs = default_params(kwargs, a="a") ... return another_fun(**kwargs) """ if default_dict is None: default_dict = kwargs else: default_dict.update(kwargs) default_dict.update(fun_kwargs) return default_dict
def digit(decimal, digit, input_base=10): """ Find the value of an integer at a specific digit when represented in a particular base. Args: decimal(int): A number represented in base 10 (positive integer). digit(int): The digit to find where zero is the first, lowest, digit. base(int): The base to use (default 10). Returns: The value at specified digit in the input decimal. This output value is represented as a base 10 integer. Examples: >>> digit(201, 0) 1 >>> digit(201, 1) 0 >>> digit(201, 2) 2 >>> tuple(digit(253, i, 2) for i in range(8)) (1, 0, 1, 1, 1, 1, 1, 1) # Find the lowest digit of a large hexidecimal number >>> digit(123456789123456789, 0, 16) 5 """ if decimal == 0: return 0 if digit != 0: return (decimal // (input_base ** digit)) % input_base else: return decimal % input_base
def dest_file(file_name): """ "Add.asm" -> "Add.hack" """ naked = file_name.rsplit('.', 1)[0] return naked + '.hack'
def flatten(seq): """ Returns a list of the contents of seq with sublists and tuples "exploded". The resulting list does not contain any sequences, and all inner sequences are exploded. For example: >>> flatten([7,(6,[5,4],3),2,1]) [7, 6, 5, 4, 3, 2, 1] """ lst = [] for el in seq: if isinstance(el, (list, tuple)): lst.extend(flatten(el)) else: lst.append(el) return lst
def _FunctionSelector(population, N, samples, stdFunction, sampleFunction, baseParams): """Fitness function that determines on the fly whether to use a sampling algorithm or not. """ L = len(population) combinations = L**N if samples < 1.0: samples = int(combinations*samples+0.5) if samples == 0: samples = 1 if samples < combinations: return sampleFunction(population, *(baseParams + (samples,))) else: return stdFunction(population, * baseParams)
def conjugate_row(row, K): """ Returns the conjugate of a row element-wise Examples ======== >>> from sympy.matrices.densetools import conjugate_row >>> from sympy import ZZ >>> a = [ZZ(3), ZZ(2), ZZ(6)] >>> conjugate_row(a, ZZ) [3, 2, 6] """ result = [] for r in row: conj = getattr(r, "conjugate", None) if conj is not None: conjrow = conj() else: conjrow = r result.append(conjrow) return result
def partial_difference_quotient(f, v, i, h): """ compute the ith partial difference quotient of f at v """ w = [v_j + (h if j == i else 0) # add h to just the ith element of v for j, v_j in enumerate(v)] return (f(w) - f(v)) / h
def determina_putere(n): """ Determina ce putere a lui 2 este prima cea mai mare decat n :param (int) n: numarul de IP-uri necesare citit de la tastatura :return (int) putere: puterea lui 2 potrivita """ putere = 1 while 2**putere < n+2: putere += 1 return putere
def calcbw(K, N, srate): """Calculate the bandwidth given K.""" return float(K + 1) * srate / N
def _is_repeating(password): """ Check if there is any 2 characters repeating consecutively """ n = 1 while n < len(password): if password[n] == password[n-1]: return True n += 1 return False
def print_summarylist(tags, vals): """ Prints a nice one-line listing of tags and their values in a nice format that corresponds to how the DIGITS regex reads it. Args: tags: an array of tags vals: an array of values Returns: print_list: a string containing formatted tags and values """ print_list = '' for i, key in enumerate(tags): if vals[i] == float('Inf'): raise ValueError('Infinite value %s = Inf' % key) print_list = print_list + key + " = " + "{:.6f}".format(vals[i]) if i < len(tags)-1: print_list = print_list + ", " return print_list
def exceptions_equal(exception1, exception2): """Returns True if the exceptions have the same type and message""" # pylint: disable=unidiomatic-typecheck return type(exception1) == type(exception2) and str(exception1) == str(exception2)
def merge_pnslots(pns1, pns2): """ Takes two sets of pronoun slots and merges them such that the result is valid for text that might follow text which resulted in either of the merged slot sets. """ result = {} for pn in pns1: if pns1[pn][1] == pns2[pn][1]: result[pn] = [max(pns1[pn][0], pns2[pn][0]), set(pns1[pn][1])] else: # Any kind of ambiguity results in an empty slot: result[pn] = [0, set()] return result