content
stringlengths
42
6.51k
def check_date_format(date): """check if date format fits the DD/MM/YYYY format""" if len(date) != 10: return False if(date[0:1].isnumeric() is False or date[3:4].isnumeric() is False or date[6:9].isnumeric() is False): return False if date[2] and date[5] != ".": re...
def iso_date(year, week, day): """Return the ISO date data structure.""" return [year, week, day]
def create_nine_digit_product(num): """ Create a nine digit string resulting from the concatenation of the product from num and multipliers (1, 2, 3,).... Return 0 if string cannot be length 9. """ result = '' counter = 1 while len(result) < 9: result += str(num * counter) ...
def unroot_schema(schema: dict): """ Modify a json-schema dictionary to make it not root. Parameters ---------- schema: dict """ terms = ("required", "properties", "type", "additionalProperties", "title", "description") return {k: v for k, v in schema.items() if k in terms}
def get_filename_safe_string(string, max_length=146): """ Converts a string to a string that is safe for a filename Args: string (str): A string to make safe for a filename max_length (int): Truncate strings longer than this length Warning: Windows has a 260 character length lim...
def str_starts_with_any_in_list(string_a, string_list): """ Check if string_a starts with any string the provided list of strings """ for string_b in string_list: if string_a.startswith(string_b): return True return False
def square_and_multiply(x, k, p=None, Verbose=False): """ Square and Multiply Algorithm x: positive integer k: exponent integer p: module Returns: x**k or x**k mod p when p is given """ b = bin(k).lstrip('0b') r = 1 for i in b: rBuffer = r r = r**2 ...
def reverseCamel(name, lower=True): """ Returns camel case reverse of name. case change boundaries are the sections which are reversed. If lower is True then the initial letter in the reversed name is lower case Assumes name is of the correct format to be Python Identifier. """ inde...
def join_zookeeper_path(root, *child): """Returns zookeeper path joined by slash. """ return '/'.join((root,) + child)
def order_by_cell(element): """Return ordering for Lint IReport""" return ( element['cellId'], element['reportType'], element['reportId'], )
def read_name(filename): """ :param filename: the file name, including the path :return: fields """ fields = filename.split('#') tmp = fields[0] env_name = tmp.split('/') env_name = env_name[-1] algo = fields[1] team_name = fields[2] name = team_name.split('.') return env...
def raises(exception_types, function, args=None, kwargs=None): """Return whether or not the given function raises the error. Parameters ========== exception_types: tuple, Exception Tuple of the types of the exceptions (or a single type of exception) that should be caught. function: ...
def get_symbol( codename, symbols ): """Helper function to build a token name""" if codename in symbols: return symbols[codename] else: return "["+str(codename)+"]"
def normalize_str_length(categories): """ method that matches the length of each label to the longest one. The difference in length will simply be filled with blanks. This eases the later formatting inside the GUI texts. F.e. considering the classes: ['airplane', 'automobile', 'bird'] the classes '...
def ordinalize(number): """ Transforms a number to its ordinal representation. Since this method should be mostly used in logging messages, only English is supported. Examples: ```python from flashback.formatting import ordinalize ordinalize(1) #=> "1st" ordi...
def _open_to_close_tag(tag): """ Given an opening xml tag, return the matching close tag eg. '<YAMAHA_AV cmd="PUT"> becomes </YAMAHA_AV> """ index = tag.find(' ') if index == -1: index = len(tag) - 1 return '</' + tag[1:index] + '>'
def simplify(x): """Convert a float to an int, if possible.""" if x // 1 == x: return int(x) else: return x
def n_rows_cols(pixel_index, block_size, rows_cols): """ Adjusts block size for the end of image rows and columns. Args: pixel_index (int): The current pixel row or column index. block_size (int): The image block size. rows_cols (int): The total number of rows or columns in the ima...
def _optimize_movement_list(movements): """ Optimize the movements list) Parameters ---------- movements : list The list of movements to optimize Returns ------- movements_optimized : list The list of movements optimized Cases ----- 1- [A , A ] or [...
def get_p_survival(block=0, nb_total_blocks=9, p_survival_end=0.5, mode='linear_decay'): """ See eq. (4) in stochastic depth paper: http://arxiv.org/pdf/1603.09382v1.pdf """ if mode == 'uniform': return p_survival_end elif mode == 'linear_decay': return 1 - ((block + 1) / nb_total_bl...
def nts(s): """Convert a null-terminated bytes object to a string. """ p = s.find(b"\0") if p != -1: s = s[:p] return s.decode("utf-8")
def square_matrix(triangular_matrix): """Fill with zeros a triangular matrix to reshape it to a square one. Args: triangular_matrix (list [list [float]]): Array of arrays of Returns: list: Square matrix. """ length = len(triangular_matrix) zero = [0.0] ...
def grep(lines, substr): """ Return a list of strings from `lines` that have `substr` as a substring. """ return [l for l in lines if substr in l]
def divisibleBy(i, nums): """assumes nums is a list of ints assumes i is an int returns a boolean, True if all the ints in nums are divisible by i. else false """ for num in nums: if num % i != 0: return False return True
def simplefilterextension(v): """Provide a simple function-based filter extension.""" return v.upper()
def pascalvoc_boxconvert_yolo(img_width, img_height, pascalvoc_box): """Convert a box with arguments to x_min, y_min, x_max, y_max to YOLO The YOLO format is x_center, y_center, width, height (Normalized) Args: img_width (int): Width of the image img_height (int): Height of the image ...
def get_node_attrs(node_id, node_label, attrs_var): """Query for retreiving node's attributes.""" query = ( "MATCH (n:{} {{ id: '{}' }}) \n".format( node_label, node_id) + "RETURN properties(n) as {}\n".format(attrs_var) ) return query
def _atomReprAsHex(s: str) -> str: """Translate CLVM integer atom repr to a 0x-prefixed hex string.""" if s.startswith("0x"): return s elif s.startswith('"'): return "0x" + s[1:-1].encode("ascii").hex() return hex(int(s))
def fix_team_tricode(tricode): """ Some of the tricodes are different than how I want them :param tricode: 3 letter team name - ex: NYR :return: fixed tricode """ fixed_tricodes = { 'TBL': 'T.B', 'LAK': 'L.A', 'NJD': 'N.J', 'SJS': 'S.J' } if tr...
def ICGTaxCredit(earned_p, earned_s, MARS, ICG_credit_c, ICG_credit_em, ICG_credit_rt, ICG_credit_thd, icg_expense, c05800, e07300, icgtc): """ Computes nonrefundable informal care giver tax credit. """ # not reflected in current law and records modified with imputati...
def partial_matches(eval_spans, gold_spans, mode): """ The partial span precision is calculated by the number of system spans which overlap in some way with a system span. :type eval_spans: OrderedDict :type gold_spans: OrderedDict """ matches = 0 if mode == 'precision': for sy...
def reconcile_sensors(sensor_key_list): """ Make a list of the unique sensors from a set of fits """ sensor_list=[] for this_dict in sensor_key_list: for key in this_dict.keys(): if key not in sensor_list: sensor_list += [key] return sensor_list
def is_args_valid(day: str) -> bool: """Validates that the supplied arg is a valid day""" if day.lower() not in [ "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", ]: return False return True
def qualified_class_name(o): """Full name of an object, including the module""" module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ return module + '.' + o.__class__.__name__
def hex8_to_u32le(data): """! @brief Build 32-bit register value from little-endian 8-digit hexadecimal string""" return int(data[0:8], 16)
def convert_cookies_format(cookies): """ Convert cookies from dictionary format to list :param cookies: dictionary contained cookies from session :type: dict :return: list of strings of format 'key=value' :type: list """ new_cookies = [] for key, value in cookies.items(): ...
def get_app_label_and_model_name(path): """Gets app_label and model_name from the path given. :param str path: Dotted path to the model (without ".model", as stored in the Django `ContentType` model. :return tuple: app_label, model_name """ parts = path.split('.') return ''.join(parts[:...
def _number_rare(freq_counts, rare_threshold, gamma=False): """Return number of individuals in rare OTUs. ``gamma=True`` generates the ``n_rare`` used for the variation coefficient. """ n_rare = 0 if gamma: for i, j in enumerate(freq_counts[:rare_threshold + 1]): n_rare = n_ra...
def normalize_rect(rect): """ Make rectangle a rotated tall rectangle, which means y-size > x-size and the angle indicates the "tilt": rotation of the longer axis from vertical :param rect: OpenCV's rectangle object :return: OpenCV's rectangle object normalized as described rect[0] is the coordi...
def findModuleStartIndex(pcbLineList, ref): """ Returns the line index at which the moduels starts """ lastModuleIndex = -1 moduleIndex = None for i, line in enumerate(pcbLineList): if 'module' in line: lastModuleIndex = i continue refStr = ' {0} '.format(...
def primes1(n): """Returns a list of primes < n""" sieve = [True] * (n // 2) for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i // 2]: sieve[i * i // 2 :: i] = [False] * ((n - i * i - 1) // (2 * i) + 1) return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]]
def Intialiation_matrix(rows, cols): """ This function creates different values in matrices A and B ,kind of random initialization rows: the number of rows the matrix cols: the number of columns the matrix """ M = [] count=0 while len(M) < rows: M...
def point_str(x,y=0,z=0): """ Returns a string repr of a point. Example: point_str(1,2,3) returns '(1.0,2.0,3.0)' Parameter x: the x coordinate Precondition: x is a number Parameter y: the y coordinate Precondition: y is a number Parameter z: the x coordinate Precondition: z...
def get_rule_type(type): """Get the rule type of schedule. :param type: The schedule type enum :return: The rule type of snapshot schedule """ schedule_type = { "ScheduleTypeEnum.N_HOURS_AT_MM": "every_n_hours", "ScheduleTypeEnum.DAY_AT_HHMM": "every_day", "ScheduleT...
def build_doi_url(doi): """ """ doi_url = 'https://doi.org/' doi_url = doi_url + str(doi) return(doi_url)
def percentage_distance_from_track_center(track_width, distance_from_center): """ Return a linear percentage distance along the track width from the center to the outside """ # make sure not negative, in case distance_from_center is over the track_width distance = distance_from_center / (track_width/2.0) re...
def validate_data_source_type(data_source_type): """ Property: DataSource.Type """ data_source_types = ( "AutoSelectOpsworksMysqlInstance", "OpsworksMysqlInstance", "RdsDbInstance", ) if data_source_type not in data_source_types: raise ValueError( "Typ...
def process_transform_funcs(trans_funcs, func_args=None, func_kwargs=None): """Process input of the apply_transform_funcs function. :param iterable trans_funcs: functions to apply, specified the function or a (function, args, kwargs) tuple :param dict func_args: function positional arguments, specified as ...
def max_key_val(d): """Return the key-value with the maximal value. Args: d (dict-like): A dictionary. """ return max(d.items(), key=lambda x: x[1])
def get_recall(rec, tru): """Recommendation recall: |{R & P}|/|P| (R - recommended products, P - relevant products)""" return len(rec & tru)/len(tru) if len(tru) != 0 else 0
def validate_bool(*args): """ validates that inputs are boolean only """ for value in args: if not isinstance(value, bool): return False return True
def compare_transcripts(comp_transcript, head_transcript): """ If a transcript differs only in a length mark or in voiced/voiceless or having post aspriation or not, it should be recognized as the same transcript (since we have already matched the corresponding word strings) """ head_ind = len(head...
def convert_inputs(inputs: dict) -> dict: """ Convert elements in the dictionary loaded by json to formats that Terra accepts as inputs """ results = {} for key, value in inputs.items(): if isinstance(value, bool): value = 'true' if value else 'false' elif isinstance(value, t...
def url_with_resources(base_url, resources=None): """Creates URL using given parameters. Args ----- base_url (str): Base url, example http://somehost resources (list[str], optional): Resource name. Defaults to None. Returns ------- Formatted URL to use with http apis. "...
def _apply_sct_header_formatting(fslhd_fields): """ Tweak fslhd's header fields using SCT's visual preferences. :param fslhd_fields: Dict with fslhd's header fields. :return modified_fields: Dict with modified header fields. """ modified_fields = {} dim, pixdim = [], [] for key, value i...
def merge_pk_maps(obj1, obj2): """ Merge pk map in `obj2` on `obj1`. """ for model, data in obj2.items(): m2_pks, m2_fields = data m1_pks, m1_fields = obj1.setdefault(model, [set(), set()]) m1_pks.update(m2_pks) m1_fields.update(m2_fields) return obj1
def _FileDirNameChk(Name, Exts): """Checks if a file ends in a certain extension. Name - Name of the file to check Exts - A tuple containing the allowed extensions. (Without periods) Intended for internal use only""" Status = False if Name[-1] == "/": return True if not Exts: ...
def find_anagrams(letters, words): """Find a collection of anagrams of given letters from a given word bank. :param letters: The letters from which to form anagrams. :param words: A set of lowercase, alphabetic English words in a word bank. :return: A set of anagrams of the given letters found in the w...
def process_which(which, max_index): """ Processes different ways of specifying the selection of wanted eigenvalues/eigenstates. Parameters ---------- which: int or tuple or list single index or tuple/list of integers indexing the eigenobjects. If which is -1, all indices up to the ...
def _add_sampling_config( config, sample_rate, rule_type, releases=None, user_segments=None, environments=None, ): """ Adds a sampling configuration rule to a project configuration """ rules = config["config"].setdefault("dynamicSampling", {}).setdefault("rules", []) if rule_...
def Interval(caseAttrib, queryValue, interval, weight): """ Returns the similarity of two numbers inside an interval. """ try: queryValue = float(queryValue) # build query string queryFnc = { "function_score": { "query": { "match_all": {} }, "script_score": { "script": { "para...
def f(x): """ A quadratic function. """ y = x**2 + 1. return y
def _column(x): """Helper function to parse indexes of columns when doing and histogram plot This function is called after ArgumentParser has parsed the args """ # we return a tuple of int, instead of an int for consistency on how we access columns # with other type of plots. return (int(x) - 1...
def convert_to_table_file_format(format_str): """Converts a legacy file format string to a TableFileFormat enum value. Args: format_str: A string describing a table file format that was passed to one of the functions in ee.data that takes table file formats. Returns: A best guess at the correspond...
def fmt_percent(value: float, edge_cases: bool = True) -> str: """Format a ratio as a percentage. Args: edge_cases: Check for edge cases? value: The ratio. Returns: The percentage with 1 point precision. """ if not (1.0 >= value >= 0.0): raise ValueError("Value '{}'...
def as_staging_name(name): """Transform the schema name to its staging position.""" return "$".join(("etl_staging", name))
def _get_readable_id(id_name, id_prefix_to_skip): """simplified an id to be more friendly for us people""" # id_name is in the form 'https://namespace.host.suffix/name' # where name may contain a forward slash! pos = id_name.find('//') if pos != -1: pos += 2 if id_prefix_to_skip: ...
def rescale_range(X, old_range, new_range): """Rescale X linearly to be in `new_range` rather than `old_range`.""" old_min = old_range[0] new_min = new_range[0] old_delta = old_range[1] - old_min new_delta = new_range[1] - new_min return (((X - old_min) * new_delta) / old_delta) + new_min
def escape_zoho_characters_v2(input_string) -> str: """ Note: this is only needed for searching, as in the yield_from_page method. This is an example :param input_string: :return: """ if r'\(' in input_string or r'\)' in input_string: #don't repeatedly escape return input_string else...
def FormatOrdinal(value): """Formats a number as an ordinal in the English language. E.g. the number 1 becomes "1st", 22 becomes "22nd". @type value: integer @param value: Number @rtype: string """ tens = value % 10 if value > 10 and value < 20: suffix = "th" elif tens == 1: suffix = "st" ...
def remove_quotes(path_string): # type: (str) -> str """ Removes Quotes from a Path (e.g. Space-Protection) :type path_string: str :param path_string: :rtype: str :return: unquoted path """ import re return re.sub('\"', '', path_string)
def _get_elementdict(dct, basename, excluded=None): """ get a dictionary of (basename-prefixed) dictionary elements, excluding the excluded names. :param dct: the dict to inspect :param basename: the prefix for the names in the result dictionary :param excluded: excluded dictionary keys [set or...
def doubleChar(words): """ Function to repeat the chars. Given a string, return a string where for every char in the original, there are two chars. Args: words (String): String provided by user Return: result (String): String with characters dupplicated """ result = ""...
def parse_imsi(imsi): """This method verifies that the input is a valid imsi, ie. it is 14 or 15 digits. It will also strip the prefix "IMSI". """ imsi = imsi[4:] if 'IMSI' in imsi else imsi if not str(imsi).isdecimal(): raise TypeError('IMSI not decimal: %s' % imsi) if len(str(imsi)) no...
def read_list(data, delims="[]", split=",", strip=" \n\t'"): """Reads a formatted string and outputs a list. The string must be formatted in the correct way. The start character must be delimiters[0], the end character must be delimiters[1] and each element must be split along the character split. Char...
def del_none(d): """ Delete keys with the value ``None`` in a dictionary, recursively. This alters the input so you may wish to ``copy`` the dict first. """ for key, value in list(d.items()): if value is None: del d[key] elif isinstance(value, dict): del_none(...
def htmlresponse(responsebody): """ Returns a binary string representation an HTTP response that can be sent on a socket. """ header = b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\n\n" body = responsebody.encode("utf-8") return header + body
def encode(value): """ Encode strings in UTF-8. :param value: value to be encoded in UTF-8 :return: encoded value """ return str(u''.join(value).encode('utf-8'))
def _ws_obj(wsid, objid, ver, is_public=True): """Create data for a dummy test workspace obj""" return { '_key': ':'.join((str(n) for n in (wsid, objid, ver))), 'name': 'obj', 'workspace_id': wsid, 'object_id': objid, 'version': ver, 'hash': 'x', 'size': 0...
def process_entry(base_url, i, entry): """Given a base URL, an index, and an entry dictionary, return a list of tests to run.""" tests = [] test = {} # Check entry data type. if type(entry) is not dict: raise ValueError('Entry %d is invalid: "%s"' % (i, entry)) # Validate "replacement" field if 'r...
def max_rewards(actions): """ Takes a set of actions and returns the maximum possible reward. :param actions: a set of mini actions such as 'attack', 'craft: planks' :return: maximum possible rewards with given mini actions """ max_reward = 0 if 'attack' in actions: max_rewar...
def VectorVector_soustraction(vectorA, vectorB): """ N diemnsional. Return an array as a vector resulting from vectorA - vectorB""" result_vector = [] for i in range(0,len(vectorA)): result_vector.append(vectorA[i] - vectorB[i]) return result_vector
def check_string(new): """Check the 'new' string to find the next {input} question.""" rec = False ques = '' for what in new: if what == '{': rec = True if rec is True: ques = ques + what if what == '}': rec = False break return...
def prox_l2_square(x, lbd): """! Compute the proximal operator of the \f$\ell_2\f$ - norm \f$ prox_{\lambda \|.\|_1} = {arg\min_x}\left\{\|.\|_2^2 + \frac{1}{2\lambda}\|x - w\|^2\right\} \f$ Parameters ---------- @param w : input vector @param lamb : penalty paramemeter Retur...
def hash_forward(a, b, c): """ 20 bits for each position, should be more than enough for any grammar """ return (a << 40) ^ (b << 20) ^ c
def find_file_with_string(flist, orb): """ FIND_FILE_WITH_STRING Return the element of a list flist containing the value of orb Parameters ========== flist: list[str] List of file list orb: str String we are looking for in the list Returns ======= ...
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ if len(input_list) < 1: return [] low = 0 high = len(input_list)-1 mid = (low+high)//2 idx = 0 ...
def bd_address_to_int(bd_address): """ Helper function converting a BD address to the corresponding integer value. """ addr_bytes = [int(v, 16) for v in bd_address.lower().split(':')] if len(addr_bytes) != 6: return None else: addr_value = addr_bytes[0] << (8 * 5) addr_v...
def proteins(strand): """ Translate RNA sequences into proteins. :param strand string - The RNA to translate. :return list - The protein the RNA translated into. """ # Some unit tests seem to be funky because of the order ... # proteins = set() proteins = [] stop_codons = ["UAA", "...
def asint(text): """ Safely converts a string to an integer, returning None if the string is None. :type text: str :rtype: int """ if text is not None: return int(text)
def eval_tuple(arg_return): """Evaluate a tuple string into a tuple.""" if type(arg_return) == tuple: return arg_return if arg_return[0] not in ["(", "["]: arg_return = eval(arg_return) else: splitted = arg_return[1:-1].split(",") List = [] for item in splitted: ...
def concatenate_dictionaries(d1: dict, d2: dict, *d): """ Concatenate two or multiple dictionaries. Can be used with multiple `find_package_data` return values. """ base = d1 base.update(d2) for x in d: base.update(x) return base
def is_sub_phrase(phrase_a, phrase_b): """ Returns true if one phrase is a sub phrase of the other. @params a (Array) an array of words @params b (Array) another array of words @return boolean - whether a or b is a sub-phrase of the other. """ # if either are empty, return false if ( ...
def apply_poly(poly, x, y, z): """ Evaluates a 3-variables polynom of degree 3 on a triplet of numbers. Args: poly: list of the 20 coefficients of the 3-variate degree 3 polynom, ordered following the RPC convention. x, y, z: triplet of floats. They may be numpy arrays of same le...
def negotiateHeartBeat(client, server): """Determine the negotiated heart-beating period. :param client: The client's proposed heart-beating period. :param server: The server's proposed heart-beating period. """ if not (client and server): return 0 return max(client, server)
def config_str_to_bool(input_str): """ :param input_str: The input string to convert to bool value :type input_str: str :return: bool """ return input_str.lower() in ['true', '1', 't', 'y', 'yes']
def gateway_environment(gateway_environment): """Ensure that the strict caching is enabled even if it is not the default in the future""" gateway_environment["BACKEND_CACHE_POLICY_FAIL_CLOSED"] = "True" return gateway_environment
def arithm_expr_eval(cell, expr): """Evaluates a given expression :param expr: expression :param cell: dictionary variable name -> expression :returns: numerical value of expression :complexity: linear """ if isinstance(expr, tuple): (left, operand, right) = expr lval = ar...
def isinstance_noimport(obj, cls_str): """Performs an isinstance() check using a stringified class name. Does not require importing the class in question, so this can be used to check for optional dependencies. """ ty = type(obj) if not hasattr(ty, "__module__") or not hasattr(ty, "__qualname...
def extract_HSD_file_name(line): """Takes a Compend 2000 data line that signals the start of high speed data adquisition, and returns the name of the data file where it has been stored. INPUT: line: string. OUTPUT: string. EXAMPLES: The string 'Fast data in =HYPE...