content
stringlengths
42
6.51k
def _build_gcp_extra(metadata): """ Helper function to build the gcp extra dict """ gcp_extra= {} gcp_extra['cloud_project_id']=metadata['project']['projectId'] gcp_extra['cloud_name'] = metadata['instance']['name'] gcp_extra['cloud_hostname'] = metadata['instance']['hostname'] gcp_extra['cloud_...
def map_wn_pos(pos): """ Map a Penn Treebank POS tag to a WordNet style one """ if pos in ['NN', 'NNS']: # not NNP! return 'n' elif pos.startswith('JJ'): return 'a' elif pos.startswith('RB'): return 'r' elif pos.startswith('VB'): return 'v' else: ...
def is_valid_name(name: str) -> bool: """Returns Ture if a given string represents a valid name (e.g., for a dataset). Valid names contain only letters, digits, hyphen, underline, or blanl. A valid name has to contain at least one digit or letter. """ allnums = 0 for c in name: if c.isalnum(): all...
def is_album_id(item_id): """Validate if ID is in the format of a Google Music album ID.""" return len(item_id) == 27 and item_id.startswith('B')
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.a...
def __parse_filter__(query): """ First checks if the provided query is a string and splits by comma to create a list, otherwise the list is used. NOTE: This must be done because falcon parse the query parameters differently depending on the encoding. :param query: The query parameter parsed by falcon ...
def __transition_map_cost(ImplementedStateN, IntervalN, SchemeN): """ImplementedStateN -- Number of states which are implemeted in the scheme. IntervalN -- Number of intervals in the transition map. SchemeN -- Number of DIFFERENT schemes in the transition map. Find a number ...
def average_precision(ret, ans): """ ret: list of tuples [ (docname, score) ] ans: python dictionary with answer as keys """ tp = [float(docID in ans) for docID, val in ret] precisions = [] ans_count = 0 for idx, (docID, val) in enumerate(ret): ans_count += tp[id...
def convert_float_time(time): """Converts a time from a string to a float. time is the time that needs to be converted.""" # If an asterisk is in the time, the time is in the wrong time # period. If the asterisk time is in teleop, the time period is # supposed to be in sandstorm, so it sets the tim...
def factorial(x): """returns factorial of x""" if type(x) != int: print("ERROR <- x in factorial(x) is not type int") return result = 1 for i in range(1,x+1): result *= i return result
def sign(a): """Gets the sign of a scalar input.""" if a >= 0: return 1 else: return 0
def string_to_list(t_str, t_char=" "): """ Returns a list of elements that are contains inside the string param. :param str t_str: string with elements and delimiters :param str t_char: delimiter of the elements :return list t_list: list of elements that were inside t_str """ t_list = t_str...
def string_to_num(word): """ Converts a string to a list of numbers corresponding to the alphabetical order of the characters in the string >>> assert string_to_num('abc') == [0, 1, 2] >>> assert string_to_num('generator') == [2, 1, 3, 1, 5, 0, 6, 4, 5] """ all_letters = sorted(list(set(word))) ...
def strand(s1, s2): """ Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length. """ return "".join(map(lambda x,y:chr(ord(x)&ord(y)), s1, s2))
def get_class_hierarchy_names(obj): """Given an object, return the names of the class hierarchy.""" names = [] for cls in obj.__class__.__mro__: names.append(cls.__name__) return names
def _transform_playlist(playlist): """Transform result into a format that more closely matches our unified API. """ transformed_playlist = dict([ ('source_type', 'youtube'), ('source_id', playlist['id']), ('name', playlist['snippet']['title']), ('tracks', playlist['conten...
def signed_to_unsigned(value: int, size: int) -> int: """Converts the given value to its unsigned representation.""" if value < 0: bit_size = 8 * size max_value = (1 << bit_size) - 1 value = max_value + value return value
def get_security_group_id(event): """ Pulls the security group ID from the event object passed to the lambda from EventBridge. Args: event: Event object passed to the lambda from EventBridge Returns: string: Security group ID """ return event.get("detail").get("requestParameter...
def flatten_json(json_dict: dict, block_i: int) -> dict: """Flatten python dict Args: json_dict (dict): post blocks dict structure block_i (int): block numeric id Returns: dict: flat dict """ out = {} def flatten(x: dict, name: str = '') -> None: if isinstance(...
def get_return_var(return_type: str) -> str: """ int foo() => return r; void foo() => '' """ s = return_type.strip() if 'void' == s: return '' return 'return r;'
def playfair_wrap(n, lowest, highest): """Ensures _n_ is between _lowest_ and _highest_ (inclusive at both ends). """ skip = highest - lowest + 1 while n > highest or n < lowest: if n > highest: n -= skip if n < lowest: n += skip return n
def assert_equal(a, b): """ Wrapper to enable assertions in lambdas """ assert a == b return True
def path_to_url(path): """Convert a system path to a URL.""" return '/'.join(path.split('\\'))
def NE(x=None, y=None): """ Compares two values and returns: true when the values are not equivalent. false when the values are equivalent. See https://docs.mongodb.com/manual/reference/operator/aggregation/ne/ for more details :param x: first value or expression :param y: second...
def errorInFile(f, line=17, name=''): """ Return a filename formatted so emacs will recognize it as an error point @param line: Line number in file. Defaults to 17 because that's about how long the copyright headers are. """ return '%s:%d:%s' % (f, line, name) # return 'File "%...
def randomize_times(times, ids = []): """ Randomize the times of the point events of all the ids that are given. This just reshuffles the event times among all the individuals taking into account. Parameters ---------- times : dictionary of lists The dictionary contains for each elem...
def kth_element(list_a: list, k: int): """Problem 3: Find the K'th Element of a List Parameters ---------- list_a : list The input list k : int The element to fetch Returns ------- element The k'th element of the input list Raises ------ TypeError ...
def find_pivot(input_arr, min_idx, max_idx): """ Find the the pivor index of an rotated array Time complexity: O(1og2(n)) Space Complexity: O(1) Args: input_array(array): rotated array Returns: pivot_idx(int) """ mid = (min_idx + max_idx) // 2 # if mid ...
def print_fileinfo(filename, line_number, message, vi=False): """Return a formatted string with filename, line_number and message. Keyword arguments: vi -- output line numbers in a format suitable for passing to editors such as vi (default False) """ if vi: return '%s +%d #%s' % (filename, ...
def get_body_payload_initial(dataset, dataset_uid, published): """ Create an initial body payload Keyword arguments: dataset: data set dataset_uid: data set UID published: True=public, False=private Returns: body_payload: initial body payload """ data_...
def trailing_zeros(n): """Returns number of trailing zeros in n factorial.""" # factorial of nums less 5 doesn't end with 0 if n < 5: return 0 # example: n = 11 # n % 5 = 1 => n - 1 = 10 => 10 // 5 = 2 reminder = n % 5 result = (n - reminder) // 5 return result
def fix_xiaomi_battery(value: int) -> int: """Convert battery voltage to battery percent.""" if value <= 100: return value if value <= 2700: return 0 if value >= 3200: return 100 return int((value - 2700) / 5)
def get_id_key(entity_name): """Get entity id key. Follows the simple convention that *id_key* is the *entity_name* followed by '_id'. Args: entity_name (str): entity_name Return: id_key (str) .. code-block:: python >>> from utils.db import get_id_key >>> ent...
def is_nonneg_int(num_str): """ Args: num_str (str): The string that is checked to see if it represents a nonneg integer Returns: bool Examples: >>> is_nonneg_int("25.6") False >>> is_nonneg_int("-25.6") False >>> is_nonneg_int("0") True ...
def _is_dynamic(module): """ Return True if the module is special module that cannot be imported by its name. """ # Quick check: module that have __file__ attribute are not dynamic modules. if hasattr(module, '__file__'): return False if hasattr(module, '__spec__'): return m...
def filter_args(arg_dict, desired_fields=None): """only pass to network architecture relevant fields.""" if not desired_fields: desired_fields = ['net_type', 'num_scales', 'in_channels', 'mid_channels', 'num_levels'] return {k:arg_dict[k] for k in desired_fields if k in arg_dict}
def __dumpbin_parse_exports(input): """Parse thr output from dumpbin as a list of symbols""" ret = [] lines = input.split('\n') for line in lines: arr1 = line.split() if len(arr1) == 4 and arr1[1] != 'number' and arr1[1] != 'hint': ret.append(arr1[3]) return ret
def glue(vec_a, vec_b): """ concatenate two smaller vectors to a larger vector vec_a : first vector vec_b : second vector """ retval = list() retval.extend(vec_a) retval.extend(vec_b) return retval
def calculo_notas(nota): """float-->float OBJ:Calcular la nota redondeando a 0.5 PRE: 10<=nota>=0""" nota_final=round(2*nota)/2 return nota_final
def one_of_k_encoding(x, allowable_set): """ Encodes elements of a provided set as integers. Parameters ---------- x: object Must be present in `allowable_set`. allowable_set: list List of allowable quantities. Example ------- >>> import deepchem as dc >>> dc.feat.graph_...
def parse_field(line, d): """ Extract regular field & value from: Destination directory = "R:\speed-test\big_files\" Directories processed = 1 Total data in bytes = 527,331,269 ... """ if " = " in line: field, value = line.split(" = ") d[fie...
def predict_column_type(data): """ Predict the data type of the elements present in a list. It will be defaulted to string. Args: data : array Returns: type: Column data type """ data_types = [type(item) for item in data] data_types = list(set(data_types)) if len(data_t...
def getgain(image): """ Get the gain from the header.""" gain = 1.0 # default # check if there's a header if hasattr(image,'meta'): if image.meta is not None: # Try all versions of gain for f in ['gain','egain','gaina']: hgain = image.meta.get(f) ...
def get_first_year(data_id): """Returns first year in which ground truth data or forecast data is available Args: data_id: forecast identifier beginning with "nmme" or ground truth identifier accepted by get_ground_truth """ if data_id.startswith("global"): return 2011 if da...
def _stringListEncoderHelper( n, maxLenS ): """ helper method for string encoding for list iterator """ maxLenS[0]= max( maxLenS[0], len( n ) ) return n.encode( "ascii", "ignore" )
def name_standard(name): """ return the Standard VERSION of the input word :param name: the name that should be standard :type name:str :return name: the standard form of word as string >>> name_standard('test') 'Test' >>> name_standard('TesT') 'Test' """ reponse_name = name[...
def scale(y, a, b): """ Scales the vector y (assumed to be in [0,1]) to [a,b] :param y: :param a: :param b: :return: """ return a * y + (b - a) * y
def hey(phrase): """ Bob is a lackadaisical teenager with limited conversational skills """ phrase = phrase.strip() if phrase == "": return "Fine. Be that way!" if phrase.upper() == phrase and phrase.lower() != phrase: return "Whoa, chill out!" if phrase.endswith("?"): ...
def validate_age(age): """ Validate that the age provided is a number """ if isinstance(age, int): return True age_okay = True age_range = age.split('-') for number in age_range: try: int(number) except ValueError: return False return age_o...
def get_all_tags(y_true): """ Return a set of all tags excluding non-annotations (i.e. "_", "O", "-") :param list y_true: a nested list of labels with the structure "[docs [sents [tokens]]]". :return: set of all labels. :rtype: set """ # keep only primary annotation when separated by a pip...
def convert_validate_date(input_date): """ :param input_date :return: validate date """ if len(input_date) == 1: input_date = '0{}'.format(input_date) return input_date
def is_float(obj): """Check if obj is float.""" return isinstance(obj, float)
def merge(source:dict, destination:dict): """ Utility function to merge two dictionaries .. code-block:: python a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } } b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } } print(merge(b, a)) # {...
def container_for_key(key): """ Determines what type of container is needed for `key` """ try: int(key) return [] except ValueError: return {}
def beaufort(ws_kts): """Return the beaufort number given a wind speed in knots""" if ws_kts is None: return None elif ws_kts < 1: return 0 elif ws_kts < 4: return 1 elif ws_kts < 7: return 2 elif ws_kts < 11: return 3 elif ws_kts < 17: return ...
def audit_renamed_col_dict(dct: dict) -> dict: """ Description ----------- Handle edge cases where a col could be renamed back to itself. example: no primary_geo, but country is present. Because it is a protected col name, it would be renamed country_non_primary. Later, it would be set as pr...
def db_tables(schema_name): """ Manifest of all application tables expected in database when all migrations are run """ if schema_name.lower() == 'transactional': tbl_list = ['participant', 'program', 'participant_program', 'program_provider', 'provid...
def get_mean(l): """ Concatenates two pandas categoricals. Parameters ---------- l : list A list of numbers. Returns ------- float The result. Examples -------- >>> from foocat_tao_huang import foocat_tao_huang >>> a = [1,2,3] >>> foocat.get_mean(a) ...
def initialize_coverage_dict(taget_revision_dict): """ Initializes coverage dictionary, containing coverage data Currently supported coverage is total document coverage and chapter coverage. total - computes the total amount of paragraphs in a given section ( = chapter, subchapter, document...)...
def find_string(s): """ Find start and end of a quoted string """ result = next((i, c) for i, c in enumerate(s) if c in ('"', "'")) if result is not None: start, quote_char = result end = next( i for i, c in enumerate(s[start + 1: ]) if c == quote_char and s[i - 1] !=...
def numf(s, defval=0.0): """Return interpreted float - unlike num default is 0.0.""" f = str(s).strip() if s else None if not f: return defval try: return float(f) except: print("Could not float(%s)" % (f,)) return defval
def _MakeSignature(app_id=None, url=None, kind=None, db_filename=None, perform_map=None, download=None, has_header=None, result_db_filename=None, dump=None, ...
def _get_coord_zoom_and_shift(ndim, nprepad=0): """Compute target coordinate based on a shift followed by a zoom. This version zooms from the center of the edge pixels. Notes ----- Assumes the following variables have been initialized on the device:: in_coord[ndim]: array containing the s...
def max_retention(frequencies): """Calculate the amount of seconds in a retention unit.""" sec_dict = { 'minute': 60, 'hourly': 3600, 'daily': 86400, 'weekly': 604800, 'monthly': 2592000, 'quarterly': 7776000, 'yearly': 31536000 } secs = [] fo...
def convert_chemformula(string): """ Convert a chemical formula string to a matplotlib parsable format (latex). Parameters ---------- string or Adsorbate: str String to process. Returns ------- str Processed string. """ result = getattr(string, 'formula', None) ...
def calculate_range_parameter(part_size, part_index, num_parts, total_size=None): """Calculate the range parameter for multipart downloads/copies :type part_size: int :param part_size: The size of the part :type part_index: int :param part_index: The index for which t...
def headers(token=None): """ Creates a dict of headers with JSON content-type and token, if supplied. :param token: access token for account :return: dictionary of headers """ data = {'Content-Type': 'application/json'} if token: data['Token'] = token return data
def dequeue(queue): """ Return anytype from queue""" return None if not queue else queue.pop(0)
def listToString(s): """ Description: Need to build function because argparse function returns list, not string. Called from main. :param s: argparse output :return: string of url """ # initialize an empty string url_string = "" # traverse in the string for ele in s: url_str...
def replace_id_to_name(main_list, type_list, str_main_id, str_type_id, str_prop): """ Return list replacing type id to type name """ for item in main_list: id_type = item[str_main_id] for type_item in type_list: if type_item[str_type_id] == id_type: item[str_...
def is_core_type(type_): """Returns "true" if the type is considered a core type""" return type_.lower() in { 'int', 'long', 'int128', 'int256', 'double', 'vector', 'string', 'bool', 'true', 'bytes', 'date' }
def get_tag_values_from_ifds(tag_num, ifds): """ Return values of a tag, if found in ifds. Return None otherwise. Assuming any tag exists only once in all ifds. """ for key, ifd in ifds.items(): if tag_num in ifd.tags: return ifd.tags[tag_num].values return None
def all_gt_counts(n_alleles, ploidy): """ all_gt_counts(n_alleles=3, ploidy=2) -> (2, 0, 0), (1, 1, 0), (1, 0, 1), (0, 2, 0), (0, 1, 1), (0, 0, 2) all_gt_counts(n_alleles=2, ploidy=3) -> (3, 0), (2, 1), (1, 2), (0, 3) """ if n_alleles == 1: return ((ploidy,),) genotype = [0] * ...
def _build_tags_predicates(match_all=None): """ Build tags predicates """ must = {} if match_all: for condition in match_all: must[condition['tag']] = condition['value'] return must
def get_shape2D(in_val): """ Return a 2D shape Args: in_val (int or list with length 2) Returns: list with length 2 """ in_val = int(in_val) if isinstance(in_val, int): return [in_val, in_val] if isinstance(in_val, list): assert len(in_val) == 2 ...
def compute_limits(numdata, numblocks, blocksize, blockn): """ Generates the limit of indices corresponding to a specific block. It takes into account the non-exact divisibility of numdata into numblocks letting the last block to take the extra chunk. Parameters ---------- ...
def _take(n, mydict): """Return first n items of the iterable as a list""" return {k: mydict[k] for k in list(mydict)[:n]}
def normalise_dict_keys(dict_obj): """replaces `:` to `-` in dict""" result = {} for key, value in dict_obj.items(): key = key.replace(":", "-") result[key] = value return result
def error_reduction(error_before_split, error_after_split): """ Purpose: Compute the difference between error before and after split Input : Error before split and error after split Output : Difference between error before and after split """ return (error_before_split - error_after_split...
def count_m_w(data): """ Count men and women in the given data (list of dict) Sex is in the 'civilite' column """ men = [item for item in data if item['civilite'] == "M."] women = [item for item in data if item['civilite'] == "Mme"] return len(men), len(women)
def lowest_weight(edges): """ Get edges based on lowest weight first """ return list(sorted(edges, key=lambda data: data[2]["weight"]))
def have_underscore_symbol(l): """Check if underscore is present""" if "_" in str(l): return 1 else: return 0
def calculate_value(player_name, game_data): """ Compute the total ship value of a player. Parameters ---------- player_name: name of the player to count value (str) game_data: game before command execution (dic) Version ------- Specification: Alisson Leist, Bayron Mahy, Nicolas Va...
def get_language(file_path): """Returns the language a file is written in.""" # print(file_path) if file_path.endswith(".py"): return "python" else: return ''
def x_to_s (x, chars): """Convert a list of integers to a string. x_to_s(x, chars) -> s The reverse of s_to_x. """ return ''.join(chars[d] for d in x)
def get_median(elements): """The midpoint value of a data set for which an equal number of samples are less than and greater than the value. For an odd sample size, this is the middle element of the sorted sample; for an even sample size, this is the average of the middle elements of the sorted sample....
def question1(s, t): """input- two strings output- True if anagram of t is substring in s, False otherwise""" if not t: return False t_list = list(t) for i in range(len(s)): value = s[i] if value in t_list: for j in range(len(t_list)): if t_lis...
def replace_elem(lst, index, elem): """Create and return a new list whose elements are the same as those in LST except at index INDEX, which should contain element ELEM instead. >>> old = [1, 2, 3, 4, 5, 6, 7] >>> new = replace_elem(old, 2, 8) >>> new [1, 2, 8, 4, 5, 6, 7] >>> new is old ...
def no_prefix(name): """does the given constant have a ZMQ_ prefix?""" return name.startswith('E') and not name.startswith('EVENT')
def fastMaxVal(toConsider, avail, memo = {}): """Assumes toConsider a list of items, avail a weight Returns a tuple of the total value of a solution to 0/1 knapsack problem and the items of that solution""" if (len(toConsider), avail) in memo: result = memo[(len(toConsider), avail)] elif...
def common_suffix(a, b): """ compute longest common suffix of a and b """ while not a.endswith(b): b = b[1:] return b
def isclassinstance(obj): """Return True if obj is an instance of a class.""" return hasattr(obj, '__class__')
def _check_axis_in_range(axis, ndim): """Checks axes are with the bounds of ndim""" if -ndim <= axis < ndim: return True raise ValueError(f'axis {axis} is out of bounds for array of dimension {ndim}')
def Quiz_Answer_Check(Question, Key, Answers): """ Function to check the Quiz Answers""" Index = 0 Q = 0 Correct = 0 while Q != Question: if Key[Index] == Answers[Index]: Correct += 1 Q += 1 Index += 1 Grade = int((Correct / Question) * 100) return Correc...
def read_str_file(file_name): """ Reads in a file with floating point value strings, 1 per line. """ x = [] try: with open(file_name, 'r') as f: lines = f.read().splitlines() for y in lines: try: x.append(float(y)) ...
def leading_zero_template(ceiling): """Return a template suitable for formatting numbers less than 'ceiling'. ceiling -- int or None Returns a string suitable for Python %-formatting numbers from 0 to ceiling-1, with leading zeros so that the strings have constant length. If ceiling is None, ther...
def get_int_default_or_max(val, default_val, max_val=None): """Given a string try to turn it into an int and enforce a max and default if the string is not a int value""" try: i = int(val) if max_val and i > max_val: i = max_val except: i = default_val return i
def fix_strength(val, default): """ Assigns given strength to a default value if needed. """ return val and int(val) or default
def pack(ascii, tail=b''): """Packs groups of 4 ascii-encoded edifact chars into 3-byte words.""" assert (len(ascii) + len(tail)) % 4 == 0 raw = [code & 0x3F for code in ascii if 32 <= code <= 94] if len(raw) < len(ascii): raise ValueError('Invalid EDIFACT') raw += tail packed = [] ...
def halvorsen(xyz, t, a): """Like a rose with only three petals. Cyclically symmetric.""" x, y, z = xyz dx = - a * x - 4 * (y + z) - y ** 2 # dt dy = - a * y - 4 * (z + x) - z ** 2 # dt dz = - a * z - 4 * (x + y) - x ** 2 # dt return dx, dy, dz