content
stringlengths
42
6.51k
def beautify_bash_oneliner(command, replacements={}): """Makes a one-line bash command more immediate by adding indentation. It also can replace tags with a specific string""" cmd_lines = [] jumpit = False nl = "" for c in command: if c != ";": nl += c elif c == ";" and not jumpit: cmd_lines.append(nl) nl = "" if c in ["(", '"', "'"]: jumpit = True elif c in [")", "'", '"'] and jumpit: jumpit = False if nl.strip(): cmd_lines.append(nl) new_command = "" ntabs = 0 for cmd_line in cmd_lines: new_line = "\t"*ntabs fields = cmd_line.split() for fi, f in enumerate(fields): if f in replacements: new_line += replacements[f] + " " elif f in ["do", "then"]: new_line += "\n" + "\t"*ntabs + f ntabs += 1 if fi != len(fields)-1: new_line += "\n" + "\t"*ntabs elif f in ["done", "fi"]: ntabs -= 1 new_line += "\n" + "\t"*ntabs + f + " " else: new_line += f + " " if new_line.strip(): new_command += new_line[:-1] new_command += '\n' return new_command
def _index_bam_cmd(i_bam_fn, nproc=1): """Index *.bam and create *.bam.bai""" return 'samtools index %s -@ %s' % (i_bam_fn, nproc)
def get_api_url(repo_url): """Return the GitHub API URL for the respository.""" api_url = None # If the remote url is set for SSH keys if repo_url[:3] == "git": api_url = ("https://api.github.com/repos/" + repo_url[repo_url.index(":") + 1: -3]) # If the remote url is set for http/https elif repo_url[:4] == "http": api_url = ("https://api.github.com/repos/" + repo_url[repo_url.index(".com/") + 5:-4]) return api_url
def data_merge(a, b): """ Merges b into a and return merged result. see http://stackoverflow.com/a/15836901 NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen. """ if b is None: return a key = None try: #if a is None or isinstance(a, str) or isinstance(a, unicode) or #isinstance(a, int) or isinstance(a, long) or isinstance(a, float): if a is None or isinstance(a, (str, int, float)): # border case for first run or if a is a primitive a = b elif isinstance(a, list): # lists can be only appended if isinstance(b, list): # merge lists for c in b: if not c in a: a.append(c) elif not b in a: # append to list a.append(b) elif isinstance(a, dict): # dicts must be merged if isinstance(b, dict): for key in b: if key in a: a[key] = data_merge(a[key], b[key]) else: a[key] = b[key] else: raise Exception('Cannot merge non-dict "%s" into dict "%s"' %\ (b, a)) else: raise Exception('NOT IMPLEMENTED "%s" into "%s"' % (b, a)) except TypeError as e: raise Exception( 'TypeError "%s" in key "%s" when merging "%s" into "%s"' %\ (e, key, b, a)) from e return a
def filter_list_of_dictionary_submission(submission_list, min_comments): """filters the list of submission dictionaries to only include submissions with more than min_comments comments""" filtered_submission_list = [] # filter submission_list for submissions with > min_comments # comments for submission_dictionary in submission_list: if submission_dictionary['num_comments'] >= min_comments: filtered_submission_list.append(submission_dictionary) return filtered_submission_list
def splitter(s, split_list): """ Splits string into smaller substring according to a list. """ # Note: This function won't work correctly if there exists splittable substrings of other splittable strings # An example would be if 'banana' was a split string and 'nana' also was one. # However there is no practical example where this is the case, ie. the function works for all current cases. # (Since most cases are latex this won't really happen as all of latex functions start with \) # for example 'or' is a substring that would occur in a lot of places, but '\or' won't. # The people making latex probably had this in mind when designing their language. split_dict = {} split_indexes = [] new_list = [] for split in split_list: for i in range(len(s)): if split != '.' and s.startswith(split, i): split_indexes.append(i) split_dict[i] = split #START ADDED BY SIEBE to avoid parentheses when a period (.) is used, or when a float is used. for i in range(len(s)-1): if (s[i] == '.' and s[i+1] not in "0123456789"): # period is used, not in a float split_indexes.append(i) split_dict[i] = '.' if (s[len(s)-1] == '.'): # period is used at end of sentence split_indexes.append(len(s)-1) split_dict[len(s)-1] = '.' #END ADDED BY SIEBE start = 0 split_indexes.sort() for split_index in split_indexes: new_list.append(s[start:split_index]) new_list.append(split_dict[split_index]) start = split_index + len(split_dict[split_index]) new_list.append(s[start:]) # new_list = filter(None, new_list) return new_list
def policy_with_role(policies, role): """Returns the policy with the given name.""" matches = [x for x in policies if x['role'] == role] if matches: return matches[0] else: raise Exception('No policy matching role {}'.format(role))
def LeakyRELU(x, alpha=0.3): """Leaky Rectified Linear Unit. It allows a small gradient when the unit is not active. `f(x) = alpha * x for x < 0, f(x) = x for x >= 0` Args: x (list or np.array): Input list or array. alpha (float): Scale factor. Returns: np.array: The LeakyRELU of the array . Examples: >>> x = np.array([[1,1,-3],[0.5,-1,1]]) >>> LeakyRELU(x) array([[ 1. , 1. , -0.9], [ 0.5, -0.3, 1. ]]) """ return (x >= 0) * x + (x < 0) * alpha * x
def incrementSparseVector(v1, scale, v2): """ Given two sparse vectors |v1| and |v2|, perform v1 += scale * v2. This function will be useful later for linear classifiers. """ # BEGIN_YOUR_CODE (our solution is 2 lines of code, but don't worry if you deviate from this) for k, val in v2.items(): v2[k] *= scale v_tmp = v1.copy() for k in v1.keys(): for k2 in v2.keys(): if k == k2: v_tmp[k] += v2[k2] else: v_tmp[k2] = v2[k2] return v_tmp # END_YOUR_CODE
def step_learning_rate(base_lr, epoch, step_epoch, multiplier=0.1): """Sets the learning rate to the base LR decayed by 10 every step epochs""" lr = base_lr * (multiplier ** (epoch // step_epoch)) return lr
def get_group_num(group_size, num_participants, additional_group=True): """Returns the number of groups required. Args: group_size: The size each group should have. num_participants: The total number of participants (teams). additional_group: True if an additional group should be created for remaining teams. Returns: The number of groups required if groups should be of size group_size. If additional_group is True it is assumed that all remaining teams are packe into an additional group. Otherwise it is assumed that all remaning teams are inserted into other groups (those leading to groups of size > group_size). """ res = num_participants // group_size if additional_group and num_participants % group_size != 0: res += 1 return res
def getObjID(objName, objList): """ Returns an object's ID (int) given its 'objName' (str) and a reference 'objList' (list) Format of 'objList' is [['name_1',id_1], ['name_2',id_2], ...] """ for i in range(0, len(objList)): if objList[i][0] == objName: return objList[i][1]
def parse_artist(data): """parse artist data in to message""" return "%s - %s followers" % (data["name"], data["followers"]["total"])
def _signature_get_bound_param(spec): """ Private helper to get first parameter name from a __text_signature__ of a builtin method, which should be in the following format: '($param1, ...)'. Assumptions are that the first argument won't have a default value or an annotation. """ assert spec.startswith('($') pos = spec.find(',') if pos == -1: pos = spec.find(')') cpos = spec.find(':') assert cpos == -1 or cpos > pos cpos = spec.find('=') assert cpos == -1 or cpos > pos return spec[2:pos]
def hasCapitalLetters(passW): """ checks if password has Capital Letters """ count = 0 for i in passW: if(i.isupper()): count+=1 return count
def find_abs_min(arr): """ Finds minimum value of the array where each element is absoluted :param arr: the input array :return: minimum value and its first index """ min_val, min_index = (abs(arr[0]), 0) for i in range(len(arr)): if min_val > abs(arr[i]): min_val, min_index = (abs(arr[i]), i) return min_val, min_index
def int_validator(inp, ifallowed): """ Test whether only (positive) integers are being keyed into a widget. Call signature: %S %P """ if len(ifallowed) > 10: return False try: return int(inp) >= 0 except ValueError: return False return True
def is_almost_zero( x: float, num_of_exponents: int = 6) -> bool: """Checks if a num is almost 0 taking into account tiny mistake by python. Sometimes in adding, division and etc. some mistakes are introduced by python. This funcions checks whether a number is 0 taking into account with a small desired window of margin. The larger num_of_exponents is, less margin for error. Args: x: The number that we want to be tested. num_of_exponents: The number of n for error of 1e-n. Returns: If the given number is almost zero or not. Raises: ValueError: When num of exponents were given negative. """ if num_of_exponents < 0: raise ValueError('Number of exponents should be positive. ' 'It was {}'.format(num_of_exponents)) window_range = 10 ** -num_of_exponents return (x >= -window_range) and (x <= window_range)
def int_to_bytes(value: int) -> bytes: """ Convert an integer value to bytes in big endian representation """ return value.to_bytes((value.bit_length() + 7) // 8, byteorder="big")
def template_subst(template, subs, delims=('<', '>')): """ Perform substitution of content into tagged string. For substitutions into template input files for external computational packages, no checks for valid syntax are performed. Each key in `subs` corresponds to a delimited substitution tag to be replaced in `template` by the entire text of the value of that key. For example, the dict ``{"ABC": "text"}`` would convert ``The <ABC> is working`` to ``The text is working``, using the default delimiters of '<' and '>'. Substitutions are performed in iteration order from `subs`; recursive substitution as the tag parsing proceeds is thus feasible if an :class:`~collections.OrderedDict` is used and substitution key/value pairs are added in the proper order. Start and end delimiters for the tags are modified by `delims`. For example, to substitute a tag of the form **{\|TAG\|}**, the tuple ``("{|","|}")`` should be passed to `subs_delims`. Any elements in `delims` past the second are ignored. No checking is performed for whether the delimiters are "sensible" or not. Parameters ---------- template |str| -- Template containing tags delimited by `subs_delims`, with tag names and substitution contents provided in `subs` subs |dict| of |str| -- Each item's key and value are the tag name and corresponding content to be substituted into the provided template. delims iterable of |str| -- Iterable containing the 'open' and 'close' strings used to mark tags in the template, which are drawn from elements zero and one, respectively. Any elements beyond these are ignored. Returns ------- subst_text |str| -- String generated from the parsed template, with all tag substitutions performed. """ # Store the template into the working variable subst_text = template # Iterate over subs and perform the .replace() calls for (k,v) in subs.items(): subst_text = subst_text.replace( delims[0] + k + delims[1], v) ## next tup # Return the result return subst_text
def get_unit(scale): """ Convert scale term to unit label """ scale2unit = { 1e-9: 'nm', 1e-6: u'\N{MICRO SIGN}m', #or hex id (lookup): u'\u00B5' 1e-3: 'mm', 0.01: 'cm', 0.1:'dm', 1:'m', 1000:'km', # time 8.6400e4:'day', 3.1536e7:'yr', 3.1536e10:'ka', 3.1536e13:'Ma', #Pressure 1e9: 'GPa', 1e6: 'MPa', } return scale2unit[scale]
def cast_type(cls, val, default): """Convert val to cls or return default.""" try: val = cls(val) except Exception: val = default return val
def calc_y(f, t): """Calc y coordinate by params. :param f: the interp params :type f: dict :param t: the accumulation of steps :type t: int :return: y coordinate :rtype: float """ return f['a_y'] + f['b_y'] * t + f['c_y'] * t * t + f['d_y'] * t * t * t
def strip_ns(ref): """ strip the namespace prefix from ``ref`` :param str ref: one word, colon delimited string, such as *nx:groupGroup* :returns str: the part to the right of the last colon """ return ref.split(":")[-1]
def function_namespace(f): """ Attempts to returns unique namespace for function """ if hasattr(f, 'im_func'): return '%s.%s.%s' % (f.__module__, f.im_class.__name__, f.__name__) else: return '%s.%s' % (f.__module__, f.__name__)
def configureXRayAccumulators(xrts, charAccum=True, charFluorAccum=False, bremFluorAccum=False, printRes=False): """configureXRayAccumulators(xrts, charAccum = True, charFluorAccum = False, bremFluorAccum = False, printRes=False) Configures the x-ray accumulators for characteristic and both bremsstrahlung and characteristic secondary fluorescences. / If printRes=True then the results are also displayed in the command window""" res = { 'Transitions' : xrts } res['Characteristic Accumulator'] = charAccum res['Char Fluor Accumulator'] = charFluorAccum res['Brem Fluor Accumulator'] = bremFluorAccum res['Print Accumulators'] = printRes return res
def _is_qualified_name(value): """Tests if the given value looks like a schema-qualified name.""" return isinstance(value, list) and len(value) == 2 and all(isinstance(item, str) for item in value)
def js_rename(jscode, cur_name, new_name): """ Rename a function or class in a JavaScript code string. Parameters: jscode (str): the JavaScript source code cur_name (str): the current name new_name (str): the name to replace the current name with Returns: jscode (str): the modified JavaScript source code """ jscode = jscode.replace('%s = function' % cur_name, '%s = function' % (new_name), 1) jscode = jscode.replace('%s.prototype' % cur_name, '%s.prototype' % new_name) jscode = jscode.replace('_class_name = "%s"' % cur_name, '_class_name = "%s"' % new_name) if '.' in new_name: jscode = jscode.replace('var %s;\n' % cur_name, '', 1) else: jscode = jscode.replace('var %s;\n' % cur_name, 'var %s;\n' % new_name, 1) return jscode
def kron_delta(a:float, b:float) -> int: """Cannonical Kronecker Delta function. Returns 1 if inputs are equal returns 0 otherwise. Args: (:obj:`float`): First input argument (:obj:`float`): Second input argument Returns: (:obj:`int`) Kronecker delta result {0, 1} """ if a == b: return 1 else: return 0
def _get_ngrams(n, text): """Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(text[i:i + n])) return ngram_set
def ordered(obj): """Sort json dicts and lists within.""" if isinstance(obj, dict): return sorted((k, ordered(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(ordered(x) for x in obj) else: return obj
def _exclude(term): """ Returns a query item excluding messages that match the given query term. Args: term (str): The query term to be excluded. Returns: The query string. """ return f"-{term}"
def as_signed(value, bits): """Converts an unsigned integer to a signed integer.""" s = 32 - bits mask = (1 << s) - 1 return (value & mask) - (value & (mask << s))
def marker_delay(session, Type='Real64', RepCap='', AttrID=1150061, buffsize=0, action=['Get', '']): """[Marker Delay] """ return session, Type, RepCap, AttrID, buffsize, action
def deep_update_dict(dct1, dct2, delete_entries=False): """ Updates the value from a given recursive dictionary with those from a second one. """ for key, value in dct2.items(): if delete_entries and value == "delete" and key in dct1: del dct1["key"] elif key.startswith("_"): dct1[key] = value elif isinstance(value, dict): if key in dct1 and isinstance(dct1[key], dict): deep_update_dict(dct1[key], value) else: dct1[key] = value else: dct1[key] = value return dct1
def addition(a, b=10): # <-- Don't forget to fill out the function arguments! """ Simple function to become familiarized with function structure, paramaters, and return statements. This function will sum to numbers together. Parameters: a (any int or float number): A number to be summed b (any int or float number): A second number to be summed, with a default value of 10 Returns: (float or int): <a> added to <b> """ c = a + b return c
def boolToYes(b): """Convert a Boolean input into 'yes' or 'no' Args: b (bool): The Boolean value to be converted Returns: str: 'yes' if b is True, and 'no' otherwise. """ if b: return "yes" else: return "no"
def as_unicode(b): """ Convert a byte string to a unicode string :param b: byte string :return: unicode string """ try: b = b.decode() except (AttributeError, UnicodeDecodeError): pass return b
def matrix_to_string(matrix, row_headers=None, col_headers=None, fmtfun=lambda x: str(int(x))): """Takes a 2D matrix (as nested list) and returns a string. """ ret = [] if col_headers: ret.append('\t' if row_headers else '' + '\t'.join(col_headers)) if row_headers: ret += [rh + '\t' + '\t'.join(fmtfun(f) for f in row) for rh, row in zip(row_headers, matrix)] else: ret += ['\t'.join(fmtfun(f) for f in row) for row in matrix] return '\n'.join(ret)
def group_type(type_string): """ Surround a type with parentheses as needed. """ return ( '(' + type_string + ')' if '|' in type_string else type_string )
def __one_both_open(x, y, c = None, l = None): """convert coordinates to zero-based, both strand, open/closed coordinates. Parameters are from, to, is_positive_strand, length of contig. """ return x - 1, y - 1
def _aisc_table(metric, version): """ Returns the name of the AISC table matching the criteria. Parameters ---------- metric : bool If True, searches for the name in the metric shape database. Otherwise, searches for the name in the imperial shape database. version : {'15.0'} The version of the shape database to query. If None, the latest version will be used. """ if version is None: # Use the latest version version = '15.0' # Return the name of the version table if version == '15.0': if metric: return 'aisc_metric_15_0' else: return 'aisc_imperial_15_0' else: raise ValueError('Version {!r} not found.'.format(version))
def form_to_dict(urlencoded: str): """Decode a form of the structure foo=bar&baz=qux&zap=zazzle""" return {obj.split('=')[0]: obj.split('=')[1] for obj in urlencoded.split('&')}
def parallelz(*args): """ parallelz Function: This function is designed to generate the total parallel impedance of a set (tuple) of impedances specified as real or complex values. Parameters ---------- Z: tuple of complex The tupled input set of impedances, may be a tuple of any size greater than 2. May be real, complex, or a combination of the two. Returns ------- Zp: complex The calculated parallel impedance of the input tuple. """ # Gather length (number of elements in tuple) L = len(args) if L==1: Z = args[0] # Only One Tuple Provided try: L = len(Z) if(L==1): Zp = Z[0] # Only one impedance, burried in tuple else: # Inversely add the first two elements in tuple Zp = (1/Z[0]+1/Z[1])**(-1) # If there are more than two elements, add them all inversely if(L > 2): for i in range(2,L): Zp = (1/Zp+1/Z[i])**(-1) except: Zp = Z # Only one impedance else: Z = args # Set of Args acts as Tuple # Inversely add the first two elements in tuple Zp = (1/Z[0]+1/Z[1])**(-1) # If there are more than two elements, add them all inversely if(L > 2): for i in range(2,L): Zp = (1/Zp+1/Z[i])**(-1) return(Zp)
def get_size(lx, ly): """ Gets columns with maximum and minimum length. Args: lx (:obj:`float`): X-axis length. ly (:obj:`float`): Y-axis length. Returns: Column indexes with maximum and minimum length, respectively. """ if lx > ly: max_size = 1 min_size = 2 else: max_size = 2 min_size = 1 return max_size, min_size
def linkify(link_template, item): """Formats a strings into a URL using string replacement Paramters --------- link_template : str The template for the URL. item : list or tuple of str The strings that will be inserted into the template """ return link_template.format(*item)
def search_req(req_id, ni_url, http_host, http_index, form_params, file_name, tempdir): """ @brief Perform a NetInf 'search' on the http_host using the form_params. @param req_id integer sequence number of message containing request @param ni_url None for earch requests @param http_host string HTTP host name to be accessed (FQDN or IP address with optional port number) @param http_index integer index of host name being processed within request @param form_params dictionary of paramter values to pass to HTTP @param file_name string file name of content to be published or None @param tempdir string ditrectory where to place retrieved response if any @return 5-tuple with: boolean - True if succeeds, False if fails string req_id as supplied as parameter integer http_index as supplied as parameter string actual response or None is no response etc dictionary returned JSON metadata if any, decoded Assume that ni_url has a valid ni URI Assume that tempdir provides a directory path into which file can be written """ return(False, req_id, http_index, None, None)
def angular_escapes(value): """Provide a basic filter to allow angular template content for Angular. Djangos 'escapejs' is too aggressive and inserts unicode. It provide a basic filter to allow angular template content to be used within javascript strings. Args: value: a string Returns: string with escaped values """ return value \ .replace('\\', '\\\\') \ .replace('"', '\\"') \ .replace("'", "\\'") \ .replace("\n", "\\n") \ .replace("\r", "\\r")
def move(pos, mov): """Change a position (pos) by a movement (mov). Both must be (x,y) tuples""" return (pos[0]+mov[0], pos[1]+mov[1])
def is_pon(item): """ :param item: array of tile 34 indices :return: boolean """ if len(item) != 3: return False return item[0] == item[1] == item[2]
def enabled(start, idx, local_list, rule_list, conf_symbol, trans_symbol): """ Returns SMT constrains that relate a configuration and a transition applied to it """ result = "" for i in range(start, idx): for j in local_list: rls = [r for r in rule_list if r["from"] == j] if len(rls) == 0: result += "(= 0 " + conf_symbol + str(i) + "_" + str(j) + ")\n" elif len(rls) == 1: result += "(= " + trans_symbol + str(i) + "_" + str(rls[0]["idx"]) + " " + conf_symbol + str(i) + "_" + str(j) + ")\n" else: rsum = "(+" for k in range(len(rls)): rsum += " " + trans_symbol + str(i) + "_" + str(rls[k]["idx"]) rsum += ")" result += "(= " + rsum + " " + conf_symbol + str(i) + "_" + str(j) + ")\n" result += "\n" return result
def tensor_diag(n: int, fr: int, to: int, w: float): """Construct a tensor product from diagonal matrices.""" def tensor_product(w1: float, w2: float, diag): return [j for i in zip([x * w1 for x in diag], [x * w2 for x in diag]) for j in i] diag = [w, -w] if (0 == fr or 0 == to) else [1, 1] for i in range(1, n): if i == fr or i == to: diag = tensor_product(w, -w, diag) else: diag = tensor_product(1, 1, diag) return diag
def look_up_data(input_string, logical_zero, logical_one): """Looks up the input data to determine if the string is a logical one, logical zero, or outside the code base. Parameters ---------- input_string : str data for analysis logical_zero : list list of strings representing a logical zero logical_one : str list of strings representing a logical one Returns ------- output_string : str result of look-up""" if input_string in logical_zero: output_string = '0' elif input_string in logical_one: output_string = '1' else: output_string = 'E' return(output_string)
def squelch(prop_call, default=None, exceptions=(ValueError,)): """ Utility function that wraps a call (likely a lambda function?) to return a default on specified exceptions """ if not exceptions: return prop_call() try: return prop_call() except exceptions: return default
def sum_square_difference(n: int) -> int: """ Calculates following formula: (1 + 2 + ... + n)^2 - (1^2 + ... + n^2) """ return sum(range(1, n+1)) ** 2 - sum(x ** 2 for x in range(1, n+1))
def invert_rule_hierarchy(rule_hierarchy): """Get inverted rule hierarchy (swapped lhs and rhs).""" new_rule_hierarchy = { "rules": {}, "rule_homomorphisms": {} } for graph, rule in rule_hierarchy["rules"].items(): new_rule_hierarchy["rules"][graph] = rule.get_inverted_rule() for (source, target), (lhs_h, p_h, rhs_h) in rule_hierarchy[ "rule_homomorphisms"].items(): new_rule_hierarchy["rule_homomorphisms"][(source, target)] = ( rhs_h, p_h, lhs_h ) return new_rule_hierarchy
def _attr_get_(obj, attr): """Returns an attribute's value, or None (no error) if undefined. Analagous to .get() for dictionaries. Useful when checking for value of options that may not have been defined on a given method.""" try: return getattr(obj, attr) except AttributeError: return None
def has_equal_block(ciphertext, block_length): """Checks if the given ciphertext contains two consecutive equal blocks""" for i in range(0, len(ciphertext) - 1, block_length): if ciphertext[i:i+block_length] == ciphertext[i+block_length:i+2*block_length]: return True return False
def partial_param_bit_shift(property_key: int) -> int: """Get the number of bits to shift the value for a given property key.""" # We can get the binary representation of the property key, reverse it, # and find the first 1 return bin(property_key)[::-1].index("1")
def project_coordinates(coordinates, projection, **kwargs): """ Apply projection to given coordinates Allows to apply projections to any number of coordinates, assuming that the first ones are ``longitude`` and ``latitude``. Examples -------- >>> # Define a custom projection function >>> def projection(lon, lat, inverse=False): ... "Simple projection of geographic coordinates" ... radius = 1000 ... if inverse: ... return (lon / radius, lat / radius) ... return (lon * radius, lat * radius) >>> # Apply the projection to a set of coordinates containing: >>> # longitude, latitude and height >>> coordinates = (1., -2., 3.) >>> project_coordinates(coordinates, projection) (1000.0, -2000.0, 3.0) >>> # Apply the inverse projection >>> coordinates = (-500.0, 1500.0, -19.0) >>> project_coordinates(coordinates, projection, inverse=True) (-0.5, 1.5, -19.0) """ proj_coordinates = projection(*coordinates[:2], **kwargs) if len(coordinates) > 2: proj_coordinates += tuple(coordinates[2:]) return proj_coordinates
def get_backends_url(config): """Return the URL for a backend.""" hub = config.get('hub', None) group = config.get('group', None) project = config.get('project', None) if hub and group and project: return '/Network/{}/Groups/{}/Projects/{}/devices/v/1'.format(hub, group, project) return '/Backends/v/1'
def countparens(text): """ proper nested parens counting """ currcount = 0 for i in text: if i == "(": currcount += 1 elif i == ")": currcount -= 1 if currcount < 0: return False return currcount == 0
def nCWRk(n, r): """Returns nCk(n+r-1, n-1) optimized for large n and small r.""" val = 1 for i in range(1, r+1): val *= n + r - i val //= i return val
def ymd_to_date(year, month, day): """ Given year, month, day (or hour, minute, second) values, returns a variable in YYYYMMDD (or HHMMSS) format. Parameters ---------- year, month, day: int Bits corresponding to year (or hour), month (or minute), and day (or second) values Returns ------- str containing the date components """ return str(year) + str(month) + str(day)
def cleanUnicodeFractions(s): """ Replace unicode fractions with ascii representation, preceded by a space. "1\x215e" => "1 7/8" """ fractions = { u'\x215b': '1/8', u'\x215c': '3/8', u'\x215d': '5/8', u'\x215e': '7/8', u'\x2159': '1/6', u'\x215a': '5/6', u'\x2155': '1/5', u'\x2156': '2/5', u'\x2157': '3/5', u'\x2158': '4/5', u'\xbc': ' 1/4', u'\xbe': '3/4', u'\x2153': '1/3', u'\x2154': '2/3', u'\xbd': '1/2', } for f_unicode, f_ascii in fractions.items(): s = s.replace(f_unicode, ' ' + f_ascii) return s
def domain(author): """Any text. Finds the first string that looks like an email address, and extracts just the domain component. Example: ``User <user@example.com>`` becomes ``example.com``. """ f = author.find(b'@') if f == -1: return b'' author = author[f + 1 :] f = author.find(b'>') if f >= 0: author = author[:f] return author
def _process_get_set_NSCProperty(code, reply): """Process reply for functions zGetNSCProperty and zSETNSCProperty""" rs = reply.rstrip() if rs == 'BAD COMMAND': nscPropData = -1 else: if code in (0,1,4,5,6,11,12,14,18,19,27,28,84,86,92,117,123): nscPropData = str(rs) elif code in (2,3,7,9,13,15,16,17,20,29,81,91,101,102,110,111,113, 121,141,142,151,152,153161,162,171,172,173): nscPropData = int(float(rs)) else: nscPropData = float(rs) return nscPropData
def sequence_word_index(sequence, word_index_dict, pad_value=0): """Sequence word transfer to sequence index. Args: sequence: pd.Series or np.array or List of lists, sample sequence. word_index_dict: dict, {word: index}. pad_value: fillna value, if word not in word_index_dict, fillna it. Returns: List of lists, sequence word transfer to sequence index list. """ if isinstance(sequence[0], str): return [word_index_dict.get(j, pad_value) for j in sequence] return [[word_index_dict.get(j, pad_value) for j in i] for i in sequence]
def _BreadthFirstSearch(to_visit, children, visited_key=lambda x: x): """Runs breadth first search starting from the nodes in |to_visit| Args: to_visit: the starting nodes children: a function which takes a node and returns the nodes adjacent to it visited_key: a function for deduplicating node visits. Defaults to the identity function (lambda x: x) Returns: A list of nodes which are reachable from any node in |to_visit| by calling |children| any number of times. """ to_visit = list(to_visit) seen = set(visited_key(x) for x in to_visit) for node in to_visit: for child in children(node): key = visited_key(child) if key not in seen: seen.add(key) to_visit.append(child) return to_visit
def linear_search(list, target): """ Returns the index position of the target if found, else returns None """ for i in range(0, len(list)): if list[i] == target: return i return None
def _FindAndRemoveArgWithValue(command_line, argname): """Given a command line as a list, remove and return the value of an option that takes a value as a separate entry. Modifies |command_line| in place. """ if argname not in command_line: return '' location = command_line.index(argname) value = command_line[location + 1] command_line[location:location + 2] = [] return value
def errors(name=None, err_msg=None, err_list=None): """ This function will return a Dialog errors dictionary that can be returned to Slack, and as a result the User will see error notifications on the dialog they are working in. The caller can use this function in one of two ways: (1) "single error message", provide BOTH the `name` and `err_msg` value (2) "multiple errors, provide the `err_list` Parameters ---------- name : str Identifies the Dialog element in the dialog. err_msg : The error message the User will see. err_list : list[tuple] A list of (name,err-msg) Returns ------- dict """ if name and err_msg: return dict(errors=[dict(name=name, error=err_msg)]) elif err_list: return dict(errors=[ dict(name=name, error=errmsg) for name, errmsg in err_list ]) else: RuntimeError('Missing name+message or err_list')
def is_on(S, j): """ Returns 1 if and only if the `j`-th item of the set `S` is on. Examples ======== Check if the 3-th and then 2-nd item of the set is on: >>> S = 0b101010 >>> is_on(S, 3), is_on(S, 2) (1, 0) """ return (S & (1 << j)) >> j
def coverageTruncatedToString(coverage) : """Converts the coverage percentage to a formatted string. Returns: coveragePercentageAsString, coverageTruncatedToOneDecimalPlace Keyword arguments: coverage - The coverage percentage. """ # Truncate the 2nd decimal place, rather than rounding # to avoid considering a non-passing percentage as # passing (e.g., if user considers 70% as passing threshold, # then 69.99999...% is technically not passing). coverage = int(1000 * coverage) / 10 if coverage - int(coverage) == 0 : covStr = "{0:d}%".format(int(coverage)) else : covStr = "{0:.1f}%".format(coverage) return covStr, coverage
def convert_ecalendar_crse(course_code): """McGill eCalendar uses a different course code format, so valid codes COMP-206D1-001 become comp-206d5""" course_code = str(course_code) course_code = course_code.lower() code_parts = course_code.split("-") if code_parts[0].isalpha() and code_parts[1].isalnum(): return code_parts[0]+"-"+code_parts[1] # gives formatted course code else: raise ValueError('Must provide valid input for course code, (ie. comp-206, cCoM-206d5, ECON-208-100)')
def findlast(text, target): """ looks for the last Occurrence of target """ last=-1 here=text.find(target) if here>-1: last=here there=0 while there>-1: there=text[last+1:].find(target) if there>-1: last+=there+1 return last
def is_number(string): """ check whether a string can be converted to a number Args: string: value as a string, could be a number Returns: True/False for whether the value can be converted to a number """ try: number = float(string) except ValueError: return False return True
def _add_allele(gene_string, allele = "*01"): """ Example ------- >>> _add_allele('TRBV12-2') 'TRBV12-2*01' """ return f"{gene_string}{allele}"
def format_pkg_list(config_dict): """ Takes the YAML configuration information and parses/formats the R package list for use with an "Rscript -e **" call. :param config_dict: The configuration dictionary created with the YAML file. """ config_dict = {k: v for k, v in config_dict.items() if "PKG_LIST" in k} fmtd_list = dict() for list_name in config_dict: pkg_dict = config_dict[list_name] pkg_list_count = len(pkg_dict) - 1 pkg_list_string = "" for k, v in enumerate(pkg_dict): if k == pkg_list_count: pkg_list_string = "%s%s=\"%s\"" % (pkg_list_string, v, pkg_dict[v]) else: sep = ", " pkg_list_string = "%s%s=\"%s\"%s" % (pkg_list_string, v, pkg_dict[v], sep) pkg_list_string = "list(%s)" % pkg_list_string fmtd_list[list_name] = pkg_list_string return fmtd_list
def is_elf(filename): """ Check that a file is in the elf format """ with open(filename, "rb") as fp: data = fp.read(4) return data == "\x7fELF"
def clean_name(name: str): """Clean name by stripping whitespace and newline.""" return name.splitlines()[0].strip()
def format_pair_list(pair_list, **kwargs): """ Given a list of 2-tuples of str, calls format with `kwargs` for each item in the 2-tuples and return the formatted list of 2-tuples. Parameters ---------- pair_list: list of 2-tuples of str kwargs: keyword arguments Arguments for the format function of each string in the 2-tuples. Returns ------- formatted_pair_list: list of 2-tuples of str """ return [(s[0].format(**kwargs), s[1].format(**kwargs)) for s in pair_list]
def ValidateChecksums(reference_checksums, new_checksums, allow_missing_projects=False): """Validates that reference_checksums and new_checksums match. Args: reference_checksums: a dict of reference checksums, mapping from a project name to a project checksum. new_checksums: a dict of checksums to be checked, mapping from a project name to a project checksum. allow_missing_projects: When True, reference_checksums may contain more projects than new_checksums. Projects missing from new_checksums are ignored. When False, new_checksums and reference_checksums must contain checksums for the same set of projects. If there is a project in reference_checksums, missing from new_checksums, ValidateChecksums will return False. Returns: True, if checksums match with regards to allow_missing_projects flag value. False, otherwise. """ if not allow_missing_projects: if len(new_checksums) != len(reference_checksums): return False for proj, checksum in new_checksums.items(): # We never computed a checksum for this project. if proj not in reference_checksums: return False # Checksum did not match. if reference_checksums[proj] != checksum: return False return True
def is_number(input_string): """ if input_string includes number only, return corresponding number, otherwise return input_string """ try: return float(input_string) except ValueError: pass try: import unicodedata return unicodedata.numeric(input_string) except (TypeError, ValueError): pass return input_string.strip('"')
def is_instance_namedtuple(obj) -> bool: """ Checks if the object is an instance of 'namedtuple'. :param obj: the object to check :return: True if the object is an instance of 'namedtuple' """ return ( isinstance(obj, tuple) and hasattr(obj, "_asdict") and hasattr(obj, "_fields") )
def convert(lons): """ 0~360 to -180~180 """ if lons > 180: lons = lons - 360 return lons
def get_name(resource): """ Returns a name, or a code, or an empty string. """ if resource.get('name'): return resource['name'][0].get('text', '') if resource.get('code'): return resource['code'][0].get('text', '') return ''
def fillText(text, continuationPrefix="", maxLineLength=76): """Add line-breaks to <text>. Replace ' ' with '\n'+<continuationPrefix> as necessary to ensure no line longer than <maxLineLength>. Return the result as a string, ending with '\n'. The text should not contain newlines, tabs, or multiple consecutive spaces. """ text = text.rstrip() if len(text) <= maxLineLength: return text + "\n" # Find a space spaceIndex = text.rfind(" ", 0, maxLineLength + 1) if spaceIndex == -1 or text[:spaceIndex].rstrip() == "": # Couldn't find an embedded space w/in line length spaceIndex = text.find(" ", maxLineLength + 1) if spaceIndex == -1: # Couldn't find any embedded space in string return text + "\n" # Split the string returnText = text[:spaceIndex] + "\n" + continuationPrefix text = text[spaceIndex+1:] maxContLength = maxLineLength - len(continuationPrefix) while len(text) > maxLineLength: # Find a space spaceIndex = text.rfind(" ", 0, maxContLength + 1) if spaceIndex == -1: # Couldn't find an embedded space w/in line length spaceIndex = text.find(" ", maxLineLength + 1) if spaceIndex == -1: # Couldn't find any embedded space in string break # Split the string returnText += text[:spaceIndex] + "\n" + continuationPrefix text = text[spaceIndex+1:] return returnText + text + "\n"
def format_list(data, wrap_every=3, sep=", ", newline="\n"): """wrap every 3 elements into a newline. Separate every element with specified separator""" if not data: return "" output = [] for idx, el in enumerate(data): suffix = sep if (idx + 1) % wrap_every == 0: suffix = newline output.append(el) output.append(suffix) return "".join(output[0:-1])
def grow_population(initial, days_to_grow): """ Track the fish population growth from an initial population, growing over days_to_grow number of days. To make this efficient two optimizations have been made: 1. Instead of tracking individual fish (which doubles every approx. 8 days which will result O(10^9) fish over 256 days), we instead compute the sum of fish with the same due date and use the due date as the offset into the current popluation list. For example, if 5 fish have a timer of 1 and 2 fish have a timer of 4 the population would be tracked as: [0, 5, 0, 0, 2, 0, 0, 0, 0] 2. Modulo arithmetic is used instead of fully iterating through the entire list to decrement the due date of each fish every day. Using modula arithmetic provides a projection into the fish data that looks like its changing each day without needing O(n) operations and instead we can update the list in constant time regardless of the number of different ages for fish. """ current = list(initial) if days_to_grow == 0: return current for day in range(0, days_to_grow): due_index = day % 9 due_count = current[due_index] current[(day+7)%9] += due_count current[(day+9)%9] += due_count current[due_index] = max(0, current[due_index] - due_count) return current
def keep(pair, selected): """ determine whether a cell pair shall be kept ie. there is no conflicting selected candidate already """ # reject unselected subject key = (pair['row_id'], pair['subj_id']) if (key in selected) and (selected[key] != pair['subj_cand']): return False # reject unselected object key = (pair['row_id'], pair['obj_id']) if (key in selected) and (selected[key] != pair['obj_cand']): return False # anything else, we keep return True
def treatGiNumber(giNumber): """ Used to return null if the gi does not exists :param giNumber: gi number :type giNumber: string :return: None if the gi number is non-existent :rtype None or string """ if giNumber == 'NA': return None else: return giNumber
def num_batches(adhoc_modelname): """ Helper function to best_accuracy_trainval_loss. Takes a model name of the form "modelnamebatch01234" and returns the number of batches used to train it, which in this example is 5 (since [0, 1, 2, 3, 4] has five elements). N.B. the number 10 counts 2 toward the number of batches. This is not a problem, since this function is only used to order lists in increasing order. """ number_of_batches = len(adhoc_modelname[adhoc_modelname.rfind("h")+1:]) return number_of_batches
def build_shared_pref_path(package, pref_name): """ Build the full path for the shared pref :param package: The package name the shred pref belongs to. :param pref_name: The shared preference name (xml extension can be ommited) """ if pref_name.endswith('.xml'): pref_name = pref_name.rsplit('.')[0] return "/data/data/{package}/shared_prefs/{pref_name}.xml".format(package=package, pref_name=pref_name)
def dot(p1, p2, debug = False): """Dot product between two points Args: p1 ([float, float]): x and y coordinates p2 ([float, float]): x and y coordinates Returns: float """ return p1[0] * p2[0] + p1[1] * p2[1]
def uncompact(creation_sequence): """ Converts a compact creation sequence for a threshold graph to a standard creation sequence (unlabeled). If the creation_sequence is already standard, return it. See creation_sequence. """ first=creation_sequence[0] if isinstance(first,str): # creation sequence return creation_sequence elif isinstance(first,tuple): # labeled creation sequence return creation_sequence elif isinstance(first,int): # compact creation sequence ccscopy=creation_sequence[:] else: raise TypeError("Not a valid creation sequence type") cs = [] while ccscopy: cs.extend(ccscopy.pop(0)*['d']) if ccscopy: cs.extend(ccscopy.pop(0)*['i']) return cs
def RunBenchmarkTasksInSeries(tasks): """Runs benchmarks in series. Arguments: tasks: list of tuples of task: [(RunBenchmarkTask, (spec,), {}),] Returns: list of tuples of func results """ return [func(*args, **kwargs) for func, args, kwargs in tasks]
def betabin_expval(alpha, beta, n): """ Expected value of beta-binomial distribution. """ return n * alpha / (alpha + beta)
def divv3s(vec, scalar): """divide elements of 3-vector by scalar""" return (vec[0]/scalar, vec[1]/scalar, vec[2]/scalar)
def list_to_str(list_arg, delim=' '): """Convert a list of numbers into a string. Args: list_arg: List of numbers. delim (optional): Delimiter between numbers. Returns: List converted to string. """ ret = '' for i, e in enumerate(list_arg): if i > 0: ret += delim ret += str(e) return ret