content
stringlengths
42
6.51k
def unique(L1, L2): """Return a list containing all items in 'L1' that are not in 'L2'""" return [item for item in L1 if item not in L2]
def sgn(x): """ Returns sign of number """ if x==0: return 0. elif x>0: return 1. else: return -1.
def validate_lists_have_same_elements(l1, l2): """ Given two lists/sets of values (from different sources), verify that they match up. Useful for comparing ids in GFF and Fasta files, or across Genomes and Assemblies. """ diff = set(l1) ^ (set(l2)) # get the symmetric difference of the sets ...
def parse_variable_field(field, re_dict): """Function takes a MARC21 field and the Regex dictgroup and return a list of the subfields that match the Regex patterns. Parameters: field -- MARC21 field re_dict -- Regular Expression dictgroup """ output = [] if field is None or re_dict is N...
def is_isogram(s): """ Determine if a word or phrase is an isogram. An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter. Examples of isograms: - lumberjacks - background - downstream """ from collections import Counter s = s.lower().strip(...
def get_size(bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor
def create_character_ngrams(text_list, length): """ Create character ngrams of the specified length from a string of text Args: text_list (list): Pre-tokenized text token to process. length (int): Length of ngrams to create. http://stackoverflow.com/questions/18658106/quick-implement...
def reasonable(n): """Is N small enough that 1/N can be represented? >>> reasonable(100) True >>> reasonable(0) True >>> reasonable(-100) True >>> reasonable(10 ** 1000) False """ return n == 0 or 1/n != 0.0
def transform(beacon_pos: list, offsets: list, offsets_types: list) -> None: """Transform beacon positions relative to a scanner.""" x_prime: int = 0 y_prime: int = 0 z_prime: int = 0 new_positions = [] for x, y, z in beacon_pos: if offsets_types[0] == 'x': x_prime = x + off...
def id_reference(obj): """ Returns a dictionary containing an 'object reference' which is required by the API in some cases. :param obj: if obj is a string it is used as the object id, otherwise a dictionary containing an 'id' key :return: a """ return {'id': str(obj)} if isinstance(obj, str)...
def sentihood_macro_F1(y_true, y_pred): """ Calculate "Macro-F1" of aspect detection task of Sentihood. """ p_all = 0 r_all = 0 count = 0 for i in range(len(y_pred) // 4): a = set() b = set() for j in range(4): if y_pred[i * 4 + j] != 0: a....
def StringToId(peg_positions): """ input a list of strings representing peg positions returns the game bitfield as integer number """ my_string = [''] * 36 cur_pos = 0 cur_bitfield = 0 for row in ['A', 'B', 'C', 'D', 'E', 'F']: for col in ['1', '2', '3', '4', '5', '...
def int2verilog(val, vw): """ :param val: A signed integer to convert to a verilog literal. :param vw: The word length of the constant value. """ sign = '-' if val < 0 else '' s = ''.join((sign, str(vw), '\'sd', str(abs(val)))) return s
def cross(u, v): """Create the cross-product of two 3-tuples u and v.""" return tuple( [ u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0], ] )
def make_dict(tokens): """Converts a parsed list of tokens to a dictionary.""" tokdict={} for t in tokens: tokdict[t[0]]=t[1:] return tokdict
def _encode_exponent_as_bitstring(exponent): """ This is expecting an integer. The purpose of this function is to return the bit_string representation of the exponent. The length of the string is 11 characters long and is meant to be combined with the 52 bit exponent and 1 sign bit to form a 64 bi...
def remove_duplicate_char(input_string): """ returns an unordered string without duplicate characters """ return "".join(set(input_string))
def get_file_name_with_extension(path): """ >>> get_file_name_with_extension('yuv/src01_hrc01.yuv') 'src01_hrc01.yuv' >>> get_file_name_with_extension('src01_hrc01.yuv') 'src01_hrc01.yuv' >>> get_file_name_with_extension('abc/xyz/src01_hrc01.yuv') 'src01_hrc01.yuv' """ return path....
def GetAllDictPaths(tree_dict): """Obtain list of paths to all leaves in dictionary. The last item in each list entry is the value at the leaf. For items in dictionary that are a list of dictionaries, each list entry is indexed by a string repesenting its position in the list. Implementation inspired by http...
def bytes_to_str(input_bytes): """Convert bytes to string. """ return input_bytes.decode()
def _get_limb_section(asm_str): """decode the limb and the section (h or l) from limb (e.g "4l")""" if len(asm_str.split()) > 1: raise SyntaxError('Unexpected separator in limb reference') if asm_str.lower().endswith('l'): s = 0 elif asm_str.lower().endswith('h'): s = 1 else:...
def find_by(dict_or_list, key, value, *args): """ Find a dict inside a dict or list by key, value properties. """ search_params = [(key, value)] if args: search_params += [(args[i], args[i+1]) for i in range(0, len(args), 2)] if isinstance(dict_or_list, dict): dict_or_list = dict...
def escape_html(text): """ Escapes all html characters in text :param str text: :rtype: str """ return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
def _real_id_to_cat_id(catId): """Note coco has 80 classes, but the catId ranges from 1 to 90!""" real_id_to_cat_id = \ {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 13, 13: 14, 14: 15, 15: 16, 16: 17, 17: 18, 18: 19, 19: 20, 20: 21, 21: 22, 22: 23, 23: 24, 24: 25, 25: 27, 26: ...
def calculate_md5(text): """Calculate the MD5 hash for the give text""" import hashlib return hashlib.md5(text.encode('utf-8')).hexdigest()
def getDictSum(a): """Get key of max element in a dict of ints or floats""" sum=0 for i in a: sum+=a[i] return sum
def make_location(location, protocol): """ Creates location object given a location and a protocol. :param str location: file path :param str protocol: protocol, for now only accepting `uri` :return: the location subconfiguration :rtype: obj :raises ValueError: if a protocol other than `uri`...
def exponentiate(base, exp, p): """ uses the square and multiply algorithm to get (base^exp)%p :param base: base of the exponentiation :param exp: power that the base is being raised to :param p: prime modulus :returns: (base^exp) mod p """ e = "{0:b}".format(exp) # bitstring of...
def rgi_code2url(rgi_num): """ Given an RGI-number, give the location of its shapefiles on GLIMS-website """ urls = ( 'rgi60_files/01_rgi60_Alaska.zip', 'rgi60_files/02_rgi60_WesternCanadaUS.zip', 'rgi60_files/03_rgi60_ArcticCanadaNorth.zip', 'rgi60_files/04_rgi60_Arc...
def nested_dict(key, value): """Create a nested dict if the key is a list of keywords""" if isinstance(key, list): d = {} ref = d for key_value in key: if key_value == key[-1]: d[key_value] = value else: d[key_value] = {} ...
def cat_and_mouse(x, y, z): """Hackerrank Problem: https://www.hackerrank.com/challenges/cats-and-a-mouse/problem Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to determine which cat will reach the mouse first, assuming the mouse doesn't m...
def not_a_test(obj): """Decorator used to suppress a functor from being treated as a TestCase""" obj.__test__ = False return obj
def is_subset(set1, set2): """ Returns True if set1 is a subset of or equal to set2 """ return all([e in set2 for e in set1])
def lower_username(username): """ Single entry point to force the username to lowercase, all the functions that need to deal with username should call this. """ if username: return username.lower() return None
def _get_owner_id_for_canonical(region_id): """Returns region specific owner id for Canonical which is the maintainer of Ubuntu images.""" if region_id.startswith('cn-'): return '837727238323' else: return '099720109477'
def make_lex_dict(lexicon_file): """ Convert lexicon file to a dictionary """ lex_dict = {} for line in lexicon_file.split('\n'): (word, measure) = line.strip().split('\t')[0:2] lex_dict[word] = float(measure) return lex_dict
def trim_docstring(docstring): """Uniformly trims leading/trailing whitespace from docstrings. Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation """ if not docstring or not docstring.strip(): return "" # Convert tabs to spaces and split into lines lines = ...
def num_examples_per_epoch(split): """Returns the number of examples in the data set. Args: split: name of the split, "train" or "validation". Raises: ValueError: if split name is incorrect. Returns: Number of example in the split. """ if split.lower().startswith('train'): return 100000 el...
def stripTag(chunk): """Strips the tag and returns the rest of the chunk. Only useful in password-protected uploads. Arguments: chunk {bytes} -- Everything inside the message field of an IOTA tx, except for the signature. Returns: [bytes] -- Chunk without the tag. """ #tag = chunk[-16:] chunkAndNonce = c...
def _centers(edges): """ This takes histogram edges and calculates the centers of each bin. All this does is take the average of each pair of edges. :param edges: List of edges of the bins of the histogram. :type edges: list :return: list of bin centers :rtype: list of float """ ce...
def check_value_type(value): """ Check value type so that we can process them differently :param value: :return: """ if isinstance(value, int): return int(value) elif isinstance(value, float): return float(value) else: return str(value).strip()
def kesirKarsilastirma(kesir1, kesir2): """ kesir1 ve kesir2, [pay, payda] seklinde tutulan iki elemanli listelerdir. Buyukten kucuge, ya da kucukten buyuge siralama yaparken iki kesrin karsilastirilmasini bu fonksiyon blogunda tanimlayiniz: Kodunuzu bu satirdan itibaren yaziniz, verilen satirlari...
def TruncateHostname(host_dns): """ This "fixes" the host name which is not correct in some circumstances. WMI wants only the first part of the address on Windows (Same string for OpenPegasus and WMI). On Linux apparently, Name="Unknown-30-b5-c2-02-0c-b5-2.home" Beware of a normal address such as: "...
def get_style(sut_name): """ get style """ color, linestyle, linewidth = None, None, None if "base" in sut_name: color, linestyle, linewidth = 'k', ':', 3.0 if "rec" in sut_name: linestyle = '--' if "hybrid" in sut_name: color, linewidth = 'k', 2.0 return (color, lines...
def parse_cid_2_text(ciddict, cid): """parse_cid_2_text""" for key in ciddict.keys(): cid = cid.replace(key, ciddict[key]) return cid
def default_holdout_frac(num_train_rows, hyperparameter_tune=False): """ Returns default holdout_frac used in fit(). Between row count 5,000 and 25,000 keep 0.1 holdout_frac, as we want to grow validation set to a stable 2500 examples. """ if num_train_rows < 5000: holdout_frac = max(0.1, mi...
def is_renderable(obj): """Check if an object complies to the render protocol""" return hasattr(obj, "moya_render")
def num_lines(file): """ Args: file: target file Returns: of lines in file """ return sum(1 for _ in open(file))
def pad_sequence(seq, max_length, pad_label = len(['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T', 'V','W','Y','X'])): """brings all sequences to same length by adding padding token seq -- sequence to pad max_length -- sequence length to pad to pad_label -- which padding label to use ...
def _normalize_target_module(source_module, target_module, level): """ Normalize relative import, to absolute import if possible. Parameters ---------- source_module : str or None Name of the module where the import is written. If given, this name should be absolute. target_module :...
def GuessType(path, mappings): """Return the type based on the path. The site config provides automatic mappings based on path.""" for type_path, type_name in mappings.items(): if path.find(type_path) >= 0: return type_name
def _get_bin(x, low, high, num_bins): """Returns bin number for value `x`, in 1D histogram defined by `low`, `high`, `num_bins`. There are `num_bins` bins, spaced evenly between `low` and `high`. The right most edge is put into bin: num_bins - 1. BEWARE: will return value outside the range [0, num_bins...
def mel_to_hertz(mel): """Returns frequency from mel-frequency input. Parameter --------- mel : scalar or ndarray Mel-frequency value or ndarray in Mel Returns ------- freq : scalar or ndarray Frequency value or array in Hz. """ return 700.0 * (10**(mel / 2595.0)) - 7...
def i_to_white(i, normalize=False): """Convert a number between 0.0 and 1.0 to a shade of white. Parameters ---------- i : float A number between 0.0 and 1.0. normalize : bool, optional Normalize the resulting RGB values. Default is to return integer values ranging from 0 to...
def get_highest_isr_exb_pair(con_exb_sites_dic, ids2isrc_dic): """ Given a dictionary of connected exon border site IDs, get pair with highest intron-spanning read count between them. If all have same ISR count, return the first one seen. >>> con_exb_sites_dic = {'id1': 1, 'id2': 1, 'id3': 1, 'id4...
def jaccard_index(tp, rank_query_taxids, rank_truth_taxids): """ Returns the Jaccard index >>> jaccard_index(test_tp, test_rank_query_taxids, test_rank_truth_taxids) 1.0 """ union = len(rank_query_taxids.union(rank_truth_taxids)) if union > 0: return tp / union else: return ...
def _get_param_name(param_name, component_type=None): """OpenMDAO won't let us have a parameter and output of the same name...""" if component_type is not None and component_type not in ('IndepVarComp', 'TestBenchComponent', 'EnumMap'): return param_name return 'param_{}'.format(param_name)
def flatten(lst): """Flattens a list by removing all sublists within it.""" return [item for sublist in lst for item in sublist]
def get_difference(one, two): """Compute the differences between two blocks.""" if len(one) != len(two): raise Exception("blocks are of different dimensions") diffs = [] for y in range(len(one)): line1 = one[y] line2 = two[y] if len(line1) != len(line2): ...
def bubble_sort(array): """ Read more about bubble sort here https://www.geeksforgeeks.org/bubble-sort/ >>> bubble_sort([3,2,1]) [1, 2, 3] """ length = len(array) # length of array for i in range(length - 1): for j in range(length - i - 1): if array[j] > array[j + 1]: ...
def check_helpers(helpers): """ 'helper' must be a comma-separated list of quoted names, e.g. ['First name', 'Second name', ...']. The list may be empty. Do not use 'TBD' or other placeholders. """ # YAML automatically loads list-like strings as lists. return isinstance(helpers, list) and ...
def filter_impossible(children, depth, wanted): """ A simple filter for removing umpossible combinations. """ i = 0 while i < len(children[depth]): child = children[depth][i] if child.count('(') > wanted.count('(') or child.count('h') > wanted.count('h'): del children[depth][i] ...
def ephemeral_profile(repo, token): """Generate a profile that's not saved on disk anywhere. This simply returns a profile dictionary with ``repo`` and ``token`` values. It does not get saved on disk anywhere. Args: repo The Github repo you want to connect to. For instance, ...
def list_same_len(*lists): """ confirm all lists have the same length """ n = len(lists[0]) return all(len(x) == n for x in lists)
def _flatten_nodes(node_info): """ Reformat node data that was formerly nested into one flat array. """ if not node_info: return [] return [node_info[0]] + _flatten_nodes(node_info[1])
def check_high_low(n): """Return True if it is in the range 1-25.""" if n in range(1, 26): return False else: return True
def camelCaseIt(snake_case_string): """ Format a string in camel case """ titleCaseVersion = snake_case_string.title().replace("_", "") camelCaseVersion = titleCaseVersion[0].lower() + titleCaseVersion[1:] return camelCaseVersion
def to_dict(arr: list): """Trasforma il risultato della classificazione in un array di dizionari pronto per essere utilizzato dagli altri script Parameters: array (list): array che deve essere trasformato array[0]: class_number (n01223984) ...
def value_for_dsd_ref(kind, args, kwargs): """Maybe replace a string 'value_for' in *kwargs* with a DSD reference.""" try: dsd = kwargs.pop('dsd') descriptor = getattr(dsd, kind + 's') kwargs['value_for'] = descriptor.get(kwargs['value_for']) except KeyError: pass ...
def boyer(pattern, text): """ Boyer-Moore algorithm """ m = len(pattern) n = len(text) if m > n: return None skip = {} for k in range(256): skip[k] = m for k in range(m - 1): skip[pattern[k]] = m - k - 1 k = m - 1 while k < n: j = m - 1 ...
def to_list(argument): """ Gets and converts the argument to list type if it's not the type of list. Args: argument (str/list): String or list of string. Returns: list: A list of strings. """ if type(argument) is not list: return [argument] ...
def isc_1km_to_5km ( i_sc_1km ) : """ return the 5km grid index cross track of a 1km pixel """ return ( i_sc_1km - 2. ) / 5.
def aggregate_files_per_issue(changes): """Associate the files with their issues. >>> i = list(aggregate_files_per_issue([('FOO-1111', '2018-03-12', ('A', 'B'), (1, 15)), ('FOO-1111', '2018-03-10', ('A', 'C'), (2, 5)), ('FOO-1112', '2018-03-11', ('A', 'D'), (2, 8))]).items()) >>> i.sort() >>> i [('...
def getCreditMultiplier(floorIndex): """ Returns the skill credit multiplier appropriate for a particular floor in a building battle. The floorIndex is 0 for the first floor, up through 4 for the top floor of a five-story building. """ # Currently, this is 1 for the first floor (floor 0), 1.5 f...
def distance1(x1, y1, x2, y2): """Retourner la "Manhattan distance" entre (x1, y1) et (x2, y2).""" return abs(x1 - x2) + abs(y1 - y2)
def robot_turn(direction, instruction_list): """ Turns robot. Returns direction.""" if instruction_list[1] == 0: direction -= 1 elif instruction_list[1] == 1: direction += 1 else: print("And I oop....robot_do_it (2)") direction %= 4 return direction
def dictkeyclean(d): """Convert all keys of the dict `d` to strings. """ new_d = {} for k, v in d.items(): new_d[str(k)] = v return new_d
def read_config(lines): """Read the config into a dictionary""" d = {} current_section = None for i, line in enumerate(lines): line = line.strip() if len(line) == 0 or line.startswith(";"): continue if line.startswith("[") and line.endswith("]"): current_s...
def tranpose_list_of_dicts(list_of_dicts): """ input: [ {key1: val1_0, key2: val2_0, ...}, {key1: val1_1, key2: val2_1, ...}, ] output: { key1: [val1_0, val1_1, ...] key2: [val2_0, val2_1, ...] } """ keys = list_of_dict...
def get_subsidiary_titles(inputs): """ Builds the subsidiary titles string. """ result = "" if inputs is None: return result for title in inputs: if inputs.index(title) == len(inputs)-2: result = result+title+" " elif inputs.index(title) == len(inputs)-1: ...
def harmonic_series(n): """ Return the sum of 1/1 + 1/2 + ... + 1/n """ sum = 0 for i in range(1,n+1): sum += 1.0/i return sum
def dims_to_targetshape(data_dims, batch_size=None, placeholder=False): """Prepends either batch size/None (for placeholders) to a data shape tensor. Args: data_dims: list, indicates shape of the data, ignoring the batch size. For an RGB image this could be [224, 224, 3] for example. batch_size: scal...
def distance_between_sq(x1: float, y1: float, x2: float, y2: float) -> float: """ Returns the squared distance between the two points (x1, y1) and (x2, y2) """ dx = x2 - x1 dy = y2 - y1 return dx**2 + dy**2
def is_odd(num : int) ->bool: """ Checks if a number is odd or not. Parameters: num: the number to be checked Returns: True if number is odd, otherwise False """ if (num%2) != 0: return True else: return False
def isAddress(string): """ Check if a string is an address / consists of hex chars only Arguments: string - the string to check Return: Boolean - True if the address string only contains hex bytes """ string = string.replace("\\x","") if len(string) > 16: return False for char in string: if char.upper()...
def validate_config(config, required_fields): """ Check that the config contains all the required fields. :param config: A config dictionary to check. :type config: dict(str: str) :param required_fields: A list of required fields. :type required_fields: list(str) :return: Whether the config...
def mean(values): """ returns mean value of a list of numbers """ return sum(values) / float(len(values))
def extract_uuid(res_id): """Extracts the UUID part of the resource id.""" return res_id.split('/')[1]
def valid_uuid(uuid): """ matches if a string is a valid uuid.hex :param uuid: :return: """ import re regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) match = regex.match(uuid) return bool(match)
def append_seq_markers(data, seq_begin=True, seq_end=True): """ `data` is a list of sequences. Each sequence is a list of numbers. For example, the following could be an example of data: [[1, 10, 4, 1, 6], [1, 2, 5, 1, 3], [1, 8, 4, 1, 2]] Assume that 0 and 11 are IDs corresponding to ...
def pad_sentence(sentences, sentence, padding_word="<PAD/>"): """ Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. """ sequence_length = max(len(x) for x in sentences) num_padding = sequence_length - len(sentence) new_senten...
def FilterFlag(args, flag): """Returns True if the flag is present in args list. The flag is removed from args if present. """ if flag in args: args.remove(flag) return True return False
def add_array(in_array): """Adds the elements of an array. Use counted repetition, using a start, finish and a step, to sum the elements of an array Args: in_array: array if numbers to be added Returns: sum: the sum of the array """ sum = 0 for i in range(0, len(...
def sigmoid_derivative(y): """ Backward propagation activation function derivative. """ #return y * (1.0 - y) return 1.0 - y * y
def _get_words(row): """function _get_words Args: row: Returns: """ data = [row['code_source'].strip().split(" ")] # print(data[0]) for ele in data[0].copy(): if ele in ['', '-', '+', '=', '*', '/', '==', '<=', '>=', '!=']: data[0].remove(ele) # pr...
def blend(color1, color2, transparency): """Mixes two 24 bit colors considering the transparency of the second color.""" invertedTransparency = 1 - transparency r = int(((color2 >> 16) * invertedTransparency + (color1 >> 16) * transparency) // 1) << 16 g = int(((color2 >> 8 & 0xff) * invertedTransparenc...
def calcMetrics(tp, n_std, n_test): """Calculate precision, recall and f1""" # default precision and recall are set to 1 # because technically an empty test corresponding to an empty standard # should be the correct answer precision = (tp / float(n_test)) if n_test > 0 else 1 recall = (tp / flo...
def rsplit1(s, sep): """The same as s.rsplit(sep, 1), but works in 2.3""" parts = s.split(sep) return sep.join(parts[:-1]), parts[-1]
def remove_inferred(gt_json_list): """Remove all unnecessary records Unnecessary records = ["reset] Arguments: gt_json_list {[list]} -- List of Day2 detection dictionaries Returns: [list] -- List of Day2 detection dictionaries with relevant records """ json_list = [] id_so_...
def tariff_transform(value): """Transform tariff from number to description.""" if value == "1": return "low" return "high"