content
stringlengths
42
6.51k
def varyingParams(intObjects, params): """ Takes a list of models or tasks and returns a dictionary with only the parameters which vary and their values """ initDataSet = {param: [i[param] for i in intObjects] for param in params} dataSet = {param: val for param, val in initDataSet.items...
def split_uri(uri, pattern='s3://', separator='/'): """Convert a URI to a bucket, object name tuple. 's3://bucket/path/to/thing' -> ('bucket', 'path/to/thing') """ assert pattern in uri parts = uri[len(pattern):].split(separator) bucket = parts[0] path = separator.join(parts[1:]) return...
def _to_full_path(item, path_prefix): """Rebuild entry with given path prefix""" if not item: return item return (item[0], item[1], path_prefix + item[2])
def get_label_dummy_goal(vertex_input): """Get the index of the fictitious dummy goal (last vertex + 1)""" if isinstance(vertex_input, int): v_g = vertex_input + 1 return v_g elif isinstance(vertex_input, list): v_g = vertex_input[-1] + 1 return v_g else: print('...
def label_texify(label): """ Convert a label to latex format by appending surrounding $ and escaping spaces Parameters ---------- label : str The label string to be converted to latex expression Returns ------- str A string with $ surrounding """ return '$' + la...
def _leading_comment_pattern(comment_string: str) -> str: """ Convert the comment string for a language into a (string) regular expression pattern that will match the comment at the beginning of a source notebook line. :param comment_string: the comment string :return: the pattern """ ...
def _GetPathFromUrlString(url_str): """Returns path component of a URL string.""" end_scheme_idx = url_str.find('://') if end_scheme_idx == -1: return url_str else: return url_str[end_scheme_idx + 3:]
def setGauss(points): """ Create a system of equations for gaussian elimination from a set of points. """ n = len(points) - 1 A = [[0 for i in range(n+2)] for j in range(n+1)] for i in range(n+1): x = points[i]["x"] for j in range(n+1): A[i][j] = x**j A[i][n+...
def controversy(upvotes, downvotes): """ Calculates controversy based on the reddit approach https://github.com/reddit-archive/reddit/blob/master/r2/r2/lib/db/_sorts.pyx#L60 """ if downvotes <= 0 or upvotes <= 0: return 0 magnitude = downvotes + upvotes balance = downvotes / upv...
def int2list(num,listlen=0,base=2): """Return a list of the digits of num, zero padding to produce a list of length at least listlen, to the given base (default binary)""" digits = []; temp = num while temp>0: digits.append(temp % base) temp = temp // base digits.extend((listlen-len(digits))*[0]...
def inHg_to_hPa(p_inHg): """Convert inches of mercury to hectopascals.""" if p_inHg is None: return None return p_inHg * 33.86389
def is_valid_ssdp_packet(data: bytes) -> bool: """Check if data is a valid and decodable packet.""" return ( bool(data) and b"\n" in data and ( data.startswith(b"NOTIFY * HTTP/1.1") or data.startswith(b"M-SEARCH * HTTP/1.1") or data.startswith(b"HTTP/1...
def determine_split_py(words): """determine word number to split on for python context sensitive search """ if words[3] == 'class': end = 5 if words[5] == 'method': end = 7 elif words[3] == 'function': end = 5 else: # if words == 'module': end =...
def percentage_of(part_1, part_2): """ Returns the percentage between 1 and (1+2) """ try: return int('%d' % (float(part_1) / float(part_1 + part_2) * 100)) except (ValueError, ZeroDivisionError): return '0'
def used_memory(unit: int = 1024 * 1024 * 1024) -> float: """ Get the memory usage of the current process. :param unit: Unit of the memory, default in Gigabytes. :return: Memory usage of the current process. """ import resource return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / un...
def rootFolder(exp=''): """ Get root folder path for POTUS modeling experiments Args: exp (str, optional): name of experiment. Defaults to ''. Returns: str: full path for a given experiment """ root_folder = '/home/azureuser/cloudfiles/code/data/processing/potus/experiment' ...
def collapse(doc): """ Turn a document into a single string """ return " ".join( " ".join(" ".join(sent) for sent in part) for part in doc )
def linear_search(searching_list, target): """ :param searching_list: takes the searching list form the user :param target: takes the target element from the user :return: Returns the index position of the target if found, else returns None """ for i in range(0, len(searching_list)): ...
def simplify_profile(profile, num_candidates): """ Simplifies a profile to only contain a certain number of candidates """ simplified_profile = [] current_candidates = len(profile[0]) for vote in profile: modified_vote = vote.copy() # Remove candidates for i in range(num_...
def format_json(_, __, ed): """Stackdriver uses `message` and `severity` keys to display logs""" ed["message"] = ed.pop("event") ed["severity"] = ed.pop("level", "info").upper() return ed
def STmag_to_flux( v ): """ Convert an ST magnitude to erg/s/cm2/AA (Flambda) mag = -2.5 \log_{10}(F) - 21.10 M0 = 21.10 F0 = 3.6307805477010028 10^{-9} erg/s/cm2/AA Parameters ---------- v: np.ndarray[float, ndim=N] or float array of magnitudes Returns --...
def time_remaining(elapsed, n, length): """ Returns a string indicating the time remaining (if not complete) or the total time elapsed (if complete). """ if n == 0: return '--:--:--' if n == length: seconds = int(elapsed) # if complete, total time elapsed else: seco...
def GetWordLeft(line): """Get the first valid word to the left of the end of line @return: string """ for idx in range(1, len(line)+1): ch = line[idx*-1] if ch.isspace() or ch in u'{;': return line[-1*idx:].strip() else: return u''
def uniqueDictID(dictionary, attribute): """This function will loop through the specified dictionary and find a unique numerical id that does not match the specified attribute""" if not dictionary: #if dictionary is empty, return 0 return 0 id = 0 #initialse id at 0 while True: #cont...
def pi_using_integer(precision): """Get value of pi via BBP formula to specified precision using integers. See: https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula :param precision: Precision to retrieve. :return: Pi value with specified precision. """ value = 0 for...
def parse_number(s): """ Somewhat mimics JavaScript's parseFloat() functionality """ if not s: return None value = float(s) return int(value) if value == int(value) else value
def _find_smallest_value(list): """ Get the intex of the smallest value in list of values :return: -1 if list empty, otherwise index of smallest value """ if len(list) < 1: return -1 min = 0 for idx, val in enumerate(list): if val < list[min]: min= idx retur...
def board_to_list(gameBoard: tuple) -> list: """ Converts rows to lists """ newBoard = [] for row in gameBoard: newBoard.append(list(row)) return newBoard
def get_network_detail(network): """ Retrieve network details from response. :param network: network details from response :return: network detail :rtype: dict """ return { 'ID': network.get('id', ''), 'Name': network.get('name', ''), 'Type': network.get('type', '') ...
def generate_checkpoint(step, hyperparameters, model_state): """Generates checkpoint contents. Args: step: Training step at which this checkpoint was generated. hyperparameters: Dictionary specifying the model hyperparameters. model_state: A JSON serializable representation of the model state. Retur...
def rol32(x, shift): """Rotate X left by the given shift value""" assert 0 < shift < 32 return (x >> (32 - shift)) | ((x << shift) & 0xffffffff)
def search_nested_key(dic, key, default=None): """Return a value corresponding to the specified key in the (possibly nested) dictionary d. If there is no item with that key, return default. """ stack = [iter(dic.items())] while stack: for k, v in stack[-1]: if isinstance(v, d...
def equal(a, b): """ Case insensitive string compare. @param a: String to compare. @param b: String to compare. @return: True if equal, False if not. """ return a.lower() == b.lower()
def cleanup_hash(sha1): """ Checks if a hash is valid. Returns the cleaned up hash if so, else False :param sha1: The hash to check :return: mixed """ sha1 = sha1.strip() try: if len(sha1) > 0 and int(sha1, 16) > 0: # Hash is valid return sha1 except ...
def deduplicate_actions(actions: list): """Returns a list of actions that contains no identical elements Two actions are considered identical if they have the same "run", "cwd" and "type" properties. "name" is ignored. The returned list is not ordered and it's not guaranteed that it will preserve ...
def items_iterator(dictionary): """Add support for python2 or 3 dictionary iterators.""" try: gen = dictionary.iteritems() # python 2 except: gen = dictionary.items() # python 3 return gen
def prettier_tuple(the_tuple, indent=4): """ pretter tuple :param the_tuple: :type the_tuple: :param indent: :type indent: :return: :rtype: """ if not the_tuple: return "()" return '(\n' + " " * indent + ("," + "\n" + " " * indent).join( str(i) for i in the_tu...
def combine(hi, lo): """Combine the hi and lo bytes into the final ip address.""" return (hi << 64) + lo
def int_or(x, y): """ used for getting or-values in binary classification """ return 1 - (1-x) * (1-y)
def guid_to_num(guid): """ Convert a DHT guid to an integer. Args: guid: The guid to convert, as a string or unicode, in hexadecimal. Returns: An integer corresponding to the DHT guid given. """ return int(guid.rstrip('L'), base=16)
def _filter_tasks_by_completed(tasks, is_completed): """ Filters tasks based on the completion status. Args: tasks ([{str:str}]): List of tasks from asana API. At the very least, must have the `completed` key. is_completed (bool or None): Whether to return tasks that are completed. ...
def _global2local_offsets(global_offsets): """ Given existing global offsets, return a copy with offsets localized to each process. Parameters ---------- global_offsets : dict Arrays of global offsets keyed by vec_name and deriv direction. Returns ------- dict Arrays of...
def escape_sh_double_quoted(s): """ The result is supposed to be double-quoted when passed to sh. """ if (s is None): return None return s.replace('\\','\\\\').replace('"','\\"')
def hello(phrase, name): """This function will return the salution phase. Args: phrase (str): salution phase name (str): person name """ return f'{name}, {phrase}'
def underscore_to_camelcase(word): """ Convert word to camelcase format """ return ''.join(x.capitalize() or '_' for x in word.split('_'))
def get_class(x): """ x: index """ # Example distribution = [1882, 3380, 5324, 6946, 8786] x_class = 0 for i in range(len(distribution)): if x > distribution[i]: x_class += 1 return x_class
def _get_numfiles(wrfseq): """Return the number of files in the sequence. This function will first try to call the builtin :meth:`len` function, but if that fails, the entire squence will be iterated over and counted. Args: wrfseq (iterable): An iterable type, which includes lists...
def parse_data_url(data_url): """ Parses a data URL and returns its components. Data URLs are defined as follows:: dataurl := "data:" [ mediatype ] [ ";base64" ] "," data mediatype := [ type "/" subtype ] *( ";" parameter ) data := *urlchar parameter := attribute "=" v...
def BC(x, y): """Used to set the boundary condition for the grid of points. Change this as you feel fit.""" return (x**2 - y**2)
def filter_commands(text, chat_id, correct_ident): """Check if text is valid command to bot. Return string(either some command or error name) or None. Telegram group may have many participants including bots, so we need to check bot identifier to make sure command is given to our bot. """ is...
def is_only_whitespace(s, *args, **kwargs): """ If the string only contains spaces and or tabs. >>> is_only_whitespace('Hi there') False >>> is_only_whitespace('42') False >>> is_only_whitespace(' 7 ') False >>> is_only_whitespace(' ') True >>> i...
def genotype_int2genotype_char(current_possible_genotypes, genotype_list): """Convert vcf file's samples' numerical genotypes to genotype characters current_possible_genotypes: List of possible genotypes with first value being the REF genotype and the rest ALT genotypes. genotype list: List of gen...
def has_variable(obj, variable): """Tries to check if an object has a variable.""" if hasattr(obj, "has_variable"): return obj.has_variable(variable) return False
def outputDecode(x): """ x = <-4.1714, 4.1714> y = <0, 1> Formula: x = (y * 8.3428) - 4.1714 """ x = float(x) return (x * 8.3428) - 4.1714
def merge_sort(collection): """Pure implementation of the merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] ...
def str_delimited(results, header=None, delimiter="\t"): """ Given a tuple of tuples, generate a delimited string form. >>> results = [["a","b","c"],["d","e","f"],[1,2,3]] >>> print(str_delimited(results,delimiter=",")) a,b,c d,e,f 1,2,3 Args: result: 2d sequence of arbitrary ty...
def _parse_nodata_values(input_str): """ Helper callback function to parse no-data values. """ return [int(part) for part in input_str.split(",")]
def f(x, y=1): """ A module-level function for testing purposes. """ return x ** 2 + y
def sort_cards(cards): """Sort a deck of cards.""" a_bucket = [] t_bucket = [] j_bucket = [] q_bucket = [] k_bucket = [] num_bucket = [] for item in cards: if item == 'A': a_bucket.append(item) elif item == 'T': t_bucket.append(item) elif i...
def pursuant_child_support(responses, derived): """ Return a list of child support bullet points, prefaced by the correct 'pursuant to' phrase. """ act = derived['child_support_acts'] act = 'Pursuant to %s,' % act if act != '' else act try: arrangements = responses.get('order_for_ch...
def hexdump(source: bytearray, length: int = 0x10, separator: str = ".", show_raw: bool = False, base: int = 0x00) -> str: """ Produces a `hexdump` command like output version of the bytearray given. """ result: list[str] = [] for i in range(0, len(source), length): s = source[i:i+length] ...
def get_decbas(line): """ Retrieve the baseline declination (typically in tenths of minutes East) from the IAGA-2002 header *line*. """ assert line.startswith(' # DECBAS') or line.startswith(' # D-conversion factor') return int(line[24:69].split(None, 1)[0])
def denormalize_m11(x): """Inverse of normalize_m11.""" return (x + 1) * 127.5
def fme(base: int, exponent: int, modulus: int) -> int: """ Algorithm for fast modular exponentiation. """ result = 1 temp = base % modulus while exponent > 0: if exponent & 1: result = (result * temp) % modulus temp = (temp * temp) % modulus exponent >>= 1 return...
def list2str(cmd): """ connect the string in list with space :param cmd: a list contains the command and flag :return: a string """ ret = "" for i in range(len(cmd) - 1): ret += cmd[i] + " " ret += cmd[-1] print(ret) return ret
def part_one(data): """Part one""" valid = 0 for row in data.splitlines(): words = sorted(row.split()) is_valid = True for i in range(1, len(words)): if words[i - 1] == words[i]: is_valid = False break if is_valid: valid...
def topic_key(locale, product_slug, topic_slug): """The key for a topic as stored in client-side's indexeddb. The arguments to this function must be strings. """ return locale + '~' + product_slug + '~' + topic_slug
def generate_playlist_url(playlist_id:str)->str: """Takes playlist Id and generates the playlist url example https://www.youtube.com/playlist?list=PLGhvWnPsCr59gKqzqmUQrSNwl484NPvQY """ return f'https://www.youtube.com/playlist?list={playlist_id}'
def ts_css(text): """applies nice css to the type string""" return '<span class="ts">%s</span>' % text
def get_title(*args: object): """Return title for printing.""" return ", ".join([str(arg).lower() for arg in args]).capitalize()
def text_to_domain_values(domain_text, domain_size): """Converts text of enumerated domain into a list of integers.""" domain_values = set() text_parts = domain_text.split(' ') for text_part in text_parts: if '..' in text_part: start, end = text_part.split('..') for i in ...
def get_test_data_clone_with_cookie_object(test_data): """ returns a clone of test_data dict with a k,v pair for a cookie Args: test_data (dict): parameters to to create the request Returns: test_data dict with """ test_data_copy = test_data.copy() if 'cookies' not in test_dat...
def rotate_left(x, y): """ Left rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_left >>> a = [0, 1, 2] >>> rotate_left(a, 1) [1, 2, 0] """ if len(x) == 0: return x y = y % len(x) retu...
def check_permutation(str1, str2): """ If two strings are permutation to one another, they should have the same characters. This solution evaluates the sum of the orders of the strings if they are the same then they are permutation to one another, otherwise, they are not and I am a f...
def probabilistic_sum_s_norm(a, b): """ Probabilistic sum s-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns probabilistic sum s-norm of a and b Examples -------- >>> a = random.random...
def get_syslog_facility(facility): """ get_syslog_facility() -- Get human-readable syslog facility name. Args (required): facility (int) - Facility number. Returns: Name of facility upon success. "UNKNOWN" on failure. """ facilities = ( (0, "KERNEL"), (1, "U...
def rm_underscore(my_word): """ my_word: string with "_ " characters, current guess of the secret word info: replaces "_ " with "_" in a string returns: my_word with "_" """ word = "" for char in my_word: word += char.strip() return word
def load_preprocessed_cord_from_dir(data_dir): """ This function currently isn't useful and serves as a template. Eventually this function will load CORD data from the data_dir. This serves as an example of good docstrings. :param data_dir: Location of the CORD pre-processed data :return: True """ print("Hello...
def _nice_case(line): """Makes A Lowercase String With Capitals.""" line = line.lower() s = "" i = 0 nextCap = 1 while i < len(line): c = line[i] if c >= "a" and c <= "z" and nextCap: c = c.upper() nextCap = 0 elif ( c == " " ...
def checksumPacket( p ): """ Calculate the checksum byte for the packet """ sum = 0 for byte in p[2:]: sum = 0xff & (sum + byte) notSum = 0xff & (~sum) return notSum
def link_id_degrees(full_id_degrees, id_degrees, i, bins): """ Puts the ids of specific updates/times into a full dictionary of id-[degrees] Takes in a specific update (id_degrees), and adds the degrees present in that update to the full id:degree dictionary. The degrees are a list of len(bins), and ea...
def extract_concat_sub_text(sub_info): """sub_info is list(dict), each dict is {"text": str, "start": float, "end": float}""" return " ".join([e["text"] for e in sub_info])
def cosin_distance(vector1, vector2): """ Calculate the cosin distance """ dot_product = 0.0 normA = 0.0 normB = 0.0 for a, b in zip(vector1, vector2): dot_product += a * b normA += a ** 2 normB += b ** 2 if normA == 0.0 or normB == 0.0: return None el...
def dict_compare(old_dict, new_dict, nested=None): """ Compare two dictionaries Only 1 level, ignoring attributes starting with '_' """ key_prefix = nested + '|' if nested else '' intersect_keys = old_dict.keys() & new_dict.keys() modified = {key_prefix + k: dict(old=old_dict[k], new=new_dic...
def merge_equivalencies(old_equivalencies, new_equivalencies): """ Utility method to merge two equivalency lists Uses a dict with concatenated units as keys """ seen = {} result = [] total_equivalencies = old_equivalencies+new_equivalencies for equivalency in total_equivalencies: ...
def strip_irrelevant_kwargs(func, *args, **kwargs): """ call a function with subsets of kwargs until it agrees to be called. quick hacky way to enable a consistent interface for callables whose real signatures cannot be inspected because they live inside extensions or whatever. """ while len...
def filter_cpg_dict_by_cov(cpgDict, coverage=1): """ Filter cpg with coverage Args: cpgDict: coverage: Returns: """ if coverage <= 1: return cpgDict retDict = {} for key in cpgDict: if len(cpgDict[key]) >= coverage: retDict[key] = cpgDict[key...
def safe_cast(obj, dest_type: type): """ Executes type-cast safely. :param obj: Object to be casted. :param dest_type: Destination type. :return: Casted `obj`. Return `None` if failed. """ try: return dest_type(obj) except Exception: return None
def normalize (pattern): """Normalizes the LED segment `pattern` by sorting it alphabetically.""" return ''.join( sorted(pattern) )
def maybe_recursive_call( object_or_dict, method: str, recursive_args=None, recursive_kwargs=None, **kwargs, ): """Calls the ``method`` recursively for the ``object_or_dict``. Args: object_or_dict (Any): some object or a dictionary of objects method (str): method name to cal...
def _get_best_indexes(logits, n_best_size): """Get the n-best logits from a list.""" index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True) best_indexes = [] for i in range(len(index_and_score)): if i >= n_best_size: break best_indexes.append(i...
def factorial(n): """ :type n: int :rtype: int """ f = n for i in range(n - 1, 0, -1): f = f * i return f
def numeric_module_version(vers): """ Converts a string into a tuple with numbers wherever possible. @param vers string @return tuple """ if isinstance(vers, tuple): return vers spl = str(vers).split(".") r = [] for _ in spl: try: i = ...
def convert_team_name(team): """ Converts team string into proper casing format :param str team: Team enum name :return: Converted string """ return team.title().replace('_', ' ')
def integer_to_base(number, base_string): """ Converts base10 integer to baseX integer (where X is the length of base_string, say X for '0123' is 4), for example: 2645608968347327576478451524936 (Which is 'Hello, world!') to 21646C726F77202C6F6C6C6548 (base16), does not account for negative numbers ...
def calafazan(char_len, *strings): """Scrieti o functie care> primeste un integer char_len si un numar variabil de stringuri. Verifica daca fiecare doua string-uri vecine respecta: al doilea string incepe cu ultimile char_len caractere a primului. """ if len(strings) <= 1: return Tru...
def joinStrings(value): """ Converts a list of strings into a single string with an oxford comma. e.g. ['a', 'b', 'c'] => "a, b, and c" ['a', 'b'] => "a and b" ['a'] => "a" """ if len(value) > 2: value[-1] = str("and " + value[-1]) return str(", ".join(value)) ...
def pod2Head(pod): """ @param pod: Snippet in POD format to be analyzed. @type pod: str @return: String of first `=headX' entry in POD snippet or empty string if none found. @rtype: str """ for line in pod.split("\n"): if line.startswith("=head"): return lin...
def _calc_crc32(num:int) -> int: """_calc_crc32(num) -> CRC_TABLE[num] calculate the value of an entry in the CRC_TABLE, at CRC_TABLE[num] """ POLY = 0xEDB88320 # reversed polynomial for _ in range(8): if num & 0x1: num = (num >> 1) ^ POLY else: num >>= 1 return num
def bool_to_yes_no(value): """ Turn a boolean into a yes/no string :param value eg True: :return string eg "yes": """ if value: return "yes" return "no"