content
stringlengths
42
6.51k
def swap_score(xs, ys): """Return the number of characters that needs to be substituted to change the characters in the first string into the second string. If the strings not of equal length, we will disregard all "extra" characters in the larger string. This function only considers the leftmost ...
def get_neighborhood_weights_edgesnumber(ns,edge_dict): """ :param ns: this is the candidate community set :param edge_dict: e.g. {node1: {node2: {weight: value1}, {node3: {weight: value2 }}}}, node1 and node2 is connected with edge-weight value1, node1 and node3 is connnected with edge-weight value2 ...
def include_base_causx_tags(tags): """we want to include certain tags no matter what, so add them in here Args: tags (dict): any existing tags Returns: dict: any existing tags, and empty tags for the required tags that aren't present """ tags_dict={"FactorClass":"","Relevance":"","...
def get_array_first(array): """ get array first :param array: :return: """ if array and isinstance(array, list) and len(array) >= 1: return array[0] return None
def vec_abs(a): """ Computes the element-wise absolute value of a vector Parameters ---------- a: list[] A vector of scalar values Returns ------- list[] The absolute vector of a """ # return [abs(a[n]) for n in range(len(a))] return [*map(lambda ai: abs(ai...
def top_two_word(counts): """ Given a list of (word, count, percentage) tuples, return the top two word counts. """ limited_counts = counts[0:2] count_data = [count for (_, count, _) in limited_counts] return count_data
def _calculate_steps(num_examples, batch_size, num_epochs, warmup_proportion=0): """Calculates the number of steps. Args: num_examples: Number of examples in the dataset. batch_size: Batch size. num_epochs: How many times we should go through the dataset. warmup_proportion: Proportion of warmup ste...
def enum_tri(n, t, start_high=None): """ Recursive enumeration of the values that are in the tri-range of 0. """ # resolve start-high for initial conditions: if start_high is None: if t % 2: # odd start_high = True else: start_high = False # trivial case ...
def merge_two_dicts(dict1, dict2): """ Merges two dictionaries into one :param dict1: First dictionary to merge :param dict2: Second dictionary to merge :return: Merged dictionary """ merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict
def int_to_hexstring(data, data_type='H', str_len=8): """ Takes an integer and creates a hex string of the appropriate length Args: data (int): value to hexlify data_type (int): one of the enumerated TAGTYPES str_len (int): number of characters in the resulting string...
def n_max(ops, key_func): """ Return the maximum element of ops according to key_func. :param ops: operations to configure the WaveShaper :type ops: list :param key_func: comparison key :type key_func: str :return: maximum element :rtype: int """ maximum = 0 for i in range(l...
def break_words(stuff): """This function will break up words for us. """ words = stuff.split(' ') return words
def convert_to_dot_notation(class_name): """take a class name from ClassAnalysis and format it for comparison against typical dot package notation eg. Lcm/aptoide/pt/v8engine/OpenGLES20Activity; --> cm.aptoide.pt.v8engine.OpenGLES20Activity Note: I think this is necesssary because the get_activitie...
def custom_format(source, language, class_name, options, md, classes=None, value_id='', **kwargs): """Custom format.""" return '<div lang="%s" class_name="class-%s", option="%s">%s</div>' % (language, class_name, options['opt'], source)
def encode_int(s: int) -> bytes: """Encodes int to little endian bytes Args: s (int): int to encode Returns: bytes: encoded int in little endian by """ return s.to_bytes(4, 'little')
def xgcd(x, y): """Extended GCD Args: x (integer) y (integer) Returns: (gcd, x, y) where gcd is the greatest common divisor of a and b. The numbers x, y are such that gcd = ax + by. """ prev_a = 1 a = 0 prev_b = 0 b = 1 while y != 0: q =...
def increment_name(_shortname): """ Increment the short name by 1. If you get, say, 'woman_detective_unqualified', it returns 'woman_detective_unqualified_1', and then 'woman_detective_unqualified_2', etc. """ last_char = _shortname[-1] if last_char.isdigit(): num = int(last_char) ...
def seqToGenbankLines(seq): """ chunk sequence string into lines each with six parts of 10bp, return as a list >>> seqToGenbankLines("aacacacatggtacacactgactagctagctacgatccagtacgatcgacgtagctatcgatcgatcgatcgactagcta") ['aacacacatg gtacacactg actagctagc tacgatccag tacgatcgac gtagctatcg', 'atcgatcgat cgactagct...
def find_parents(childs): """ finds the parent of each BeautifulSoup-Element given in a list (childs). in case of multiple childs having the same parent, the index of the parent will be returned for each element after the first""" parents = [] for child in childs: b_found = False fo...
def parse_port(arg): """Parse port argument and raise ValueError if invalid""" if not arg: return None arg = int(arg) if arg < 1 or arg > 65535: raise ValueError("invalid port value!") return arg
def edges(tt): """Edges of the fundamental polygon""" n = len(tt) e=[] for i in range(n-1): e += [(i,i+1)] e += [(n-1,0)] return e
def _encode_hmc_values(values): """Encrypts any necessary sensitive values for the HMC entry""" if values is not None: values = values.copy() #Make sure to Encrypt the Password before inserting the database ## del two lines by lixx #if values.get('password') is not None: ...
def milliseconds_to_tc(milliseconds): """converts the given milliseconds to FFMpeg compatible timecode :param milliseconds: :return: """ hours = int(milliseconds / 3600000) residual_minutes = milliseconds - hours * 3600000 minutes = int(residual_minutes / 60000) residual_seconds = resid...
def bytesToSigned24(bytearr): """ converts the last 3 bytes of a 5 byte array to a signed integer """ unsigned=(bytearr[2]<<16)+(bytearr[3]<<8)+bytearr[4] return unsigned-16777216 if bytearr[2]&128 else unsigned
def classname(instance): """ Returns instance class name. Parameters ---------- instance : object Returns ------- str """ return instance.__class__.__name__
def get_search_query_context(name, type, fields=None): """ Create search multi-field query object Params ------ name: str type: str fields: list Returns ------- list Notes ----- Some fields contain same text but are analyzed differently. Making other fields availabl...
def _scan_pattern_for_literal(text, character=None, target=None): """returns the number of repeating <characters>, subtracting the # of '?' characters until <target> is hit""" count = 0 qcount = 0 for c in text: if c == "?": qcount = qcount + 1 if c == target: ret...
def get_alt_sxy(x_sum: float, y_sum: float, xy_sum: float, n: int) -> float: """calculate sxy by given sum values""" return xy_sum - x_sum / n * y_sum - y_sum / n * x_sum + x_sum * y_sum / n
def fragmentate_dictionary(old_dictionary): """This splits dictionary entries like "FW": 0 into "F":0 and "W": 0. Args: old_dictionary (dict): a dictionary containing either hydrophobicity or size scores for amino acids Returns: dict: a less-readable but more computatio...
def median(list_in): """ Calculates the median of the data :param list_in: A list :return: float """ list_in.sort() half = int(len(list_in) / 2) if len(list_in) % 2 != 0: return float(list_in[half]) elif len(list_in) % 2 ==0: value = (list_in[half - 1] + list_in[half...
def solr_escape(text): """ Escape reserved characters for pysolr queries. https://lucene.apache.org/solr/guide/6_6/the-standard-query-parser.html#TheStandardQueryParser-EscapingSpecialCharacters https://docs.mychem.info/en/latest/doc/chem_query_service.html#escaping-reserved-characters """ impor...
def octetsToHex(octets): """ convert a string of octets to a string of hex digits """ result = '' while octets: byte = octets[0] octets = octets[1:] result += "%.2x" % ord(byte) return result
def eratosthenes_sieve(n): """Return primes <= n.""" def add_prime(k): """Add founded prime.""" primes.append(k) pos = k + k while pos <= n: numbers[pos] = 1 pos += k numbers = [0] * (n + 1) primes = [2] for i in range(3, n + 1, 2): i...
def end_with(string, ending): """ Boolean return value if string has the same ending as another string. :param string: the string to be checked. :param ending: the ending string. :return: True if the last characters of string are the same as ending otherwise, False. """ return string.endswit...
def is_irs2(readpatt): """Return True IFF `readpatt` is one of the IRS2 READPATTs. >>> is_irs2("NRSIRS2") True >>> is_irs2("NRSIRS2RAPID") True >>> is_irs2("NRSN32R8") False >>> is_irs2("ALLIRS2") True """ return 'IRS2' in readpatt
def map_age(age): """Map ages to standard buckets.""" try: age = int(age) if age >= 90: return '90+' lower = (age // 10) * 10 upper = age+9 if age % 10 == 0 else ((age + 9) // 10) * 10 - 1 return f'{lower}-{upper}' except: if 'month' in age.lower...
def find_when_start(char=None,list=[]): """ find first element in list that start with a char >>> find_when_start('a',['abc','bcd','cde']) 'abc' >>> find_when_start(char='a',list=['abc','bcd','cde']) 'abc' >>> find_when_start() """ element = None try: for object in list: if char =...
def prefix1bits(b): """ Count number of bits encountered before first 0 """ return 0 if b&1==0 else 1+prefix1bits(b>>1)
def decimal_to_roman(dec): """Convert decimal number to roman numerals. Args: dec (int): Decimal. Returns: str: Return roman numerals. """ to_roman = [('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ...
def get_pipe_dict(d, i): """ given a dictionary d for a given instrument, return the dictionary for the ith pipeline version """ pipe_versions = list(d.keys()) k = pipe_versions[i] mode = list(d[k].keys())[0] return d[k][mode]
def validate_license_model(license_model): """ Validate LicenseModel for DBInstance Property: DBInstance.LicenseModel """ VALID_LICENSE_MODELS = ( "license-included", "bring-your-own-license", "general-public-license", "postgresql-license", ) if license_mode...
def getitem_helper(obj, elem_getter, length, idx): """Helper function to implement a pythonic getitem function. Parameters ---------- obj: object The original object elem_getter : function A simple function that takes index and return a single element. length : int The...
def getFileDialogTitle(msg, title): """ Create nicely-formatted string based on arguments msg and title :param msg: the msg to be displayed :param title: the window title :return: None """ if msg and title: return "%s - %s" % (title, msg) if msg and not title: r...
def merged_value(values1, values2): """ combines values of different devices: (right now since primitive generator takes only one value we use max value) try: #val1={'res': '13.6962k', 'l': '8u', 'w': '500n', 'm': '1'} #val2 = {'res': '13.6962k', 'l': '8u', 'w': '500n', 'm': '1'} #merged_val...
def calculate_total (price, percent): """ Parameters ---------- price : TYPE float percent : TYPE integer Returns ------- New number showing the price + the tip Should return number as a FLOAT """ total = price + price*percent/100 return total
def _create_text_labels(classes, scores, class_names): """ Args: classes (list[int] or None): scores (list[float] or None): class_names (list[str] or None): Returns: list[str] or None """ labels = None if classes is not None and class_names is not None and len(cl...
def find(f, seq): """Return first item in sequence where f(item) == True.""" for item in seq: if f(item): return item
def binsearch(array, val): """ Binary search. The input `array` must be sorted. Binary search of `val` in `array`. Returns `idx` such as `val == array[idx]`, returns `None` otherwise. """ left, right = 0, len(array) while left <= right: mid = (left + right) // 2 if array...
def parse_array(raw_array): """Parse a WMIC array.""" array_strip_brackets = raw_array.replace('{', '').replace('}', '') array_strip_spaces = array_strip_brackets.replace('"', '').replace(' ', '') return array_strip_spaces.split(',')
def calc_zeta_induced_quasisteady(E, x): """ Induced zeta potential (quasi-steady limit) """ zeta_induced_quasisteady = E*x return zeta_induced_quasisteady
def _get_upload_headers(first_byte, file_size, chunk_size): """Prepare the string for the POST request's headers.""" content_range = 'bytes ' + \ str(first_byte) + \ '-' + \ str(first_byte + chunk_size - 1) + \ '/' + \ str(file_size) return {'Content-Range': content...
def indexOf(list, predicate): """ Return the index of the first element that satisfies predicate. If no element is found, return -1 """ for i, x in enumerate(list): if predicate(x): return i return -1
def define_op_expr(left_expr, opr, right_expr): """Returns op expression""" obj = { "left": left_expr, "op": {"name": opr}, "right": right_expr, } return obj
def _get_verticalalignment(angle, location, side, is_vertical, is_flipped_x, is_flipped_y): """Return vertical alignment along the y axis. Parameters ---------- angle : {0, 90, -90} location : {'first', 'last', 'inner', 'outer'} side : {'first', 'last'} is_vertica...
def parse_arxiv_url(url): """ examples is http://arxiv.org/abs/1512.08756v2 we want to extract the raw id and the version """ ix = url.rfind('/') idversion = url[ix+1:] # extract just the id (and the version) parts = idversion.split('v') assert len(parts) == 2, 'error parsing url ' + url return parts...
def Dup(x, **unused_kwargs): """Duplicate (copy) the first element on the stack.""" if isinstance(x, list): return [x[0]] + x if isinstance(x, tuple): return tuple([x[0]] + list(x)) return [x, x]
def pascal(n): """ pascal: Method for computing the row in pascal's triangle that corresponds to the number of bits. This gives us the number of layers of the landscape and the number of mutants per row. Parameters ---------- n : int row of pascal's triangle to compute Returns...
def get_media_edge_comment_string(media): """AB test (Issue 3712) alters the string for media edge, this resoves it""" options = ['edge_media_to_comment', 'edge_media_preview_comment'] for option in options: try: media[option] except KeyError: continue return ...
def check_spg_settings(fs, window, nperseg, noverlap): """Check settings used for calculating spectrogram. Parameters ---------- fs : float Sampling rate, in Hz. window : str or tuple or array_like Desired window to use. See scipy.signal.get_window for a list of available windows. ...
def is_valid_ip_addr(ip_addr): """Validates given string as IPv4 address for given string. Args: ip_addr (str): string to validate as IPv4 address. Returns: bool: True if string is valid IPv4 address, else False. """ ip_addr_split = ip_addr.split('.') if len(ip_addr_split) != ...
def reformat_conversation_context(context): """ Reformat context for conversation related commands (from having used string_to_context_key) to desired output format. parameter: (dict) context The context to reformat returns: The reformatted context """ to_emails = context.g...
def max_common_prefix(a): """ Given a list of strings (or other sliceable sequences), returns the longest common prefix :param a: list-like of strings :return: the smallest common prefix of all strings in a """ if not a: return '' # Note: Try to optimize by using a min_max function t...
def add_res(acc, elem): """ Adds results to the accumulator :param acc: :param elem: :return: """ if not isinstance(elem, list): elem = [elem] if acc is None: acc = [] for x in elem: acc.append(x) return acc
def fibonacci_recursive(n): """Recursive implementation of the fibonacci function time: (2^n) more precisely O((1+sqrt(5))/2)^n) space: O(n) note that one recursive is fully resolved before the other begins """ if n < 2: return n return fibonacci_recursive(n - 1) + fibon...
def key_description(character): """generate a readable description for a key""" ascii_code = ord(character) if ascii_code < 32: return 'Ctrl+{:c}'.format(ord('@') + ascii_code) else: return repr(character)
def isPal(x): """ >>> isPal(['a', 'b']) ['a', 'b'] ['a', 'b'] ['b', 'a'] ['a', 'b'] False >>> isPal(['a', 'b', 'a']) ['a', 'b', 'a'] ['a', 'b', 'a'] ['a', 'b', 'a'] ['a', 'b', 'a'] True """ assert type(x) == list, 'not a list' # assert to make sure x is a list tmp = x[:] ...
def save_eval(val): """Evaluate variables, assuming they are str representations of e.g. int-types. Args: val (any): Value that shall be evaluated. Returns: res (any): Evaluated version of value if built-in `eval` was successful, otherwise `val`. """ try: ...
def route_fitness(r, c, length_fun, **kwargs): """ fitness of a route """ black_list = kwargs.get("black_list") return 1 / length_fun(r, c, black_list)
def get_span_string(run0, run1, runs=None): """Returns string of run0-run1, (or run0 if run0 == run1) """ if runs is not None: string = '' for run in runs: string += f'{run},' return string elif run0 == run1: return f'{run0}' else: return f'{run0}...
def space_name(prefix, index): """Construct name of space from the prefix and its index.""" return "{p}{i}".format(p=prefix, i=index)
def build_default_endpoint_prefixes(records_rest_endpoints): """Build the default_endpoint_prefixes map.""" pid_types = set() guessed = set() endpoint_prefixes = {} for key, endpoint in records_rest_endpoints.items(): pid_type = endpoint['pid_type'] pid_types.add(pid_type) i...
def major_formatter(x, pos): """Return formatted value with 2 decimal places.""" return "[%.2f]" % x
def querify(query): """Return `query` as list""" if ' ' in query: queries = query.split(' ') else: queries = [query] return queries
def dewPointToRH(t_dry, t_dew): """ Calculate relative humidity from dry bulb and dew point (in degrees Celsius) :param float t_dry: Dry bulb temperature (degrees Celsius). :param float t_dew: Dew point temperature (degrees Celsius). :returns: Relative humidity (%) :rtype: float """ ...
def clamp_angle(angle, min_val, max_val): """clamp angle to pi, -pi range""" if angle < -360: angle += 360 if angle > 360: angle -= 360 clamp = max(min(angle, max_val), min_val) return clamp
def _tabulate(rows, headers, spacing=5): """Prepare simple table with spacing based on content""" if len(rows) == 0: return "None\n" assert len(rows[0]) == len(headers) count = len(rows[0]) widths = [0 for _ in range(count)] rows = [headers] + rows for row in rows: for index...
def get_spatial_cell_id(dataset_uuid:str, tile_id:str, mask_index:int)->str: """Takes a dataset uuid, a tile_id within that dataset, and a mask_index number within that tile to prodduce a unique cell ID""" return "-".join([dataset_uuid, tile_id, str(mask_index)])
def check_value_above_filter(value, threshold): """ Returns a boolean to indicate value at or above threshold. :param value: integer from a column "*read count". :param threshold: threshold for the filtering of these read counts. :return: boolean whether integer is equal or greater than threshold. ...
def Rs(ca, cb, n1, n2): """ Refraction coefficient Neglects absorption. Parameters ---------- ca: cos alpha cb: cos beta n1: refective index of medium 1 n2: refrective index of medium 2 Returns ------- Reflection coefficient """ return ((n1*ca - n2*cb)/(n1*ca + ...
def has_wav(wav_names, wav_prefix): """True if WAV file with prefix already exists.""" for wav_name in wav_names: if wav_name.startswith(wav_prefix): return True return False
def get_key(data, keyfields): """Return a tuple of key with the data and keyfields indexes passed""" return tuple([data[i-1] for i in map(int, keyfields.split(','))])
def message_to_str(message): """ Convert message to string """ # body may be bytes if isinstance(message["request"]["body"], bytes): message["request"]["body"] = message["request"]["body"].decode() return message
def intersection(l1, l2): """Return intersection of two lists as a new list:: >>> intersection([1, 2, 3], [2, 3, 4]) [2, 3] >>> intersection([1, 2, 3], [1, 2, 3, 4]) [1, 2, 3] >>> intersection([1, 2, 3], [3, 4]) [3] >>> intersection([1, 2, 3], [4, 5, 6]) ...
def get_dict_item(from_this, get_this): """ get dic object item """ if not from_this: return None item = from_this if isinstance(get_this, str): if get_this in from_this: item = from_this[get_this] else: item = None else: for key in get_this: ...
def topLeftToCenter(pointXY, screenXY, flipY=False): """ Takes a coordinate given in topLeft reference frame and transforms it to center-based coordiantes. Switches from (0,0) as top left to (0,0) as center Parameters ---------- pointXY : tuple The topLeft coordinate which ...
def _must_decode(value): """Copied from pkginfo 1.4.1, _compat module.""" if type(value) is bytes: try: return value.decode('utf-8') except UnicodeDecodeError: return value.decode('latin1') return value
def flatten_list(list_of_lists): """Flatten a nested list of values. Args: list_of_lists (list): A nested list, example: ['a', ['b', 'c']] Returns: flat_list (list): A flattened list, example: ['a', 'b', 'c'] """ flat_list = [] for i in list_of_lists: ...
def cross_product(vec1, vec2): """Cross product of two 2d vectors is a vector perpendicular to both these vectors. Return value is a scalar representing the magnitude and direction(towards positive/negative z-axis) of the cross product. """ (px1, py1), (px2, py2) = vec1, vec2 retur...
def _delElement(an_iterable, idx): """ :param iterable an_iterable: :param int idx: :return list: list without element idx """ a_list = list(an_iterable) new_list = a_list[0:idx] back_list = a_list[(idx+1):] new_list.extend(back_list) return new_list
def IsPng(png_data): """Determines whether a sequence of bytes is a PNG.""" return png_data.startswith('\x89PNG\r\n\x1a\n')
def get_item(dictionary, key): """ Return a key value from a dictionary object. **Parameters** ``dictonary`` Python dictionary object to parse ``key`` Key name tor etrieve from the dictionary """ # Use `get` to return `None` if not found return dictionary.get(key)
def disjoint(L1, L2): """returns non-zero if L1 and L2 have no common elements""" used = dict([(k, None) for k in L1]) for k in L2: if k in used: return 0 return 1
def ids_filter(doc_ids): """Create a filter for documents with the given ids. Parameters ---------- doc_id : |list| of |ObjectIds| The document ids to match. Returns ------- dict A query for documents matching the given `doc_ids`. """ return {'_id': {'$in': doc_ids...
def fix_characters(cadena): """ Replaces unicode characters and encodes the string in utf-8 """ d = { '\xc1':'A', '\xc9':'E', '\xcd':'I', '\xda':'U', '\xdc':'U', '\xd1':'N', '\xc7':'C', '\xed':'i', '\xf3':'o', '\xf1':'n', '\xe7':'c', '\xba':'', '\xb0':'', '\x3a':'', '\xe1':'a', '\xe2':...
def card_average(hand): """ :param hand: list - cards in hand. :return: float - average value of the cards in the hand. """ return sum(hand) / len(hand)
def replace_keys(my_dict, transform_key): """ Filter through our datastructure """ # # The idea here is to transform key values and list items # for key in my_dict.keys(): new_key = transform_key(key) if new_key != key: my_dict[new_key] = my_dict.pop(key) ...
def experiment_key(study_id=None, experiment_id=None, fly_id=None, obj=None): """Exhibit A why duck typing is just shit sometimes""" if obj: return f"{obj.study_id}-{obj.experiment_id}-{obj.fly_id}" else: return f"{study_id}-{experiment_id}-{fly_id}"
def polygonAppendCheck(currentVL, nextVL): """Given two polygon vertex lists, append them if needed. Polygons will always have the last coordinate be the same as the first coordinate. When appending, they may, or may not, have the last coordinate of the first vertex list be the same as the first co...
def jacobi_symbol(n, k): """Compute the Jacobi symbol of n modulo k See http://en.wikipedia.org/wiki/Jacobi_symbol For our application k is always prime, so this is the same as the Legendre symbol.""" assert k > 0 and k & 1, "jacobi symbol is only defined for positive odd k" n %= k t = 0 w...
def leading_spaces_count(line): """ (Used by tab-to-spaces converter code, for example.) """ i, n = 0, len(line) while i < n and line[i] == " ": i += 1 return i