content
stringlengths
42
6.51k
def _merge_weights(spin_d1, spin_d2): """Sum the weights stored in two dictionaries with keys being the spins""" if len(spin_d1) != len(spin_d2): raise RuntimeError("Critical - mismatch spin-dict length") out = {} for spin in spin_d1: out[spin] = spin_d1[spin] + spin_d2[spin] return ...
def _sqrt_nearest(n, a): """Closest integer to the square root of the positive integer n. a is an initial approximation to the square root. Any positive integer will do for a, but the closer a is to the square root of n the faster convergence will be. """ if n <= 0 or a <= 0: raise Va...
def translate(x, y): """ Generate an SVG transform statement representing a simple translation. """ return "translate(%i %i)" % (x, y)
def bb_IoU(boxA, boxB): """Compute Intersection over Union (IoU) for two bboxes Args: boxA: [x1, y1, x2, y2] boxB: [x1, y1, x2, y2] Returns: the iou score between 0-1 """ # determine the (x, y)-coordinates of the intersection rectangle xA = max(boxA[0], boxB[0]) yA ...
def cumulative_sum(t): """ Return a new list where the ith element is the sum of all elements up to that position in the list. Ex: [1, 2, 3] returns [1, 3, 6] """ res = [t[0]] for i in range(1, len(t)): res.append(res[-1] + t[i]) return res
def postprocess_answer_extraction_output(answer_extraction_output: str): """ Args: answer_extraction_output (str): decoded answer extraction output Returns: answer_text_list (List[str]) """ # parse answers answers = answer_extraction_output.split("<sep>")[:-1] # normalize an...
def dockerize_windows_path(dkrpath: str) -> str: """Returns a path that can be mounted as a docker volume on windows Docker uses non-standard formats for windows mounts. Note that different components of the docker ecosystem may support a different set of formats for paths. This one seems to work across...
def check_key_value(data, key, value): """Checks a key for the given value within a dictionary recursively.""" if isinstance(key, dict): for k, v in key.items(): return check_key_value(data[k], v, value) if data[key] == value: return True return False
def single(sequence, condition=None): """ Returns the single item in a sequence that satisfies specified condition or raises error if none or more items found. Args: sequence: iterable Sequence of items to go through. condition: callable Condition to...
def exp(x) -> float: """Returns e ^x""" if x == 0: return 1 if x < 0: return 1 / exp(-x) total = 1 denominator = 1 last = float('inf') k_times = 1 x_top = x # Uses e^x taylor series # to compute the value # e^x = sum n^x / n! while True: try: ...
def relativeBCPIn(anchor, BCPIn): """convert absolute incoming bcp value to a relative value""" return (BCPIn[0] - anchor[0], BCPIn[1] - anchor[1])
def merge_segments(lst): """Try to merge segments in a given list in-place.""" ii = 0 while True: jj = ii + 1 if len(lst) <= jj: return lst seg1 = lst[ii] seg2 = lst[jj] if seg1.merge(seg2): if seg2.empty(): del lst[jj] ...
def bytes_in_context(data, index): """Helper method to display a useful extract from a buffer.""" start = max(0, index - 10) end = min(len(data), index + 15) return data[start:end]
def set_local_fonts_enabled(enabled: bool) -> dict: """Enables/disables rendering of local CSS fonts (enabled by default). Parameters ---------- enabled: bool Whether rendering of local fonts is enabled. **Experimental** """ return {"method": "CSS.setLocalFontsEnabled", "params...
def is_blank(x): """Checks if x is blank.""" return not x.strip()
def extract_type(item): """Extract item possible types from jsonschema definition. >>> extract_type({'type': 'string'}) ['string'] >>> extract_type(None) [] >>> extract_type({}) [] >>> extract_type({'type': ['string', 'null']}) ['string', 'null'] """ if not item or "type" not...
def factorial_loop(number): """Calculates factorial using loop. :param number: A number for which factorial should be calculated. :return: Factorial number. >>> factorial_loop(-1) 1 >>> factorial_loop(0) 1 >>> factorial_loop(1) 1 >>> factorial_loop(3) 6 >>> factorial_lo...
def filter_units(line, units="imperial"): """Filter or convert units in a line of text between US/UK and metric.""" import re # filter lines with both pressures in the form of "X inches (Y hPa)" or # "X in. Hg (Y hPa)" dual_p = re.match( "(.* )(\d*(\.\d+)? (inches|in\. Hg)) \((\d*(\.\d+)? hP...
def is_valid_key(key: str) -> bool: """Check if an exiftool key is valid and interesting.""" # https://exiftool.org/TagNames/Extra.html file_keys = ( 'FileName', 'Directory', 'FileSize', 'FileModifyDate', 'FileAccessDate', 'FileInodeChangeDate', 'FilePermissions', 'FileType', 'FileType', ...
def nb_year(p0, percent, aug, p): """ In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater ...
def get_log_number_of_restricted_partitions(m, n): """Get Number of restricted partitions of m into at most n parts""" if n <= 0 or m <= 0: if m == 0: return 0 return float('-inf') elif m < NUMBER_OF_RESTRICTED_PARTITIONS_PRECOMPUTED_LIMIT: if m < n: return LO...
def get_broken_fuzz_targets(bad_build_results, fuzz_targets): """Returns a list of broken fuzz targets and their process results in |fuzz_targets| where each item in |bad_build_results| is the result of bad_build_check on the corresponding element in |fuzz_targets|.""" broken = [] for result, fuzz_target in z...
def increase_parameter_closer_to_value(old_value, target_value, coverage): """ Simple but commonly used calculation for interventions. Acts to increment from the original or baseline value closer to the target or intervention value according to the coverage of the intervention being implemented. Args: ...
def trapezoid_area(base_minor, base_major, height): """Returns the area of a trapezoid""" # You have to code here # REMEMBER: Tests first!!! area = height * ((base_minor + base_major)/ 2) return area
def replace_all(text, dic): """ Replaces all occurrences in text by provided dictionary of replacements. """ for i, j in list(dic.items()): text = text.replace(i, j) return text
def find_gcd(number1: int, number2: int) -> int: """Returns the greatest common divisor of number1 and number2.""" remainder: int = number1 % number2 return number2 if remainder == 0 else find_gcd(number2, remainder)
def partition_at_level(dendogram, level) : """Function which return the partition of the nodes at the given level. A dendogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best partition is at height [len(...
def matrix_transpose(matrix: list) -> list: """ Compute the transpose of a matrix """ transpose: list = [] for row in range(len(matrix[1])): column = [] for col in range(len(matrix)): column.append(matrix[col][row]) transpose.append(column) return transpose
def get_subs(relativize_fn, links): """ Return a list of substitution pairs, where the first item is the original string (link) and the second item is the string to replace it (relativized link). Duplicate subs are filtered out.""" subs = ((l, relativize_fn(l)) for l in links) subs = filter(lambda p: p[0] != p[1],...
def wordSlices(a_string): """assumes a_string is a string of lenght 1 or greater returns a list of strings, representing the slices of 2+ chars that can be taken from a_string """ # handle short strings if len(a_string) < 3: return [a_string] # innitialize variables slice_list = ...
def filter_nbases(Seq): """This command takes a seq and returns the Seq after removing n bases.""" Seq = Seq.upper() for i in Seq: if i not in 'AGCTN': return 'Invalid Seq' Seq = Seq.replace("N", "") return Seq
def Tree(data, *subtrees): """ """ t = [data] t.extend(subtrees) return t
def _add_dot(ext_list): """ PURPOSE: This private function is used to add a dot ('.') to the beginning of each file extension in an *_exts list; if a dot is not already present. """ # LOOP THROUGH EXTENSIONS for idx, ext in enumerate(ext_list): # TEST FOR DOT (.ext) >> IF NOT, ...
def equalizer(n: int, m: int, total: int): """ Receives total, m and n [0..total] Returns a tuple (a, b) so that their sum -> total, and a / b -> 1 """ oddity = total % 2 smallest = min(n, m, total // 2 + oddity) if smallest == n: return (n, min(m, total-n)) elif smallest == m: ...
def traverse(start_cell, direction, num_steps): """ Iterates over the cells in a grid in a linear fashion and forms a list of traversed elements. start_cell is a tuple (row, col) where the iteration starts. direction is a tuple that contains the difference between the positions of consecutive ...
def latex_safe(value): """ Filter that replace latex forbidden character by safe character """ return str(value).replace('_', '\_').replace('$', '\$').replace('&', '\&').replace('#', '\#').replace('{', '\{').replace('}','\}')
def parse_line_contents(line): """Extract the sigma, gamma, lambda and m from the line: just read until we get something looking like a float and then store the first three of them""" #Split by spaces spl = line.split() res = [] for ss in spl: try: float(ss) re...
def classify_segment(height_r, dist_r, height_l, dist_l): """ Classify a road segment based on height and distance values. This function is used by the averaging method. """ # Sometimes the buildings in the dataset don't have any data. # Function returns 0 then and we just classify as 4 because...
def _get_opening_root_tag(html_input): """Read through html input and return the full html tag (< to >) of the opening tag Args: html_input (str or bytes): HTML string to read the opening tag from Returns: str: the full opening tag string, e.g. <div id="ires"> Raises: ValueErr...
def nCkModp(n, k, p): """ Returns nCk % p Parameters ---------- n : int denotes n in nCk%p k : int denotes k in nCk%p p : int denotes p in nCk%p return : int returns an integer """ if (k > n- k): k = n - k Coef = [0 for i i...
def Mj_from_spt(x): """ Lepine Mj to SpT relationship (Lepine et al. 2013, Equation 23, page 24) :param x: numpy array, SpT :return: """ return 5.680 + 0.393*x + 0.040*x**2
def recurse_mirror(s, olds=""): """Attempt at mirror() recursively though i'm failing. olds gets pushed onto the stack before the final return value collection so the order of olds and s is reversed.""" if not s: return olds elif olds < s: olds = s return s[-1] + recurse_mirror(s...
def is_ref(prop): """ Returns True if prop is a reference. """ return list(prop.keys()) == ['$ref']
def knapsack01(W, wt, val, n): """ Soluzione dello zaino 0-1 utilizzando la programmazione dinamica Argomenti: W (int): peso totale wt (list): lista dei pesi degli oggetti val (list): lista dei valori degli oggetti n (int): numero degli oggetti ...
def human_readable_size(byte_size): """Convert a number of bytes to a human-readable string.""" i = 0 suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] while byte_size >= 1024 and i < len(suffixes) - 1: byte_size /= 1024. i += 1 size = ('{0:.2f}'.format(byte_size)).rstrip('0').rstrip(...
def strlist(ls): """Format a list as a comma-separated string.""" return ','.join(str(p) for p in ls)
def wav2RGB(wavelength): """ Converts a wavelength to RGB. Arguments: wavelength (float) : the wavelength (in nm). Returns: (tuple of int, int, int): the converted RGB values. """ wavelength = int(wavelength) R, G, B, SSS = 0, 0, 0, 0 # get RGB values i...
def parse_years(year_range): """Parse year_range into year list. Args: year_range: A string in the format aaaa-bbbb. Returns: A list of years from aaaa to bbbb, including both ends. """ st, ed = year_range.split("-") st, ed = int(st), int(ed) return [year for year in range(st...
def list_to_set(lst): """convert list to set""" res = {} for each in lst: res[each] = True return res
def buildLabel(nodeId, labelText, labelLink): """Build a label cell nodeId -- name of the node that the popup refers to labelText -- text of the label itself labelLink -- link to follow when label is clicked (if any) """ if len(labelLink) > 0: onClick = '' href = labelLink ...
def replace_key_value(lookup, new_value, expected_dict): """ Replaces the value matching the key 'lookup' in the 'expected_dict' with the new value 'new_value'. """ for key, value in expected_dict.items(): if lookup == key: if isinstance(value, dict) and isinstance(new_value, dic...
def babylonian_sqrt(rough, n): """https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method""" iterations = 10 for _ in range(iterations): rough = 0.5 * (rough + (n / rough)) return rough
def chunks(l, n): """Yield successive n-sized chunks from l. Parameters ---------- l : list The list to split in_ chunks n : int The target numbers of items in_ each chunk Returns ------- list List of chunks """ pieces = [] for i in range(0, len(l),...
def force_correct(word): """ arg: commonly misspelt word that the spell-checker cannot catch return: correct spelling of word """ if word=='unc': return 'nunc' elif word=='gnus': return 'agnus' elif word=='yrie': return 'kyrie' elif word=='redo': return 'credo' elif word=='ominus': return 'dominus' ...
def nome(inpt): """ Towards a tool that can get the name of a variable """ for k, v in locals().items(): if v == inpt: return k
def make_bool(mixed): """ Convert value to boolean """ if mixed is None: return False if isinstance(mixed, bool): return mixed try: return int(mixed) != 0 except ValueError: pass if isinstance(mixed, str): mixed = mixed.lower() if mixed ...
def split(list): """ divide the unsorted list at midpoint into sublists Return two sublists - left and right takes overall O(log n) time, it is the ideal runtime for the merge sort and not for the given one runtime for this operation is O(k log n) similarity for the merge operation it becomes O...
def make_valid_filename(str): """ From http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python """ return "".join((x if x.isalnum() else "_") for x in str)
def find_first_slice_value(slices, key): """For a list of slices, get the first value for a certain key.""" for s in slices: if key in s and s[key] is not None: return s[key] return None
def remove_doubles(lst): """given a sorted list returns a new sorted list with duplicates removed""" if len(lst) == 1: return [lst[0]] newlist = [lst[0]] for i in range(1,len(lst)): if newlist[-1] != lst[i]: newlist.append(lst[i]) return newlist
def currency_filter(value): """Outputs comma separated rounded off figure""" number = float(value) rounded_number = round(number) integer_number = int(rounded_number) return "{:,}".format(integer_number)
def time_delta(t1: str, t2: str, fmt='%a %d %b %Y %X %z') -> int: """ >>> time_delta('Sun 10 May 2015 13:54:36 -0700', ... 'Sun 10 May 2015 13:54:36 -0000') 25200 >>> time_delta('Sat 02 May 2015 19:54:36 +0530', ... 'Fri 01 May 2015 13:54:36 -0000') 88200 >>> time_delta('Wed 12 May 2269 ...
def corrections(mean_onbit_density): """Calculate corrections See :func:`similarity` for explanation of corrections. Args: mean_onbit_density (float): Mean on bit density Returns: float: S\ :sub:`T` correction, S\ :sub:`T0` correction """ p0 = mean_onbit_density corr_st = ...
def get_default_extra_suffix(related_docs=True): """Return extra suffix""" extra_suffix = "-related-fullcontent" if related_docs else "-random-fullcontent" return extra_suffix
def dedent(string): """Remove the maximum common indent of the lines making up the string.""" lines = string.splitlines() indent = min( len(line) - len(line.lstrip()) for line in lines if line ) return "\n".join( line[indent:] if line else line for line in lin...
def get_next_satisfying(vector, starting_position, condition_fun): """find next pixel in the vector after starting position that satisfies the condition (boolean) return -1 if not found""" position = starting_position while(position < len(vector) and not(condition_fun(vector[position]))): ...
def remove_first_space(x): """ remove_first_space from word x :param x: word :type x: str :return: word withou space in front :rtype: str """ try: if x[0] == " ": return x[1:] else: return x except IndexError: return x
def make_build_cmd(parameters, import_path_labels=()): """Build Cap'n Proto schema for Python packages.""" cmd = ['build'] if import_path_labels: cmd.append('compile_schemas') for import_path_label in import_path_labels: cmd.append('--import-path') cmd.append(paramete...
def fileno(fil): """Return the file descriptor representation of the file. If int is passed in, it is returned unchanged. Otherwise fileno() is called and its value is returned as long as it is an int object. In all other cases, TypeError is raised. """ if isinstance(fil, int): return ...
def make_tsv_line(vals,outfields,empty_string_replacement='',sep='\t'): """Does not have the \n at the end""" l = [] for tag in outfields: val = vals[tag] if type(val) is str: if empty_string_replacement and not val: l.append( empty_string_replacement ) ...
def convert(s): """Convert to integer.""" x = -1 try: x = int(s) # print("Conversion succeeded! x =", x) except (ValueError, TypeError): # can accept tuple of types # print("Conversion failed!") pass # syntactically permissable, semantically empty return x
def _show_capture_callback(x): """Validate the passed options for showing captured output.""" if x in [None, "None", "none"]: x = None elif x in ["no", "stdout", "stderr", "all"]: pass else: raise ValueError( "'show_capture' must be one of ['no', 'stdout', 'stderr', '...
def tail_slices (l) : """Returns the list of all slices anchored at tail of `l` >>> tail_slices ("abcdef") ['abcdef', 'bcdef', 'cdef', 'def', 'ef', 'f'] """ return [l [i:] for i in list (range (len (l)))]
def unique(sequence): """ Return a list of unique items found in sequence. Preserve the original sequence order. For example: >>> unique([1, 5, 3, 5]) [1, 5, 3] """ deduped = [] for item in sequence: if item not in deduped: deduped.append(item) return deduped
def fixdotslashspacehyphen(to_translate): """for paths, . and / to _, also space to _ """ dotslash = u'./ ' translate_to = u'-' translate_table = dict((ord(char), translate_to) for char in dotslash) return to_translate.translate(translate_table)
def iterative(array, element): """ Perform Linear Search by Iterative Method. :param array: Iterable of elements. :param element: element to be searched. :return: returns value of index of element (if found) else return None. """ for i in range(len(array)): if array[i] == element: ...
def send_analytics_tracker(name, uid=None): """Send setup events to Google analytics""" # This function is not required anymore as we expect # users to report usage through github issues, or by # giving a 'star'. # Only thing we learnt from this is, External, Replica3 # and Replica1 are preferr...
def to_dict(object, classkey='__class__'): """ Get dict recursively from object. https://stackoverflow.com/questions/1036409/recursively-convert-python-object-graph-to-dictionary :param object: object :type object: object or dict :param classkey: save class name in this key :type classkey: ...
def is_tomodir(subdirectories): """provided with the subdirectories of a given directory, check if this is a tomodir """ required = ( 'exe', 'config', 'rho', 'mod', 'inv' ) is_tomodir = True for subdir in required: if subdir not in subdirectori...
def midi_to_pitch(midi: int) -> float: """Returns the absolute pitch in Hz for the given MIDI note value.""" return 440 * (2 ** ((midi - 69) / 12))
def wrap_server_method_handler(wrapper, handler): """Wraps the server method handler function. The server implementation requires all server handlers being wrapped as RpcMethodHandler objects. This helper function ease the pain of writing server handler wrappers. Args: wrapper: A wrapper f...
def remove_empty(d): """ Helper function that removes all keys from a dictionary (d), that have an empty value. """ for key in list(d): if not d[key]: del d[key] return d
def convert_clip_ids_to_windows(clip_ids): """ Inverse function of convert_windows_to_clip_ids Args: clip_ids: list(int), each is a index of a clip, starting from 0 Returns: list(list(int)), each sublist contains two integers which are clip indices. [10, 19] meaning a 9 clip win...
def intersection_over_union(box1, box2): """ Input : box1: [xmin, ymin, xmax, ymax], box2: [xmin, ymin, xmax, ymax]\n Output: IoU """ xmin1, ymin1, xmax1, ymax1 = box1 xmin2, ymin2, xmax2, ymax2 = box2 width1 = xmax1 - xmin1 + 1 height1 = ymax1 - ymin1 + 1 width2 = xmax2 - x...
def coalesce(*xs): """ Coalescing monoid operation: return the first non-null argument or None. Examples: >>> coalesce(None, None, "not null") 'not null' """ if len(xs) == 1: xs = xs[0] for x in xs: if x is not None: return x return None
def extract_full_names(people): """Return list of names, extracting from first+last keys in people dicts. - people: list of dictionaries, each with 'first' and 'last' keys for first and last names Returns list of space-separated first and last names. >>> names = [ ... {'f...
def __discord_id_from_mention(discordid:str) -> str: """Checks Discord ID from possible mention and returns Discord ID""" if discordid.startswith("<@!"): #This checks to see if Discord ID is actually a mention, if it is, unwrap the id discordid = discordid[3:-1] # format is <@!0123456789> and we need 01...
def check_restraint_pairs_for_doubles(list): # Also consider that a1 and a2 can be switches """ check_restraint_pairs_for_doubles checks a list of pairs for doubles. Pairs count as doubles if the order of elements is changed. Parameters ---------- list : t.List[t.Tuple] A list of...
def count_char(char, text): """Count number of occurences of char in text.""" return text.count(char)
def strip_dash(text): """ Strip leading dashes from 'text' """ if not text: return text return text.strip("-")
def arshift(x, disp): """Return x floor div (//) of two to the power of <disp>.""" return x // (2 ** disp)
def sim_file_to_run(file): """Extracts run number from a simulation file path Parameters ---------- file : str Simulation file path. Returns ------- run : int Run number for simulation file Examples -------- >>> file = '/data/ana/CosmicRay/IceTop_level3/sim/IC7...
def _check_type(type_, value): """Return true if *value* is an instance of the specified type or if *value* is the specified type. """ return value is type_ or isinstance(value, type_)
def axes_ticks_style(ticks=True): """toggle axes ticks on/off""" ticks_style = { "xtick.bottom": False, "ytick.left": False, } # Show or hide the axes ticks if ticks: ticks_style.update({ "xtick.bottom": True, "ytick.left": True, }) return ...
def concatSC(m, n, k=1): """Worst case state complecity for concatenation :arg m: number of states :arg n: number of states :arg k: number of letters :type m: integer :type n: integer :type k: integer :returns: state compelxity :rtype: integer""" return m * 2 ** n - k * 2 ** (n ...
def get_index_action(index_name, document_type, document): """Generate index action for a given document. :param index_name: Elasticsearch index to use :type index_name: str :param document_type: Elasticsearch document type to use :type index_name: str :param document: Document to be indexed ...
def unblock_list(blocked_ips_list, to_block_list): """ This function creates list of IPs that are present in the firewall block list, but not in the list of new blockings which will be sent to the firewall. :param blocked_ips_list: List of blocked IPs. :param to_block_list: List of new blockings. ...
def parse_parameters(parameters): """Parse job parameters""" return parameters.get('working_directory', '.'), parameters.get('extra', '')
def solution(N, A): """ This problem took me a good while to solve. The problem in itself is not hard, but the description is not very clear. I had to read it several times and even then, it took me a good few tries until I realised what it was asking me to do. If I had been given this task in ...
def Levenshtein(s1,s2): """return Levenshtein distance Parameters ---------- s1 : list list of activities, which is the first sequence to be aligned s2 : list list of activities, which is the second sequence to be aligned Returns ------- score : float Distan...