content
stringlengths
42
6.51k
def thederiv(y): """ Parameters ---------- y Returns ------- """ dyc = [0.0] * len(y) dyc[0] = (y[0] - y[1]) / 2.0 for i in range(1, len(y) - 1): dyc[i] = (y[i + 1] - y[i - 1]) / 2.0 dyc[-1] = (y[-1] - y[-2]) / 2.0 return dyc
def is_tuple(value): """ Check if an object is a tuple :param value: :return: """ return isinstance(value, tuple)
def xml_escape(x): """Paranoid XML escaping suitable for content and attributes.""" res = '' for i in x: o = ord(i) if ((o >= ord('a')) and (o <= ord('z'))) or \ ((o >= ord('A')) and (o <= ord('Z'))) or \ ((o >= ord('0')) and (o <= ord('9'))) or \ ...
def in_range(x, a, b): """ Tests if a value is in a range. a can be greater than or less than b. """ return (x >= a and x <= b) or (x <= a and x >= b)
def is_linear(scan_range): """ For any 1-demensional data structure containing numbers return True if the numbers follows a linear sequence. Within the context of PySCeSToolbox this function will be called on either a linear range or a log range. Thus, while not indicative of log ranges, this i...
def ngram(string: str, n: int) -> tuple: """ constructs all possible ngrams from the given string. If the string is shorter then the n then the string is returned Parameters ---------- string n : int value must be larger at least 2 Returns ------- tuple of strings ...
def _line_format(name, tags, fields, timestamp=None): """ Format a report as InfluxDB line format :param name: name of the report :type name: str :param tags: tags identifying the specific report :type tags: dict[str] :param fields: measurements of the report :type fields: dict[str] ...
def xproto_tosca_field_type(type): """ TOSCA requires fields of type 'bool' to be 'boolean' TOSCA requires fields of type 'int32' to be 'integer' """ if type == "bool": return "boolean" elif type == "int32": return "integer" else: return type
def evaluate_findings(findings): """Evaluate the findings of the scan against local policy.""" total = 0 total += findings.get('malware', 0) total += findings.get('unresolved', {}).get('defcon1', 0) total += findings.get('unresolved', {}).get('critical', 0) total += findings.get('unresolved', {}...
def _fix_datetime(datetime_string): """Get date with 4 digit year, milliseconds and 4 digit timezone. >>> _fix_datetime('15-05-26T18:09:51+00') '2015-05-26T18:09:51.000+0000' >>> _fix_datetime('2015-05-26T18:09:51.000+0000') '2015-05-26T18:09:51.000+0000' """ year_part, _, non_year_parts = d...
def otu_list_to_dict(otu_list): """ :param otu_list: should be of the form [{seqA, seqB}, {seqC, secD}, {secE}] where the index in the list is the OTU ID. :return: an otuMap """ return {seq: idx for idx, otu in enumerate(otu_list) for seq in otu}
def flatten(array: list): """Flatten nested list to a single list""" return [item for sublist in array for item in sublist]
def OutputNameForIndex(index): """Gets the final output DLL name, given a zero-based index.""" if index == 0: return "chrome.dll" else: return 'chrome%d.dll' % index
def get_item_price_data(price, item_attribute): """Given an SoftLayer_Product_Item_Price, returns its default price data""" result = '-' if item_attribute in price: result = price[item_attribute] return result
def evaluate_labeled_example_targetid(goldtargets, prediction): """ Labeled lexical unit evaluation. """ tp = fp = fn = 0.0 for target_pos in goldtargets: goldlu = goldtargets[target_pos][0] if target_pos in prediction and prediction[target_pos][0] == goldlu: tp += 1 ...
def to_bytes(v, length, byteorder="big"): """For python 3, which has a native implementation of this function.""" return v.to_bytes(length, byteorder=byteorder)
def list_check(lst): """Are all items in lst a list? >>> list_check([[1], [2, 3]]) True >>> list_check([[1], "nope"]) False """ for item in lst: if not isinstance(item,list): return False return True
def crossover(x, y): """ Last two values of X serie cross over Y serie. """ return x[-1] > y[-1] and x[-2] < y[-2]
def jekyllurl(path): """ Take the filepath of an image output by the ExportOutputProcessor and convert it into a URL we can use with Jekyll """ return path.replace("../..", "")
def map_collection(collection, map_fn): """Applies ``map_fn`` on each element in ``collection``. * If ``collection`` is a tuple or list of elements, ``map_fn`` is applied on each element, and a tuple or list, respectively, containing mapped values is returned. * If ``collection`` is a dictionary, ``m...
def replace_ext(filename, oldext, newext): """Safely replaces a file extension new a new one""" if filename.endswith(oldext): return filename[:-len(oldext)] + newext else: raise Exception("file '%s' does not have extension '%s'" % (filename, oldext))
def null_distance_results(string1, string2, max_distance): """Determines the proper return value of an edit distance function when one or both strings are null. Parameters ---------- string_1 : str Base string. string_2 : str The string to compare. max_distance : int ...
def lines_are_parallel(line_1, line_2) -> bool: """Determine if line_1 and line_2 are parallel. line_1 = [a,b,c] line_2 = [a,b,c] """ slope_line_1 = line_1[0] // line_1[1] slope_line_2 = line_2[0] // line_2[1] if slope_line_1 == slope_line_2: return True return False
def combineImages(center, left, right, measurement, correction): """ Combine the image paths from `center`, `left` and `right` using the correction factor `correction` Returns ([imagePaths], [measurements]) """ imagePaths = [] imagePaths.extend(center) imagePaths.extend(left) imagePaths....
def tests_in_compile_targets(api, compile_targets, tests): """Returns the tests in |tests| that have at least one of their compile targets in |compile_targets|.""" result = [] for test in tests: test_compile_targets = test.compile_targets(api) # Always return tests that don't require compile. Otherwise...
def role_to_tag(role: str) -> str: """Return the isRole object bool tag for the given object role.""" return 'is' + role.title().replace(' ', '')
def to_char(num): """ Converts class index to char :param num: class index :return: corresponding char """ if num < 10: return str(num) elif num < 36: return chr(num + 55) else: return chr(num + 61)
def Sdif(M0, dM0M1, alpha): """ :math:`S(\\alpha)`, as defined in the paper, computed using `M0`, `M0 - M1`, and `alpha`. Parameters ---------- M0 : ndarray or matrix A symmetric indefinite matrix to be shrunk. dM0M1 : ndarray or matrix M0 - M1, where M1 is a positive defini...
def kronecker( i, j ): """ Definition of the Kronecker delta function for two numbers i and j. Args: i (int): index i j (int): index j Returns: int: return the Kronecker delta value. Testing: >>> kronecker( 2, 2 ) 1 >>> kronecker...
def _lsplit(s, sep, maxsplit): """ not yet in TS """ if maxsplit == 0: return [s] split = s.split(sep) if not maxsplit: return split ret = split.slice(0, maxsplit, 1) if len(ret) == len(split): return ret ret.append(sep.join(split[maxsplit:])) return ret
def extended_gcd(num1, num2): """Extended GCD algorithm. Return s, t, g such that num1 * s + num2 * t = GCD(num1, num2) and s and t are co-prime. """ old_s, s = 1, 0 old_t, t = 0, 1 old_r, r = num1, num2 while r != 0: quotient = old_r / r old_r, r = r, old_r - quot...
def remark_docstyle(source_files, docstyle_checks_total, ignored_pydocstyle_files, display_results): """Generate remark when not all source files are checked by pydocstyle.""" if not display_results: return "<li>docstyle checker is not setup</li>" elif source_files != docstyle_checks_total + ignored...
def spearman_squared_distance(r_1, r_2): """ Computes a weighted Spearman's Rho squared distance. Runs in O(n) Args: r_1, r_2 (list): list of weighted rankings. Index corresponds to an item and the value is the weight Entries should be positive and sum ...
def just_ints(the_string): """Returns only the digits from a string as an integer.""" # print(the_string) int_str_list = [character for character in the_string if character.isdigit()] # print(int_str_list) ret_val = int(''.join(int_str_list)) return ret_val
def orbit_decomposition( L, cyc_act ): """ Returns the orbit decomposition of L by the action of cyc_act INPUT: - L -- list - cyc_act -- function taking an element of L and returning an element of L (must define a bijection on L) OUTPUT: - a list of lists, the orbits under the cyc_act a...
def call_sacct(args) -> str: """ The arguments passed to `call_command` when executing `sacct` are: ['sacct', '-n', '-j', '<comma-separated list of job-ids>', '--format', 'JobIDRaw,State,ExitCode', '-P', '-S', '1970-01-01'] The multi-line output is something like: 1234|COMPLETED|0:0 ...
def number_of_stations(group): """ Culculates number of different stations in detection. """ return len(set([x['station']['station'] for x in group]))
def scaled(signal, factor): """" scale the signal """ scaled_signal = signal * factor return scaled_signal
def get_extra_options_appropriate_for_command (appropriate_option_names, extra_options): """ Get extra options which are appropriate for pipeline_printout pipeline_printout_graph pipeline_run """ appropriate_options = dict() for option_name in appropriate_option_names: ...
def create_condition_resource(condition_id: str, patient_reference: dict, onset_datetime: str, condition_code: dict, severity = None) -> dict: """ Create condition resource following the FHIR ...
def eval_expr(expr, dict_data): """ If expr is a string, will do a dict lookup using that string as a key. If expr is a callable, will call it on the dict. """ if callable(expr): return expr(dict_data) else: return dict_data.get(expr, None)
def first(iterable, condition=lambda x: True): """ Returns the first item in the `iterable` that satisfies the `condition`. If the condition is not given, returns the first item of the iterable. Raises `StopIteration` if no item satysfing the condition is found. >>> first( (1,2,3), condit...
def quaternion_multiply(r, q): """Multiplies two quaternions. Parameters ---------- r : list Quaternion as a list of four real values ``[rw, rx, ry, rz]``. q : list Quaternion as a list of four real values ``[qw, qx, qy, qz]``. Returns ------- list Quaternion :m...
def semivariogram(D, vrange, nugget, sill): """ Semivariogram functions""" if D > vrange: F = sill else: tmp = D/vrange F = nugget + (sill-nugget)*(1.5*tmp - 0.5*tmp**3) return F
def make_bytes(s: str) -> bytes: """Helper function to convert a string of digits into packed bytes. Ignores any characters other than 0 and 1, in particular whitespace. The bits are packed in little-endian order within each byte. """ buf = [] byte = 0 idx = 0 for c in s: if c =...
def is_debug_node(node_name): """Determine whether a node name is that of a debug node. Such nodes are inserted by TVM core upon request in RunOptions.debug_options.debug_tensor_watch_opts. Parameters ---------- node_name : str Name of the node. Returns ------- value : boo...
def non_strict_eq(a, b): """Equality between non-strict values Arguments: - `a`: a value or None - `b`: a value of a type comparable to a or None """ if a == None or b == None: return None else: return a == b
def base_to_integer(base_number, base_string): """ Converts baseX integer to base10 integer (where X is the length of base_string, say X for '0123' is 4), for example: 21646C726F77202C6F6C6C6548 (base16) to 2645608968347327576478451524936 (Which is 'Hello, world!'), does not account for negative numbers...
def apply_data(context, form_fields, data, adapters=None, update=False): """Save form data (``data`` dict) on a ``context`` object. This is a beefed up version of zope.formlib.form.applyChanges(). It allows you to specify whether values should be compared with the attributes on already existing objects...
def __error_is_logged(exception: BaseException) -> bool: """Check if exception has custom added attribute is_logged""" return hasattr(exception, "is_logged")
def join_parser(lines, join_str=" ", chars_to_strip=" ;."): """return a joined str from a list of lines, strip off chars requested from the joined str""" # a str will not be joined if isinstance(lines, str): result = lines else: result = join_str.join(lines) return result.strip(...
def get_path(path, search_space, include_key=False): """Retrieve a value from a nested dict by following the path. Throws KeyError if any key along the path does not exist""" if not isinstance(path, (tuple, list)): path = [path] current_value = search_space[path[0]] if len(path) == 1: ...
def rec_mergeSort(array): """ Perform merge sort by recursively splitting array into halves until all the values are separated then do a piece wise comparason to fill the array in order """ # check if array is none if len(array) > 1: # find mid index of list mid = len(array) // 2...
def get_pngdata_from_picodata(picodata, pngdata, attrs): """Encodes PICO-8 bytes into a given PNG's image data. Args: picodata: The PICO-8 data, a bytearray of 0x8000 bytes. pngdata: The PNG image data of the original cart image, as an iterable of rows as returned by pypng. attr...
def to_str(bytes_or_text, encode="utf-8"): """Bytes transform string.""" if isinstance(bytes_or_text, bytes): return bytes_or_text.decode(encode) if isinstance(bytes_or_text, str): return bytes_or_text raise TypeError("Param isn't str or bytes type, param={}".format(bytes_or_text))
def lineWidth(requestContext, seriesList, width): """ Takes one metric or a wildcard seriesList, followed by a float F. Draw the selected metrics with a line width of F, overriding the default value of 1, or the &lineWidth=X.X parameter. Useful for highlighting a single metric out of many, or having multipl...
def changeColorCov(r, g, b, dataset, oldColors): """Callback to set new color values. Positional arguments: r -- Red value. g -- Green value. b -- Blue value. dataset -- Currently selected dataset. oldColors -- Previous colors in case none values are provided for r/g/b. """ if r == ...
def get_primary_transcript(database): """ Get the ID to identify the primary transcript in the GTF file with the miRNA and precursor coordinates to be able to parse BAM files with genomic coordinates. """ if database.find("miRBase") > -1: return "miRNA_primary_transcript" e...
def get_cmd_args(input): """Retuns cmd and its args from the input string. Args: input: the input string captured from the command line. Returns: (command, args[]) """ arr = input.split(' ', 1) if arr.__len__() == 1: cmd, args = arr[0], [] elif arr.__len__() == ...
def calculate_arc_degrees(viewing_distance, circumference): """ Calculate how many degrees an arc of the given length would cover of the circle. http://www.regentsprep.org/regents/math/geometry/gp15/circlearcs.htm """ return (viewing_distance / circumference) * 360
def eqri(registers, opcodes): """eqri (equal register/immediate) sets register C to 1 if register A is equal to value B. Otherwise, register C is set to 0.""" return int(registers[opcodes[1]] == opcodes[2])
def find_version(fn): """ Try to find a __version__ assignment in a source file """ return "0.0.0" import compiler from compiler.ast import Module, Stmt, Assign, AssName, Const ast = compiler.parseFile(fn) if not isinstance(ast, Module): raise ValueError("expecting Module") s...
def tokenize(records): """Create a token mapping from objects to integers. Parameters ---------- records : array_like of iterables. Collection of nested arrays. Returns ------- enum_map : dict Enumeration map of objects (any hashable) to tokens (int). """ unique_ite...
def map_efo(trait_2_efo_dict, name_list): """ Function accepts a dict with mappings from clinvar trait names to tuples containing ontology ids and labels, and a list with clinvar trait names for one trait. Returns the clinvar trait name (in lowercase) that is earliest in the list and has a mapping in th...
def equals(arg1, arg2): """ check if two object equal >>> equals('a', 'b') """ if arg1 == arg2: return True if (arg1 is None) or (arg2 is None): return False return arg1.__eq__(arg2)
def power_level(xpos, ypos, grid_serial): """ (xpos, ypos) are in the 1,300 coordinate system. """ rack_id = xpos + 10 start_level = rack_id * ypos power = start_level + grid_serial power *= rack_id return int((power % 1000) / 100) - 5
def get_line_type(line): """Return either 'test' or 'train' depending on line type """ line_type = None if line.find('Train') != -1: line_type = 'train' elif line.find('Test') != -1: line_type = 'test' return line_type
def _encode_csv(iterable_items): """ Encodes CSVs with special characters escaped, and surrounded in quotes if it contains any of these or spaces, with a space after each comma. """ cleaned_items = [] need_escape_chars = '"\\' need_space_chars = ' ,' for item in iterable_items: n...
def fetch_from_graph(list_of_names, graph): """ Returns a list of shared variables from the graph """ if "__datasets_added__" not in graph.keys(): # Check for dataset in graph raise AttributeError("No dataset in graph! Make sure to add " "the dataset using add_datase...
def init_bytearray(payload=b'', encoding='utf-8'): """Initialize a bytearray from the payload.""" if isinstance(payload, bytearray): return payload if isinstance(payload, int): return bytearray(payload) if not isinstance(payload, bytes): try: return bytearray(payload....
def __checkIfPGPMsg(msg): """ Helper-Method: Check if a given decoded messages starts and ends witch the specific PGP message block syntax. @param msg: The message to check. @return: True if it is a valid PGP message, else False. """ if msg.strip().startswith(b'-----BEGIN PG...
def _parse_locations_as_set(locations): """Parse grid element locations as a set. Parameters ---------- locations : str or iterable of str Grid locations. Returns ------- set Grid locations as strings. Raises ------ ValueError If any of the locations ar...
def extract_extension_attributes(schema: dict) -> dict: """Extract custom 'x-*' attributes from schema dictionary Args: schema (dict): Schema dictionary Returns: dict: Dictionary with parsed attributes w/o 'x-' prefix """ extension_key_format = 'x-' extensions_dict: dict = { ...
def round_to_pow2(x: int) -> int: """ Round up to the nearets power of 2. """ return 1<<(x-1).bit_length()
def needs_text_relocation(m_type, m_subtype): """Returns True if the file with MIME type/subtype passed as arguments needs text relocation, False otherwise. Args: m_type (str): MIME type of the file m_subtype (str): MIME subtype of the file """ return m_type == 'text'
def convert_to_positive_int(value): """Converts value to positive int.""" value = int(float(value)) if value <= 0: raise ValueError("Value {0} has to be positive integer".format(value)) return value
def time_to_string(time: int) -> str: """Convert time to string representation Args: time (int): Time in seconds Returns: str: Time in MM:SS format """ if time < 0: raise ValueError("Negative integer not supported") return "%02d:%02d" % (time // 60, time % 60)
def color_rgb_to_hex(r: int, g: int, b: int) -> str: """Return a RGB color from a hex color string.""" return f"{round(r):02x}{round(g):02x}{round(b):02x}"
def check_dict_of_arrays(doa, columns): """ Checks the data-structure that dict of arrays has at least the keys in columns and that each entry's length is the same as the others. - doa: (Dict String (Array String)), dictionary with string keys to arrays of string - columns: (Array String), the colum...
def ts_or_tv(b1, b2): """Inspired by https://github.com/yesimon/rosalind/blob/master/TRAN.py Returns None if any of the two given bases is not in 'ACGT' """ type_map = { frozenset(['A', 'G']): 'ts', frozenset(['C', 'T']): 'ts', frozenset(['A', 'C']): 'tv', frozenset(['G'...
def reordered(num1, num2): """Returns True if two are reorderings of each other, otherwise False""" a, b = [list(str(num1)), list(str(num2))] for char in a: try: b.remove(char) except ValueError: return(False) return(b == [])
def password_check_weak(password): """Weak password checker: Only checks if the password is longer than 6 characters and doesn't container any spaces. Returns true when the password is strong and false when it isn't """ return len(password) > 6 and not password.isspace()
def get_size_for_unit(unit_name): """ Return the scale multiplier in blender units (m) """ if (unit_name == 'Inches'): return 0.0254 elif (unit_name == 'Centimeters'): return 0.01 else: return 1
def get_array_sizes(list, name): """ Expand the elements of an array for 1, 2, and 3D arrays """ t_list = [] if len(list) == 1: for t in range(0, list[0]): t_list.append(name + "[%s]" % t) elif len(list) == 2: for t1 in range(0, list[0]): for t2 in range(...
def _count(obj, item): """ Count in either a list or add on to an integer :param obj: either an integer or a list of individuals :param item: an string containing the indi code :return: inc(obj), or append(item) """ if isinstance(obj, list): obj.append(item) else: obj += ...
def mapChars (text, m): """ For all characters in text, replace if found in map m or keep as-is """ return ''.join (map (lambda x: m.get (x, x), text))
def calculate_global_throughput(samples, bucket_interval_secs=1): """ Calculates global throughput based on samples gathered from multiple load generators. :param samples: A list containing all samples from all load generators. :param bucket_interval_secs: The bucket interval for aggregations. :ret...
def remove_last_blank_character(response): """ Last value of response could be ''. Remove that if that's the case """ if response[-1] == '': response = response[:-1] return response
def gen(c, N): """ gen func. convert decinal representation of Nbased num to, N-basesed represetation """ degit_dict = "0123456789ABCDEF" if c // N == 0: return degit_dict[c%N] else: return gen(c//N, N) + degit_dict[c%N]
def kfold_split(num_objects, num_folds): """Split [0, 1, ..., num_objects - 1] into equal num_folds folds (last fold can be longer) and returns num_folds train-val pairs of indexes. Parameters: num_objects (int): number of objects in train set num_folds (int): number of folds for cross-validatio...
def sum3(mv1, mv2, mv3): """ returns mv1+mv2+mv3; they should be dimensioned alike.""" mv = mv1+mv2+mv3 if hasattr(mv, 'long_name'): if mv.long_name == mv1.long_name: mv.long_name = '' return mv
def partition(data, train_part=0.8, val_part=0.1, test_part=0.1): """Splits groups into training, validation, and test partitions. Args: data (list): list of units (e.g. dicts). train_part (float): proportion in [0, 1] of units for training. val_part (float): self-explanatory. t...
def reverse_complement_record(gene_strand, snp_strand): """returns True if the Ensembl 71 SNP record needs to be reverse complemented to put on transcribed strand""" # rc if the strands are different if gene_strand not in [-1,1] or snp_strand not in [-1, 1]: raise ValueError("strand must be -1 or 1"...
def join_commands(cmds): """Joins a list of shell commands with ' && '. Args: cmds: The list of commands to join. Returns: A string with the given commands joined with ' && ', suitable for use in a shell script action. """ return " && ".join(cmds)
def split_rows(sentences, column_names): """ Creates a list of sentence where each sentence is a list of lines Each line is a dictionary of columns :param sentences: :param column_names: :return: """ new_sentences = [] for sentence in sentences: rows = sentence.split('\n') ...
def find_item(list_containing_list, item): """ Find the index of the list that contains the item :param list_containing_list: List of lists; one of them must contain the item :param item: The item we are looking for :return: Index of the item in the outer list >>> find_item([[1,2,3],[4,5,6]],5...
def get_unique_name(obj): """ Creates a unique name (hopefully) of producer and product. """ return obj['producer'].lower() + "_" + obj['product'].lower().replace('/', ' ')
def evalBasis1D(x, basis, interval=None): """ evaluation of the basis functions in one dimension """ if interval is None: return 1.0 - abs(x * 2 ** basis[0] - basis[1]) else: pos = (x - interval[0]) / (interval[1] - interval[0]) return 1.0 - abs(pos * 2 ** basis[0] - basis[1])
def compute_approach(power, interest): """ Computes the approach to managing a stakeholder according to the power/interest model. Parameters ---------- power : str The stakeholder's level of power, either `high` or `low`. interest : str The stakeholder's level of ...
def _to_list(var) -> list: """Store the passed variable into a list and return it. If the variable is already a list, it is returned without modification. If `None` is passed, the function returns an empty list. Parameters ---------- var : Arbitrary variable Returns ------- ...