content
stringlengths
42
6.51k
def fromatJSON(injson): """ Format a json (in this case dict with run as key and list of lumis as element --> For CMS jsons we need list of json ranges. Will replace limis with [lumi, lumi] """ formattedJSON = {} for run in injson: formattedJSON[run] = [] for ls in injson[run]: ...
def _neq(x, y): """ Tests a pair of strings for non-equivalence by attempting to convert them to floats and falling back to string comparison. :param x: string :type x: str :param y: string :type y: str :return: boolean :rtype: bool """ try: return float(x) != float...
def torusGrad(x,y,z,rin,rout): """Return the derivatives of the Torus surface function with origin tangent to outer surface.""" dfdz = 4*(rin+rout+z)*(2*rin*(rout+z)+2*rout*z+x**2+y**2+z**2) dfdy = 4*y*(2*rin*(rout+z)+2*rout*z+x**2+y**2+z**2) dfdx = 4*x*(-rin**2+(rin+rout+z)**2+rout**2+x**2+y**2) ...
def _add_vector_dim(dims, coords): """Adds a 'vector' dimension with coords (eR, ePhi, eZ)""" dims = list(dims) dims.append("vector") coords = dict(coords) coords["vector"] = ["eR", "ePhi", "eZ"] return dims, coords
def longueurPlusGrandeLigne(source): """returns the lenght of the longest line in the source file""" try: with open(source, "r", encoding="utf-8") as f: max = 0 for ligne in f: if len(ligne) > max: max = len(ligne) return max ex...
def parse_conda_package(dep): """Parse conda package into channel and environment Args: dep: string in the form '<channel>::<package>' or '<package>' Returns: tuple: ('<channel>', '<package>') or ('defaults', '<package>') """ if "::" in dep: try: channel, package = ...
def is_digit(check_input): """ function to check whether the input is an integer digit returns : bool """ if check_input.isdigit(): return True return False
def example_roi_func_constant(zg, yg, xg): """ Example RoI function which returns a constant radius. Parameters ---------- zg, yg, xg : float Distance from the grid center in meters for the x, y and z axes. Returns ------- roi : float Radius of influence in meters "...
def GetElementsPresentInMolecule(list): """ input: list of elements and their xyz coordinates (as string values) summary: checks for first value of each entry in list, if symbol present, skip output: a list of all the elements present (no repeats) """ l = [] for entry in list: if ent...
def validateData(response): """validates that NASA API response returned data Args: response (Dict): custom response from API Returns: Boolean: True is data was returned False otherwise """ """ this is NASA's service response when they have no data for the day { "code": 404, ...
def int_to_tuple(number): """ Change the int into a tupple if applicable. If the arg is already a tuple, return it directly. Args: number (int or tuple): The number to convert in tuple if not already a tuple. Returns: tuple: The number formated into tuple to return. "...
def remove_dups(list_): """Get new list without duplicates, order-preserving.""" seen = set() seen_add = seen.add return [x for x in list_ if not (x in seen or seen_add(x))]
def get_num_rows(viewconf): """Get the number of rows for a layout if it's using fixed grid format. Args: viewconf (dict): The dashboard configuration Returns: int: returned if the number of modules can be determined None: returned if viewconf is invalid or the layout type ...
def get_set_of_list_and_keep_sequence(list): """ Returns the set of the specified list but keeps the sequence of the items.""" seen = set() return [x for x in list if not (x in seen or seen.add(x))]
def linearize_rowmajor(i, j, m, n): # calculate `v` """ Returns the linear index for the `(i, j)` entry of an `m`-by-`n` matrix stored in row-major order. """ return i*n + j
def check_def_topol_consistency(dic_Cname2Hnames, lipid_top): """Check the consistency between the lipid topology and the def file. Ensure that the carbons in the def file are present in the topology. Ensure that all hydrogens of a given carbon as described in the topology are present in the def file. ...
def create_pvc_spec(name): # type: (str) -> dict """ Generate a volume manifest using the given name for the PVC. This spec is used to test dynamically provisioned PersistentVolumes (those created using a storage class). """ return { 'name': 'pod-data', 'persistentVolumeClai...
def to_list(value): """ Put value into a list if it's not already one. Return an empty list if value is None. """ if value is None: value = [] elif not isinstance(value, list): value = [value] return value
def bond_profit(price, sellprice=1000.0): """ Bond total profit for a zero coupon bond :param price: Price which the bond was purchased :param sellprice: Price which the bond was sold :return: 1 - price/sellprice """ return 1 - price/sellprice
def _get(pseudodict, key, single=True): """Helper method for getting values from "multi-dict"s""" matches = [item[1] for item in pseudodict if item[0] == key] if single: return matches[0] else: return matches
def sizeof_fmt(num, suffix='B'): """Format the size of a file in human-readable values. Parameters ---------- num : int File size in bytes. suffix : str Suffix to use. Returns ------- output : str Human readable filesize. Notes ----- Follows the Dja...
def using_append_to_construct_a_list(n): """ Constructs [1, 2, 3, ... n] by using the append list method. """ new = [] for k in range(1, n + 1): new.append(k) return new
def convert_multi_slots_to_single_slots(slots): """ covert the data which text_data are saved as multi-slots, e.g() """ if len(slots) == 1: return slots[0] else: return ' '.join(slots)
def force_list(elements=None, to_tuple=False): """ Makes sure `elements` is returned as a list, whether `elements` is a single item, already a list, or a tuple. Args: elements (Optional[any]): The inputs as single item, list, or tuple to be converted into a list/tuple. If None, returns ...
def manhattan_distance(node1, node2): """Retourner la "Manhattan distance" (distance L1) entre 2 noeuds.""" return abs(node2[0] - node1[0]) + abs(node2[1] - node1[1])
def cnn_params(kernel: int, in_channels: int, out_channels: int, bias: bool = True): """ Return the number of parameters in a CNN. Args: kernel: Kernel size, it is assumed to be squared. in_channels: Number of input channels. out_channels: Number of output channels i.e. number of ker...
def RPL_TRACENEWTYPE(sender, receipient, message): """ Reply Code 208 """ return "<" + sender + ">: " + message
def GetWsdlArrayName(name): """Get WSDL array name""" if name: return "ArrayOf" + name[0].capitalize() + name[1:] else: return None
def repair_attribute_name(attr): """ Remove "weird" characters from attribute names """ import re return re.sub('[^a-zA-Z-_\/0-9\*]','',attr)
def enketo_error502_mock(url, request): # pylint: disable=unused-argument """ Returns mocked Enketo Response object for all queries to enketo.ona.io that may result in an HTTP 500 error response. """ return {'status_code': 502, 'content': "Unavailable"}
def convert_coords(coords, zero_to_360=False): """Convert latitude coordinates to [-180, 180] or [0, 360]. Args: coords (:obj:`list` of :obj:`tuple` of :obj:`float`): latitude [-90, 90] and longitude [-180 180] or [0 360] of the requested point. zero_to_360 (:obj:`bool`, optional) I...
def tb(string): """ Return a byte representation of a string """ return bytes(string, "UTF-8")
def get_identifier_ref(ref): """Parses an indentifier reference given in the form '[prefix:]name'""" if ref.find(":") == -1: prefix = None name = ref else: [prefix, name] = ref.split(':', 1) return (prefix, name)
def fib(n: int, litter: int) -> int: """ Find Fibonnaci """ nums = [0, 1] for i in range(n - 1): nums.append((nums[-2] * litter) + nums[-1]) return nums[-1]
def integrations_required_keys(modules:list) -> set: """ Gets the variables that the external integrations need to function :param modules: Integration initialization modules :return: The keys required to initialize all the integrations for this API """ req_keys = set() for module in modul...
def get_tags(data): """ Convert the AWS ASG tags into something more useful """ return dict((x['Key'], x['Value']) for x in data)
def compute_reporting_interval(item_count): """ Computes for a given number of items that will be processed how often the progress should be reported """ if item_count > 100000: log_interval = item_count // 100 elif item_count > 30: log_interval = item_count // 10 else: ...
def voltage(raw_value, v_min=0, v_max=10, res=32760, gain=1): """Converts a raw value to a voltage measurement. ``V = raw_value / res * (v_max - v_min) * gain`` """ return (float(raw_value) / res * (v_max - v_min) * gain, "V")
def calculate_percentage(data): """ calculate the percentage of examples in each category :param data: vector (column in matrix) :return: dictionary with category as key and percentage as value {'category1': percentage1, 'category2': percentage2, ...} """ dic = {} for val in data: ...
def get_log_level(quiet=False, verbose=False): """return logging level depending on verbosity args""" if quiet: return "WARNING" if verbose: return "DEBUG" return "INFO"
def distinct_powers(ceiling): """ Returns the number of distinct terms in the sequence generated by a^b for 2 <= a, b, <= ceiling. """ powers = set() for a in range(2, ceiling + 1): for b in range(2, ceiling + 1): powers.add(a**b) return len(powers)
def convert_int_bytes(data, length): """ convert int to bytes data: int value length: bytes number """ bytes_data = data.to_bytes(length, 'big') return bytes_data
def bitmap2str(b, n, on='o', off='.'): """ Generate a length-n string representation of bitmap b """ return '' if n==0 else (on if b&1==1 else off) + bitmap2str(b>>1, n-1, on, off)
def find_type(string_in): """ Checks for int/float before settling on string """ out = string_in try: out = int(string_in) except ValueError: try: out = float(string_in) except ValueError: pass return out
def even_or_odd(number): """Return 'Even' or 'Odd' if number is even or odd.""" if number % 2 == 0: return "Even" return "Odd"
def clean_empty(d): """ Remove keys with None or empty list throughout dictionary """ if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (clean_empty(v) for v in d) if v] return {k: v for k, v in ((k, clean_empty(v)) for k, v in d.items()) if v}
def get_si_factor(ci, li, conc='ini19'): """S_i factor defined in FONDECYT Regular or Iniciacion""" # import pdb; pdb.set_trace() if conc in ['ini19', 'reg19']: si = li*((1 + ci)**0.5) else: raise ValueError('Not implemented for this concurso: {}.'.format(conc)) return si
def get_object_root_module(obj): """ Get the obj module version :param T obj: Any object :rtype: str :return The root module of the object's type """ return type(obj).__module__.split('.')[0]
def isInt(val): """We'll try to convert val to an int and if we fail it obviously isn't one""" try: int(val) return True except ValueError: return False
def pad(x, pad_len): """Old versions of transformers do not pad by default""" return x + [0] * (pad_len - len(x))
def get_freq_score(message): """ Evaluates the given message according to its character frequency. The higher the score, the likelier it is for the text to be human-readable. """ score = 0 common_letters = 'etaoin shrdlu' for c in message: if c in common_letters: score +...
def _pf1e(val1, val2): """ Parameters ---------- val1 : float Description of the parameter Value 1 - Line 1. Description of the parameter Value 1 - Line 2. Description of the parameter Value 1 - Line 3. val2 : list(str) Description of the parameter Value 2 - Line 1. ...
def insert_after(circle, three, pos): """ >>> insert_after([3, 2, 5, 4, 6, 7], [8, 9, 1], 1) [3, 2, 8, 9, 1, 5, 4, 6, 7] >>> insert_after([1, 9, 2, 5, 8, 4], [3, 6, 7], 1) [1, 9, 3, 6, 7, 2, 5, 8, 4] """ return circle[: pos + 1] + three + circle[pos + 1 :]
def make_timestamp(el_time): """ Generate an hour-minutes-seconds timestamp from an interval in seconds. Assumes numeric input of a time interval in seconds. Converts this interval to a string of the format "#h #m #s", indicating the number of hours, minutes, and seconds in the interval. Intervals gr...
def find_first(iterable, matcher): """Find and return the first element that matches the filter condition or None if not found. :param matcher Filter expression. :type matcher callable """ return next((v for v in iterable if matcher(v)), None)
def import_teamocil(session_config): """Return tmuxp config from a `teamocil`_ yaml config. .. _teamocil: https://github.com/remiprev/teamocil Parameters ---------- session_config : dict python dict for session configuration Notes ----- Todos: - change 'root' to a cd or...
def get_filename_from_url(path: str): """ Get filename from path """ return path.split("/")[-1]
def mget(lst, ind): """ Returns a list 'lst2' such that lst2[i] = lst[ind[i]] In otherwords, get the subsequence of 'lst'. """ return [lst[i] for i in ind]
def to_boolean(value): """ Convert a string to boolean, case insensitively, where true values are: true, t, and 1 and false values are: false, f, 0. Raise a ValueError for all other values. """ if isinstance(value, bool): return value if isinstance(value, str): lower_value =...
def get_tricks_needed(active_players): """Determines how many tricks left are actual needed in aggregate""" tricks_needed = 0 for player in active_players: tricks_needed += max(player.bid - player.curr_round_tricks, 0) return tricks_needed
def filter_bad_results(search_results, guessit_query): """ filter out search results with bad season and episode number (if applicable); sometimes OpenSubtitles will report search results subtitles that belong to a different episode or season from a tv show; no reason why, but it seems to work well ...
def prepend_lines(prepend, iterable): """Prepend every line in iterable with ``str``, most probably ``CHECK``. :param prepend: ``str`` to prepend to every line in iterable. :param iterable: Iterable to prepend with ``str``. :return: Constructed ``str``. """ return "\n".joi...
def is_local_pip_requirement(line): """Return whether a pip requirement (e.g. in requirements.txt file) references a local file""" # trim comments and skip empty lines line = line.split("#", 1)[0].strip() if not line: return False if line.startswith(("-r", "-c")): # local -r or -c re...
def _gaspr_input(endfin, pendfin, pendfout, **kwargs): """Write gaspr input. Parameters ---------- endfin : `int` tape number for input ENDF-6 file pendfin : `int` tape number for input PENDF file pendfout : `int` tape number for output PENDF file ...
def RR_calc(classes, TOP): """ Calculate Global performance index (RR). :param classes: confusion matrix classes :type classes: list :param TOP: number of positives in predict vector per class :type TOP: dict :return: RR as float """ try: class_number = len(classes) ...
def ERR_USERONCHANNEL(sender, receipient, message): """ Error Code 443 """ return "ERROR from <" + sender + ">: " + message
def similarity(text1, text2): """ more coarse estimation of similarity, but fast, not as slow as a full diff """ text1 = text1.splitlines() text2 = text2.splitlines() changed = 0.0 for t1 in text1: if t1 not in text2: changed += 1.0 for t2 in text2: if t2 not...
def clean(string): """ Cleans the string by making the case uniform and removing spaces. """ if string: return string.strip().lower() return ''
def getter(x, k: str, *args): """ get an attribute (from an object) or key (from a dict-like object) `getter(x, k)` raise KeyError if `k` not present `getter(x, k, default)` return default if `k` not present This is a convenience function that allows you to interact the same with an object or...
def get_doc_str(fun): """Get the doc string for a function and return a default if none is found.""" if fun.__doc__: return '\n'.join([line.strip() for line in fun.__doc__.split('\n')]) else: return 'No documentation provided for %s()' % fun.__name__
def filter_files(filetypes, files): """Filters a list of files based on a list of strings.""" filtered_files = [] for file_to_filter in files: filename = file_to_filter if type(file_to_filter) != "string": filename = file_to_filter.basename for filetype in filetypes: ...
def extractNameComponents(value): """This function tries to extract a family name and a last name from the input and returns them as a tuple. >>> extractNameComponents('Lieber, Sven') ('Lieber', 'Sven') >>> extractNameComponents('van Gogh, Vincent') ('van Gogh', 'Vincent') Empty strings are returned if it...
def is_leapyear(year): """ Return True if year is a leap year, False otherwise. """ return year % 400 == year % 100 + year % 4 != 0
def extract_table_data(row_list, n): """ Extract table tows from all row as a list of tuples for persisting. First :param n rows of csv are metadata, header rows. Thus, returns rows n and onwards :param row_list: List of all rows in csv used for table creation :param n: Represents how any rows in th...
def compute_F1(TP, TN, FP, FN): """ Return the F1 score """ numer = 2 * TP denom = 2 * TP + FN + FP F1 = numer/denom Acc = 100. * (TP + TN) / (TP + TN + FP + FN) return F1, Acc
def thisorthat(this, that): """ If this is None takes that otherwise takes this. :param this: :param that: :return: """ if this is None: return that else: return this
def add_sid_token(reqs_data: dict, sid: str) -> dict: """ add sid token in requests params :param reqs_data: requests kwargs :param sid: sid token :return: """ if 'params' not in reqs_data: reqs_data['params'] = {} # api params may in forms sometimes if 'api' not in reqs_dat...
def solve_table_prefix(table: str, default_table_prefix: str) -> str: """Solve table name prefix Args: table (str): Table name default_table_prefix (str): If project or dataset that configured table have are omitted, it will be complement this prefix. Defaults to None. ...
def is_note(c: str) -> bool: """ checks char for valid note symbol """ return c in "CDEFGABcdefgab^=_"
def reverse_aba(aba: str) -> str: """ Calculate the reverse of an 'aba' (e.g. 'efe' becomes 'fef') """ return aba[1] + aba[0] + aba[1]
def array_class_from_type(name): """ Given a DataTypeClass class name (such as "BooleanType"), return the corresponding Array class name. """ assert name.endswith("Type") return name[:-4] + "Array"
def stop_tuning(step): """ stop tuning the current step method """ if hasattr(step, 'tune'): step.tune = False elif hasattr(step, 'methods'): step.methods = [stop_tuning(s) for s in step.methods] return step
def isPow2(num) -> bool: """ Check if number or constant is power of two """ if not isinstance(num, int): num = int(num) return num != 0 and ((num & (num - 1)) == 0)
def _is_fedora(distname): """detect Fedora-based distro (e.g Fedora, CentOS, RHEL)""" distname = distname.lower() for x in ["fedora", "centos", "red hat"]: if x in distname: return True return False
def find_min(l): """ generic function that takes a list of numbers and returns smallest number in that list its index. return optimal value and the index of the optimal value as a tuple. :param l: list :return: tuple """ return(min(l),l.index(min(l))) pass
def to_string(ip): """Convert 32-bit integer to dotted IPv4 address.""" return ".".join(map(lambda n: str(ip >> n & 0xFF), [24, 16, 8, 0]))
def find_key(key, obj): """ Athena openx SerDe is case insensitive, and converts by default each object's key to a lowercase value: https://docs.aws.amazon.com/athena/latest/ug/json-serde.html Here we convert the DataMapper value for the column identifier (for instance, customerid) to the JSON's ob...
def get_path_and_name(full_name): """ Split Whole Patch onto 'Patch' and 'Name' :param full_name: <str> Full Resource Name - likes 'Root/Folder/Folder2/Name' :return: tuple (Patch, Name) """ if full_name: parts = full_name.split("/") return ("/".join(parts[0:-1]), parts[-1]) if l...
def decidir_invitar(peli: dict, edad_invitado: int, autorizacion_padres: bool) -> bool: """Verifica si es posible invitar a la persona cuya edad entra por parametro a ver la pelicula que entra igualmente por parametro. Para esto verifica el cumplimiento de las restricciones correspondientes. Par...
def getModClass(name): """converts 'app_name.ModelName' to ['stuff.module', 'ClassName']""" try: dot = name.rindex('.') except ValueError: return name, '' return name[:dot], name[dot + 1:]
def integrate(f, a, b, n=1000): """ Numerically integrate the function 'f' from 'a' to 'b' using a discretization with 'n' points. Args: - f -- A function that eats a float and returns a float. - a -- Lower integration bound (float) - b -- Upper integration bound (float) - n -- number of sa...
def xy_to_z(xy): """ Returns the *z* coordinate using given *xy* chromaticity coordinates. Parameters ---------- xy : array_like *xy* chromaticity coordinates. Returns ------- numeric *z* coordinate. References ---------- .. [2] `RP 177-1993 SMPTE RECOMMEN...
def replace_periods(dict_val, replace_with='_'): """ Recursively replace "." fonud in keys in the given dict with the value of replace_with """ facts = dict() for k, v in dict_val.items(): if '.' in k: if replace_with: k = k.replace('.', '_') if is...
def chunked(arr, chunk_size: int, include_remainder=True): """ return an array of array chucks of size chunk_size. This is NOT an iterable, and returns all the data. """ size = (len(arr) + chunk_size - 1) if include_remainder else len(arr) return [arr[chunk_size*i:chunk_size*(i+1)] for i in rang...
def lerp(a, b, w): """ linear interpolation """ return a + w*(b-a)
def set_biosphere_type(data): """Set CF types to 'biosphere', to keep compatibility with LCI strategies. This will overwrite existing ``type`` values.""" for method in data: for cf in method['exchanges']: cf[u'type'] = u'biosphere' return data
def quadratic_model ( p, agdd ): """A quadratic phenology model. Takes in a lenght 3 vector with parameters for a quadratic function of AGDD ``agdd``""" return p[0]*agdd**2 + p[1]*agdd + p[2]
def _selector(gvar): """ Internal function to return a valid selector value based on the user paramaters. """ selector = {} if 'cloud-name' in gvar['user_settings']: selector['cloud_name'] = gvar['user_settings']['cloud-name'] if 'vm-hosts' in gvar['user_settings']: selector['ho...
def make_dict(table, key_col): """ Given a 2D table (list of lists) and a column index key_col, return a dictionary whose keys are entries of specified column and whose values are lists consisting of the remaining row entries """ table_dict = {} for key in table: table...
def hostexists(hostname): """ is this host in DNS """ import socket try: ret = socket.gethostbyname(hostname) return True except socket.gaierror: return False