content
stringlengths
42
6.51k
def is_exe(filename): """ Check that a file is a Windows executable. """ return filename.endswith((".exe", ".dll"))
def _drive_id_from_url(url: str) -> str: """Get an ID from a Google Drive URL. Args: url (str): Publicly visible Google Drive URL. Returns: str: Google Drive ID. """ url_prefixes = [ "https://drive.google.com/file/d/", "https://drive.google.com/open?id=", ] ...
def is_empty_list_or_dict(o): """Check if object is a list or a dict and if it is empty""" return (isinstance(o, list) or isinstance(o, dict)) and len(o) == 0
def sqrt(num): """ Find the Square Root on integer without using internal sqrt :param num: integer :return: floor(sqrt(num)) """ if num < 2: return num result = 0 start, end = 1, num // 2 while start <= end: mid = (start + end) // 2 sqr = mid ** 2 # ...
def blurhash_validity_checker(blurhash: str) -> bool: """Checks if a blurhash is valid and returns True or False""" if len(blurhash) < 6: return False characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~" characters_values = dict(zip(characters, rang...
def image_index(pathname): """ Helper function for submission. Takes the path to an image, e.g. "./image_folder/15.jpg", and returns the image name, in this example "15.jpg". """ return pathname[pathname.rfind("/")+1:]
def incrochet(strg): """ get content inside crochet Parameters ---------- strg : string Returns ------- lbra : left part of the string inbr : string inside the bracket Examples -------- >>> strg ='abcd[un texte]' >>> lbra,inbr = incrochet(strg) >>> assert(lbra=='ab...
def user_playlist_tracks_remove_specific_occurences(user_id, playlist_id, tracks, snapshot_id=None): """ tracks: list of {'uri': 'something', positions: [0,4,6]} objects """ payload = {'tracks': tracks} if snapshot_id: payload['snapshot_id'] = snapshot_id return ( 'DELETE', '/use...
def dtocard(d): """Converts degrees to cardinal direction.""" c = '' if d >= 348.75 or d < 11.25: c = 'N' elif d < 33.75: c = 'NNE' elif d < 56.25: c = 'NE' elif d < 78.75: c = 'ENE' elif d < 101.25: c = 'E' elif d < 123.75: c = 'ESE' e...
def add_scope_to_name(scope, name): """ Prepends the provided scope to the passed-in op or tensor name. """ return "%s/%s" % (scope, name)
def water_evapotranspiration_flux(evap): """Water evapotranspiration flux ``evspsbl`` [mm]. Computes water evapotranspiration flux ``evspsbl`` from surface evaporation. """ return evap * (-1)
def merge_json(conf, json) : """ merge in a json dict with the existing one in: configuration dict, json dict out: configuration' """ for (key, val) in json.items() : if key in conf : #there's a match, do a more detailed merge oldval = conf[key] if type(oldval) == dict and type(val) == d...
def return_label(predicted_probs): """ Function that takes in a list of 7 class probabilities and returns the labels with probabilities over a certain threshold. """ threshold = 0.4 labels = [] classes = ['not toxic', 'toxic', 'severe toxic', 'obscene', 'threat', 'insult',...
def fix_url(url): # type: (str) -> str """ Fix a url to be used in the rest of the program example: api.gdc.cancer.gov -> https://api.gdc.cancer.gov/ """ if not url.endswith("/"): url = "{0}/".format(url) if not (url.startswith("https://") or url.startswith("http://")):...
def parse_components(components, trans_to_range): """Get genes data. Each gene has the following data: 1) It's ID 2) Included transcripts 3) Genomic range. """ genes_data = [] # save gene objects here for num, component in enumerate(components, 1): gene_id = f"reg_{num}" # nee...
def have_mod_symbol(l): """Check if modulus is present""" if "%" in str(l): return 1 else: return 0
def isvar(name): """Is thsi the name of a var?""" return name.startswith("var")
def has_field(analysis, field): """Return true or false if given field exists in analysis""" for f in field: try: analysis = analysis[f] except: return False return True
def approx_sqrt(n): """ function approx_sqrt Args: param1 : n - positive integer Returns: sqrt """ #local variables epsilon = .01 step = epsilon ** 2 counter = 0 sqrt = 0.0 if ( n <= 0 ): n = abs(n) print("Finding approx sqrt of {0}".format(n)) while ( abs(sqrt * sqrt - n) > epsilon): s...
def one_format_as_string(ext, format_name): """('.py', None) to 'py', etc""" if ext.startswith('.'): ext = ext[1:] if format_name: return ext + ':' + format_name return ext
def sample_rate(session, Type='Real64', RepCap='', AttrID=1150020, buffsize=0, action=['Get', '']): """[Sample Rate (Hz)] The sample rate, in Hz, of the time record returned by Get Data or Get Data Block. """ return session, Type, RepCap, AttrID, buffsize, action
def compute_markevery(data, max_points=200): """Compute number of points that will be dropped to compress the plot.""" num_points = len(data) markevery = max(num_points // max_points, 1) return markevery
def quote_argument(arg): """Wraps the given argument in quotes if needed. This is so execute_subprocess output can be copied and pasted into a shell. Args: arg: The string to convert. Returns: The quoted argument. """ if '"' in arg: assert "'" not in arg return "'" + arg + "'" if "'" in...
def color_dist_sq(x,y): """ Simple squared euclidean distance for color tuples """ return (x[0]-y[0])**2 + (x[1]-y[1])**2 + (x[2]-y[2])**2
def check_pkt_filter_report_hash(mode): """Check if Flow Director hash match reporting mode is valid There are three modes for the reporting mode. * none * match (default) * always """ if mode in ['none', 'match', 'always']: return True else: return False
def scalar_addition(seq, scalar, mod = 0): """ Returns the result of adding scalar (a number) to all elements in seq. If mod is not 0, then all addition occurs modulo mod. Note: this function is an "analogue" of scalar multiplication - an operation where every element in a sequence is...
def check_ttl(ttl): """ttl less than 3600""" try: ttl = int(ttl) if ttl > 0 and ttl <= 3600: return True else: return False except Exception: return False
def generate_coordinate_rect(x_start, x_finish, y_start, y_finish): """ Generate tuples for coordinates in rectangle (x_start, x_finish) -> (y_start, y_finish) """ coords = [] for i in range(x_start, x_finish): for j in range(y_start, y_finish): coords.append((i, j)) return c...
def unsolved_remaining(cards): """Return True if there are any unsolved questions.""" for card in cards: if not card[4]: return True else: return False
def add(b1, b2): """ Returns bbox that contains two bboxes. """ return (min(b1[0],b2[0]),min(b1[1],b2[1]),max(b1[2],b2[2]),max(b1[3],b2[3]))
def to_py_type(value): """ Convert qe string object to a standard Python object. Args: obj (str): QE string value Returns: conv_obj: Python typed object """ value = value.strip() value = value.replace(',', '') is_int = None try: is_int = int(value) excep...
def mergeRangeList(lst): """Assumes lst is a list returns a list of tuples of int and the elements of lst,n of lenght = len(lst)""" return list(zip(list(range(1, len(lst)+1)), lst))
def line_numbers(start, end): """ Return a list of line numbers, in [start, end] (inclusive). """ return list(range(start, end + 1))
def remove_center(lst): """Remove the center of a list favoring the position just left of center""" center = len(lst) // 2 return lst[:center] + lst[(center+1):]
def vector_cross(vect1=(), vect2=()): """ Computes the cross-product of the input vectors. :param vect1: input vector 1 :type vect1: tuple :param vect2: input vector 2 :type vect2: tuple :return: result of the cross-product :rtype: list """ if not vect1 or not vect2: raise V...
def death_x(well): """If the well is a xantophore, kill it""" if well == 'X': return 'S' else: return well
def parity_even_p(state, marked_qubits): """ Calculates the parity of elements at indexes in marked_qubits Parity is relative to the binary representation of the integer state. :param state: The wavefunction index that corresponds to this state. :param marked_qubits: The indexes to be considered i...
def gen_ticks(bound: int): """Generate increasing ticks from a reversed axis. Parameters ---------- bound : `int` The highest value, tick for this is 0 Returns ------- `List[int]` Array of tick positions """ res = [bound] while bound >= 0: bound -= 7 ...
def byte_to_megabyte(byte): """ Convert byte value to megabyte """ return byte / (1024.0 ** 2)
def _is_interactive_opt(bk_opt): """ Heuristics to detect if a bokeh option is about interactivity, like 'selection_alpha'. >>> is_interactive_opt('height') False >>> is_interactive_opt('annular_muted_alpha') True """ interactive_flags = [ 'hover', 'muted', '...
def to_base(base: int, number: int) -> str: """ Changes an integer from decimal base to other base. Args: base (int): New base of the number to be converted. number (int): Number to be converted to the new base. Returns: str: A string representation of the number in the new base. ...
def create_env_setup_script(ws_path, master_hostname, hostname): """ Create ROS environment setup script. """ template = [ '#!/bin/bash', '', 'source {}/setup.bash'.format(ws_path), '', 'export ROS_MASTER_URI="http://{}.local:11311"'.format(master_hostname), ...
def _convert_to_float(score): """ Convert a string ('score') to float. If the string is empty, return None. If the string is float-like, return its float. """ if len(score) == 0: return None else: return float(score)
def factorial_recursion(number): """Calculates factorial using recursion. :param number: A number for which factorial should be calculated. :return: Factorial number. >>> factorial_recursion(-1) 1 >>> factorial_recursion(0) 1 >>> factorial_recursion(1) 1 >>> factorial_recursion...
def max_two_values(d): """ a) create a list of the dict's keys and values; b) return the two keys with the max values """ v=list(d.values()) k=list(d.keys()) result1 = k[v.index(max(v))] del d[result1] v=list(d.values()) k=list(d.keys()) result2 = k[v.index(max(v))] ...
def _backtrack_norec(t, ref, can): """Read out LCS.""" i = len(ref) j = len(can) lcs = [] while i > 0 and j > 0: if ref[i - 1] == can[j - 1]: lcs.insert(0, i-1) i -= 1 j -= 1 elif t[i][j - 1] > t[i - 1][j]: j -= 1 else: i -= 1 return lcs
def _HasFieldName(proto_field_name): """Returns the name of the (internal) instance attribute which objects should use to store a boolean telling whether this field is explicitly set or not. Args: proto_field_name: The protocol message field name, exactly as it appears (or would appear) in a .proto f...
def is_namedtuple(x): """Checks if x is a namedtuple instance. Taken from https://stackoverflow.com/a/2166841 .""" t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, '_fields', None) if not isinstance(f, tuple): return False return all(type(n)==str for n...
def make_func_args(params, func_state, rng, batch, has_state: bool, has_rng: bool): """Correctly puts all arguments to the function together.""" func_args = (params,) if has_state: if func_state is None: raise ValueError("The `func_state` is None, but the argument `has_state` " ...
def get_indices_to_prune(layer): """ input: conv2d layer """ # nn.AvgPool2d: c x h x w -> 1 x c # get M of size n x c return None
def cipher(text, shift, encrypt=True): """ Caesar cipher, one of the simplest and most widely known encryption techniques. In short, each letter is replaced by a letter some fixed number of positions down the alphabet. Parameters ---------- text: str A string that you want to encrypt or...
def _get_weights_manifest_for_group(group): """Gets the weights entries manifest JSON for a group. Args: group: A list of weight entries. Returns: An list of manifest entries (dicts) to be written in the weights manifest. """ weights_entries = [] for entry in group: is_quantized = 'quantization...
def form_array_from_string_line(line): """Creates an array from a (space|comma) delimited string. Args: line: A string of input line (usually from a text file) with integers contained within, separated by spaces. Returns: array: List object (Python's standard 'array' type) feat...
def circumcentre(A,B,C): """ SUMMARY computes the centre of the circumscribed circle PARAMETERS A: coordinates of vertex A B: coordinates of vertex B C: coordinates of vertex C RETURNS (float, float) """ D = 2 * (A[0]*(B[1]-C[1]) + B[0]*(C[1]-A[1]) + C[0...
def dict_is_test(data): """helper function to check whether passed argument is a proper :class:`dict` object describing a test. :param dict data: value to check :rtype: bool """ return ( isinstance(data, dict) and "type" in data and data["type"] == "test" and "id" in...
def subuple(tuple1, tuple2): """ Vector substraction """ return tuple(x1-x2 for x1,x2 in zip(tuple1, tuple2))
def divide_kernel(numerator: float, denominator: float) -> float: """Divides one number by another number. Args: numerator: the number for the top of your fraction denominator: the number for the bottom of your fraction Returns: a float representing one number that was divided by a...
def get_int_or_minus_1(v: str) -> int: """Helper function to parse the command line""" try: return int(v) except ValueError: return -1
def str2bool(value): """ helper function to return Python boolean type (source: https://stackoverflow.com/a/715468) :param value: value to be evaluated :returns: `bool` of whether the value is boolean-ish """ value2 = False if isinstance(value, bool): value2 = value else: ...
def get_word_key(word): """Generates redis keyname for word""" return "w_%s" % word.lower()
def recursive_replace(steps: int, to_expand: str, rules: dict) -> str: """ Replace the given string with a new replacement string, according to the rules. Args: steps (int): How many iterations. Decremented with each recursion. Recursion ends when step=0. input (str): Input str. The str to be r...
def merge(dict_1, dict_2): """Merge two dictionaries. Values that evaluate to true take priority over falsy values. `dict_1` takes priority over `dict_2`. """ return dict((str(key), dict_1.get(key) or dict_2.get(key)) for key in set(dict_2) | set(dict_1))
def transformation_fn(results): """ """ results_cleaned = results return results_cleaned
def linear_search(myList, item): """Linear search through a list to find an item.""" """ Args: myList: List to search through. item: Item to find. Return: Return True if item is found and False otherwise. """ position = 0 found = False while position < len(myList) and no...
def weighted_jaccard_similarity(A, B): """ Function computing the weighted Jaccard similarity. Runs in O(n), n being the sum of A & B's sizes. Args: A (Counter): First weighted set. B (Counter): Second weighted set. Returns: float: Weighted Jaccard similarity between A & B...
def extendedGcd(a, b): """ Extended Euclidean Algorithm - gcd(a,b) = a * x + b * y that returns x and y as well as the gcd value of the operands :param a: first operand :param b: second operand :return: (gcd(a,b), x, y) """ res = [a, 1, 0] tmpRes = [b, 0, 1] while tmpRes[0] !...
def rating_to_traditional_range(rating_f): """ Returns a rating from 0-40 in the traditional -30 to 10ish, with the -1 to 1 kyu/dan boundary expanded. """ rating = rating_f - 30.0 if (rating > -1.0): rating += 2.0 return rating
def _find_line(lines, prefix): """Find a line that starts with prefix in lines list. :type lines: list :arg lines: list of strings :type prefix: str :arg prefix: search prefix :rtype: int :returns: index of string that starts with 'prefix'; -1 if not found """ for i, line in enume...
def intersection(*arrays): """Computes the intersection of all the passed-in arrays. Args: arrays (list): Lists to process. Returns: list: Intersection of provided lists. Example: >>> intersection([1, 2, 3], [1, 2, 3, 4, 5]) [1, 2, 3] .. versionadded:: 1.0.0 ...
def judge_neighbor(i, j, vertices): """ Judge whether the item align with the money. Return 1 if aligned, 0 if not aligned. """ vi = vertices[i] vj = vertices[j] # use the height of money box as threshold threshold = abs(vi[1][1] - vi[2][1]) flag = 1 for a, b in zip(vi, vj): ...
def eval_expression(expression, dico): """Evaluates an expression containing integer variables and the following operators: +, -, *, /, & (and), | (or), ! (not), <, >, giving to the variables the values found in dico, or 0 otherwise. """ if not expression: return 1 expression = expressi...
def difference(lists): """ Return the first set minus the rest. """ if len(lists) == 0: return lists if len(lists) == 1: return lists[0] finalList = set(lists[0]) for aList in lists[1:]: finalList = finalList - set(aList) return list(finalList)
def getw(height, aspect_ratio=16 / 9, only_even=True): """ Returns width for image. """ width = height * aspect_ratio width = int(round(width)) return width // 2 * 2 if only_even else width
def list_or_int_or_float_or_str(value): """ Parses the value as an int, else a float, else a string. If the value contains commas, treats it as a list of ints or floats or strings. Also handles None, True, and False. """ if "," in value: return [list_or_int_or_float_or_str(item) for item...
def make_histogram(s): """Make a map from letters to number of times they appear in s. s: string Returns: map from letter to frequency """ hist = {} for x in s: hist[x] = hist.get(x, 0) + 1 return hist
def add_dummy_data(bitmap, width, height): """ Adds dummy data to a bitmap to ensure the width is divisible by 4. This is required because the SSD1322 OLED driver maintains a single column address for four pixels. bitmap (list): A list of integers (pixel values) width (int): The wi...
def expand_abbreviations(template, abbreviations): """ Expand abbreviations in a template name. :param template: The project template name. :param abbreviations: Abbreviation definitions. """ if template in abbreviations: return abbreviations[template] # Split on colon. If there is...
def ishex(c): """Return true if the byte ordinal 'c' is a hexadecimal digit in ASCII.""" assert isinstance(c, bytes) return b'0' <= c <= b'9' or b'a' <= c <= b'f' or b'A' <= c <= b'F'
def average(dictionarry: dict) -> float: """Returns the average of the values of the dictionary Args: d (dict): A dictionary with str as key and int/float as value Returns: float: average of the values of the dictionary """ dict_len: int = len(dictio...
def digits_seen(number): """Return a list of digits in the number num.""" return set([str(d) for d in str(number)])
def format_face_coords(ibm_analyze_result): """ Parse the face coords extracted from IBM service_v4. :param ibm_analyze_result: the json object directly returned from IBM face detection service_v4 see an example in "watson_experiment/sample_face_and_result/sample_output.json" :return: a list of...
def f2f(value): """Converts a fortran-formatted double precision number (e.g., 2.323d2) to a python float. value should be a string. """ value = value.replace('d', 'e') value = value.replace('D', 'e') return float(value)
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a ...
def _normalize_dicts(dict1, dict2): """Convert two dicts to lists that are aligned to each other.""" def add_keys_from(dist1, dist2): """If dist1 contains a key that dist2 doesn't, add it to dict2.""" for k in dist1.keys(): if k not in dist2: dist2[k] = 0 def va...
def float_to_pcnt(x): """Convert a float to a percentage string, e.g. 0.4 -> '40%'.""" return '{}%'.format(round(x * 100))
def build_get_desc_value(desc_type, desc_index): """Build and return a wValue field for control requests.""" return (desc_type << 8) | desc_index
def total_seconds(timedelta): """ Some versions of python don't have the timedelta.total_seconds() method. """ if timedelta is None: return None return (timedelta.days * 86400) + timedelta.seconds
def is_true_batch(value): """Return a batch comment if value is False.""" if value: return '' else: return ' #'
def decode_mac_address(encoded_mac_address): """ Returns a readable MAC Address. """ return ":".join(["{:02x}".format(ch) for ch in encoded_mac_address])
def filter_to_sentry(event, hint): """filter_to_sentry is used for filtering what to return or manipulating the exception before sending it off to Sentry (sentry.io) The 'extra' keyword is part of the LogRecord object's dictionary and is where the flag for sending to Sentry is set. Example...
def flatten_list(lst): """ to flatten a list """ return [item for sublist in lst for item in sublist]
def FracDegToDegMin(lat, lon): """Converts location in format of total fractional degrees to separated format of deg and minutes lat is in signed fractional degrees positive = North negative = South lon in in signed fractional dregrees positive = East negative = West latDeg are in signed...
def isprime_ver1(n): """ Returns True if n is prime, False otherwise. * Checks all factors of n. * Rediculously slow. For checking up to 100k, takes over a minute. """ if n < 2: return False i = 2 while i < n: if n % i == 0: return False i += 1 ret...
def yes_i_know_that_python_handles_hex(h_string): """Just to prove that I know the right way to do this in Python.""" return int(h_string, 16)
def from_csv_str(s: str): """Escapes a string that is read from a csv file""" return s.replace('\\n', '\n')
def defined_split(data): """ split train/valid/test data according to "Splits" column """ train_idxs, test_idxs = [], [] for i, split in enumerate(data): assert split in ['test', 'train'] if split == 'test': test_idxs.append(i) elif split == 'train': t...
def not_string(str_: str) -> str: """Add `not` to string. Returns a new string with `not` in front or an unchanged string if `not` was already there. """ if str_[:3] == 'not': return str_ return f'not {str_}'
def user_titles_table(raw_titles, raw_users): """ :param raw_titles: list of titles from csv_reader :param raw_users: list of users from csv_reader :return: dictionary from users to a single long title (all their titles concatenated) """ table = {} for title, users in zip(raw_titles, raw_use...
def check_image_valid(im_source, im_search): """Check if the input images valid or not.""" if im_source is not None and im_source.any() and im_search is not None and im_search.any(): return True else: return False
def get_inx(x, image_width, target_width, coordinate_transformation_mode): """Infer input x from output x with various coordinate transformation methods""" scale = image_width / target_width if coordinate_transformation_mode == "half_pixel": in_x = (x + 0.5) * scale - 0.5 elif coordinate_transfo...