content
stringlengths
42
6.51k
def ascii_line(chunk): """Create ASCII string from bytes in chunk""" return ''.join([ chr(d) if 32 <= d < 127 else '.' for d in chunk])
def missing_query(*args, **kwags): """ A query returning something not in the local DB """ response = { 'responseHeader': {'params': {'rows': 1}}, 'response': { 'numFound': 1, 'docs': [{ 'id': 'abcde', 'chec...
def get_geonames_uri(geonames_id): """ Returns tuple of 0. GeoNames place URI 1. GeoNames place description URL """ geonames_uri = "http://sws.geonames.org/%s/"%(geonames_id,) geonames_url = "http://sws.geonames.org/%s/about.rdf"%(geonames_id,) return (geonames_uri, geonames_ur...
def topic_with_device_name(device_name, topic): """Creates fully-formed topic name from device_name (string) and topic (string)""" if device_name: topic = device_name + "/" + topic return topic
def getParentProxyId(proxy): """ Return '0' if the given proxy has no Input otherwise will return the parent proxy id as a String. """ if proxy and proxy.GetProperty("Input"): parentProxy = proxy.GetProperty("Input").GetProxy(0) if parentProxy: return parentProxy.GetGlobalIDAsStr...
def classToDict(obj=None): """ Transform an object into a dict so it can be JSONified. Useful for turning custom classes into JSON-compatible dictionaries. """ if obj == None: return {} _obj = {} _obj.update(obj.__dict__) return _obj
def avg(l): """Helper function to return the average of a list of numbers""" return sum(l)/len(l)
def hms(seconds): """ Return time as hours, minutes seconds :param seconds: input seconds :return: hours, minuted, seconds """ mins, sec = divmod(seconds, 60) hours, mins = divmod(mins, 60) return hours, mins, sec
def extract_coordinates(url): """Given Google maps url with coordinates in a query string extract latitude and longitude""" try: coordinates = url.split('q=')[-1] lat, lon = [coor.strip() for coor in coordinates.split(',')] except AttributeError: return None, None return lat, lon
def print_list_body(list_in, tabs, output="", indent=4): """Enumerate through each file key's parameter list items""" tabs += 1 for item in list_in: output += (" " * indent) * tabs + str(item) + "\n" return output
def sphinx_role(record, lang): """ Return the Sphinx role used for a record. This is used for the description directive like ".. c:function::", and links like ":c:func:`foo`. """ kind = record["kind"] if kind in ["class", "function", "namespace", "struct", "union"]: return lang + ...
def calculate_scan_time(metadata): """Parse scan time from metadata. Returns: timestamp string """ scan_time = None if 'terraref_cleaned_metadata' in metadata and metadata['terraref_cleaned_metadata']: scan_time = metadata['gantry_variable_metadata']['datetime'] else: ...
def averages(arr): """ Computes the average of two integers and returns an array of them. :param arr: array of integers. :return: an array of the averages of each integer-number and his follower. """ if arr is None: return [] return [(arr[x] + arr[x+1]) / 2 for x in range(len(arr)-1)...
def numTrees(n): """ O(n^2) / O(n). :type n: int :rtype: int """ N = {} N[0] = 1 N[1] = 1 for i in range(2, n + 1): N[i] = 0 for j in range(0, i): N[i] += N[j] * N[i - j - 1] return N[n]
def str_to_bool_safe(s, truelist=("True", "true", "T"), falselist=("False", "false", "F")): """ Converts a boolean codified as a string. Instead of using 'eval', compares with lists of accepted strings for both true and false bools, and raises an error if the string does not match any case. Parameters ...
def getattr_by_path(obj, attr, *default): """Like getattr(), but can go down a hierarchy like 'attr.subattr'""" value = obj for part in attr.split('.'): if not hasattr(value, part) and len(default): return default[0] value = getattr(value, part) if callable(value): ...
def reverse_rows_ud(matrix): """ Flip order of the rows in the matrix[row][col] Using numpy only fits matrix lists with numbers: np_matrix = np.array(matrix) return np_matrix.flipud().tolist() To suit any list element type use general flipud. This reverse_rows_ud() is equ...
def value_or_none(elem): """Gets element value or returns None, if element is None :param elem: dataset element or None :return: element value or None """ return elem.value if elem else None
def createCGImageWithQuickTimeFromURL(url): """ Note: this function doesn't actually worked because the APIs used in here aren't properly wrapped (yet). """ return None imageRef = None err = noErr result, dataRef, dataRefType = QTNewDataReferenceFromCFURL(url, 0, None, None) if ...
def quadratic_interp(a,f,x): """Compute at quadratic interpolant Args: a: array of the 3 points f: array of the value of f(a) at the 3 points Returns: The value of the linear interpolant at x """ answer = (x-a[1])*(x-a[2])/(a[0]-a[1])/(a[0]-a[2])*f[0] answer += (x-a[0])*...
def strip_keys(data, keys): """return a copy of dict `data` with certain keys missing""" return dict([(key, val) for key, val in data.items() if key not in keys])
def title_case(sentence): """ :param sentence: sentence tp be converted :return: ret: string :example: >>> titlecase("This iS tHe") This Is The """ return ' '.join([i.capitalize() for i in sentence.split()])
def get_flow_output_value(flow, configuration): """ Extracts outputs from the flow record based on the configuration. :param flow: flow record in JSON format :param configuration: loaded application configuration :return: dictionary of outputs defined by name as a key and element as a value """...
def ordinal_number(num): """create string with ordinal representation of number given """ # 10 through 20 all get 'th' suffix if num >=10 and num <=20: suffix = 'th' # suffix for all other numbers depends on the last digit in the number else: last_digit = num % 10 i...
def qinv(x, y, z, w): """ compute quaternion inverse """ inv_squared_magnitude = 1. / ( x*x + y*y + z*z + w*w ) invx = -x * inv_squared_magnitude invy = -y * inv_squared_magnitude invz = -z * inv_squared_magnitude invw = w * inv_squared_magnitude return invx,invy,invz,invw
def pad(octet_string, block_size=16): """ Pad a string to a multiple of block_size octets""" pad_length = block_size - len(octet_string) return octet_string + b'\x80' + (pad_length-1)*b'\x00'
def flatten_object(obj): """flatten an object into paths for easier enumeration. Args: an object Returns: a flat object with a list of pairs [(p_1, v_1), ..., (p_k, v_k)], (paths and values) Example: {x: 1, y : {z: [a, b], w: c}} will be flatten into [("/x", 1), ("/y/z/0", a), ("/y/z/1", b), ("/y/w...
def sort_by(array, key, descending=False): """ Sort an "array" by "key". >>> sort_by([{'a': 10, 'b': 0}, {'a': 5, 'b': -1}, {'a': 15, 'b': 1}], 'a') [{'a': 5, 'b': -1}, {'a': 10, 'b': 0}, {'a': 15, 'b': 1}] :param tp.List[tp.Mapping] array: list of dicts. :param str key: key name to use when s...
def app_model_or_none(raw_model): """ Transforms `raw_model` to its application model. Function can handle `None` value. """ return raw_model.get_app_model() if raw_model is not None else None
def binary_search(input_array, value): """Your code goes here.""" array_length = len(input_array) #("array length:", array_length) left = 0 right = array_length-1 while left <= right: mid = ( left + right ) // 2 #print("mid, mid value: ", mid, input_a...
def clean_config_for_pickle(full_conf): """Clean out any callable method instances, such as the gene_test_callback parameter passed to geneticalgorithm, as these are not pickleable. Acts in-place on full_conf parameter. Inputs: full_conf: The full_config dict structure, containing a ...
def get_index_table_name_for_release(data_release): """ Some datareleases are defined purely as ints which make invalid MySQL table names Fix that here by always prefixing release_ to the data_release name to make the MySQL table_name """ table_name = 'release_{}'.format(data_release) return tab...
def encode(s: str, encoding="utf8") -> bytes: """Shortcut to use the correct error handler""" return s.encode(encoding, errors="dxfreplace")
def _text_indent(text, indent): # type: (str, str) -> str """ indent a block of text :param str text: text to indent :param str indent: string to indent with :return: the rendered result (with no trailing indent) """ lines = [line.strip() for line in text.strip().split('\n')] return ...
def __get_average_kor__(qars): """ Get the average of kor in the benin republic area """ total = 0 count = len(qars) if count == 0: count = 1 for i, x in enumerate(qars): total += x.kor result = total / count return "{:.2f}".format(result) if result != 0 else "NA"
def _wrap_string(some_string,soft_wrap_length=4): """ Do a soft wrap of strings at space breaks. """ fields = some_string.split() lengths = [len(f) for f in fields] wrapped = [[fields[0]]] current_total = lengths[0] + 1 for i in range(1,len(lengths)): if current_total >= soft_wr...
def find_empty(brd): """ Uses the Sudoku problem as a Matrix input and returns the row/column location of the next empty field. :param brd: Matrix input of the board needed to solve for the Sudoku problem. :return: The row/column of the next empty field as a tuple. """ for i in range(len(brd)):...
def cmp_subst(subst_1, subst_2): """Compare two substitution sets. :arg dict subst_1: Substitution set. :arg dict subst_2: Substitution set. :returns bool: True if `subst_1` equals `subst2`, False otherwise. """ if len(subst_1) != len(subst_2): return False for item in subst_1: ...
def sla_colour(value, arg): """ Template tag to calculate the colour of caseworker/templates/includes/sla_display.html """ since_raised = int(value) if arg == "hours": if since_raised >= 48: return "red" else: return "orange" elif arg == "days": ...
def matriz_identidade(ordem: int = 1) -> list: """Cria uma matriz identidade.""" matriz = [] for linha in range(ordem): nova_coluna = [] for coluna in range(ordem): nova_coluna.append(0) if linha != coluna else nova_coluna.append(1) matriz.append(nova_coluna) return m...
def is_num(var): """Check if var string is num. Should use it only with strings.""" try: int(var) return True except ValueError: return False
def _styleof(expr, styles): """Merge style dictionaries in order""" style = dict() for expr_filter, sty in styles: if expr_filter(expr): style.update(sty) return style
def _feet_to_alt_units(alt_units: str) -> float: """helper method""" if alt_units == 'm': factor = 0.3048 elif alt_units == 'ft': factor = 1. else: raise RuntimeError(f'alt_units={alt_units} is not valid; use [ft, m]') return factor
def is_student(user_bio): """Checks whether a GitHub user is a student. The bio of a user is parsed. If it contains phd the user will not be marked as a student. If the bio contains only the word student the user will be marked as a student. Args: user_id (string): user id which is named a...
def check_auth_by_token(token): """ This function is called to check if a token is valid """ return token == 'CRAZYTOKEN'
def jaccard(seq1, seq2): """Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. from: https://github.com/doukremt/distance """ set1, set2 = set(seq1), set(...
def g(*args): """REGEX: build group.""" txt = '' for arg in args: if txt == '': txt = arg else: txt += '|' + arg return '(' + txt + ')'
def read_nion_image_info(original_metadata): """Read essential parameter from original_metadata originating from a dm3 file""" if not isinstance(original_metadata, dict): raise TypeError('We need a dictionary to read') if 'metadata' not in original_metadata: return {} if 'hardware_source...
def _try_eval(x, globals_, locals_): """return eval(x) or x""" try: return eval(x, globals_, locals_) except: return x
def timestr2sec(time_string): """ Convert a time string to a time interval Parameters ---------- time_string : str The string representing the time interval. Allowed units are y (years), d (days), h (hours), m (minutes), s (seconds) Returns ------- delta_t : float ...
def _generate_var_name(prefix, field_name): """ Generate the environment variable name, given a prefix and the configuration field name. Examples: >>> _generate_var_name("", "some_var") "SOME_VAR" >>> _generate_var_name("my_app", "some_var") "MY_APP_SOME_VAR" :param prefix: the pr...
def human_time(milliseconds, padded=False): """Take a timsetamp in milliseconds and convert it into the familiar minutes:seconds format. Args: milliseconds: time expressed in milliseconds Returns: str, time in the minutes:seconds format For example: """ milliseconds = int(...
def right_shift(number, n): """ Right shift on 10 base number. Parameters ---------- number : integer the number to be shift n : integer the number of digit to shift Returns ------- shifted number : integer the number right shifted by n digit Examples ...
def camelcase(text): """ >>> camelcase("A Test title") 'aTestTitle' """ words = text.split() first = False for word in words: if not first: text = word.lower() first = True elif len(word) > 1: text += word[:1].upper() + word[1:] eli...
def remove_comments(sql: str) -> str: """Remove comments from SQL script.""" # NOTE Does not strip multi-line comments. lines = map(str.strip, sql.split("\n")) return "\n".join(line for line in lines if not line.startswith("--"))
def preprocessing_tolist(preprocess): """ Transform preprocess into a list, if preprocess contains a dict, transform the dict into a list of dict. Parameters ---------- preprocess : category_encoders, ColumnTransformer, list, dict, optional (default: None) The processing apply to the origin...
def solve_part1(puzzle_input): """Solve part 1 of today's puzzle. Find the two entries that sum to 2020; what do you get if you multiply them together? Parameters ---------- puzzle_input : str The puzzle input provided by the Advent of Code website. Returns ------- part1_a...
def _finditem(obj, key): """ Check if giben key exists in an object :param obj: dictionary/list :param key: key :return: value at the key position """ if key in obj: return obj[key] for k, v in obj.items(): if isinstance(v, dict): item = _finditem(v, key) ...
def sum_two_smallest_numbers(numbers): """The function that calculates the sum of lowest numbers.""" order = sorted(numbers, key=int) return order[0] + order[1]
def check_subtraction_file_type(file_name: str) -> str: """ Get the subtraction file type based on the extension of given `file_name` :param file_name: subtraction file name :return: file type """ if file_name.endswith(".fa.gz"): return "fasta" else: return "bowtie2"
def get_unallocated_seats(plan): """ Return a collection of unallocated seats :param plan: The seating plan for which to return the seats :return: A list of unallocated seat numbers """ return [ seat_number for row in plan.keys() if row.isnumeric() for seat_number in pla...
def isnan(x): """Is x 'not a number' or 'None'""" from numpy import isnan try: return isnan(float(x)) except: return True
def bit_not(n, bit_length): """ defines the logical not operation :param n: the number to which the not operation is applied :param bit_length: the length of the bit to apply the not operation :return: """ return (1 << bit_length) - 1 - n
def _cross_ratio(z1, z2, z3, z4): """Calculate cross ratio between four values on a line""" nom = (z3 - z1) * (z4 - z2) den = (z3 - z2) * (z4 - z1) return nom / den
def block_to_smiles(block): """ Convert the formula of a block to a SMILES string """ if block == 'CH2': return 'C' elif block == 'NH': return 'N' elif block == 'O': return 'O' elif block == 'C6H4': return 'C1=CC=CC=C1' elif block == 'C4H2S': return 'C1=CS...
def redshift_to_frequency(z): """ Input : redshift Output : frequency in MHz """ nu = 1420/(1+z) return nu
def get_IO(IOfile): """ Given an IO specification for a network, Q, return a list of the input and output events. format is like ... [chanName]: I: [inputs] O: [outputs] """ events = set() chan = None lineType = lambda x: 2 if "O:" in x else 1 if "I:" in x else 0 try: with open(...
def check_profile_naming_to_id(profile_naming_to_id): """ :param profile_naming_to_id: :return: """ key_list = list(profile_naming_to_id.keys()) if type(key_list[0]) == str: return profile_naming_to_id elif type(key_list[0]) == int: return_dict = {} for i in profile_...
def nlbs(t9): """Finds the library number tuples in a tape9 dictionary. Parameters ---------- t9 : dict TAPE9 dictionary. Returns ------- decay_nlb : 3-tuple Tuple of decay library numbers. xsfpy_nlb : 3-tuple Tuple of cross section & fission product library num...
def _strip_shape(name: str) -> str: """Strip the dimension name.""" if name[0] == "/": return name[1:] return name
def get_object_row_ids(object_metadata_records, id_field_key): """ Return a dict where each key is an object's ID and each value is the corresponding row ID of that object in the admin metadata table. We need row ID so that we can populate the connection field between field metadata records and thei...
def forgiving_join(seperator, iterator): """ A join function that is more forgiving about the type of objects the iterator returns. """ return seperator.join(str(it) for it in iterator)
def status_map(state): """Return a numeric value in place of the string value for state""" if state == 'green': retval = 0 elif state == 'yellow': retval = 1 elif state == 'red': retval = 2 else: retval = 3 # fail return retval
def any_of(*args): """Return regex that matches any of the input regex patterns. The returned value is equivalent to writing:: r'(<arg1>|<arg2>|...)' """ return "({})".format("|".join(args))
def _getcontextrange(context, config): """Return the range of the input context, including the file path. Return format: [filepath, line_start, line_end] """ file_i = context['_range']['begin']['file'] filepath = config['_files'][file_i] line_start = context['_range']['begin']['line'][0...
def ToUnixLineEnding(s): """Changes all Windows/Mac line endings in s to UNIX line endings.""" return s.replace('\r\n', '\n').replace('\r', '\n')
def tic_tac_toe(board): """Lazy function to check if 3 in a row is obtained""" if (board[0][0] == board[1][0]) and (board[0][0] == board[2][0]) or \ (board[0][1] == board[1][1]) and (board[0][1] == board[2][1]) or \ (board[0][2] == board[1][2]) and (board[0][2] == board[2][2]) or \ ...
def is_another_day(time_web: str, time_mobile: str) -> bool: """checks if days are different""" if time_web is None: return True if time_web < time_mobile: time_web, time_mobile = time_mobile, time_web year1 = time_web[0:4] year2 = time_mobile[0:4] if year1 != year2: retu...
def merge(*args): """Implements the 'merge' operator for merging lists.""" ret = [] for arg in args: if isinstance(arg, list) or isinstance(arg, tuple): ret += list(arg) else: ret.append(arg) return ret
def unemployment_rate(earning, earning_new, unemployment): """ Args: earning: how much money the player earned last round earning_new: how much money the player earned this round unemployment: unemployment rate of the player had last round Returns: unemplo...
def get_bbox_and_label(results, model_labels, image_width, image_height): """Draws the bounding box and label for each object in the results.""" bboxes = [] labels = [] scores = [] for obj in results: # Convert the bounding box figures from relative coordinates # to absolute coordin...
def arguments_to_args_renames(arguments): """ The doc-opt parsed arguments include the - and -- and certain names are different. In order to have an apples-to-apples comparison with the new argparse approach, we must rename some of the keys. """ args = {} for k, v in arguments.items(): ...
def to_comma(string): """Replaces all the points in a string with commas. Args: string (str): String to change points for commas Returns: str: String with commas """ # Replace the points with strings in string try: string = string.replace(".", ",") except: ...
def last_line_var(varname, code): """ Finds the last line in the code where a variable was assigned. """ code = code.split("\n") ret = 0 for idx, line in enumerate(code, 1): if "=" in line and varname in line.split("=")[0]: ret = idx return ret
def mac_str(n): """ Converts MAC address integer to the hexadecimal string representation, separated by ':'. """ hexstr = "%012x" % n return ':'.join([hexstr[i:i+2] for i in range(0, len(hexstr), 2)])
def sqrt_int(n): """ Calculate the integer square root of n, defined as the largest integer r such that r*r <= n Borrowed from: https://gist.github.com/hampus/d2a2d27f37415d37f7de Parameters ---------- n: int The integer to calculate the square root from Returns ------- out...
def generate_hosts_inventory(json_inventory): """Build a dictionary of hosts and associated groups from a Ansible JSON inventory file as keys. Args: json_inventory (dict): A dictionary object representing a Ansible JSON inventory file. Returns: dict(list(str)): A dictionary of hosts with e...
def generate_new_row(forecast_date, target, target_end_date, location, type, quantile, value): """ Return a new row to be added to the pandas dataframe. """ new_row = {} new_row["forecast_date"] = forecast_date new_row["target"] = target new_row["target_end_date"] = targ...
def color_switch(color): """ Rgb color switch for bounding box color, in case debugging is enabled. Keyword arguments: color -- color, in string format Return variables: integer, integer, integer (int, int, int; DEFAULT 0,0,0) """ if color == "white": return 255, 255, 255 e...
def it(style, text): """ colored text in terminal """ emphasis = { "red": 91, "green": 92, "yellow": 93, "blue": 94, "purple": 95, "cyan": 96, } return ("\033[%sm" % emphasis[style]) + str(text) + "\033[0m"
def spin(programs, steps): """Spin programs from the end to the front.""" return programs[-int(steps):] + programs[:-int(steps)]
def restart_function(func): """ :param func: a function that returns None if it needs to be rerun :return: the value returned by func """ while True: returned_value = func() if returned_value == None: continue else: break return returned_value
def xgcd(a, b): """Calculates the extended greatest common divisor for two numbers (extended Euclidean algorithm). Parameters ---------- a : int First number. b : int Second number. Returns ------- int: The extended greatest common divisor for the two given numb...
def set_default(obj): """ change sets to lists for json """ if isinstance(obj, set): return list(obj)
def find_opt(state, pair, data): """ return the best action available from the state """ lookup = "" for i in range(len(state)): lookup += str(state[i]) if i < len(state)-1: lookup += "," if lookup not in data[pair]: return "s" moves = data[pair][lookup] ...
def generate_file_name(runtime): """ Every runtime has -specific file that is expected by google cloud functions """ runtimes = { 'python37': 'main.py', 'nodejs8': 'index.js', 'nodejs10': 'index.js', 'go111': 'function.go' } return runtimes.get(runtime)
def unground(arg): """ Doc String """ if isinstance(arg, tuple): return tuple(unground(e) for e in arg) elif isinstance(arg, str): return arg.replace('QM', '?') else: return arg
def fibo(n): """Compute the (n+1)th Fibonacci's number""" a, b = 1, 1 i = 0 while i<n: a, b = b, a+b i += 1 return a
def generate_accessories(accessories, is_male): """ Generates a sentence based on the accessories defined by the attributes """ sentence = "He" if is_male else "She" sentence += " is wearing" def necktie_and_hat(attribute): """ Returns a grammatically correct sentence based on ...
def default(input_str, name): """ Return default if no input_str, otherwise stripped input_str. """ if not input_str: return name return input_str.strip()