content
stringlengths
42
6.51k
def num_ids_from_args(arg_ranges): """Return the number of argument combinations (and thus the number of corresponding ids)""" from functools import reduce import operator return reduce(operator.mul, [len(r) for r in arg_ranges], 1)
def _validate_name(name): """Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid. """ if name is None: return # The first and last characters must be alphanumeric. if not all([name[0].isalnum(), name[-1].isalnum()]): raise ValueError("Bucket names must start and end with a number or letter.") return name
def get_full_item_name(iteminfo: dict, csgo_english: dict) -> str: """ Function which adds data to the skin info retrieved from GC :param iteminfo: item info dict. :type csgo_english: csgo_english vdf parsed :rtype: str """ name = '' # Default items have the "unique" quality if iteminfo['quality'] != 4: name += f"{iteminfo['quality_name']}" # Patch for items that are stattrak and unusual (ex. Stattrak Karambit) if iteminfo.get('killeatervalue') is not None and iteminfo['quality'] != 9: name += f" {csgo_english['strange']}" name += f" {iteminfo['weapon_type']} " if iteminfo['weapon_type'] in ['Sticker', 'Sealed Graffiti']: name += f"| {iteminfo['stickers'][0]['name']}" # Vanilla items have an item_name of '-' if iteminfo["item_name"] and iteminfo["item_name"] != '-': name += f"| {iteminfo['item_name']} " if iteminfo.get('wear_name') and iteminfo["item_name"] != '-': name += f"({iteminfo['wear_name']})" return name.strip()
def levenshtein(a,b): """Calculates the Levenshtein distance between *strings* a and b. from http://hetland.org/coding/python/levenshtein.py """ n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n,m)) space a,b = b,a n,m = m,n current = range(n+1) for i in range(1,m+1): previous, current = current, [i]+[0]*n for j in range(1,n+1): add, delete = previous[j]+1, current[j-1]+1 change = previous[j-1] if a[j-1] != b[i-1]: change = change + 1 current[j] = min(add, delete, change) return current[n]
def get_corner_coord(vhpos): """Convert textbox corner coordinate from str to float""" if (vhpos is None) or (vhpos == 'right') or (vhpos == 'top'): return 0.9 else: return 0.1
def str_to_bool(s): """ Translates string representing boolean value into boolean value """ if s == 'True': return True elif s == 'False': return False else: raise ValueError
def Fastaline(x, **kwargs): """Convert a sequence to FASTA format(60 per line)""" res = '' while len(x) != 0: res += ''.join(x[:60]) + '\n' x = x[60:] return res
def _normalize_integer_rgb(value: int) -> int: """ Internal normalization function for clipping integer values into the permitted range (0-255, inclusive). """ return 0 if value < 0 else 255 if value > 255 else value
def event_log_formatter(events): """Return the events in log format.""" event_log = [] log_format = ("%(event_time)s " "[%(rsrc_name)s]: %(rsrc_status)s %(rsrc_status_reason)s") for event in events: event_time = getattr(event, 'event_time', '') log = log_format % { 'event_time': event_time.replace('T', ' '), 'rsrc_name': getattr(event, 'resource_name', ''), 'rsrc_status': getattr(event, 'resource_status', ''), 'rsrc_status_reason': getattr(event, 'resource_status_reason', '') } event_log.append(log) return "\n".join(event_log)
def mergeLists(lst1, lst2): """asssumes lst1 and lst2 are lists returns a list of tuples of the elementsts of lst1 and lst2""" return list(zip(lst1, lst2))
def joblib_log_level(level: str) -> int: """ Convert python log level to joblib int verbosity. """ if level == 'INFO': return 0 else: return 60
def snake_to_darwin_case(text: str) -> str: """Convert snake_case to Darwin_Case.""" return "_".join(map(str.capitalize, text.split("_")))
def get_output_filename(dest_dir, class_name): """Creates the output filename. Args: dataset_dir: The dataset directory where the dataset is stored. split_name: The name of the train/test split. Returns: An absolute file path. """ return '%s/ON3D_%s.tfrecord' % (dest_dir, class_name)
def hits_boat( direction, position, boat_size, board_matrix, ): """ :param direction: :param position: :param boat_size: :param board_matrix: :return: """ if direction == 'UP': first_square = position['y'] for currentY in range(first_square + 1 - boat_size, first_square + 1): if board_matrix[currentY][position['x']] != 0: return True elif direction == 'DOWN': first_square = position['y'] for currentY in range(first_square, first_square + boat_size): if board_matrix[currentY][position['x']] != 0: return True elif direction == 'RIGHT': first_square = position['x'] for currentX in range(first_square, first_square + boat_size): if board_matrix[position['y']][currentX] != 0: return True elif direction == 'LEFT': first_square = position['x'] for currentX in range(first_square + 1 - boat_size, first_square + 1): if board_matrix[position['y']][currentX] != 0: return True return False
def round_down(rounded, divider): """Round down an integer to a multiple of divider.""" return int(rounded) // divider * divider
def make_netloc(data): """Make the `netloc` portion of a url from a `dict` of values. If `netloc` is found in the `dict`, it is returned; otherwise, the `netloc` is `[{username}[:{password}]@]{hostname}[:{port}]`. If `hostname` is not found, `host` is used instead. If neither `netloc`, `hostname`, nor `host` are found, a `ValueError` is raised. """ netloc = data.get('netloc') if netloc: return netloc username = data.get('username') password = data.get('password') hostname = data.get('hostname') or data.get('host') port = data.get('port') if not hostname: raise ValueError('requires at least one of netloc, hostname, or host') if username and password: username = '{}:{}'.format(username, password) netloc = '{}{}{}{}{}'.format( username or '', '@' if username else '', hostname, ':' if port else '', port or '' )
def create_label_column(row) -> str: """ Helper function to generate a new column which will be used to label the choropleth maps. Function used to label missing data (otherwise they will show up on the map as "-1 SEK"). Parameters ---------- row : Returns ------- str Column label to show when user hovers mouse over a choropleth map. """ if row["Median Rent (SEK)"] > 0: return "Median Cost: " + str(int(row["Median Rent (SEK)"])) + " SEK" else: return "Missing Data"
def sat(x, xmin, xmax): """! Saturates the input value in the given interval @param x: value to saturate @param xmin: minimum value of the interval @param xmax: maximum value of the interval @return: saturated value """ if x > xmax: return xmax if x < xmin: return xmin return x
def is_directive(headers, data): """ checks if a part (of multi-part body) looks like a directive directives have application/json content-type and key 'directive' in the top-level JSON payload object :param headers: dict of Part headers (from network, bytes key/values) :param data: dict part content, type depends on content-type (dict if application/json) :return: True if part looks like a directive, False otherwise """ return b'application/json' in headers[b'Content-Type'] and 'directive' in data
def data_by_class(data): """ Organize `data` by class. Parameters ---------- data : list of dicts Each dict contains the key `symbol_id` which is the class label. Returns ------- dbc : dict mapping class labels to lists of dicts """ dbc = {} for item in data: if item["symbol_id"] in dbc: dbc[item["symbol_id"]].append(item) else: dbc[item["symbol_id"]] = [item] return dbc
def _consolidate_elemental_array_(elemental_array): """ Accounts for non-empirical chemical formulas by taking in the compositional array generated by _create_compositional_array_() and returning a consolidated array of dictionaries with no repeating elements :param elemental_array: an elemental array generated from _create_compositional_array_() :return: an array of element dictionaries """ condensed_array = [] for e in elemental_array: exists = False for k in condensed_array: if k["symbol"] == e["symbol"]: exists = True k["occurances"] += e["occurances"] break if not exists: condensed_array.append(e) return condensed_array
def get_rnn_hidden_state(h): """Returns h_t transparently regardless of RNN type.""" return h if not isinstance(h, tuple) else h[0]
def attack(suffix_bits, suffix): """ Returns a number s for which s^3 ends with the provided suffix. :param suffix_bits: the amount of bits in the suffix :param suffix: the suffix :return: the number s """ assert suffix % 2 == 1, "Target suffix must be odd" s = 1 for i in range(suffix_bits): if (((s ** 3) >> i) & 1) != ((suffix >> i) & 1): s |= (1 << i) return s
def string_in_file(file, str_to_check, repetitions=1): """Check if a string is present in a file. You can also provide the number of times that string is repeated. :param file: File where the string is searched :type file: str :param str_to_check: String to search :type str_to_check: str :param repetitions: Number of repetitions, default is 1 :type repetitions: int :return: True if the string is present in the file, False otherwise :rtype: bool """ lines_with_string = 0 with open(file, "r") as r: for line in r: if str_to_check in line: lines_with_string += 1 if lines_with_string != repetitions: return False return True
def has_module(module_name, members=[]): """Returns whether or not a given module can be imported.""" try: mod = __import__(module_name, fromlist=members) except ImportError: return False for member in members: if not hasattr(mod, member): return False return True
def same_ratio(img_ratio, monitor_ratio, file): """ :param img_ratio: Float :param monitor_ratio: Float :param file: Str :return: Bool """ percent = img_ratio / monitor_ratio diff = int(abs(percent - 1) * 100) if percent > 1: print("Image is " + str(diff) + "% too wide for screen. Sides must be cropped off, or top/bottom filled.") same = False elif percent < 1: print("Image is " + str(diff) + "% too narrow for screen. Top/bottom must be cropped off, or sides filled.") same = False else: print("Image is the same aspect ratio as the screen.") n = input("Press enter to exit.") same = True return same
def _globtest(globpattern, namelist): """ Filter names in 'namelist', returning those which match 'globpattern'. """ import re pattern = globpattern.replace(".", r"\.") # mask dots pattern = pattern.replace("*", r".*") # change glob sequence pattern = pattern.replace("?", r".") # change glob char pattern = '|'.join(pattern.split()) # 'or' each line compiled = re.compile(pattern) return list(filter(compiled.match, namelist))
def factorial(n): """ returns the factorial of n """ if n < 0: return None if n == 0: return 1 if n < 2: return 1 return n * factorial(n-1)
def convert_fiscal_quarter_to_fiscal_period(fiscal_quarter): """ Returns None if fiscal_quarter is invalid or not a number. """ return {1: 3, 2: 6, 3: 9, 4: 12}.get(fiscal_quarter)
def convert_extension(filename, extensions=('yaml', 'yml',)): """ Convert YeT extension in filename to .tex :param filename: string of file name. validity not checked. :param extensions: tuple of extensions (without dot) to treat as YeT """ # change YAML extension to .tex if '.' in filename: ext = filename.split('.')[-1] if ext in extensions: idx = filename.rindex('.') return f'{filename[:idx]}.tex' # or append .tex if appropriate extension is not found return f'{filename}.tex'
def belong(candidates,checklist): """Check whether a list of items appear in a given list of options. Returns a list of 1 and 0, one for each candidate given.""" return [x in checklist for x in candidates]
def collect_swift_version(copts): """Returns the value of the `-swift-version` argument, if found. Args: copts: The list of copts to be scanned. Returns: The value of the `-swift-version` argument, or None if it was not found in the copt list. """ # Note that the argument can occur multiple times, and the last one wins. last_swift_version = None count = len(copts) for i in range(count): copt = copts[i] if copt == "-swift-version" and i + 1 < count: last_swift_version = copts[i + 1] return last_swift_version
def validate1(s, a): """validate1(s, a): list comprehension with a.index""" try: [a.index(x) for x in s] return True except: return False
def is_simple_passphrase(phrase): """ Checks whether a phrase contains no repeated words. >>> is_simple_passphrase(["aa", "bb", "cc", "dd", "ee"]) True >>> is_simple_passphrase(["aa", "bb", "cc", "dd", "aa"]) False >>> is_simple_passphrase(["aa", "bb", "cc", "dd", "aaa"]) True """ return not any(phrase.count(word) > 1 for word in phrase)
def R10_yield(FMTab, Apmin, PG): """ R10 Determining the surface pressure Pmax (Sec 5.5.4) For the maximum surface pressure with yield or angle controlled tightening techniques. """ # Pmax = 1.40 * (FMTab / Apmin) # (R10/3) # Alternative safety verification Sp = PG / Pmax # (R10/4) if Sp > 1.0 : print('Sp > {} --> PASS'.format(Sp)) else: print('Sp < {} --> FAIL'.format(Sp)) # return Pmax #
def initial_global_jql(quarter_string, bad_board=False): """ Helper function to return the initial global JQL query. :param String quarter_string: Quarter string to use :param Bool bad_board: Are we creating the JQL for the bad board :return: Initial JQL :rtype: String """ if bad_board: return f"(remainingEstimate > 0 OR duedate < endOfDay() " \ f"OR status not in (Closed, Resolved) OR cf[11908] " \ f"is not EMPTY) AND labels = {quarter_string} ORDER BY Rank ASC" else: return f"labels = {quarter_string} ORDER BY Rank ASC"
def remove_multiple_elements_from_list(a_list, indices_to_be_removed): """ remove list elements according to a list of indices to be removed from that list :param a_list: list list to be processed :param indices_to_be_removed: list list of the elements that are no longer needed """ return [a_list[i] for i in range(len(a_list)) if i not in indices_to_be_removed]
def inverse(sequence): """ Calculate the inverse of a DNA sequence. @param sequence: a DNA sequence expressed as an upper-case string. @return inverse as an upper-case string. """ # Reverse string using approach recommended on StackOverflow # http://stackoverflow.com/questions/931092/reverse-a-string-in-python return sequence[::-1]
def multiply (m1, m2): """ Multiply two matrices. """ m1r = len (m1) m1c = len (m1[0]) m2r = len (m2) m2c = len (m2[0]) rr = m1r rc = m2c assert m1c == m2r, "Matrix multiplication not defined. Invalid dimensions." newRows = [] for i in range (0, rr): newRow = [] for k in range (0, rc): val = 0 for j in range (0, m1c): val = val + (m1[i][j] * m2[j][k]) newRow.append (val) newRows.append (tuple (newRow)) return tuple(newRows)
def spin_words(sentence): """Spin words greater than five char long in a string. preserving white spaces """ temp = [] spl = sentence.split() for char in spl: if len(char) >= 5: spin = char[::-1] temp.append(spin) else: temp.append(char) output = ' '.join(temp) return output
def subtract(value, arg): """subtracts arg from value""" return int(value) - int(arg)
def rreplace(s: str, old: str, new: str, occurrence: int) -> str: """ Reverse replace. :param s: Original string. :param old: The character to be replaced. :param new: The character that will replace `old`. :param occurrence: The number of occurrences of `old` that should be replaced with `new`. """ return new.join(s.rsplit(old, occurrence))
def instruction_list_to_easm(instruction_list: list) -> str: """Convert a list of instructions into an easm op code string. :param instruction_list: :return: """ result = "" for instruction in instruction_list: result += "{} {}".format(instruction["address"], instruction["opcode"]) if "argument" in instruction: result += " " + instruction["argument"] result += "\n" return result
def step(x): """ A neighbor of x is either 2*x or x+3""" return [x+3, 2*x]
def get_fragment(text, startend): """Return substring from a text based on start and end substrings delimited by ::.""" startend = startend.split("::") if startend[0] not in text or startend[1] not in text: return start_idx = text.index(startend[0]) end_idx = text.index(startend[1]) if end_idx < start_idx: return return text[start_idx: end_idx+len(startend[1])]
def get_integer(bool_var): """Returns string value for the bool variable.""" if bool_var: return "1" else: return "0"
def get_sorted_start_activities_list(start_activities): """ Gets sorted start attributes list Parameters ---------- start_activities Dictionary of start attributes associated with their count Returns ---------- listact Sorted start attributes list """ listact = [] for sa in start_activities: listact.append([sa, start_activities[sa]]) listact = sorted(listact, key=lambda x: x[1], reverse=True) return listact
def applianceLogsDirName(config): """ Returns the name of the directory containing the appliance log files. """ return config['converter.appliance_logs_dir']
def find_used_entities_in_string(query, columns, tables): """Heuristically finds schema entities included in a SQL query.""" used_columns = set() used_tables = set() nopunct_query = query.replace('.', ' ').replace('(', ' ').replace(')', ' ') for token in nopunct_query.split(' '): if token.lower() in columns: used_columns.add(token.lower()) if token.lower() in tables: used_tables.add(token.lower()) return used_columns, used_tables
def get_source_url_output(function_name): """ Generates the Cloud Function output with a link to the source archive. """ return { 'name': 'sourceArchiveUrl', 'value': '$(ref.{}.sourceArchiveUrl)'.format(function_name) }
def get_schema(dictionary, parameters=False, delimiter="_"): """Get a schema of the config of the dictionary""" global_definition = "" def get_key_schema(dl, definition=None): definition = "" if definition is None else definition if isinstance(dl, dict): for key in sorted(dl.keys()): defin = definition + delimiter + key if definition != "" else key get_key_schema(dl[key], defin) elif isinstance(dl, list): for item in sorted(dl): get_key_schema(item, definition) else: if parameters: final_value = definition + delimiter + str(dl) else: final_value = definition + delimiter + "value" nonlocal global_definition global_definition += final_value + "\n" get_key_schema(dictionary) return global_definition
def cumulative_gain(rank_list): """Calculate the cumulative gain based on the rank list and return a list.""" cumulative_set = [] cumulative_set.append(rank_list[0]) for i in range(1, len(rank_list)): cg = cumulative_set[i-1] + rank_list[i] cumulative_set.append(cg) return cumulative_set
def create_incident_field_context(incident): """Parses the 'incident_fields' entry of the incident and returns it Args: incident (dict): The incident to parse Returns: list. The parsed incident fields list """ incident_field_values = dict() for incident_field in incident.get('incident_field_values', []): incident_field_values[incident_field['name'].replace(" ", "_")] = incident_field['value'] return incident_field_values
def get_timeout(gross_time, start, end, precision, split_range): """ A way to generate varying timeouts based on ranges :param gross_time: Some integer between start and end :param start: the start value of the range :param end: the end value of the range :param precision: the precision to use to generate the timeout. :param split_range: generate values from both ends :return: a timeout value to use """ if split_range: top_num = float(end) / precision bottom_num = float(start) / precision if gross_time % 2 == 0: timeout = top_num - float(gross_time) / precision else: timeout = bottom_num + float(gross_time) / precision else: timeout = float(gross_time) / precision return timeout
def _convert_to_float(frac_str): """Converts a string into a float""" try: return float(frac_str) except ValueError: num, denom = frac_str.split('/') try: leading, num = num.split(' ') whole = float(leading) except ValueError: whole = 0 if float(denom) == 0: return 0 fraction = float(num) / float(denom) return whole - fraction if whole < 0 else whole + fraction
def get_2nd_ck_line_from_line( line ): """ A check line may contain more than 1 check. Here we get only the info(line aka string) from the 2nd check. """ splited = line.split() ck2 = splited[4:] ck2 = ' '.join(ck2) # bc next functions expect lines to be strings # print('ck2 == ', ck2) return ck2
def index_by_iterable(obj, iterable): """ Index the given object iteratively with values from the given iterable. :param obj: the object to index. :param iterable: The iterable to get keys from. :return: The value resulting after all the indexing. """ item = obj for i in iterable: item = item[i] return item
def row_str(dflen: int) -> str: """String wrapper for the million of rows in a dataframe Args: dflen (int): the length of a dataframe Returns: str: rows in millions """ return str(round(dflen / 1000000, 1)) + "M rows"
def factorial(n: int) -> str: """factorial function that returns the answer in a string. This so sqlite can save the large integers. """ if n < 2: return "1" else: return str(n*int(factorial(n-1)))
def get_hex(input_list): """ Convert a list of bytes into hex string """ o = "" for i in input_list: o += "%02X"%ord(i) return o
def get_neighboring_ap_ids(current_ap_location, neighboring_aps, location_to_ap_lookup): """ Helper method to remove current ap from neighboring aps and return list of neighboring ap ids """ neighboring_ap_ids = [] if isinstance(current_ap_location, list): current_ap_location = tuple(current_ap_location) for ap_location in neighboring_aps: if current_ap_location != ap_location: neighboring_ap_ids.append( location_to_ap_lookup[ap_location]) return neighboring_ap_ids
def three_way_partition(seq, left, right): """ Three-way-partisions a sequence. Partitions a sequence of values consisting of three distinct different types of elements such that the resulting sequence is sorted. Loop invariants: 1. All values to the left of i are of type 'left' 2. All values to the right of n are of type 'right' 3. Values after j have not been looked at. 4. j <= n for all iterations. Makes at most N swaps. Arguments: seq (iterable): The sequence to partition. left: The first category, will end up on the left. right: The third category, will end up on the right. Returns: The sorted (three-way-partitioned) sequence. """ i = j = 0 n = len(seq) - 1 while j <= n: value = seq[j] if value == left: seq[i], seq[j] = seq[j], seq[i] i += 1 j += 1 elif value == right: seq[j], seq[n] = seq[n], seq[j] n -= 1 else: j += 1 return seq
def delistify(x): """ A basic slug version of a given parameter list. """ if isinstance(x, list): x = [e.replace("'", "") for e in x] return '-'.join(sorted(x)) return x
def classify(tree, input): """classify the input using the given decision tree""" # if this is a leaf, return it if tree in [True, False]: return tree # find correct subtree attribute, subtree_dict = tree subtree_key = input.get(attribute) if subtree_key not in subtree_dict: subtree_key = None subtree = subtree_dict[subtree_key] return classify(subtree, input)
def t_iso(M): """ Isolation disruption timescale (2-body evaporation)""" return 17. * (M / 2E5)
def xgcd(a, b): """ Performs the extended Euclidean algorithm Returns the gcd, coefficient of a, and coefficient of b """ x, old_x = 0, 1 y, old_y = 1, 0 while (b != 0): quotient = a // b a, b = b, a - quotient * b old_x, x = x, old_x - quotient * x old_y, y = y, old_y - quotient * y return a, old_x, old_y
def unique_elements(array): """Return a list of unique elements of an array.""" unique = [] for x in array: if x not in unique: unique.append(x) return unique
def is_namedtuple_cls(cls): """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple""" try: if issubclass(cls, tuple): bases = getattr(cls, "__bases__", []) or [None] module = getattr(cls, "__module__", None) return module == "torch.return_types" or ( bases[0] is tuple and hasattr(cls, "_make") and hasattr(cls, "_fields") ) except TypeError: pass return False
def fromhex(n): """ hexadecimal to integer """ return int(n, base=16)
def get_date_print_format(date_filter): """ Utility for returning the date format for a given date filter in human readable format @param date filter : the given date filter @return the date format for a given filter """ vals = {"day": "[YYYY-MM-DD]", "hour": "[YYYY-MM-DD : HH]"} return vals[date_filter]
def string_contains_numeric_value(s): """Returns true if the string is convertible to float.""" try: float(s) return True except ValueError: return False
def factorial(n): """Return the factorial of n, an exact integer >= 0. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(30) 265252859812191058636308480000000 >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 Factorials of floats are OK, but the float must be an exact integer: >>> factorial(30.1) Traceback (most recent call last): ... ValueError: n must be exact integer >>> factorial(30.0) 265252859812191058636308480000000 It must also not be ridiculously large: >>> factorial(1e100) Traceback (most recent call last): ... OverflowError: n too large """ import math if not n >= 0: raise ValueError("n must be >= 0") if math.floor(n) != n: raise ValueError("n must be exact integer") if n + 1 == n: # catch a value like 1e300 raise OverflowError("n too large") result = 1 factor = 2 while factor <= n: result *= factor factor += 1 return result
def get_relative_path_from_module_source(module_source: str) -> str: """Get a directory path from module, relative to root of repository. E.g. zenml.core.step will return zenml/core/step. Args: module_source: A module e.g. zenml.core.step """ return module_source.replace(".", "/")
def quotePosix(args): """ Given a list of command line arguments, quote them so they can be can be printed on POSIX """ def q(x): if " " in x: return "'" + x + "'" else: return x return [q(x) for x in args]
def parse_unknown_params(params): """Purpose of this function is to parse multiple `--metadata.{field}=value` arguments. :arg:params: tuple of unknown params """ structured_params = dict() for param in params: param = param.strip('--') key, value = param.split('=') if key in structured_params.keys(): structured_params[key] = structured_params[key] + (value,) else: structured_params[key] = (value,) return structured_params
def find(n: int) -> int: """ This function return the sum of all multiples of 3 and 5. """ return sum([i for i in range(2, n + 1) if not i % 3 or not i % 5])
def _prepare_labels(labels, label_map): """ Converts an array of labels into an array of label_ids Arguments: labels (arr) : array of the names of labels label_map (dict) : key - name of label, value - label-id Returns: (arr) : array of the names of labels """ converted_labels = [] for label in labels: converted_labels.append(label_map[label]) return converted_labels
def glob_all(folder: str, filt: str) -> list: """Recursive glob""" import os import fnmatch matches = [] for root, dirnames, filenames in os.walk(folder, followlinks=True): for filename in fnmatch.filter(filenames, filt): matches.append(os.path.join(root, filename)) return matches
def survival_score(timeSurvived, duration, winPlace): """ survival_score = 80% * survival time score + 20% * win place score : type timeSurvived: int -- participant time survived : type duration: int -- match duration time : type winPlace: int : rtype survival_score: int """ survival = (timeSurvived / duration) * 100 if winPlace == 1: win_place = 100 else: win_place = 100 - winPlace survival_score = int(survival * 0.8 + win_place * 0.2) if survival_score < 50: survival_score = 50 return survival_score
def quote(s): """Removes the quotes from a string.""" return s.strip('"\'')
def float_format(number): """Format a float to a precision of 3, without zeroes or dots""" return ("%.3f" % number).rstrip('0').rstrip('.')
def param_string_to_kwargs_dict(multiline_param_string): """ From a multiline parameter string of the form: parameter value Return a kwargs dictionary E.g. param_string = \"\"\"base_margin_initialize: True colsample_bylevel: 1.0 colsample_bytree: 0.5\"\"\" kwargs_param_dict = param_string_to_kwargs_dict(param_string) kwargs_param_dict {'base_margin_initialize': True, 'colsample_bylevel': 1.0, 'colsample_bytree': 0.5, 'interval': 10} """ params = [] param_vals = [] for index, param in enumerate(multiline_param_string.split("\n")): if (index == 0) | (index % 2 == 0): params.append(param.replace(":", "")) else: # Get the python dtype of parameter value # Cast to Numeric try: param = int(param) except ValueError: try: param = float(param) except ValueError: pass # Check for booleans if param == 'True': param = True if param == 'False': param = False param_vals.append(param) # Create the dictionary kwargs_params = dict(zip(params, param_vals)) return kwargs_params
def visible_onerow(array): """ :return visible number in one row. """ out_temp = 1 len_t=len(array) for i in range(len_t - 1): for j in range(i+1,len_t): if array[i] < array[j]: break else: pass else : out_temp += 1 return out_temp
def _extr_parameter(cmd): """Extra parameter for parameterized gate in HiQASM cmd.""" return [float(i) for i in cmd.split(' ')[-1].split(',')]
def exact_dp4(a_v, b_v): """ Exact version (formal) of 4D dot-product :param a_v: left-hand-side vector :type a_v: list(SollyaObject) :param b_v: right-hand-side vector :type b_v: list(SollyaObject) :return: exact 4D dot-product :rtype: SollyaObject (value or expression) """ prod_v = [a * b for a, b in zip(a_v, b_v)] acc = 0 for p in prod_v: acc = p + acc return acc
def calculate_adjoint_source_raw(py, nproc, misfit_windows_directory, stations_path, raw_sync_directory, sync_directory, data_directory, output_directory, body_band, surface_band): """ At the first step, we should calculate the adjoint source for all the events. """ script = f"ibrun -n {nproc} {py} -m seisflow.scripts.source_inversion.mpi_calculate_adjoint_source_zerolagcc_single_event --misfit_windows_directory {misfit_windows_directory} --stations_path {stations_path} --raw_sync_directory {raw_sync_directory} --sync_directory {sync_directory} --data_directory {data_directory} --output_directory {output_directory} --body_band {body_band} --surface_band {surface_band}; \n" return script
def str2bool(v: str) -> bool: """This function converts the input parameter into a boolean Args: v (*): input argument Returns: True: if the input argument is 'yes', 'true', 't', 'y', '1' False: if the input argument is 'no', 'false', 'f', 'n', '0' Raises: ValueError: if the input argument is none of the above """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise ValueError('Boolean value expected.')
def outlook_days_of_week(event_data): """ Converts gathered event data to Outlook-API consumable weekday string params: event_data: dictionary containing event data specific to an outlook calendar occurrence returns: weekday_list: list containing days of the week for the calendar occurence in an outlook-API friendly format. """ weekday_list = [] if event_data["Sun"] == "TRUE": weekday_list.append("Sunday") if event_data["Mon"] == "TRUE": weekday_list.append("Monday") if event_data["Tue"] == "TRUE": weekday_list.append("Tuesday") if event_data["Wed"] == "TRUE": weekday_list.append("Wednesday") if event_data["Thu"] == "TRUE": weekday_list.append("Thursday") if event_data["Fri"] == "TRUE": weekday_list.append("Friday") if event_data["Sat"] == "TRUE": weekday_list.append("Saturday") return weekday_list
def getFileExt(fileName): """returns the fileextension of a given file name""" lastDot = fileName.rindex('.') return fileName[lastDot:]
def format_proxy(proxy_config, auth=True): """Convert a Mopidy proxy config to the commonly used proxy string format. Outputs ``scheme://host:port``, ``scheme://user:pass@host:port`` or :class:`None` depending on the proxy config provided. You can also opt out of getting the basic auth by setting ``auth`` to :class:`False`. """ if not proxy_config.get('hostname'): return None port = proxy_config.get('port', 80) if port < 0: port = 80 if proxy_config.get('username') and proxy_config.get('password') and auth: template = '{scheme}://{username}:{password}@{hostname}:{port}' else: template = '{scheme}://{hostname}:{port}' return template.format(scheme=proxy_config.get('scheme') or 'http', username=proxy_config.get('username'), password=proxy_config.get('password'), hostname=proxy_config['hostname'], port=port)
def double_eights(n): """Return true if n has two eights in a row. >>> double_eights(8) False >>> double_eights(88) True >>> double_eights(2882) True >>> double_eights(880088) True >>> double_eights(12345) False >>> double_eights(80808080) False """ temp = 0 count = 0 while n > 0: temp = n%10 n//=10 if (temp==8): count+=1 else: count = 0 if (count==2): return True return False
def matrix_divided(matrix, div): """ divides matrix by input divisor""" if div == 0: raise ZeroDivisionError('division by zero') if not isinstance(div, (int, float)): raise TypeError('div must be a number') new = [] rowlen = len(matrix[0]) for row in matrix: sub = [] if len(row) != rowlen: raise TypeError('Each row of the matrix must have the same size') for i in range(len(row)): if not isinstance(row[i], (int, float)): raise TypeError('matrix must be a matrix (list of lists) of ' 'integers/floats') sub.append(round((row[i] / div), 2)) new.append(sub) return new
def identidade_matriz(N): """Cria matriz quadrada identidade""" MI = [] for l in range(N): linha = [] for c in range(N): if l == c: valor = 1 else: valor = 0 linha.append(valor) MI.append(linha) return MI
def xor(bytes_1, bytes_2): """XOR two bytearrays of the same length.""" l1 = len(bytes_1) l2 = len(bytes_2) assert l1 == l2 result = bytearray(l1) for i in range(l1): result[i] = bytes_1[i] ^ bytes_2[i] return result
def get_second_smallest(values): """ returns the second lowest value in a list of numbers Args: values: a list of floats Returns: the second lowst number in values """ smallest, second_smallest = float("inf"), float("inf") for value in values: if value <= smallest: smallest, second_smallest = value, smallest elif value < second_smallest: second_smallest = value return second_smallest
def unpack_args(args): """ unpacks args Used by jsonifiers """ if isinstance(args, tuple): return args else: return (args, {})
def remove_comments(line): """remove # comments from given line """ i = line.find("#") if i >= 0: line = line[:i] return line.strip()
def format_vertex(body): # pragma: no cover """Format vertex data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ vertex = body['vertex'] if '_oldRev' in vertex: vertex['_old_rev'] = vertex.pop('_oldRev') if 'new' in body or 'old' in body: result = {'vertex': vertex} if 'new' in body: result['new'] = body['new'] if 'old' in body: result['old'] = body['old'] return result else: return vertex
def is_comment(line, comments): """ A utility method to tell if the provided line is a comment or not Parameters ---------- str line: The line string in a file list comments: A list of potential comment keywords """ return line.lstrip(' ')[0] in comments
def greatest_product_subarray(arr:list, subarray_len:int): """ returns the subarray having the greatest product in the array and the greatest product Args: arr (list): list of integers subarray_len (int): length of subarray Returns: (list,int): subarray,max product """ if subarray_len >= len(arr): return arr prod = 1 for i in range(0, subarray_len): prod *= arr[i] max_prod = prod end_index = subarray_len - 1 i = end_index+1 while i in range(end_index+1,len(arr)): if arr[i] != 0: if arr[i-subarray_len] == 0: prod = 1 for j in range(i-subarray_len+1, i+1): prod *= arr[j] else: prod = (prod//arr[i-subarray_len])*arr[i] if prod > max_prod: max_prod = prod end_index = i i += 1 else: i = i+subarray_len return arr[end_index-subarray_len+1:end_index+1], max_prod