content
stringlengths
42
6.51k
def find(collection, item, field='name'): """ Finds an element in a collection which has a field equal to particular item value Parameters ---------- collection : Set Collection of objects item value of the item that we are looking for field : string Name of the ...
def remove_suffix(suffix, string): """Removes suffix for string if present. If not, returns string as is Example: remove_suffix(".com", "example.com") => "example" """ if string.endswith(suffix): ls = len(suffix) return string[:-ls] else: return string
def interpolate(a0, a1, w): """ Interpolate between the two points, with weight 0<w<1 """ # return (a1 - a0) * w + a0 # Can make this smoother later return (a1 - a0) * ((w * (w * 6.0 - 15.0) + 10.0) * w * w * w) + a0
def get_email_headers(email) -> dict: """ Extracts the headers from the email and returns them as a dict. :param email: The email to extract the sender from. :return: The headers of the email. """ headers = {"sender": "N/A", "subject": "N/A"} for header in email["payload"]["headers"]: ...
def parse_table_name(default_schema, table_name, sql_mode=""): """Parse table name. Args: default_schema (str): The default schema. table_name (str): The table name. sql_mode(Optional[str]): The SQL mode. Returns: str: The parsed table name. """ quote = '"' if "ANSI...
def jaccard_score(a, b, ab): """Calculates the Jaccard similarity coefficient between two repositories. :param a: Number of times the second event occurred w/o the first event :param b: umber of times the first event occurred w/o the second event :param ab: Number of times the two events occurred toget...
def write_file(bytes, path: str): """Write to disk a rexfile from its binary format""" newFile = open(path + ".rex", "wb") newFile.write(bytes) return True
def alterModelDef(dbTuple, name=None, format=None, dbType=None, single=None, official=None, numver=None, purgeAge=None): """Alter GFE database definition. The definition is used in the dbs setting and has form: (name, format, type, single, official, numVer, purgeAge) ...
def inputs(form_args): """ Creates list of input elements """ element = [] html_field = '<input type="hidden" name="{}" value="{}"/>' for name, value in form_args.items(): element.append(html_field.format(name, value)) return "\n".join(element)
def has_duplicates(s): """Returns True if any element appears more than once in a sequence. s: string or list returns: bool """ # make a copy of t to avoid modifying the parameter t = list(s) t.sort() # check for adjacent elements that are equal for i in range(len(t)-1): if ...
def gcd(a: int, b: int) -> int: """ Computes the gcd of a and b using the Euclidean algorithm. param a: int param b: int return: int gcd of a and b """ while b != 0: a, b = b, a % b return a
def _join_prefix(prefix, name): """Filter certain superflous parameter name suffixes from argument names. :param str prefix: The potential prefix that will be filtered. :param str name: The arg name to be prefixed. :returns: Combined name with prefix. """ if prefix.endswith("_specification")...
def tagsoverride(msg, override): """ Merge in a series of tag overrides, with None signaling deletes of the original messages tags """ for tag, value in override.items(): if value is None: del msg[tag] else: msg[tag] = value return msg
def value_to_angle(value, min_val, max_val): """Return angle for gauge plot""" angle = (value - min_val) / (max_val - min_val) angle *= 180 angle = max(min(angle, 180), 0) return 180 - angle
def centeroidOfTriangle(pa, pb, pc): """ when given 3 points that are corners of a triangle this code calculates and returns the center of the triangle. the exact type of center is called "centeroid". it is the intersection point of the connection of each angle to the middle of its opposed edge....
def red(s): """Color text red in a terminal.""" return "\033[1;31m" + s + "\033[0m"
def add_newlines_by_spaces(string, line_length): """Return a version of the passed string where spaces (or hyphens) get replaced with a new line if the accumulated number of characters has exceeded the specified line length""" replacement_indices = set() current_length = 0 for i, char in enumerate(st...
def _get_last_layer_units_and_activation(num_classes, use_softmax=True): """Gets the # units and activation function for the last network layer. Args: num_classes: Number of classes. Returns: units, activation values. """ if num_classes == 2 and not use_softmax: activation ...
def format_text_list(text_list): """Create a formatted version of the given string according to MCF standard. This is used to format many columns from the drugs and genes dataframes like PubChem Compound IDentifiers or NCBI Gene ID. Args: text_list: A single string representing a comma separat...
def C(b: int) -> dict: """Setting up type mismatch.""" return {'hi': 'world'}
def split_choices(choices, split): """Split a list of [(key, title)] pairs after key == split.""" index = [idx for idx, (key, title) in enumerate(choices) if key == split] if index: index = index[0] + 1 return choices[:index], choices[index:] else: return choices, []
def break_condition_final_marking(marking, finalMarking): """ Verify break condition for final marking Parameters ----------- marking Current marking finalMarking Target final marking """ finalMarkingDict = dict(finalMarking) markingDict = dict(marking) finalMark...
def create_paths(inputs): """Create an adjancency list of orbitor -> orbitee With the restriction that each object only orbits one other, this could/should have been a simple map, which might have made things easier """ objects = {} for line in inputs: try: a, b = line.split...
def divide_list(input_list, n): """ Split a list into 'n' number of chunks of approximately equal length. Based on example given here: https://stackoverflow.com/questions/2130016/splitting-a-list-of-into-n-parts-of-approximately-equal-length :param input_list: list list to be split :p...
def fibonacci(n): """ Return the n-th Fibonacci number :param n: n-th fibonacci number requested :return: the n-th Fibonacci number """ if n in (0, 1): return n return fibonacci(n - 2) + fibonacci(n - 1)
def integrate(x_dot, x, dt): """ Computes the Integral using Euler's method :param x_dot: update on the state :param x: the previous state :param dt: the time delta :return The integral of the state x """ return (dt * x_dot) + x
def extendGcd(a, b): """ ax + by = gcd(a, b) = d (Introduction to Algorithms P544) we have two case: a. if b == 0 ax + 0 = gcd(a, 0) = a --> x = 1 y = 0,1,... --> y = 0 b. if a*b != 0 then, ax + by = ax' + (a%b)y'.And a % b = a - (a/b)*b so, ax + by= ay' +...
def f_check_param_definition(a, b, c, d, e): """Function f Parameters ---------- a: int Parameter a b: Parameter b c : Parameter c d:int Parameter d e No typespec is allowed without colon """ return a + b + c + d
def add_collect_stats_qs(url, value): """if :url is `page.html?foo=bar` return. `page.html?foo=bar&MINCSS_STATS=:value` """ if '?' in url: url += '&' else: url += '?' url += 'MINCSS_STATS=%s' % value return url
def approx_2rd_deriv(f_x0,f_x0_minus_1h,f_x0_minus_2h,h): """Backwards numerical approximation of the second derivative of a function. Args: f_x0: Function evaluation at current timestep. f_x0_minus_1h: Previous function evaluation. f_x0_minus_2h: Function evaluations two timesteps ago....
def usual_criterion(distance): """ implements usual criterion """ if distance > 0: return 1 else: return 0
def canon_besteffort(msg): """ Format is any: 2a00f6 2a#00f6 2a,00,f6 0x89,0x30,0x33 (123.123) interface 2a#00f6 ; comment (case insensitive) """ msg = msg.strip() msg = msg.split(';')[0] msg = msg.split(' ')[-1] msg = msg.replace(',', '') msg = msg.replace('#', '') msg...
def func2(x, y): """second test function Parameters ---------- x : int, float or complex first factor y : int, float or complex second factor Raises ------ ValueError if both are 0 Returns ------- product : int, float or complex the product ...
def remove_element_two_pointers(nums, val): """ Remove elements with given value in the given array :param nums: given array :type nums: list[int] :param val: given value :type val: int :return: length of operated array :rtype: int """ # traverse from left to right left = 0 ...
def rolling_average(current_avg: float, new_value: float, total_count: int) -> float: """Recalculate a running (or moving) average Needs the current average, a new value to include, and the total samples """ new_average = float(current_avg) new_average -= new_average / total_count new_average +...
def is_parenthetical(s): """ (str) -> bool Returns True if s starts with '(' and ends with ')' """ if len(s) < 2: return False else: return s[0] == "(" and s[-1] == ")"
def scientific_label(obj, precision): """ Creates a scientific label approximating a real number in LaTex style Parameters ---------- obj : float Number that must be represented precision : int Number of decimal digits in the resulting label Return...
def capitalize_first_letter(word): """ Function that capitalizes the first letters of words in the input.""" j = 0 capitalized_word = "" list_of_words_in_name = word.split() for word_in_name in list_of_words_in_name: i = 0 for char in word_in_name: if i == ...
def _dominates(w_fitness, w_fitness_other): """ Return true if ALL values are [greater than or equal] AND at least one value is strictly [greater than]. - If any value is [less than] then it is non-dominating - both arrays must be one dimensional and the same size, we don't check for this! """ ...
def _jinja2_filter_humanizetime(dt, fmt=None): """ humanizes time in seconds to human readable format Args: dt: fmt: Returns: """ days = int(dt / 86400) hours = int(dt / 3600) % 24 minutes = int(dt / 60) % 60 seconds = int(dt) % 60 microseconds = int(((dt % 1.0) ...
def _sort_merge(left: list, right: list) -> list: """Merge and sort list:left and list:right and return list:res""" res = [] i = j = 0 while(i < len(left) and j < len(right)): if left[i] <= right[j]: res.append(left[i]) i += 1 else: res.append(right[j]...
def indent(text: str, amount: int) -> str: """indent according to amount, but skip first line""" return "\n".join( [ amount * " " + line if id > 0 else line for id, line in enumerate(text.split("\n")) ] )
def to_tractime(t): """Convert time to trac time format. Type of t needs float, str or int.""" st = '' if isinstance(t, str): st = t else: st = repr(t) st = ''.join(st.split('.')) if len(st) > 16: st = st[0:16] elif len(st) < 16: st = st + '0' * (16 - len...
def aes_pad_ (data): """Adds padding to the data such that the size of the data is a multiple of 16 bytes data: the data string Returns a tuple:(pad_len, data). pad_len denotes the number of bytes added as padding; data is the new data string with padded bytes at the end """ pad_len = l...
def rosenbrock_grad(x, y): """Gradient of Rosenbrock function.""" return (-400 * x * (-(x ** 2) + y) + 2 * x - 2, -200 * x ** 2 + 200 * y)
def power_iterative(base, exp): """Funkce vypocita hodnotu base^exp pomoci iterativniho algoritmu v O(exp). Staci se omezit na prirozene hodnoty exp. """ output = 1 for i in range(exp): output *= base return output
def is_null(left: str, _right: None) -> str: """Check if the `left` argument doesn't exist.""" return left + ' IS NULL'
def extract_from_lib(lib): """Extract relevant parameters from lib. Returns ------- [plx, plx_e, dist, dist_e, rad, rad_e, temp, temp_e, lum, lum_e] """ if lib is None: return [-1] * 10 return [ lib.plx, lib.plx_e, lib.dist, lib.dist_e, lib.rad, lib.rad_e, ...
def move_location(current_location, direction): """Return a new (x, y) tuple after moving one unit in direction current_location should be tuple of ints (x, y) Direction is one of: ^ north v south > east < west """ direction_table = {"^": (0, 1), "v": (0, -1...
def poly_extend(p, d): """Extend list ``p`` representing a polynomial ``p(x)`` to match polynomials of degree ``d-1``. """ return [0] * (d-len(p)) + list(p)
def state_support(state): """ Count number of nonzero elements of the state """ n = 0 for s in state: if s != 0: n += 1 return n
def escape_backslash(s: str) -> str: """Replaces any \\ character with \\\\""" return s.replace('\\', '\\\\')
def _get_or_add(cfg, name): """Gets cfg[name], or adds 'name' with an empty dict if not present.""" if name not in cfg: cfg.update({name: {}}) return cfg[name]
def strip_quotes(text: str) -> str: """Remove the double quotes surrounding a string.""" text = text.strip(' "') return text
def _parse_draw_keys(keys): """Convert keys on input from .draw.""" kwargs = dict( char='', codepoint=None, tags=[], ) # only one key allowed in .draw, rest ignored key = keys[0] try: kwargs['char'] = chr(int(key, 16)) except (TypeError, ValueError): k...
def read_dm3_eels_info(original_metadata): """Reed dm3 file from a nested dictionary like original_metadata of sidpy.Dataset""" if 'DM' not in original_metadata: return {} main_image = original_metadata['DM']['chosen_image'] exp_dictionary = original_metadata['ImageList'][str(main_image)]['Imag...
def escape_url(raw): """ Escape urls to prevent code injection craziness. (Hopefully.) """ from urllib.parse import quote return quote(raw, safe="/#:")
def formatter(ms): """ formats the ms into seconds and ms :param ms: the number of ms :return: a string representing the same amount, but now represented in seconds and ms. """ sec = int(ms) // 1000 ms = int(ms) % 1000 if sec == 0: return '{0}ms'.format(ms) return '{0}.{1}s'....
def staircase(n: int, choices: set) -> int: """case 2 Generalized situation. In this case the sum would be f(n) = f(n-x1) + f(n-x2) + ... time complexity: O(n*|x|) space complexity: O(n) """ cache = [0] * (n + 1) cache[0] = 1 for i in range(1, n + 1): cache[i] = sum(cache[i - v]...
def _check_dict(values): """ Checks if dictionary's value is set to None and replaces it with an empty string. None values cannot be appended to in auditors. :param values: dictionary of key-values :return: configurations dictionary """ # check if value is None for key in values: ...
def rename(filepath: str, name: str, file_format: str, net: str) -> str: """ :param filepath: path to file to create a new name for :param name: name of the object drawn :param file_format: type of content: video, picture of rosbag :param net: mainnet/testnet :return: new filename with a filepat...
def placekitten_src(width=800, height=600): """ Return a "placekitten" placeholder image url. Example: {% placekitten_src as src %} {% placekitten_src 200 200 as mobile_src %} {% include 'components/image/image.html' with mobile_src=mobile_src src=src alt='placekitten' only %} ...
def call_if_callable(func, *args, **kwargs): """Call the function with given parameters if it is callable""" if func and callable(func): return func(*args, **kwargs) return None
def cohen_kappa(ann1: list, ann2: list, verbose=False): """Computes Cohen kappa for pair-wise annotators. :param ann1: annotations provided by first annotator :type ann1: list :param ann2: annotations provided by second annotator :type ann2: list :rtype: float :return: Cohen kappa statistic ...
def pars_to_descr(par_str): """ pars_to_descr() Converts numeric parameters in a string to parameter descriptions. Required args: - par_str (str): string with numeric parameters Returns: - par_str (str): string with parameter descriptions """ vals = [128.0, 256.0, 4.0, 1...
def str_to_bool(value): """Python 2.x does not have a casting mechanism for booleans. The built in bool() will return true for any string with a length greater than 0. It does not cast a string with the text "true" or "false" to the corresponding bool value. This method is a casting function. It is ...
def TSKVolumeGetBytesPerSector(tsk_volume): """Retrieves the number of bytes per sector from a TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. Returns: int: number of bytes per sector or 512 by default. """ # Note that because pytsk3.Volume_Info does not explicitly ...
def get_intersect_point(a1, b1, c1, d1, x0, y0): """Get the point on the lines that passes through (a1,b1) and (c1,d1) and s closest to the point (x0,y0).""" a = 0 if (a1 - c1) != 0: a = float(b1 - d1) / float(a1 - c1) c = b1 - a * a1 # Compute the line perpendicular to the line of the OF v...
def split_list(alist, wanted_parts=1): """ Split a list into a given number of parts. Used to divvy up jobs evenly. :param alist: list o' jobs :param wanted_parts: how many chunks we want :return: list o' lists """ length = len(alist) return [ alist[i * length // wanted_parts : (...
def complete_urls(setlist_urls): """Completes the setlist urls adding http://setlist.fm/ to each url""" complete_setlist_urls = [] for i in setlist_urls: link = "http://www.setlist.fm/" + i complete_setlist_urls.append(link) return complete_setlist_urls
def calculate_syntax_error_score(navigation_subsystem): """ Calculate syntax error score :param navigation_subsystem: list of chunks :return: syntax error score and filtered chunks """ score = 0 uncomplete_lines = [] for line in navigation_subsystem: stack = [] corrupte...
def fromVlqSigned(value): """Converts a VLQ number to a normal signed number. Arguments: value - A number decoded from a VLQ string. Returns: an integer. """ negative = (value & 1) == 1 value >>= 1 return -value if negative else value
def RPL_NOTOPIC(sender, receipient, message): """ Reply Code 331 """ return "<" + sender + ">: " + message
def format_number(num): """ Removing trailing zeros. :param num: input number :type num: float :return: formatted number as str """ str_num = str(num) if "." in str_num: splitted_num = str_num.split(".") if int(splitted_num[-1]) == 0: return "".join(splitted_...
def iterate_pagerank(corpus, damping_factor): """ Return PageRank values for each page by iteratively updating PageRank values until convergence. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All PageRank values should su...
def sub_size_tag_from_sub_size(sub_size): """Generate a sub-grid tag, to customize phase names based on the sub-grid size used. This changes the phase name 'phase_name' as follows: sub_size = None -> phase_name sub_size = 1 -> phase_name_sub_size_2 sub_size = 4 -> phase_name_sub_size_4 """ ...
def construct_engine_options(ts_directives, tm_engine_options, synctex=True): """Construct a string of command line options. The options come from two different sources: - %!TEX TS-options directive in the file - Options specified in the preferences of the LaTeX bundle In any case ``nonst...
def ParseNatList(ports): """ Support a list of ports in the format "protocol:port, protocol:port, ..." examples: tcp 123 tcp 123:133 tcp 123, tcp 124, tcp 125, udp 201, udp 202 User can put either a "/" or a " " between protocol and ports Port ranges can ...
def get_bucket_and_object(resource_name): """Given an audit log resourceName, parse out the bucket name and object path within the bucket. Returns: (str, str) -- ([bucket name], [object name]) """ pathparts = resource_name.split("buckets/", 1)[1].split("/", 1) bucket_name = pathparts[0] ...
def _slope_one(p, x): """Basic linear regression 'model' for use with ODR. This is a function of 1 variable. Assumes slope == 1.0. """ return x + p[0]
def get_videos_meta(frame_width, frame_height, total_frames): """ get frame's meta """ meta = [] meta4 = [] meta.append(dict(nframes = total_frames, H = frame_height * 4, W = frame_width * 4)) meta4.append(dict(nframes = total_frames, H = frame_height, W = frame_width)) return meta...
def length_func(list_or_tensor): """ Get length of list or tensor """ if type(list_or_tensor) == list: return len(list_or_tensor) return list_or_tensor.shape[0]
def _parse_output(out): """ >>> out = 'BLEU = 42.9/18.2/0.0/0.0 (BP=1.000, ratio=0.875, hyp_len=14, ref_len=16)' >>> _parse_output(out) [42.9, 18.2, 0.0, 0.0] :param out: :return: """ out = out[len('BLEU = '):out.find('(') - 1] numbers = out.split('/') return list(map(float, num...
def get_interface_type(interface): """Gets the type of interface Args: interface (str): full name of interface, i.e. Ethernet1/1, loopback10, port-channel20, vlan20 Returns: type of interface: ethernet, svi, loopback, management, portchannel, or unknown """ if in...
def get_intrinsic_name(signature): """ Get the intrinsic name from the signature of the intrinsic. >>> get_intrinsic_name("int8x8_t vadd_s8(int8x8_t a, int8x8_t b)") 'vadd_s8' >>> get_intrinsic_name("int32x4_t vaddl_high_s16(int16x8_t a, int16x8_t b)") 'vaddl_high_s16' >>> get_intrinsic_n...
def build_token_dict(vocab): """ build bi-directional mapping between index and token""" token_to_idx, idx_to_token = {}, {} next_idx = 1 vocab_sorted = sorted(list(vocab)) # make sure it's the same order everytime for token in vocab_sorted: token_to_idx[token] = next_idx idx...
def node_info(node_id, node_dict): """ ([(node_id, { 'label': 'diminuition...'))...] -> string with stats Takes a list of tuples (node_id, node_dict) Wraper which returns importance measures for a given node """ return '%s & %s & %.3f & %.3f' % (node_id, node_dict['label'], ...
def user_model(username): """Return a user model""" return { 'login': username, }
def myint(value): """ round and convert to int """ return int(round(float(value)))
def remove_keys_from_array(array, keys): """ This function... :param array: :param keys: :return: """ for key in keys: array.remove(key) return array
def get_prominent_color(layers): """returns the first non-transparent pixel color for each pixel""" final = [3] * len(layers[0]) for i in range(len(final)): for layer in layers: if layer[i] != 2: final[i] = layer[i] break return final
def to_c_str(v): """ Python str to C str """ try: return v.encode("utf-8") except Exception: pass return b""
def _get_filter_text(method, min_freq, max_freq): """Get the notes attribute text according to the analysis method and frequency range.""" filter_text = '%s with frequency range: %s to %s' %(method, min_freq, max_freq) return filter_text
def largest_minus_one_product(nums): """ Question 22.4: Find the maximum of all entries but one """ # iterate through and count number of negatives # least negative entry, least positive entry # greatest negative idx number_of_negatives = 0 least_negative_idx = -1 least_positive...
def total_cost(J_content, J_style, alpha = 10, beta = 40): """ Computes the total cost function Arguments: J_content -- content cost coded above J_style -- style cost coded above alpha -- hyperparameter weighting the importance of the content cost beta -- hyperparameter weighting the im...
def accusative(pronoun): """ Method to convert a pronoun to accusative form """ if pronoun == 'she': return 'her' elif pronoun in ['he','his']: return 'him' elif pronoun in ['they','their']: return 'them' else: return pronoun
def fuzzy_list_match(line, ldata): """ Searches for a line in a list of lines and returns the match if found. Examples -------- >>> tmp = fuzzy_list_match("data tmp", ["other", "data", "else"]) >>> print(tmp) (True, "data") >>> tmp = fuzzy_list_match("thing", ["other", "else"]) >>...
def filter_words(st): """ Write a function taking in a string like WOW this is REALLY amazing and returning Wow this is really amazing. """ return st.capitalize()
def nomial_latex_helper(c, pos_vars, neg_vars): """Combines (varlatex, exponent) tuples, separated by positive vs negative exponent, into a single latex string.""" pvarstrs = ['%s^{%.2g}' % (varl, x) if "%.2g" % x != "1" else varl for (varl, x) in pos_vars] nvarstrs = ['%s^{%.2g}' % (var...
def is_phrase_a_substring_in_list(phrase, check_list): """ :param phrase: string to check if Substring :param check_list: list of strings to check against :return: True if phrase is a substring of any in check_list, otherwise false >>> x = ["apples", "bananas", "coconuts"] >>> is_phrase_a_subs...