content
stringlengths
42
6.51k
def SumCoeffsOverIndexList(summing_list, A): """Returns the sum of the coefficient and summing lists mulitplied element-wise. """ return sum(A[i] * summing_list[i] for i in range(len(summing_list)))
def fixNewlines(text): """ Homogenise line endings. Different web clients send different line ending values, but other systems (eg. email) don't necessarily handle those line endings. Our solution is to convert all line endings to LF. """ if text is not None: text = text.rep...
def is_root(path): """Returns True if path is an image, False otherwise.""" components = path.split('/') return len(components) <= 1 or not components[1]
def first_true(iterable, default=False, pred=None): """ >>> first_true([None, 0, {}, 1, True, False]) 1 """ return next(filter(pred, iterable), default)
def _get_features_flags(features): """ Constructs a string containing the feature flags from the features specified in the features attribute. """ features_flags = [] for feature in features: features_flags += ["--cfg feature=\\\"%s\\\"" % feature] return features_flags
def get_scenario_start_index(naming_data): """ Get scenario start index from naming data :param naming_data: :return: """ if naming_data: scenario_indices = [val["scenario_index"] for val in naming_data.values()] return max(scenario_indices) + 1 return 1
def fmt(s): """ Helper for formating values with separator """ return '{:,}'.format(s)
def adjust_longitude(in_fc): """Adjusts longitude if it is less than -180 or greater than 180. Args: in_fc (dict): The input dictionary containing coordinates. Returns: dict: A dictionary containing the converted longitudes """ try: keys = in_fc.keys() if "geometr...
def _convert_ordering(layers): """Wrap nodes in a single band, if none are specified.""" for item in layers: if any(isinstance(x, str) for x in item): return tuple((tuple(layer_nodes), ) for layer_nodes in layers) return tuple(tuple(tuple(band_nodes) for band_nodes in layer_bands) ...
def PNT2TidalOcto_Tv16(XA,beta0PNT=0,beta1PNT=0): """ TaylorT2 1PN Octopolar Tidal Coefficient, v^16 Timing Term. XA = mass fraction of object beta0PNT = 0PN Octopole Tidal Flux coefficient beta1PNT = 1PN Octopole Tidal Flux coefficient """ XATo2nd = XA*XA XATo3rd = XATo2nd*XA XATo4th = XATo3rd*XA ...
def _link_to_json(value): """Returns a list representation of the specified HTTP Link header information. `value` is a string containing the link header information. If the link header information (the part of after ``Link:``) looked like this:: <url1>; rel="next", <url2>; rel="foo"; bar="baz"...
def is_less_than(val_a, val_b): """Return True if val_a is less than val_b (evaluate as integer)""" size = len(val_a) if size != len(val_b): return False for i in reversed(range(size)): if val_a[i] < val_b[i]: return True elif val_a[i] > val_b[i]: return F...
def square_to_point(sq): """(str) -> tuple Compute the (x, y) coordinates of the center of a square. Used to properly place the square's owner when it's captured. """ if sq == 'top_left': return (200, 400) elif sq == 'top_right': return (400, 400) elif sq == 'bottom...
def get_pointer_to(iter_, path, backpointers=[]): """Return the structure(s) holding the last key from the given path.""" if type(iter_) == list: out = [] for element in iter_: r = get_pointer_to(element, path, backpointers) if r is not None and r not in out: ...
def _sort_point_list(list, option=1): """option=1, ordered by y; option=0, ordered by x""" reorder_list = [] for i in range(len(list)-1): min, k = list[0][option], 0 for j in range(1,len(list)): if list[j][option] < min: min = list[j][option] k = j...
def avg(list): """ Compute the average of a list """ return sum(list) / float(len(list))
def df_update_status(df_row): """ Function used in dataframe's apply call to determine overall status of material as outcome of the analysis Parameters: ----------- df_row : dataFrame row """ yes_no_movement = 'YES -> without movements' yes_curr_stock = 'YES -> decrease current ...
def cero(f, df, x0, tol): """ busca un 0 de la funcion f con derivada df usando el algoritmo de Newton, con tolerancia tol, partiendo desde x_0 Params: :param f: la funcion a evaluar :param df: la derivada de la funcion f :param x0: la aproximacion inicial del 0 de f :pa...
def is_better(ori_value, comparing_value, is_greater): """ This module compare the two values based on what we are looking for (Min or Max). :param ori_value: Original value. :type ori_value: number :param comparing_value: New value to compare with. :type comparing_value: number :param ...
def unpackCommitPinUpdateMessage(msg): """if 'msg' is a commit-pin update message, return the repo, branch, and sha-hash of the updated pin.""" lines = msg.split("\n") if len(lines) < 4: return None firstline = "Updating pin " secondline = "New commit in pinned branch " thirdline = " ...
def modifyOutput(text, mod=None): """Modify the output text color to Discord. Use ``mod=o`` in order to get orange colored text as output :param text: Text to be modified :type text: string """ if mod == 'o': return '```fix\n{}\n```'.format(text) else: return text
def get_square_box(big, small): """ :param big: Bigger side :param small: Smaller side :return: tuple(x1,x2,y1,y2) if big is width and (y1,y2,x1,x2) if big is height """ b1 = (big - small) / 2 b2 = b1 + small s1 = 0 s2 = small return b1, b2, s1, s2
def to_multiline_string(data, end_of_line="\r\n"): """Return a string from a list""" if hasattr(data, "__iter__"): data = end_of_line.join(data) return data
def create_empty_endpoint_dict(full_values): """ Creates an empty endpoint dictionary (for use in other functions) """ endpoint_dict = {"IPAddress": [], "OS": []} # type: dict if full_values: endpoint_dict["MACAddress"] = [] endpoint_dict["Domain"] = [] return endpoint_dict
def counting_valleys(n, s): """altitude, down_count, valley_count = 0, 0, 0 for i in range(len(s)): letter = s[i] if letter == 'U' and altitude < 0: altitude += 1 # if down_count > 0: # down_count -= 1 elif letter == 'D': # down_count += 1 ...
def extract_in_files(in_file_string): """ Parses sting of paths for individual input files. Args: in_file_string (string): collection of paths """ split_list = in_file_string.split(".csv") in_file_tup = () for num, path in enumerate(split_list): in_file_tup += (path[1:] + ".csv",) if num != 0...
def _get_record_depends(fn, record, instructions): """ Return the depends information for a record, including any patching. """ record_depends = record.get('depends', []) if fn in instructions['packages']: if 'depends' in instructions['packages'][fn]: # the package depends have already b...
def odds_to_probability(odds): """Convert odds to proportion. Returns the corresponding proportion Return proportion/probability odds: -odds that is desired to transform into a proportion """ return odds / (1 + odds)
def remove_newlines(bib): """Removes all newlines with spaces in the values of a dictionary result item""" for key in bib: bib[key] = bib[key].replace('\n',' ') return bib
def RemoveAcents(Names): """ Put the plant type in the initial caracter (S or E), and remove the acents INPUTS Names : list of names OUTPUTS List of plant names corrected """ acent = [u'\xe1',u'\xe9', u'\xed', u'\xf3',u'\xfa'] vowel = ['a', 'e', 'i', 'o', 'u'] Nam = Names.cop...
def compute_temp_terminus(temp, temp_grad, ref_hgt, terminus_hgt, temp_anomaly=0): """Computes the (monthly) mean temperature at the glacier terminus, following section 2.1.2 of Marzeion et. al., 2012. The input temperature is scaled by the given temperature gradient and the elevat...
def parse_lossless_compression_options(arguments): """ Function to parse compression options for the lossless case Input ----- arguments: list of strings Output ----- compression_method : "lossless" compression_opts: tuple (backend:string, clevel:int) ...
def is_toa5(record): """ Utility function to check if a supplied record (as generated by hievpy.search) is in TOA5 format Input ----- Required - record: record object returned by the search function Returns ------- True or False """ if record['format'] == 'TOA5' and record['f...
def merge(user, default): """Merges a user configuration with the default one. Merges two dictionaries, replacing default values of similar matching keys from user. Parameters: user (dict): A user defined dictionary default (dict): Returns: A new merged diction...
def add_one(number): """ Example of a simple function. Parameters ---------- number: int, float, str Returns ------- out: int, float, str The input value plus one. Raises TypeError if the input is not the expected type """ if isinstance(number, (float, int)): ...
def intersection(A, D, tangA, tangD): # <<< """returns the intersection parameters of two evens they are defined by: x(t) = A + t * tangA x(s) = D + s * tangD """ det = -tangA[0] * tangD[1] + tangA[1] * tangD[0] try: 1.0 / det except ArithmeticError: return None, No...
def DictInvert(aDict): """\\ Inverts a dictionary; {(key,value)} is turned into {(value, [key1, key2, ...])}. For example, {(1,'a'), (2,'b'), (3,'a')} is turned into {('a',[1,3]), ('b',2)} """ invDict = {}; for k,v in aDict.items(): invDict[v] = invDict.get(v, []); invDict[v].app...
def write_number(num): """Return the written English language string representation of *num* :param num: An integer number For example:: >>> write_num(132) >>> 'one hundred and thirty-two' """ ones = ["zero","one","two","three","four","five","six","seven","ei...
def combine_players_seasons_games_lists(players, seasons, games): """ """ # only add seasons for players we know about for season in [valid_season for valid_season in seasons if players.has_key(valid_season.id())]: players[season.id()].add_season(season) # only add games for players we know ab...
def sliding_box(start, stop, size, step=1): """ Find sliding boxes of region Parameters: ----------- start: int 0 based start coordinate of the region. stop : int 0 based stop coordinate of the region, i.e. stop is not part of the region anymore; size : int T...
def cpe(*args): """Concatenate values as strings using ':', replace None with '*' :param args: sequence of values :return: string in CPE format """ return ":".join(map(lambda x: "*" if x is None else str(x), args))
def build_request_message_view( actions_fixture: dict = {} ): """ Create a message containing a given action """ return { "type": "block_actions", "user":{ "id": "user_id", "username": "username", "name": "name", "team_id": "team_id" }, "api_app_id":...
def car(lst): """ :param lst: :return: """ return (lst or [None])[0]
def combine_files(*args): """ Combines file dictionaries as returned by the methods of Dataset. :param args: file dictionaries :return: combined file dictionaries """ if len(args) < 1: raise ValueError('Pass at least one argument!') # make sure all elements contain the same numb...
def is_namedtuple(x): """Return whether ``x`` is an instance of a namedtuple.""" return isinstance(x, tuple) and hasattr(x, '_fields')
def neg2D(v2D): """Returns the negative of the vector""" return -v2D[0], -v2D[1]
def UnderscoreToLowerCamelCase(text): """Convert underscores to lower camel case (e.g. 'foo_bar' --> 'fooBar').""" parts = text.lower().split('_') return parts[0] + ''.join(part.capitalize() for part in parts[1:])
def ast_rotate_left(ast): """Performs a left rotation of the binary AST around its root. Args: ast: The AST dict. Returns: The new root of the rotated AST. """ root = ast if "right" in root: # If root is binary pivot = root["right"] if "left" in pivot: # If pi...
def chunks(l, n): """Yield successive n-sized chunks from l. Args: l:``list`` list of data n:``int`` n-sized Return: list of list: [[]] """ temp_l = [] for i in range(0, len(l), n): temp_l.append(l[i : i + n]) return te...
def get_size(num: int) -> int: """ Finds the amount of bits on integer """ if num < 0: return 32 count: int = 0 while num > 0: num >>= 1 # Removes one bit from integer count += 1 return count
def _stringify(x): """Converts dict values to strings. Useful for mapping integer labels.""" return {k: str(v) for k, v in x.items()}
def tokenizeFloat(token, tokens, char, parseFloatState): """ Incrementally parse floats as a single token Floats are a special case of tokenization because '+' and '-' are valid components @param token: the token that has been built so far @param tokens: the list of tokens to modify @param char: the next characte...
def join(strin, items): """ Ramda implementation of join :param strin: :param items: :return: """ return strin.join(map(lambda item: str(item), items))
def centres(L): """ L est une liste de taille n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Renvoie une liste de longueur n-1 contenant les valeurs (L[i]+L[i+1])/2. """ R=[] for i in range(len(L)-1): R.append((L[i]+L[i+1])/2) return R
def build_patt_header(text=''): """return standard header for pattern """ if text == '': text = 'Patterns per instrument:' return [text, '']
def dist_to_px(dist, spacing): """ distance in um (or rather same unit as the spacing) """ dist_px = int(round(dist / spacing)) return dist_px
def get_features(waze_info, properties, num_snapshots): """ Given a dict with keys of segment id, and val a list of waze jams (for now, just jams), the properties of a road segment, and the total number of snapshots we're looking at, update the road segment's properties to include features Args:...
def soft_min_max(values, soft_add=1, soft_bounds=1): """ Returns [min, max + soft_add] if difference of min and max is less than the soft bound. Args: values: Iterable of numeric. soft_add: Increment to max if difference is too small. soft_bounds: If difference is smaller than...
def _pick_repository(parameters_json: dict) -> str: """ return ARCHT for Architectural Lantern Slides, else UNDA """ part_of = parameters_json.get('partOf', '') while isinstance(part_of, list): part_of = part_of[0] if parameters_json.get('collectionId', '') == "qz20sq9094h" or "qz20sq9094h" in p...
def fib(n): """Return the nth fibonacci number. >>> fib(6) 8 >>> [fib(n) for n in range(6)] [0, 1, 1, 2, 3, 5] >>> fib(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 """ if not n >= 0: raise ValueError("n must be >= 0") i, a, b = 0, 0...
def subclassof(c, b): """Wrap issubclass to return True/False without throwing TypeError""" try: return issubclass(c, b) except TypeError: return False
def strip_name(name): """ Remove the last component of a Lean name.""" return '.'.join(name.split('.')[:-1])
def changes(new_cmp_dict, old_cmp_dict, id_column, columns): """Return a list dict of the changes of the rows that exist in both dictionaries User must provide an ID column for old_cmp_dict """ update_ldict = [] same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict)) for same_ke...
def parse_dict_from_string(a_string): """ This takes a string that is formatted to create a dict. The format is that each key/value pair is separated by a "," and each key and value are separated with a ":" Args: a_string (int): The input string Returns: A dictionary with the functions...
def _incrementResourceVersion(version): """ Pyrsistent transformation function which can increment a ``v1.ObjectMeta.resourceVersion`` value (even if it was missing). :param version: The old version as a ``unicode`` string or ``None`` if there wasn't one. :return unicode: The new version, ...
def make_args_string(args_dict): """ - args_dict: dict, the dictionary of local variable to value such as returned by locals() RETURN: string, all arguments in a string """ return ", ".join( [f"{k}={repr(v)}" for k, v in reversed(list(args_dict.items()))])
def escape(html): """ Replaces ampresands, quotes and carets in the given HTML with their safe versions. :return: Escaped HTML """ return html.replace('&', '&amp;').replace('<', '&lt;').replace(' > ', '&gt;').replace('"', '&quot;').replace("'", '&#39;')
def runge_kutta4(current_y, y_deriv_func, step): """ Fourth order Runge Kutta http://lpsa.swarthmore.edu/NumInt/NumIntFourth.html for example y' = -2*y then y_deriv_func = y' that accepts y and y is current_y """ k1 = y_deriv_func(current_y) y1 = current_y + k1 * step / 2 k...
def get_nodes(G,**kwargs): """ search nodes having the given attributes :param G: graph where nodes are searched :param kwargs: atom= , in_cycle= :return: a list of nodes :rtype: list """ nodes=[] if G!=None: for n in G.nodes(): match=True for k,v...
def get_formatted_chrm(chr_string): """ Returns chromosome as an integer or -1 if invalid. """ #Check for start with chr if chr_string.lower().startswith("chr"): chr_string=chr_string[3:] #Check for X if chr_string.lower() == "x": return 23 if chr_string.lower() == "y": return 24 if chr_string.isdigi...
def only_ascii(value: str) -> str: """ Remove non-ascci characters. """ return "".join(char for char in value if ord(char) < 128)
def rgb_to_hex(rgb): """ Covert RGB tuple to Hex code """ return f'0x{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}'
def compare(value1, value2, comparison): """ Compare 2 values :type value1: object :param value1: The first value to compare. :type value2: object :param value2: The second value to compare. :type comparison: string :param comparison: The comparison to make. Can be "is", "or", "and". ...
def step_count(group_idx): """Return the amount of index changes within group_idx.""" cmp_pos = 0 steps = 1 if len(group_idx) < 1: return 0 for i in range(len(group_idx)): if group_idx[cmp_pos] != group_idx[i]: cmp_pos = i steps += 1 return steps
def drawAsInfinite(requestContext, seriesList): """ Takes one metric or a wildcard seriesList. If the value is zero, draw the line at 0. If the value is above zero, draw the line at infinity. If the value is null or less than zero, do not draw the line. Useful for displaying on/off metrics, such as exit c...
def _partition_name(dev): """ Derive the first partition name for a block device :param: dev: Full path to block device. :returns: str: Full path to first partition on block device. """ if dev[-1].isdigit(): return '{}p1'.format(dev) else: return '{}1'.format(dev)
def calculate_inverse_density(cluster): """Calculate the inverse of Density of a cluster. inverse of density = volume / size Args: clusters (list): list of clusters Returns: float: inverse of density """ inverse_density = cluster['volume'] / cluster['size'] return inverse...
def affine(r, c, x0, dxx, dyx, y0, dxy, dyy): """ Returns the affine transform -- normally row, column to x,y position. If this is the geotransform from a gdal geotiff (for example) the coordinates are the displayed pixel corners - not the center. If you want the center of the pixel then use affine_cent...
def isLevel(lvl): """renvoit 1 si c'est un level correct 0 sinon""" assert isinstance(lvl, int) if lvl <= 40 and lvl > 0: return 1 else: return 0
def monthly_soil_heat_flux2(t_month_prev, t_month_cur): """ Estimate monthly soil heat flux (Gmonth) [MJ m-2 day-1] from the mean air temperature of the previous and current month, assuming a grass crop. Based on equation 44 in Allen et al (1998). If the air temperature of the next month is availabl...
def SPLIT(expression, delimiter): """ Divides a string into an array of substrings based on a delimiter. https://docs.mongodb.com/manual/reference/operator/aggregation/split/ for more details :param expression: The string or expression of the string :return: Aggregation operator """ retu...
def _get_transition_attr(trans_prod, transition_attr_operations): """Return the attribute of a transition constructed by taking the product of transitions in trans_prod. @type trans_prod: `list` of `Transitions` objects @type transition_attr_operations: `dict` whose key is the transition attribute key ...
def tune_step_size_random_walk(step_size, acc_rate): """Keep acceptance rate within 25% - 40% acceptance.""" if acc_rate < 0.001: step_size *= 0.1 elif acc_rate < 0.05: step_size *= 0.5 elif acc_rate < 0.25: step_size *= 0.9 elif acc_rate > 0.95: step_size *= 10.0 ...
def url_pattern(pattern: str): """ Convert a string *pattern* where any occurrences of ``{{NAME}}`` are replaced by an equivalent regex expression which will assign matching character groups to NAME. Characters match until one of the RFC 2396 reserved characters is found or the end of the *pattern* is r...
def distance_squared(a, b): """The square of the distance between two (x, y) points.""" xA, yA = a xB, yB = b return (xA - xB)**2 + (yA - yB)**2
def periods_constructor(duration, year_start, year_end, stride=1): """ Construction of individual calibration periods Input: duration: the required duration in calender years, int year_start: the first year considered, int year_end: the last year considered, int stride: default=1 Output:...
def result_hash(result): """ Given a results object, generate a hashable value that can be used for comparison. """ node_bindings_information = frozenset( (key, frozenset(bound["id"] for bound in value)) for key, value in result["node_bindings"].items() ) edge_bindings_inform...
def calculate_grade(is_elective, grade): """ (bool, int) -> object Precondition: 0 <= grade <= 100 is_elective refers to True iff this course is being taken as an elective. Return the grade if the course is not being taken as an elective, and either 'Pass' or 'Fail' (depending on whether grade is at least 50) ...
def get_unique_open_finding_context(unique_open_findings_dict, href): """ Prepare open findings dictionary for context data. This method is used in 'risksense-get-unique-open-findings' command. :param unique_open_findings_dict: Dictionary representing open host findings. :param href: hyperlink for ...
def init_bitstring_groundstate(occ_num: int) -> int: """Occupy the n lowest orbitals of a state in the bitstring representation Args: occ_num (integer) - number of orbitals to occupy Returns: (integer) - bitstring representation of the ground state """ return (1 << occ_num) - 1
def buy_near_high_switch(value): """enable/disable buy size amount""" if "disablebuynearhigh" in value: return False return True
def _indent(lines, prefix=" "): """Indent some text. Note that this is present as ``textwrap.indent``, but not in Python 2. Args: lines (str): The newline delimited string to be indented. prefix (Optional[str]): The prefix to indent each line with. Default to two spaces. ...
def tan2costwo(tan: float) -> float: """returns Cos[2*ArcTan[x]] assuming -pi/2 < x < pi/2.""" return (1 + tan) * (1 - tan) / (tan ** 2 + 1)
def sqrt_improve(guess: float, x: float) -> float: """ Sec 3.5.3 sqrt-improve """ return (guess + x / guess) / 2.0
def is_all_unique_str(s): """Uses no extra space at the expense of time.""" for i in range(len(s)): if s[i] in s[i+1 :]: return False return True
def titleize(title): """Return a correctly capitalised show title. Usage: >>> print(titleize('the cat in the hat')) >>> 'The Cat in the Hat' """ titleized = [] for idx, word in enumerate(title.split()): if idx == 0 or word not in ['a', 'of', 'in', 'the', 'v']: word = wor...
def traverse_get(target, *args): """ Travel down through a dict >>> traverse_get({"one": {"two": 3}}, ["one", "two"]) 3 """ current = target for level in args: current = current[level] return current
def transf(values): """ Convert dictionary to a string Input : dictionary Output: string of length 81 """ return len("".join([value for value in values.values()]))
def unquote_label(txt): """Remove (one level of) enclosing single or double quotes. .. versionadded :: 1.0 """ return txt[1:-1] if txt and txt[0] in "'\"" and txt[0] == txt[-1] else txt
def isShorty(name): """Checks if it is a valid shorty name.""" nLen = len(name) return nLen == 1 or nLen == 2