content
stringlengths
42
6.51k
def list_to_json(source_list): """ Serialise all the items in source_list to json """ result = [] for item in source_list: result.append(item.to_json()) return result
def kehrbruch(bruch): """berechnet den Kehrbruch zu einem Bruch der Form [zaehler, nenner]""" return [bruch[1], bruch[0]]
def convert_number(n): """ Convert number to , split Ex: 123456 -> 123,456 :param n: :return: """ if n is None: return '0' n = str(n) if '.' in n: dollars, cents = n.split('.') else: dollars, cents = n, None r = [] for i, c in enumerate(str(dollar...
def is_leq_than(x,y): """ x is not None and less than or equal to y """ if x != None: if x<=y: return True return False
def is_gremlin_entity(data): """utility method used to check to see if a value from a gremlin response is supposed to be an entity or not """ try: if not isinstance(data, (list, tuple, dict)): return False if isinstance(data, dict): data = [data, ] if is...
def arg_type_to_string(arg_type) -> str: """ Converts the argument type to a string :param arg_type: :return: String representation of the argument type. Multiple return types are turned into a comma delimited list of type names """ union_params = ( getattr(arg_type, '_...
def not_success(message=None, data=None): """ Get a web response with not success, message and data """ response = {"success": False} if message: response["message"] = message if data: response["data"] = data return response
def d_v_eos(v, v0, b0, b0p): """Numerical differentiation of Vinot EOS""" return ( b0 * (-1.5 * (b0p - 1) * ((v / v0)**(1 / 3) - 1)) * ( 1.5 * b0p * (v / v0)**(2 / 3) - 1.5 * b0p * (v / v0)**(1 / 3) - 1.5 * (v / v0)**(2 / 3) + 2.5 * (v / v0)**(1 / 3) - 2 ) ) / (v * (v...
def subdict(dictionary, keys): """ >>>a={1:3, 4:5, 6:7} >>>subdict(a, [4,6]) {4: 5, 6: 7} """ return (dict((k, dictionary[k]) for k in keys if k in dictionary) if len(keys) > 0 else dictionary)
def get_dict_value(dict_var, key, default_value=None): """ This is like dict.get function except it checks that the dict_var is a dict in addition to dict.get. @param dict_var: the variable that is either a dict or something else @param key: key to look up in dict @param default_value: return va...
def media_attachment(url, content=None, options=None): """iOS media_attachment builder. :keyword url: String. Specifies the URL to be downloaded by the UA Media Attachment extension. :keyword content: Optional dictionary. Describes portions of the notification that should be modified if the...
def _binary_repr(num: int, width: int) -> str: """Return a binary string representation of `num` zero padded to `width` bits.""" return format(num, 'b').zfill(width)
def parser_shortname(parser_argument): """Return short name of the parser with dashes and no -- prefix""" return parser_argument[2:]
def correct_mosaic_placement(p, avail, needed, full): """ ---------- Author: Damon Gwinn (gwinndr) ---------- - Helper for place_image_mosaic - Corrects given point, p, and available dim, avail, so that avail >= needed - Function may do no corrections if avail >= needed already - Functio...
def EI(inc): """ Given a mean inclination value of a distribution of directions, this function calculates the expected elongation of this distribution using a best-fit polynomial of the TK03 GAD secular variation model (Tauxe and Kent, 2004). Parameters ---------- inc : inclination in d...
def spring1s(ep,ed): """ Compute element force in spring element (spring1e). :param float ep: spring stiffness or analog quantity :param list ed: element displacements [d0, d1] :return float es: element force [N] """ k = ep return k*(ed[1]-ed[0]);
def sortable(obj): """Returns True if *obj* is sortable else returns False.""" try: sorted([obj, obj]) return True except TypeError: return False
def _size(width, height): """Performs a non-proportional resize.""" return ("-vf", r"scale={width}:{height}".format(width=width, height=height))
def pick_from_candle(candle_list, pick='close'): """Transform candle API result Args: candle_list (list): list of dict, coin candle data. pick (str): 'close', 'open', 'low', 'high', 'volume', 'timestamp' Returns: list, list of value """ k = {'close': 'c', 'open': '...
def cal_DTP_HP(Pin_ast, Pout, Pper): """ Calculate Delta_T P for Hagen-Poiseuille (HP) flow using Eq. (8) in [1] No particle-contributed osmotic pressure """ return (1/2.)*(Pin_ast + Pout) - Pper
def fancy_join(lst, sep=", ", final_sep=" and "): """ Join a list using a different separator for the final element """ if len(lst) > 2: head, tail = lst[:-1], lst[-1] lst = [sep.join(head), tail] return final_sep.join(lst)
def _merge_1(left, right): """ Merge sorted lists left and right into a new list and return that new list. @param list left: left elements of desired list @param list right: right elements of desired list @rtype: list >>> _merge_1([1, 3, 5], [2, 4,6]) [1, 2, 3, 4, 5, 6] """ res...
def read_lines(filename): """Return split lines from file without line endings.""" try: input_file = open(filename) try: lines = input_file.read().splitlines() finally: input_file.close() except IOError: return None return lines
def _partition(s, sep, find): """ (str|unicode).(partition|rpartition) for Python 2.4/2.5. """ idx = find(sep) if idx != -1: left = s[0:idx] return left, sep, s[len(left)+len(sep):]
def dict_to_string(m: dict) -> dict: """Convert dict values to strings Parameters ---------- m : dict Returns ------- dict """ for k, v in m.items(): if isinstance(v, dict): m[k] = dict_to_string(v) else: m[k] = str(v) return m
def normalize_message(body): """Normalize the message body to make it commit-worthy. Mostly this just means removing HTML comments, but also removes unwanted leading or trailing whitespace. Returns the normalized body. """ while "<!--" in body: body = body[: body.index("<!--")] + body[...
def matrix_mult(a, b): """ Function that multiplies two matrices a and b Parameters ---------- a,b : matrices Returns ------- new_array : matrix The matrix product of the inputs """ new_array = [] for i in range(len(a)): new_a...
def _option_char(compiler): """-L vs /L""" return "-" if compiler != "Visual Studio" else "/"
def search_range(nums, target): """ Find first and last position of target in given array by binary search :param nums: given array :type nums : list[int] :param target: target number :type target: int :return: first and last position of target :rtype: list[int] """ result = [-1...
def IfIn(words, text, opr="or"): """[It take a array of words and checks if the words are present in the text and return their AND or OR relation mentioned in the arguments.] Args: words ([list of strings]): [The words to check if present in text] text ([string]): [The simple string text] ...
def common_path(path1, path2, common=[]): """ Compute the common part of two paths *path1* and *path2* """ if len(path1) < 1: return (common, path1, path2) if len(path2) < 1: return (common, path1, path2) if path1[0] != path2[0]: return (common, path1, path2) return common...
def get_properties(entity): """Returns the dictionary of properties of the given Entity.""" return entity.properties if hasattr(entity, 'properties') else entity
def is_all_same_value(a_list, test_val): """ Simple method to find whether all values in list are equal to a particular value. Args: a_list: The list being interrogated test_val: The value to compare the elements of the list against """ for val in a_list: if val != test_val...
def mod_rec_exponentiate(number, exponent, mod): """ Modular exponentiation - recursive method Complexity: O(logEXPONENT) Sometimes, when the number can be extremely big, we find the answer modulo some other number. We can do it in both the recursive and the serial way. For simplicity we just ...
def does_mount_point_exist(mnt): """ Checks whether the specified point moint exists. Args: mnt (str) : Mount point to check. Returns: True, if the specified mount point exists; otherwise False """ with open("/proc/mounts") as f: for line in f: devi...
def check_i(i): """ simply skips the urls without a comic or that the comic isn't an image """ if i == 404: """ this one took me a while to figure out turns out he skipped 404 for 'obvious reasons' """ return False if i == 1350 or i == 1608 or i == 2198: print...
def typeAndClickFileName(language: str) -> str: """ The name of the file where the Type and Click web application should be saved """ return language + "ClickTypist.html"
def rgb_to_hex(rgb) -> str: """ RGB to hex color code. Argument must be iterable. """ return "#" + "".join(map(lambda n: f"{n % 256:0>2x}", rgb[0:3]))
def findBorder(num, border): """ Determine if there is anything next to num (index) :param num: :param border: :return: """ if num < 0: return 0 if num > border: return border return num
def oc_process(row): """Create opencast processing details for an event""" conf = {"flagForCutting": "false", "flagForReview": "false", "publishToEngage": "true", "publishToHarvesting": "true", "straightToPublishing": "true"} process = {"workflow": row["workfl...
def join(a, b, sep="."): """Joins `a` and `b` using `sep`.""" if not a: return b return f"{a}{sep}{b}"
def average_key(value, key): """Returns the average value in a 'column' in a list of dictionaries or objects. Positional arguments: value -- list of dictionaries or objects to iterate through. Returns: Sum of the values. """ values = [r.get(key, 0) if hasattr(r, 'get') else getatt...
def recite_verse(verse_number): """Function that the verse from the twelve days of Christmas specified by its number""" verse_start = "On the {} day of Christmas my true love gave to me: " days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth",...
def average_data(imu1, imu2, imu3): """ Takes average of data from three IMU's :param imu1: acc, gyro, mag :param imu2: acc, gyro :param imu3: acc :return: averaged acc_data, gyro_data, mag_data """ avg_acc = [sum(x) / 3 for x in zip(imu1["acc"], imu2["acc"], imu3["acc"])] avg_gyro =...
def is_same_shape(d1, d2): """ Returns true if the two dictionaries have the same shape. Meaning same structure and keys, values may differ. """ if isinstance(d1, dict): if isinstance(d2, dict): # then we have shapes to check return (d1.keys() == d2.keys() ...
def get_soc_name(soc): """Returns the SOC name used in Elements.""" return soc.replace('-', '')
def _displaystr2num(st): """Return a display number from a string""" num = None for s, n in [('DFP-', 16), ('TV-', 8), ('CRT-', 0)]: if st.startswith(s): try: curnum = int(st[len(s):]) if 0 <= curnum <= 7: num = n + curnum ...
def eval_python(code_string): """ Evaluate Python expression ``code_string`` in the context of ``cui.api``. :param code_string: A string containing a python expression """ try: code_object = compile(code_string, '<string>', 'eval') except SyntaxError: code_object =...
def get_short(byte_str): """ Get a short from byte string :param byte_str: byte string :return: byte string, short """ short = int.from_bytes(byte_str[:2], byteorder="little") byte_str = byte_str[2:] return byte_str, short
def head(text, places=50): """ Get the first part of a string, append '...' if it was truncated. """ if len(text) <= places: return text short = ' '.join(text[:places - 2].split(' ')[:-1]) if len(short) < max(places * 0.8, places - 10): short = text[:places - 3] return short + '...'
def parse_mapping_file(filename): """Parse mapping file.""" mappings = {} with open(filename) as handle: for line in handle: line = line.strip().split() if len(line) < 2 or line[1] == "": # Skip line, if it does not contain names of both sources. ...
def fix_date(x): """ Fixes dates which are in 20xx """ temp = x.split('/') if int(temp[0]) > 12: year = temp[0] return x[5:] + '/' + year else: year = x.split('/')[2] if int(year) < 1900: if int(year) <= 19: return x[:-2] + '20' + year ...
def is_leading_low(x, j): """Return True if bit ``j`` is the lowest bit set in ``x``.""" return x & ((1 << (j+1)) - 1) == 1 << j
def remove_ribozyme_if_possible(rna_type, _): """ This will remove the ribozyme rna_type from the set of rna_types if there is a more specific ribozyme annotation avaiable. """ ribozymes = set(['hammerhead', 'hammerhead_ribozyme', 'autocatalytically_spliced_intron']) if 'ri...
def get_fqn(obj): """Get the fully qualified name of the given object.""" return f'{obj.__module__}.{obj.__name__}'
def get_rank_npes(n_tabs=2, tab_char=" "): """Generates the code for getting MPI rank and size This is to keep the block clean later on, but can also handle having a different number of indents with custom tab characters. Parameters ---------- n_tabs : int, optional The indentat...
def extractParameters(config): """ Extract only the parameters from the configuration. :param config: dict of the complete configuration :return: dict of just the parameters. """ parameters = {} for key in config: if key != 'identifier': values = config[key] ...
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i
def find_next_match(_list, _start_idx, _match): """Finds next _match from _start_idx""" for _curr_idx in range(_start_idx, len(_list)): if _list[_curr_idx] == _match: return _curr_idx return -1
def segment_id_to_name(sid): """ GOAL segment ID to name string """ if sid == 0: return "main" elif sid == 1: return "debug" elif sid == 2: return "top-level" else: return "INVALID-SEGMENT"
def iterative_mean(i_iter, current_mean, x): """Iteratively calculates mean using http://www.heikohoffmann.de/htmlthesis/node134.html. Originally implemented in treeexplainer https://github.com/andosa/treeexplainer/pull/24 :param i_iter: [int > 0] Current iteration. :param current_mean: [ndarray] C...
def get_outputfilename(modname): """get the name of the file that the module is being documented in""" return modname+".html"
def get_type_abbrev(ctype): """Converts course type to an abbreviation""" ctypes = {'Lecture': 'Lec','Tutorial': 'Tut','Conference': 'Conf','Seminar': 'Sem','Laboratory': 'Lab','Student Services Prep Activity': 'StudSrvcs'} if ctype in ctypes: return ctypes[ctype] else: return ctype
def _module_parser(modules): """Returns an ordered dict of module classes to be run""" if not modules: return {} modules_str_list = modules.split(";") result_modules = {} for index, module in enumerate(modules_str_list): if module.startswith("custom/"): module_class = ...
def find_max_patterns(patterns): """ This function simply returns the class value with the highest count of patterns, and is used in conjunction with get_num_patterns """ max_pattern = None max_value = -1 for p in patterns: if max_pattern is None or max_value < patterns[p]: ...
def prunecontainers(blocks, keep): """Prune unwanted containers. The blocks must have a 'type' field, i.e., they should have been run through findliteralblocks first. """ pruned = [] i = 0 while i + 1 < len(blocks): # Searching for a block that looks like this: # # +...
def is_symbol(c: str) -> bool: """! Checks belonging of the symbol to the alphabet param c symbol return: True is in alphabet return: False not in the alphabet """ return 'a' <= c <= 'z'
def clean_instance_id(string): """ clean a string so that it can be used as an instance id """ return str(string).title().strip().replace(" ", "")
def GenerateDictionaryString(inputDict): """Return a string extracted from a dictionary""" resultString = "" for key, word in inputDict.items(): resultString += key + word + '\n' # When decompressing we need to know when the dictionary ends # We use this string to mark the end of the dicti...
def path(path=""): """ Will return the specified path joined with os.getcwd(). """ import os return os.path.join(os.getcwd(), path)
def bounding_box(points): """returns a list containing the bottom left and the top right points in the sequence Here, we use min and max four times over the collection of points """ top_left_x = min(point[0] for point in points) top_left_y = min(point[1] for point in points) bot_r...
def item_list(items): """Generate normal-text version of list of items, with commas and "and" as needed.""" return ' and '.join(', '.join(items).rsplit(', ', 1))
def merge_diagnoses(args): """Merge lines of diagnosis produced by diagnose()""" if not args: return '' args = [a.rstrip() for a in args] result = [' '] * max([len(a) for a in args]) for text in args: for i, c in enumerate(text): if c != ' ': result[i] =...
def list2str(alist, add_space=True): """ Concatenate elements of a list into a string param alist: list of items """ my_string = "" for item in alist: if add_space: my_string = my_string + " " + item my_string = my_string.strip() else: my_s...
def SaveEnergy(NumberOfNodes, E_guess, E_guess_try): """This function saves the guessed energy and the number of nodes corresponding to it. Parameter: ---------- NumerberOfNodes (int) : Defines the number of nodes in the wave function (the number of time this function passed by the x axis). The num...
def evaluate(data): """ Cost function evaluation parameters: - average_total_time - average_total_queue_time - average_utility_rate (inverse relationship) """ average_total_time = sum(v[10] - v[0] for v in data.values()) / len(data.values()) average_t...
def cgi_decode(s): """Decode the CGI-encoded string `s`: * replace "+" by " " * replace "%xx" by the character with hex number xx. Return the decoded string. Raise `ValueError` for invalid inputs.""" # Mapping of hex digits to their integer values hex_values = { '0': 0, '1': 1...
def convert_to_int(s): """Convert any object to int if possible, otherwise return original object.""" try: return int(s) except (ValueError, TypeError): return s
def get_base_branch(cherry_pick_branch): """ return '2.7' from 'backport-sha-2.7' """ prefix, sep, base_branch = cherry_pick_branch.rpartition('-') return base_branch
def poincare_polydisk_params(n_samples): """Generate poincare polydisk benchmarking parameters. Parameters ---------- n_samples : int Number of samples to be used. Returns ------- _ : list. List of params. """ manifold = "PoincarePolydisk" manifold_args = [(3,),...
def _escape_ffarg(arg): """ Escape FFmpeg filter argument. See ffmpeg-filters(1), "Notes on filtergraph escaping". """ arg = arg.replace('\\', r'\\') # \ -> \\ arg = arg.replace("'", r"'\\\''") # ' -> '\\\'' arg = arg.replace(':', r'\:') # : -> \: return "'{}'".format(arg)
def data_cleaning(post: dict): """ Functionality to clean up data and pass back only desired fields :param post: dict content and metadata of a reddit post :return: tuple of fields for insertion into database """ unwanted_authors = ['[deleted]', '[removed]', 'automoderator'] # sk...
def generate_unsafe_secgroup_entry(security_group: dict, unsafe_ingress_entries: list) -> dict: """ Generates a dictionary from an unsafe security group, receiving all unsafe ingress entries related to this security group to the analysis response """ unsafe_group = { "GroupName": securit...
def _is_variable_assignation(line: str) -> bool: """Check if the line is a variable assignation. This function is used to check if a line of code represents a variable assignation: * if contains a "=" (assignation) and does not start with import, nor @, nor def, nor class. * then it is ==> is...
def sexticipc(ipparams, position, etc = []): """ This function fits the intra-pixel sensitivity effect using a 2D 6th-order polynomial, with cross terms. Parameters ---------- y#: #-ordered coefficient in y x#: #-ordered coefficient in x y2x: cofficient for cross-term xy^2 x2y: coefficien...
def _get_quantification_value(metadata): """Gets the quantification value (to compute correct reflectances)""" if metadata['PROCESSING_LEVEL'] == 'Level-1C': quantification_value = float(metadata['QUANTIFICATION_VALUE']) else: # L2A quantification_value = float(metadata['BOA_QUANTIFICATION...
def _compute_tick_multiplier(interval: float) -> int: """ The tick multiplier is the order of magnitude by which the ``interval`` has to be multiplied such that the interval is a number >= 1. The tick multiplier simplifies the math to determine the sub slot count when the ``Clock``'s tick interval ...
def trapezoid_area(base_minor, base_major, height): """Returns the area of a trapezoid""" return height * (base_minor + base_major) / 2
def perturbDemandConstant(g, constant): """ Perturb demand by a random constant value Parameters ---------- g: demand dict max_var: maximum percentage of the demands which is goinf to variate either increase or decrease Returns ------- a perturbed demand dict """ a = {} ...
def check_terse_mode(text): """ example: please no need to say please print this works print no need to say please before each line """ terse_mode_on = False checkphrases = ['please no need to say please', 'please use enter mode', 'please use short...
def count_increases_in_window(numbers, window_length=3): """Count number of times sum of the window with window_length increases.""" increases = 0 for index, _ in enumerate(numbers[:-window_length]): prev_window = sum(numbers[index:index + window_length]) cur_window = sum(numbers[index + 1:i...
def add_plugin_to_endpoints(endpoints, plugin): """ Add the endpoint key to each endpoint dictionary in the list :param endpoints: List of endpoint dictionaries :param plugin: String of the plugin name """ for endpoint in endpoints: endpoint.update({ 'plugin': plugin, ...
def cylinder_volume(height, radius): """ Function to calculate the volume of the cylinder """ pi = 3.14159 return height * pi * (radius ** 2)
def _drop(x): # pylint: disable=invalid-name """Helper: pop top element of a stack (make it a non-list if length is 1).""" result = x[1:] if len(result) == 1: return result[0] return result
def _get_BD_range(x): """Getting the BD range from a fraction ID (eg., "1.710-1.716"). Parameters ---------- x : str fraction ID Returns ------- tuple -- BD start, middle end """ if x.startswith('-'): [start,_,end] = x.rpartition('-') else: [start,_...
def solve(task): """Solve puzzle. Args: task (str): Puzzle input Returns: int: Puzzle solution """ answer = None level = 0 i = 0 for char in task: i += 1 if char == "(": level += 1 elif char == ")": level -= 1 if ...
def _separate_substructures(path): """Returns a list of subpaths, each representing substructures the glyph.""" substructures = [] curr = [] for cmd in path: if cmd[0] in 'mM' and curr: substructures.append(curr) curr = [] curr.append(cmd) if curr: sub...
def space_out_camel_case(stringAsCamelCase): """ Note to self: There has to be a better way. """ part = [] parts = [part] for this, next in zip(stringAsCamelCase, stringAsCamelCase[1:] + "#"): part.append(this) if this.islower() != next.islower(): part = [] ...
def transform_query_results(rows): """ Transform query results """ dates_map = {} for row in rows: date = row[0] resource = row[1] count = row[2] date_data = dates_map.get(date) if not date_data: date_data = {} date_data['date'] = date ...
def _calculate_varint_size(value): """For an integral value represented by a varint, calculate how many bytes are necessary to represent the value in a protobuf message. (see https://developers.google.com/protocol-buffers/docs/encoding# varints) Args: value (int) - The value whose varint ...