content
stringlengths
42
6.51k
def toJadenCase(string): """ Convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them. Example: Not Jaden-Cased: "How can mirrors be rea...
def recursiveUpdate(target, source): """ Recursively update the target dictionary with the source dictionary, leaving unfound keys in place. This is different than dict.update, which removes target keys not in the source :param dict target: The dictionary to be updated :param dict source: The dicti...
def find_in_dict(data, keys): """ Finds the value in a potentially nested dictionary by a key or set of nested keys. Parameters: ---------- data: :obj:`dict` The dictionary for which we want to find the value indexed by the potentially nested keys. keys: :obj:`list`, :obj:`t...
def risIndependentField_map(ris_text_line_list, ris_fields_dict): """ params: ris_text_line_list, [[],[],[], ...] ris_fields_dict , {} return: ris_text_line_list_dict, [{},[],[],[], ...] """ # ris_text_line_dict_list = [] for ris_line in ris_text_line_list: if isinstance(ris...
def n_colors(lowcolor, highcolor, n_colors): """ Splits a low and high color into a list of n_colors colors in it Accepts two color tuples and returns a list of n_colors colors which form the intermediate colors between lowcolor and highcolor from linearly interpolating through RGB space """ ...
def parentheses_to_snake(x): """ Convert a string formatted as "{a} ({b})" to "{a}_{b}" Args: x: input string Returns: Formatted string """ x_split = x.split(" (") return f"{x_split[0]}_{x_split[1][:-1]}"
def jaccard_similarity(list_1, list_2): """ Function to calculate the jaccard similarity, between two list. If either of them is empty, the similarity is 0.0. """ if not list_1 or not list_2: return 0.0 set1 = set(list_1) set2 = set(list_2) return len(set1.interse...
def sort_dict(resDict): """ sort_dict orders every timeseries in a hierarchy of dataset by its timestamps. """ def sort_timeserie(timeserie): timeserie["values"], timeserie["timestamps"] = zip(*sorted(zip( timeserie["values"], timeserie["timestamps"]), key=lambda x: (x[1...
def quanta_to_string(lx, ly, lz): """Pretty print monomials with quanta lx, ly, lz.""" string = "" string += "X" * lx string += "Y" * ly string += "Z" * lz # if lx: # string += 'x' # if lx > 1: # string += '^{}'.format(lx) # if ly: # string += 'y' # if ly > 1:...
def unify_seq_len(dataset, seq_len, default_id=0): """Cut or extend each sequence in dataset to have the same length. :param dataset a 2-d array, contains sequences of token ids. :param seq_len integer, desired sequence length. :param default_id if a sequence is shorter than seq_len, default_id ...
def clean_none(value): """Convert string 'None' to None.""" if str(value).lower() == 'none': return None return value
def alter_attribute(job_id, attribute): """ Change job attribute :param job_id: int, job id :param attribute: string, job attribute :return: if success, return 1, else return 0 """ import subprocess try: parameter = ['qalter'] parameter.extend(attribute) parameter...
def print_character(ordchr): """Return a printable character, or '.' for non-printable ones.""" if 31 < ordchr < 126 and ordchr != 92: return chr(ordchr) else: return '.'
def lineDis(m,y,point): """slope in decimal, y intercept, (x,y)""" a = m b = -1 c = y m = point[0] n = point[1] return abs(a*m+b*n+c)/((a)**2+(b)**2)**.5
def get_at_least_one_clip_level_cstr_for_video( id_tracklet, tbound_track, groupby, gt, tmp_cstr, extra_info): """ Get data for individual video. Args: id_tracklet: tbound_track: groupby: gt: tmp_cstr: extra_info: Not used here Returns: has_con...
def _match_keys(flow_to_install, stored_flow_dict, flow_to_install_keys): """Check if certain keys on flow_to_install match on stored_flow_dict.""" for key in flow_to_install_keys: if key not in stored_flow_dict["match"]: return False if flow_to_install["match"][key] != stored_flow_d...
def checkfordate(data, date): """ see if date is in data (list of feed items). """ if not data: return False for item in data: try: d = item['updated'] except (KeyError, TypeError): continue if date == d: return True return False
def combine_maps(*maps): """Merge the contents of multiple maps, giving precedence to later maps. Skips empty maps and deletes entries with value None.""" result = {} for map in maps: if not map: continue for key, value in map.iteritems(): if value is None and key...
def convert_null_to_empty_string(value): """ Convert `None` type to empty strings. Used specifically to work around DynamoDB's limitation of not allowing empty strings. See https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-attributes Args: value: The v...
def get_program_dir(parser_name): """Return a directory name given a parser name. In at least one case (GAMESS-UK) the directory is named differently. """ if parser_name == "GAMESSUK": return "GAMESS-UK" return parser_name
def simplify(text, space=" \t\r\n\f", delete=""): """Returns the text with multiple spaces reduced to single spaces The space parameter is a string of characters each of which is considered to be a space. Any characters in delete are excluded from the resultant string. >>> simplify(" this and\\...
def generate_match_indeces(index_list): # "The Permutator" """ The hard part: generating every possible list of indeces :param index_list: list of lists of possible indeces :return: array of possible index lists """ # permutations will be the size of the return value (number of rows) permut...
def as_grid(array, board_size): """Convert a 1D array into a 2D array with given board size.""" return [array[i : i + board_size] for i in range(0, len(array), board_size)]
def to_name(desc): """ Convert an enumeration description to a literal. Not complete! """ return desc.replace(" ","_").replace("/","_").replace("-","_").lower()
def break_segments_by_duration(duration, label, segment_len): """ Return a list of [(duration, label1, label2, ...), ...] such that each duration is == segment_len if set. Note label can be a scalar or vector (in case of multi-label cls) """ if not isinstance(label, list): label ...
def to_int(value): """ >>> to_int('A') 65 >>> to_int(0xff) 255 >>> list(to_int(i) for i in ['T', 'i', 'n', 'y', 0xff, 0, 0]) [84, 105, 110, 121, 255, 0, 0] """ try: return ord(value) except (ValueError, TypeError): return int(value)
def create_list(number_values): """Funtion that creates a list, prompting the user to input the values of the list Args: number_values (int): Number of values that the list will contain Returns: list: List with the values introduced by the user """ list = [] for index in range(...
def serialize_forma_recepcion(forma_recepcion): """ # $ref: '#/components/schemas/formaRecepcion' """ if forma_recepcion: return forma_recepcion.forma_recepcion return ""
def get_colors_for_class_ids(class_ids): """Set color for class.""" colors = [] for class_id in class_ids: if class_id == 1: colors.append((.941, .204, .204)) return colors
def weave_lists(tables, non_tables, text_first): """ Takes a list of tables, non-tables and a boolean indicating which should come first and returns a single list of lines. """ new_list = [] total_blocks = len(tables) + len(non_tables) for i in range(total_blocks): if text_first: ...
def get_exon_pairs(exon_stat): """Get pairs of I exons to check for split stop codons.""" pairs = [] pair_init = None for num, stat in enumerate(exon_stat): if num == 0: # X - placeholder continue prev_num = num - 1 prev_stat = exon_stat[prev_num] if...
def to_bool(value): """ Converts value to a bool """ return value.lower() in ['true', 'yes', 'on']
def chose_score_type(score_type, gts): """ Return the proper score type according to the following rules Parameters --- score_type : list of str The key to retrieve the list of notes from the ground_truths. If multiple keys are provided, only one is retrieved by using the f...
def LimiterG2forDYS(dU1, dU2, dU3): """Return the limiter for Davis-Yee Symmetric TVD limiter function. This limiter is further used to calculate the flux limiter function given by Equation 6-141. Calculated using Equation 6-143 in CFD Vol. 1 by Hoffmann. """ if dU1 != 0: S = dU...
def parse_shader_error( error ): """Parses a single GLSL error and extracts the line number and error description. Line number and description are returned as a tuple. GLSL errors are not defined by the standard, as such, each driver provider prints their own error format. Nvidia print using ...
def get_common_bit(readings, index): """ Returns the most common bit at index index in list readings :param readings: List:str :param index: int :return: """ zeros, ones = 0, 0 for reading in readings: if reading[index] == '0': zeros += 1 elif reading[index] =...
def convertSucPrecListToIntList(spList): """Method to convert the comma seperated string values to integer list for usage returns None is the input is None, else returns an integer list depending on the input value count""" if spList is not None: stringListPreceeders=spList.split(",") ...
def ignore_file(file, ignore): """ Ignores file if the file is within any of the user specified directories :param file: str, path to a file :param ignore: list, directories to ignore :return: bool, True if the directory is in the file path, False otherwise """ for directory in ignore: ...
def _recurse_replace(obj, key, new_key, sub, remove): """Recursive helper for `replace_by_key`""" if isinstance(obj, list): return [_recurse_replace(x, key, new_key, sub, remove) for x in obj] if isinstance(obj, dict): for k, v in list(obj.items()): if k == key and v in sub: ...
def _get_prediction_length(predictions_dict): """Returns the length of the prediction based on the index of the first SEQUENCE_END token. """ tokens_iter = enumerate(predictions_dict["predicted_tokens"]) return next(((i + 1) for i, _ in tokens_iter if _ == "</s>"), len(predictions_dict["predicte...
def decode_modified_utf8(s: bytes) -> str: """ Decodes a bytestring containing modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param s: bytestring to be converted. :returns: A unicode representation of the original string. """ s_out = [] s_len = len(s) s_ix = 0...
def parse_wire(line): """Parse line to directions with steps creating wire.""" wire = [] for instruction in line.split(','): direction, *steps = instruction wire.append((direction, int(''.join(steps)))) return wire
def verify(data): """ Sanity check on read CSV data. :param list data: Read data as list of lists :return: Same data but with headers removed :rtype: list of lists """ headers = data.pop(0) expected = ['Date', 'Time', 'Amount', 'Location', 'Notes'] check = [e for e in expected for h...
def translate_keys(d, translations, ignore=None): """Cambia las keys del diccionario 'd', utilizando las traducciones especificadas en 'translations'. Devuelve los resultados en un nuevo diccionario. Args: d (dict): Diccionario a modificar. translations (dict): Traducciones de keys (key...
def to_hex(val, nbits): """Convert a long to hex. :param val: long. :param nbits: The number of bit two's complement. :return: hex value. """ return hex((val + (1 << nbits)) % (1 << nbits))
def combine(tree, context, attribs): """A meta-feature combining n-tuples of other features (as found in context['feats']). @rtype: dict @return: dictionary with keys composed of combined keys of the original features \ and values equal to 1. """ cur = context['feats'][attribs[0]] for a...
def has_latex_attr(x): """ Return ``True`` if ``x`` has a ``_latex_`` attribute, except if ``x`` is a ``type``, in which case return ``False``. EXAMPLES:: sage: from sage.misc.latex import has_latex_attr sage: has_latex_attr(identity_matrix(3)) True sage: has_latex_attr...
def parse_create_or_delete(message): """ Parses create or delete event. """ return { 'type': message["type"], 'event': message["action"], 'values': { 'user': message["data"]["owner"]["name"], 'subject': message["data"]["subject"] if "subject" i...
def _parse_svg_unit_as_pixels(unit): """Parse a unit from a SVG file.""" if unit.endswith('pt'): value = float(unit[:-2]) # Magic value which seems to works fine for what pdf2svg and dvisvgm outputs return round(value * 1.777778) else: # Looks like we need no other unit for o...
def per_user_hourly_data(data_per_month_gb, percentage_share): """ Estimate the per user data demand in Mbps. """ per_user_mbps = ( data_per_month_gb * 1000 * 8 * (1/30) * (percentage_share/100) * (1/3600) ) return per_user_mbps
def calculate_position(moving_average_1, moving_average_2, moving_average_3, moving_average_4): """ DOCSTRING """ if moving_average_4 > moving_average_1 > moving_average_2 > moving_average_3: return 1 elif moving_average_1 > moving_average_4 > moving_average_2 > moving_average_3: ret...
def ArgsHaveTunnelThroughIap(args): """Determine if the current track has this flag and if it is also enabled.""" return hasattr(args, 'tunnel_through_iap') and args.tunnel_through_iap
def _add_no_underscore_compatibility(classes): """ Add class names without underscores for compatibility. Previously, no resources had underscores in APIClient. Parsing of resources has been fixed so now these resources will have underscores. This adds an extra class for those resources without an und...
def is_registered(delegate): """ Returns True if delegate is present and a keypad has been assigned. :param delegate: User object :return: bool """ return delegate is not None and hasattr(delegate, 'keypad') and delegate.is_present
def sort_counts(counts): """ Sorting """ print("Sorting by count") countofwords = [(count, word) for word, count in counts.items()] sortedcounts = sorted(countofwords, reverse=True) return sortedcounts
def printStuff(old, fileCoocs, env): """ coocinfos = defaultdict(list) for cooc in fileCoocs: if cooc.relation == None and not cooc.sameSentence: continue coocinfos[(cooc.gene, cooc.mirnaFound, cooc.mirna)].append((cooc.pubmed, cooc.relation)) if len(coocinfos) > 0: ...
def yesish(value): """Typecast booleanish environment variables to :py:class:`bool`. :param string value: An environment variable value. :returns: :py:class:`True` if ``value`` is ``1``, ``true``, or ``yes`` (case-insensitive); :py:class:`False` otherwise. """ if isinstance(value, bool): ...
def to_python_type(py_type: str) -> type: """Transform an OpenAPI-like type to a Python one. https://swagger.io/docs/specification/data-models/data-types """ TYPES = { 'string': str, 'number': float, 'integer': int, 'boolean': bool, 'array': list, 'object'...
def _gen_keys_from_multicol_key(key_multicol, n_keys): """Generates single-column keys from multicolumn key.""" keys = [('{}{:03}of{:03}') .format(key_multicol, i+1, n_keys) for i in range(n_keys)] return keys
def info(text): """Create a pretty informative string from text.""" return f"\033[92m{text}\033[m"
def _get_all_risks(risk): """ called by build_risk() to get all risks in a friendly string """ risk_filtered = list(filter(lambda x: x['count'] > 0, risk)) risk_str = ','.join(map(lambda x: x['countType'], risk_filtered)) return risk_str
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return username == 'admin' and password == 'secret'
def create_price_table_row(header, description, final_url, price_in_micros, currency_code, price_unit, final_mobile_url=None): """Helper function to generate a single row of a price table. Args: header: A str containing the header text of this row. description: A str description of this row in the p...
def get_sentinel_incident_ids(sentinel_incident): """ Returns: [str]: [sentinel_indident_id or None if not found] """ if not sentinel_incident: return None return sentinel_incident['name'], sentinel_incident['properties']['incidentNumber']
def splitIgnoringQuotes(string, charToSplitOn=" "): """ will split on charToSplitOn, ignoring things that are in quotes """ string = string.lstrip() # strip padding whitespace on left toReturn = [] thisWord = [] lastSplitPos = 0 inQuote = False for char in string: if (in...
def is_meeting_metadata(json_record): """ returns true if given record is a header :param json_record: :return: """ if 'startTime' in json_record: return True elif "type" in json_record and json_record["type"] == "meeting started": return True else: return False
def _build_pos_map(smap, placements): """Build a dict of sprite ref => pos.""" return dict((n.fname, p) for (p, n) in placements)
def handle_latex_preprocessing(latex_string): """ Preprocesses the LaTeX string to be parsed in Sympy. Args: latex_string (str): The string with the LaTeX input. Returns: str: The cleaned LaTeX string. """ try: # Remove any unneeded tags latex_string = latex...
def constraint_class(kind): """ The convention is that name of the class implementing the constraint has a simple relationship to the constraint kind, namely that a constraint whose kind is 'this_kind' is implemented by a class called ThisKindConstraint. So: min --> MinConstraint ...
def to_minutes(hour, minute): """ converts hours to minutes and adds extra minutes in the time... returns the sum """ return (hour * 60) + minute
def mySqrt(x): """ :type x: int :rtype: int """ return int(x**0.5)
def build_url(selector, child_key, parent_key): """Return url string that's conditional to `selector` ("site" or "area").""" if selector == "site": return "https://%s.craigslist.org/" % child_key return "https://%s.craigslist.org/%s/" % (parent_key, child_key)
def get_unique_cves_context(unique_cves_list, host_finding_id): """ Iterate over vulnerability list and extract attribute for context data. This method is used in 'risksense-get-unique-cves' command. :param unique_cves_list: List of vulnerabilities. :param host_finding_id: The unique host finding I...
def fwhm(fwhm_now, lambda_now, secz_now, lambda_next, secz_next): """Predict the fwhm. Parameters: ----------- fwhm_now : The fwhm value of the current exposure lambda_now : The wavelength of the current exposure secz_now : The airmass of the current exposure lambda_next : The wavele...
def _is_class_obj(obj): """ A dummy way of telling if an object is a Class Object""" return callable(obj) and not hasattr(obj, '__code__')
def HAMM(dna1, dna2): """Not bounded by DNA length version.""" return sum(c1 != c2 for c1, c2 in zip(dna1, dna2))
def to_dict(obj): """Convert a dictionary-like object to a dictionary. >>> to_dict({'key': 42}) {'key': 42} >>> to_dict("key=42") {'key': '42'} >>> to_dict("key") {'key': None} >>> to_dict(None) {} """ if isinstance(obj, dict): return obj elif isinstance(obj,...
def taylor_4(xs, h, y0, f, df_x, df_y, df_xx, df_yy, df_xy, **derivatives): """Taylor 4rd""" ys = [y0] for k in range(len(xs)): second_summand = f(xs[k], ys[k]) * h third_summand = ( df_x(xs[k], ys[k]) + df_y(xs[k], ys[k]) * f(xs[k], ys[k]) ) * (h ** 2) / 2 fourth...
def label_preprocess(entry, responses): """ Returns integer ID corresponding to response for easy comparison and classification Args: entry: query item responses: dict containing all the template responses with their corresponding IDs Return: integer correspondin...
def rescale_center_xy(obj, config): """ obj: dictionary containing xmin, xmax, ymin, ymax config : dictionary containing IMAGE_W, GRID_W, IMAGE_H and GRID_H """ center_x = .5 * (obj['xmin'] + obj['xmax']) center_x = center_x / (float(config['image_w']) / config['grid_w']) center_y = .5...
def blend_color(a, b): """ Blends two colors together by their alpha values. Args: a(tuple): the color to blend on top of b b(tuple): the color underneath a Return: The blended color. """ if len(a) == 3: a = (*a, 255) if len(b) == 3: b = (*b, 255) ...
def inv_mod_p(a, p): """ Returns the inverse of a mod p Parameters ---------- a : int Number to compute the inverse mod p p : int(prime) Returns ------- m : int Integer such that m * a = 1 (mod p) Raises ------ ValueError If p is not a prime num...
def min_edit_distance( source: str, target: str, del_cost=1, ins_cost=1, sub_cost=2, ): """Minimum-Edit-Distance(DP) Args: `source`: source chars. `target`: target chars. `del_cost`: delete cost. `ins_cost`: insert cost. `sub_cost`: substitute cost. ...
def get_maplist(matchs_data): """Returns the lists of every map played, in order, and the list of unique map played Each map is identified by a string giving the map nameS List of unique map played: corresponds to the maps encontered at least once by the team """ map_list = [] for match in...
def axis_check(shape_len, axis): """Check the value of axis and return the sorted axis.""" def _axis_value_type_check(value): if not isinstance(value, int): raise RuntimeError("type of axis value should be int") if value >= shape_len or value < -shape_len: raise RuntimeEr...
def return_dict_values(dct: dict) -> list: """ Returns keys of a dict in a list >>> return_dict_values({'a':1, 'b':2, 'c':3}) [1, 2, 3] """ return list(dct.values())
def digits(s): """grab digits from string""" return str("".join([c for c in s if c.isdigit()]))
def _get_index(x, x_levels): """Finds element in list and returns index. Parameters ---------- x: float Element to be searched. x_levels: list List for searching. Returns ------- i: int Index for the value. """ for i, value in enumerate(x_levels): ...
def build_definition(config): """ Build a pipeline definition based on given configuration. """ definition = { 'sources': [ { 'type': 'timestamp', 'id': 'timekey', 'config': { 'iso8601': True, # Key for InfluxDB ...
def no_anagrams(passphrase): """Checks if passphrase doesn't contain words that are anagrams.""" anagrams = set(''.join(sorted(word)) for word in passphrase) return len(passphrase) == len(anagrams)
def strip_field(f, keep_filters=False): """Helper tool: remove parameters from VOTABLE fields However, this should only be applied to a subset of VOTABLE fields: * ra * dec * otype * id * coo * bibcodelist *if* keep_filters is specified """ if '(' in f: root =...
def count_characters_at_position(seqAtPosition): """ Count the occurence of each character at a given position in an alignment. This information is used to determine if the aligment is parsimony informative or not. When count characters, gaps ('-') are excluded Arguments --------- argv...
def get_new_mean(value, current_mean, count): """Given a value, current mean, and count, return new mean""" summed = current_mean * count return (summed + value)/(count + 1)
def kmp(haystack, needle): """ Run KMP search on haystack on needle and return all matching indexes Return empty list on no result :param haystack: :param needle: :return: """ needle = list(needle) len_needle = len(needle) shifts = [1] * (len_needle + 1) shift = 1 for...
def validate_user_data(user_data): """ Validate user_data dict by checking that the majority of the keys have non-empty values. Return an empty dictionary if main keys' values are empty, otherwise the original dictionary. :param user_data: :return: dict """ try: if user_data...
def time_str_from_datetime_str(date_string: str) -> str: """ Extracts the time parts of a datetime. Example: 2019-12-03T09:00:00.12345 will be converted to: 09:00:00.12345 :param date_string: :return: """ return date_string.split('T')[1]
def gcd(a: int, b: int): """Problem 32: Determine the greatest common divisor of two positive integer numbers. Parameters ---------- a : int An positive integer number b : int An positive integer number Returns ------- int The greatest common divisor of the give...
def normalize_angle(ang,type): """ Normalizes any angle in degrees to be in the interval [0.,360.) or [-180.,180.). nangle = Ngl.normalize_angle(angle, option) angle -- An angle in degrees. option -- An option flag that is either zero or non-zero. """ # # This function normalizes the angle (assumed to be in deg...
def norm(X, n=2): """Return the n-norm of vector X""" return sum([x**n for x in X])**(1/n)
def authenticate(username, password): """ Returns the user payload (dict) if login is valid else returns False. """ if username == "test" and password == "test": user_payload = {"username": username} return user_payload else: return False