content
stringlengths
42
6.51k
def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new ha...
def _formulate_smt_constraints_final_layer( z3_optimizer, smt_output, delta, label_index): """Formulates smt constraints using the logits in the final layer. Generates constraints by setting the logit corresponding to label_index to be more than the rest of the logits by an amount delta for the forward pass ...
def conddb_url(api=''): """Return CondDB URL for given API name""" return 'http://cms-conddb.cern.ch/%s' % api
def calc_montage_horizontal(border_size, *frames): """Return total[], pos1[], pos2[], ... for a horizontal montage. Usage example: >>> calc_montage_horizontal(1, [2,1], [3,2]) ([8, 4], [1, 1], [4, 1]) """ num_frames = len(frames) total_width = sum(f[0] for f in frames) + (border_siz...
def get_class_name(name): """ tries to return a CamelCased class name as good as poosible capitalize split at underscores "_" and capitelize the following letter merge this_is_Test => ThisIsTest test => Test testone => Testone """ #print("class_name: "...
def getAccentedVocal(vocal, acc_type="g"): """ It returns given vocal with grave or acute accent """ vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'}, 'e': {'g': u'\xe8', 'a': u'\xe9'}, 'i': {'g': u'\xec', 'a': u'\xed'}, 'o': {'g': u'\xf2', 'a': u'\xf3'}, ...
def _MillerRabin(n: int, a: int) -> bool: """ Miller-Rabin test with base a Args: n (int): number to test a (int): base Returns: bool: result """ d = n - 1 while (d & 1) == 0: d >>= 1 t = pow(a, d, n) while d != n - 1 and t != n - 1 and t != 1: ...
def get_overspending_handling(data, category): """ Find the overspendingHandling for a category in a month """ for subcategory in data: if subcategory["categoryId"] == category: if "overspendingHandling" in subcategory: return subcategory["overspendingHandling"] ...
def smoothed_relative_freq(n_focus, n_ref, size_focus, size_ref, N=1): """Simple maths method for finding relative frequency of a word in the focus corpus compared to the reference corpus. Frequencies are calculated per million and N is the smoothing parameter (default N = 1). Args: n_focus (in...
def __splitTime(sec): """Returns time in the format H:MM:SS @rtype: str @return: Time in the format H:MM:SS""" min, sec = divmod(sec, 60) hour, min = divmod(min, 60) return (hour, min, sec)
def check_order_history_product(order_list, username): """ check order history and returns products same as\ or similar to the given username ordered """ category_purchased = set() product_ids = set() for order in order_list: if order['username'] == username: ...
def _h_n_linear_geometry(bond_distance: float, n_hydrogens: int): # coverage: ignore """Create a geometry of evenly-spaced hydrogen atoms along the Z-axis appropriate for consumption by MolecularData.""" return [('H', (0, 0, i * bond_distance)) for i in range(n_hydrogens)]
def product_code(d, i, r): """Get product code :param d: Report definition :type d: Dict :param i: Item definition :type i: Dict :param r: Meter reading :type r: usage.reading.Reading :return: product code from item :rtype: String """ return i.get('product_code', '')
def complement(intervals, first=None, last=None): """complement a list of intervals with intervals not in list. >>> complement([(10,20), (15,40)]) [] >>> complement([(10,20), (30,40)]) [(20, 30)] >>> complement([(10,20), (30,40)], first=5) [(5, 10), (20, 30)] Arguments --------- ...
def similarL1(a, b): """ get similar between a string and a string in a list :param a: String :param b: List of strings :return: boolean """ for x in b: if x.lower() in a.lower(): return True return False
def step_schedule_with_warmup(step, step_size, warmup_steps=0, hold_max_steps=0, lr_start=1e-4, lr_max=1e-3, step_decay=.5): """ Create a schedule with a step decrease preceded by a warmup period during which the learning rate increases linearly between {lr_start} and {lr_max}. """ if step < warmup...
def parse_line(line): """return the index and direct links described by a string representing a pipe""" k, v = line.strip().split(' <-> ') return k, v.split(', ')
def uvm_object_value_str(v): """ Function- uvm_object_value_str Args: v (object): Object to convert to string. Returns: str: Inst ID for `UVMObject`, otherwise uses str() """ if v is None: return "<null>" res = "" if hasattr(v, 'get_inst_id'): res = "{}"....
def climbStairs(n, dic = {0:0,1:1,2:2}): """ LeetCode-Problem: You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Solution: Exploring all possible ways to climb the stairs in 1 or 2 s...
def check_unique_list(input): """ Given a list, check if it is equal to a sorted list containing 1-9 Return True if the given list is unique, False otherwise """ # convert list string into list of int and sort it int_list = list(map(int, input)) int_list.sort() return int_list == [1, 2, ...
def _pad(data): """Pad the data to encrypt to be a multiple of 16.""" # return data if no padding is required if len(data) % 16 == 0: return data # subtract one byte that should be the 0x80 # if 0 bytes of padding are required, it means only # a single \x80 is required. padding_requ...
def get_names_from_lines(lines, frac_len, type_function): """Take list of lines read from a file, keep the first fract_len elements, remove the end of line character at the end of each element and convert it to the type definded by function. """ return [type_function(line[:-1]) for line in lines[:fr...
def bitparity(x): """return the bit parity of the word 'x'. """ assert x >= 0, "bitparity(x) requires integer x >= 0" while x > 0xffffffff: x = (x >> 32) ^ (x & 0xffffffff) x ^= x >> 16 x ^= x >> 8 x ^= x >> 4 return (0x6996 >> (x & 15)) & 1
def clean_laughs(text): """ Removes laughs. Parameters ---------- text : str Returns ------- str """ laughs = ['ah', 'eh', 'he' 'ih', 'hi', 'oh'] vowels = ['a', 'e', 'i', 'o', 'u'] text_words = text.split() new_words = [word for word in text_words if word.lower(...
def get_ngrams(s, ngmin, ngmax, separator="", bos="<", eos=">", suffix="", flatten=True): """ For the given sequence s. Return all ngrams in range ngmin-ngmax. spearator is useful for readability bos/eos symbols are added to indicate beginning and end of seqence suffix is an a...
def extinction_law(a, b, Rv = 3.1): """Eqn 1 from Cardelli 1989""" a_lam_aV = a + b / Rv return a_lam_aV
def base_b(n: int, b: int): """ Return the string representation of n in base-b. Example: base_b(11, 3) = '102' """ e = n // b q = n % b if n == 0: return '0' elif e == 0: return str(q) else: return base_b(e, b) + str(q)
def read_singles(singles_file): """ Read the table of reads per gene and return a dictionary """ if not singles_file: return None counts = {} try: for line in open(singles_file): spl = line.strip().split() try: counts[spl[0]] = sum([int(k) ...
def splituser(host): """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" user, delim, host = host.rpartition('@') return (user if delim else None), host
def getNegativeSamples(outsideWordIdx, dataset, K): """ Samples K indexes which are not the outsideWordIdx """ negSampleWordIndices = [None] * K for k in range(K): newidx = dataset.sampleTokenIdx() while newidx == outsideWordIdx: newidx = dataset.sampleTokenIdx() negSamp...
def rubygems_api_url(name, version=None): """ Return a package API data URL given a name, an optional version and a base repo API URL. For instance: >>> url = rubygems_api_url(name='turbolinks', version='1.0.2') >>> assert url == 'https://rubygems.org/api/v2/rubygems/turbolinks/versions/1.0.2.j...
def cache_clear_mutation(dataset_id): """Update the draft HEAD reference to an new git commit id (hexsha).""" return { 'query': 'mutation ($datasetId: ID!) { cacheClear(datasetId: $datasetId) }', 'variables': {'datasetId': dataset_id} }
def get_service_name(pod_name): """Returns the service name from the pod name.""" return pod_name[:-6]
def compact_dict_none(dct): """ Compacts a dct by removing pairs with a None value. Other nil values pass :param dct: :return: The filtered dict """ return dict(filter(lambda key_value: key_value[1] != None, dct.items()))
def version_is_locked(version): """ Determine if a version is locked """ return getattr(version, "versionlock", None)
def solution(array): """ Finds the smallest positive integer not in array. The smallest possible answer is 1. :param array: list of integers :return: smallest positive integer not in array. """ # smallest answer so far i = 1 # visited values visited = [] for value in array: visited.append(...
def parse_field(field_string): """ Get a tuple of the first entries found in an psimitab column (xref, value, desc) :param field_string: :return: A tuple (xref, value, desc) - desc is optional """ parts = field_string.split(":") xref = parts[0] rest = parts[1] if "(" in rest: ...
def get_errno(exc): # pragma: no cover """ Get the error code out of socket.error objects. socket.error in <2.5 does not have errno attribute socket.error in 3.x does not allow indexing access e.args[0] works for all. There are cases when args[0] is not errno. i.e. http://bugs.python.org/issue64...
def test_for_short_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 "short" in first_element.lower(): return True ...
def arg_parse(text, j): """Parsing arguments in op_par_loop to find the correct closing brace""" depth = 0 loc2 = j while 1: if text[loc2] == '(': depth = depth + 1 elif text[loc2] == ')': depth = depth - 1 if depth == 0: return loc2 loc2 = loc2 + 1
def mlist(x): """make sure x is a list""" if isinstance(x, list): return(x) else: return([x])
def subdict(d, keys): """Returns a new dictionary composed of the (key, value) pairs from d for the keys specified in keys""" return {k: d[k] for k in keys}
def isupper(char): """ Indicates if the char is upper """ if len(char) == 1: if ord(char) >= 0x41 and ord(char) <= 0x5A: return True return False
def manage_user_group_verification(config, tables, users, groups): """ Make sure the specified users and groups exist. """ if users: # if there is only one user, make it a list anyway if isinstance(users, str): user_list = users.split(',') else: user_list...
def s2i(s): """ Convert a string to an integer even if it has + and , in it. """ # Turns out sometimes there can be text in the string, for example "pending", # and that made this function crash. if type(s)==type(0): # Input is already a number return s try: # Sometimes inpu...
def get_default_bbox(kind): """ Get default rough estimate of face bounding box for `get_identity_descriptor()`. Args: kind: `str` Crop type that your model's pose encoder consumes. One of: 'ffhq', 'x2face', 'latentpose'. Returns: bbox: `...
def driver_function(prices,n): """The driver holds the lookup dictionary and makes the original function call to rodcut function. """ dict = {} def rodcut(prices,n): """ Note: this function was found in C++ on: https://www.techiedelight.com/rot-cutting/ In...
def is_prime(num): """ Returns true is the number is prime. To check if a number is prime, we need to check all its divisors upto only sqrt(number). Reference: https://stackoverflow.com/a/5811176/7213370 """ # corner case. 1 is not a prime if num == 1: return Fal...
def string_enc(x): """ Fixing a string's coding""" try: return x.encode('latin').decode('utf-8') except: return x
def zero_hit_count_rules(hit_count_rules): """ Get list of zero hit count rules :param hit_count_rules: dictionary which contain json response with all hit count rules :return: list with all zero hit count rules (contain rule name, id, type and access policy name) ...
def query_tw_author_id(author_id): """ES query by Twitter's author_id Args: author_id (str) Returns: ES query (JSON) Note: INCA """ return { "query": { "bool": { "filter": [ {"term": {"doctype": "tweets2"}}, ...
def to_listdict(list_list): """Converts a list-of-lists to a list-of-dicts. Ex: [["a","b"],[1, 2],[3, 4]] ---> [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] Args: list_list (<list<list>>): A 2d list with a header row. Ex. [['a','b'], [1, 2], [3, 4]] Returns: <list<dict>>: list-of-dicts. Ex: [{...
def set_size(width, fraction=1, subplots=(1, 1)): """ Set figure dimensions to avoid scaling in LaTeX. Parameters ---------- width: float or string Document width in points, or string of predined document type fraction: float, optional Fraction of the width which you wish th...
def newline(text, number=1): """adds number newlines to the end of text""" return text.strip() + ("\n" * number)
def hhmmss_to_seconds(hhmmss): """ Translates HHMMSS or HHMM formatted time into seconds. Args: hhmmss (str): String in HHMMSS or HHMM format Returns: seconds (int): Converted seconds """ hhmmss_split = hhmmss.split(":") try: seconds = (int(hhmmss_split[0]) * 60 * 6...
def calculations(pyramid, i): """ Calculate the value of the given path. """ res = 1 for x, row in enumerate(pyramid): res *= row[i[x]] return res
def is_video_json_valid(json_payload): """ Validates a video dictionary JSON from the client. Args: json_payload (dict): A JSON payload received from the client. Returns: bool: Whether or not the video JSON format was valid. """ if not json_payload["videoUri"] or not json_paylo...
def get_canonical_prob_name(prob_name): """Transform string to match name of a probability function.""" prob_name = prob_name.lower() if not prob_name.endswith('_probability'): prob_name = prob_name + '_probability' return prob_name
def convert_codewords(codewords): """ Changes the codewords list of lists to a list of strings Parameters ---------- codewords : list allowed codewords for logical zero Returns ------- list_of_strings : list a list of strings Notes ----- No longer needed at pr...
def format_float(val): """Set a floating point number into a specific format.""" return f'{val:.2f}'
def no_dups(recommend: list) -> list: """Remove the duplicates""" new = [] for x in recommend: if x not in new: new.append(x) return new
def pos_embed(x, position_num): """ get position embedding of x """ maxlen = int(position_num / 2) return max(0, min(x + maxlen, position_num))
def wordinset_wild(word, wordset, wild='*'): """Return True if word not in wordset, nor matched by wildcard. Note: accepts a wildcard (default '*') for '0 or more letters'. """ if word in wordset: return True else: if word[-1] != wild: word += wild while len(word...
def rgb2hex(r, g, b): """ Convert RGB to color hex Args: r (int): Red g (int): Green b (int): Blue Returns: **hex** (string) - Hex color code """ return '#%02x%02x%02x' % (r, g, b)
def product_of_2( numbers ): """ From the given list of numbers, find the pair of numbers that sum up to 2020. This function returns the prduct of those 2 numbers. """ numbers = [ int( item ) for item in numbers ] for i in range( len(numbers) ): for j in range( i+1, len(numbers) ): ...
def validate_scalingpolicyupdatebehavior(scalingpolicyupdatebehavior): """ Validate ScalingPolicyUpdateBehavior for ScalingInstruction Property: ScalingInstruction.ScalingPolicyUpdateBehavior """ VALID_SCALINGPOLICYUPDATEBEHAVIOR = ( "KeepExternalPolicies", "ReplaceExternalPolicies"...
def invert_dict(old_dict): """ Helper function for assign_colors_to_clusters(). """ inv_dict = {} for k, v in old_dict.items(): inv_dict [v] = inv_dict.get(v, []) inv_dict [v].append(k) return inv_dict
def is_valid_hcl(value: str) -> bool: """ Return if value is a valid hcl (hair color). Parameter --------- value: str a hcl. Return ------ bool True if hcl is valid, False othewise. """ if value[0] != "#": return False return all((char.isdigit() or c...
def format_dictionary_durations(dictionary): """ Takes a dict with values in seconds and rounds the values for legibility""" formatted_dict = {} for k, v in dictionary.items(): try: formatted_dict[k] = round(v) except TypeError: pass return formatted_dict
def open_table(table_name, append=False, default=None): """Open output file if file name specified.""" if not table_name: return default return open(table_name, "at" if append else "wt")
def RemoveSlash( dirName ): """Remove a slash from the end of dir name if present""" return dirName[:-1] if dirName.endswith('/') else dirName
def distx2(x1,x2): """ Calculate the square of the distance between two coordinates. Returns a float """ distx2 = (x1[0]-x2[0])**2 + (x1[1]-x2[1])**2 + (x1[2]-x2[2])**2 return distx2
def msg_from_harvester(timestamp_str: str, ip_address: str, node_id: str) -> str: """Get a fake log msg when a farmer receives data from a harvester""" line = ( f"{timestamp_str} farmer farmer_server : DEBUG" + f" <- farming_info from peer {node_id} {ip_address}" ) return...
def bytesto(bytes, to, bsize=1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesto(314575262000000, 'm'))) sample output: mb= 300002347.946 """ a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 } r = float(bytes) for i in rang...
def jaccard_word_level_similarity(y_true: str, y_pred: str) -> float: """ Compute word level Jaccard similarity Parameters ---------- y_true : str True text y_pred : str Predicted text Returns ------- float Word level Jaccard similarity Examples ---...
def should_check_integrity(f): """Returns True if f should be checked for integrity.""" return f not in ('README.md', 'TRAINING_LOG', 'checksum.md5', 'data') and not f.startswith('.')
def dont_exceed_max(Max,code_list): """I need to ensure that NetSurfP is not overwhelmed - so I split the queries to ensure that each is less than Max I will use Max = 100000""" C = len(code_list) temp_list=[] for_inclusion=[] limit = 0 for i in range(C): a,b = code_list[i] B = ...
def verify_structure(memlen, itemsize, ndim, shape, strides, offset): """Verify that the parameters represent a valid array within the bounds of the allocated memory: char *mem: start of the physical memory block memlen: length of the physical memory block offset: (char *)buf...
def factorial(n): """ Return n! - the factorial of n. >>> factorial(1) 1 >>> factorial(0) 1 >>> factorial(3) 6 """ if n<=0: return 0 elif n==1: return 1 else: return n*factorial(n-1)
def _call_if_callable(s): """Call a variable if it's a callable, otherwise return it.""" if hasattr(s, '__call__'): return s() return s
def extract_package(path, output_directory): """Extract package at path.""" if path.lower().endswith('.tar.gz'): import tarfile try: tar = tarfile.open(path) tar.extractall(path=output_directory) tar.close() return True except (tarfile.Read...
def filter_float(value): """ Filter given float value. :param value: given value :type value: float :return: filtered version of value """ if isinstance(value, (float, int)): return value return None
def title_extractior(obj): """Extract title from content. Use NTLK to do stuff with text. - maybe later for know i will use first sentence in text @return: 'title', generated_content""" _, _, _, content = obj if not content: return 'title', '' cut = 40 if len(content) >= 40 else...
def multiples(x, n): """x is the number in question, n is a power of 2""" multiple = 2 if n >= x: return n else: while n * multiple < x: if n * multiple > x: print(n * multiple) return else: multiple += 1 pri...
def sum_str(a, b): """Add two strings of ints and return string.""" if a == '' or a == ' ': a = 0 if b == '' or b == ' ': b = 0 return str(int(a) + int(b))
def format_response_not_found_error(command_text): """Format an ephemeral error when no Quip is found.""" response = { "response_type": "ephemeral", "text": f"No quip found for `{command_text}`.", } return response
def parts_to_decimal(major, minor): """ Convert an ICD9 code from major/minor parts to decimal format. """ if major[0] in ("V", "E"): major = major[0] + major[1:].lstrip("0") if len(major) == 1: major = major + "0" else: major = major.lstrip("0") if len(m...
def merge_dict(base, to_merge, merge_extend=False) -> dict: """Deep merge two dictionaries""" if not isinstance(to_merge, dict): raise Exception(f"Cannot merge {type(to_merge)} into {type(base)}") for key, value in to_merge.items(): if key not in base: base[key] = value e...
def get_prices_of_products_in_discounted_collections(order, discounted_collections): """Get prices of variants belonging to the discounted collections.""" line_prices = [] if discounted_collections: for line in order: if not line.variant: continue product_coll...
def kdelta(i, j): """ Kronecker delta function """ assert i in (0,1) assert j in (0,1) return i*j
def get_highest_knowledge(knowledge): """ We assume that the N has the highest knowledge of N. """ k = {} for key in knowledge.keys(): k[key] = knowledge[key][key] return k
def _convert_from_degrees(value): """ Helper function to convert float format GPS to format used in EXIF. :param value: :return: """ degrees = int(value) temp = value - degrees temp = temp * 3600 minutes = int(temp / 60) seconds = temp - minutes * 60 return degrees, minutes, ...
def is_fast_round(rnd: int, r_fast: int, r_slow: int) -> bool: """Determine if the round is fast or slow. :meta private: """ remainder = rnd % (r_fast + r_slow) return remainder - r_fast < 0
def parse_military_friendly(parts): """ Parse whether or not the ad indicates "military friendly". parts -> The backpage ad's posting_body, separated into substrings """ for part in parts: if 'military' in part: return 1 return 0
def print_nicely(counts): """ This function iterates through a count dictionary and prints the values in a user-friendly way :param counts: Dict, :return: None """ print("pdb id\tarticles\treviews") for entry_id in counts.keys(): print("%s\t%i\t%i" % (entry_id, ...
def starify_rating(rating): """Creates a number of full and half stars according to the given rating.""" rate = 0 try: rate = float(rating.split('/')[0]) except ValueError: print('Could not parse recipe rating: ', rating) full = ''.join('\uf005' * int(rate)) half = '\uf089' if ra...
def compute_image_shape(width: int, height: int, fmt: str) -> tuple: """Compute numpy array shape for a given image. The output image shape is 2-dim for grayscale, and 3-dim for color images: * ``shape = (height, width)`` for FITS images with one grayscale channel * ``shape = (height, width, 3)`` for ...
def rounddown(num, multiple): """Rounds a number to the nearest lower multiple. Returns an int.""" return int(num / multiple) * multiple
def get_address(iface): """ Returns an IP address from an iface dict, preferring node_addr """ if iface["iface_addr"] is None: return iface["node_addr"] else: return iface["iface_addr"]
def title_case(sentence): """ Convert a string to title case. Parameters ---------- sentence: string String to be converted to title case Returns ---------- ret : string String converted to title case. Example ---------- >>> title_case('ThIS iS a StrInG to ...