content
stringlengths
42
6.51k
def human2bytes(string, binary=True): """Converts a string such as '3.072GiB' to 3298534883 bytes. If "binary" is set to True (default due to Microsoft), it will use powers of 1024, otherwise powers of 1000 (decimal). Returns 0 on failure. """ try: string = string.lower() if 'kib' in...
def numeric_type(param): """ Checks parameter type True for float; int or null data; false otherwise :param param: input param to check """ if ((type(param) == float or type(param) == int or param == None)): return True return False
def parsePyMus(text): """Read data from a PyMus string.""" textlines = text.split("\n") name = textlines[0].replace("NAME=","").replace("\n","") beatlength = int(textlines[1].replace("BEATLENGTH=","").replace("\n","")) lines = [] readlines = textlines[2:] for i in range(0, len(readlines)): ...
def expand_onPremisesExtensionAttributes(entry): """ entry - a dictionary that must have the "onPremisesExtensionAttributes" key defined This transformer takes a dictionary, and returns the same dictionary, but with the "onPremisesExtensionAttributes" value expanded into it's own key: value pair. T...
def base_prob(phred_score): """ Returns the probabilty that a base is incorrect, given its Phred score. """ prob = 10.0**(-float(phred_score)/10) return prob
def _positive(i): """ Ensures that a number is bound to >= 0 """ if i < 0: return 0 else: return i
def Choose(index, *args): """Choose from a list of options If the index is out of range then we return None. The list is indexed from 1. """ if index <= 0: return None try: return args[index-1] except IndexError: return None
def _get_and_clean_attribute(attribute): """Get and clean attribute.""" try: # The attribute can be in a text file with open(attribute, 'r') as fid: attribute = fid.read() except (FileNotFoundError, TypeError): pass try: # Or as a string attribute = at...
def _is_indirect(member, doc): """ Given string repr of doc and member checks if the member contains indirect documentation """ d = member in doc e = 'indirect doctest' in doc if not d and not e: return True else: return False
def has_og_property(meta_tag, properties): """ Checks if the given meta tag has an attribute property equals to og:something, something being in properties. Returns: None if the given tag "is" not og:something. something otherwise. """ try: if not meta_tag["property"].startswith(...
def masked_outer(row, col, x, y): """Compute `(x @ y.T)[row, col]`.""" return x[row] * y[col]
def parse_seed(seeds): """ parse the seed provided by the user in arguments """ return seeds.strip().split("|")
def construct_filter_url(zipcode, page_num=1): """ Return a landing url that filters by zipcode. page_num is used to determine the page of the search results. Redfin search results are up to 18 pages long. In the current version, the filter is set to 'sold-3yr' and could be expanded to include 'sol...
def _pop_multiple(d, default, *args): """ A helper function for dealing with the way that matplotlib annoyingly allows multiple keyword arguments. For example, ``edgecolor`` and ``ec`` are generally equivalent but no exception is thrown if they are both used. *Note: This function does throw a :...
def same_list(list1, list2): """Returns a boolean indicating whether the items in list1 are the same items present in list2 (ignoring order).""" return (len(list1) == len(list2) and all( [item in list2 for item in list1] + [item in list1 for item in list2]))
def replace_repetitive_column_names(column_name, buildings): """ Returns column_name _unless_ it's one of a few special cases (building names, PIPE names, NODE names, srf names) :param str column_name: the name of the column :return: column_name or similar (for repetitive column names) """ if co...
def read_file(filename): """ Read file into a list of strings, uncluding direct reading of ".gz" files Different operations required for gzip files in Python 3 because they are read as binary (rather than text) files """ import gzip #If the first file is a gzipped file, open it via the gzip module if(filena...
def group_by(key_func, iterable): """Group all the item of the iterable depending on their key """ result = {} for item in iterable: key = key_func(item) if key not in result: result[key] = [] result[key] += [item] return result
def generate_new_uri(params): """ Generate new magnet uri from params dictionary :param params: list of trackers :return: a string in URI / Magnet format """ uri = 'magnet:?' uri = uri + 'xt=' + params['xt'] + '&' for tr in params['tr']: uri = uri + 'tr=' + tr + '&' return ur...
def hargreaves(tmin, tmax, tmean, et_rad): """ Estimate reference evapotranspiration over grass (ETo) using the Hargreaves equation. Generally, when solar radiation data, relative humidity data and/or wind speed data are missing, it is better to estimate them using the functions available in th...
def forestvar(z_in): """ Return intrinsic variance of LyaF variance for weighting. This estimate is roughly from McDonald et al 2006 Parameters ---------- z_in : float or ndarray Returns ------- fvar : float or ndarray Variance """ fvar = 0.065 * ((1.+z_in)/(1.+2.25))**3...
def _romberg_diff(b, c, k): """ Compute the differences for the Romberg quadrature corrections. See Forman Acton's "Real Computing Made Real," p 143. """ tmp = 4.0 ** k return (tmp * c - b) / (tmp - 1.0)
def get_export_options(defaults=None): """code export related options """ if defaults is None: defaults = {} options = { # ID of the model to generate a local model '--model': { 'action': 'store', 'dest': 'model', 'default': defaults.get('mo...
def euclid(a, b): """ Applies the Euclidean algorithm to find gcd(a, b) PARAMS: a (int) b (int) RETURNS: int: The greatest common demoninator """ if a < b: a, b = b, a if a % b == 0: return b q = a % b return euclid(b, q)
def get_sigcon_junc_relation(sig_con_tab, sig_group_conn_d, junc_tab): """ allocates the VISSIM signalcontrollers to SUMO junctions """ sigCon_junc_d = {} for sig_con in sig_con_tab: conn_l = [] for sg in sig_con["_sgs"]: if sg["_sg"] in sig_group_conn_d: ...
def remove_query_field(input_query, target_field): """Remove the target query field from the search query""" # split the query split_query = input_query.split(',') # allocate memory for the result output_query = [] # for all the parts for parts in split_query: # split in field and qu...
def smooth(x, y): """ Smooth a curve """ xs = x[:] ys = y[:] d = 0 for i in range(0, len(ys)): num = min(len(ys), i+d+1) - max(0, i-d) total = sum(ys[max(0, i-d):min(len(ys), i+d+1)]) ys[i] = total/float(num) return xs, ys
def translate_pattern(pattern): """Translate a string pattern to a list pattern. Parameters ---------- pattern : str Input pattern as a string. The ``raw_`` wrappers use these patterns. Returns ------- pattern_list Pattern translated to list, as used by the full fledged wra...
def isstr(obj): """Return whether an object is instance of `str`.""" return isinstance(obj, str)
def deep_merge(dict1, dict2): """overrides entries in dict1 with entries in dict2 recursively""" if isinstance(dict1, dict) and isinstance(dict2, dict): tmp = {} for key in dict1: if key not in dict2: tmp[key] = dict1[key] else: tmp[key] = ...
def sum_and_count(x, y): """A function used for calculating the mean of a list from a reduce. >>> from operator import truediv >>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9] >>> truediv(*reduce(sum_and_count, l)) == 20.11111111111111 True >>> truediv(*fpartial(sum_and_count)(l)) == 20.11111111111111...
def _compareName(resp, respName, compareName): """ Search a list of objects (services, policies, priortities, etc.) and return the id for the search name :param resp: :param respName: :param compareName: :return: id found or None """ for item in resp[respName]: if item['name'].lo...
def _handle_response(output, errors): """ Prints response received from Zanata client """ if not errors and '\n' in output: for response in output.split('\n'): print(response) return True else: print(errors.strip()) return False
def last_but_one_word(string): """Function to get the last but one word of a sentence in lower case""" try: return (string.rsplit(None, 2)[-2]).lower() except: return None
def to_binary(string: str) -> str: """ Convert String to numerical binary numbers returns numerical binary string :param string: String to convert Example: >>> to_binary("test") >>> "1110100 1100101 1110011 1110100" """ bin_conv = [] for c in string: ascii_val = ...
def rect(t): """Defines a rect function.""" return abs(t) < 0.5 * 1.0
def format_for_output(metric_dict): """ Coverts a dictionary into a list of strings of key,value pairs for output logging # Parameters matric_dict: `Dict[str, Dict[str, str or float]] # Returns `List[str]` """ return ["{}: {}\n".format(k, v) for k, v in metric_dict.items()] + [...
def remove_punctuation(argument_text: str) -> str: """ Remove multiple punctuations at the end of a line. :param argument_text: :return: """ offset = len('</' + 'span' + '>') if argument_text.endswith('</' + 'span' + '>') else 1 while argument_text[:-offset].endswith(('.', '?', '!')): ...
def every(predicate, iterable): """Determines whether the predicate is true for all elements in the iterable. :param predicate: Predicate function of the form:: f(x) -> bool :param iterable: Iterable sequence. :returns: ``True`` if the predicate is true for all elements in the iter...
def norm(str): """Normalize string for checking""" return ' '.join(str.strip().split()).lower()
def isprop(object_): """ Return true if the object is a property of the class. Used to extent inspect built-in Python module. References: - https://docs.python.org/3/library/inspect.html. """ return isinstance(object_, property)
def compose_triple(triple_names, triple_values): """Creates a triple given the object (of/os) and properties names (pf/ps) and their corresponding value. e.g. ('of1', 'pf2', 'of2') becomes: ('Immanuel_Kant', 'influencedBy', 'Georg_Wilhelm_Friedrich_Hegel') Parameters ----------...
def vecvecmul(vec1, vec2): """Elementwise multiplication res[i] = vec1[i] * vec2[i]""" return [v1 * v2 for v1, v2 in zip(vec1, vec2)]
def remainder(num1, num2): """ REMAINDER num1 num2 outputs the remainder on dividing ``num1`` by ``num2``; both must be integers and the result is an integer with the same sign as num1. """ v = num1 % num2 if v < 0 and num1 > 0 or v > 0 and num1 < 0: v = v + num1 return v
def device_driver(model): """ Returns the information needed to parse switch CLI output model: The model name string returns: Dictionary with the CLI command the units and output format """ return{ 'ubiquiti_edgeswitch' : ['ubiquiti_edgeswitch','show fiber-ports optics all','dBm',4...
def date_to_days(date_str: str) -> int: """Converts a date given in-game ("2200.03.01") to an integer counting the days passed since 2200.01.01. :param date_str: Date in YYYY.MM.DD format :return: Days passed since 2200.01.01 """ y, m, d = map(int, date_str.split(".")) return (y - 2200) * 3...
def appnetconf(appnet, appname): """ Return domain specific application configuration """ conf = appnet['applications'] for sub in appname.split('.'): conf = conf[sub] return conf
def recip(startA, endA, startB, endB, frac): """ Test if two intervals share a specified reciprocal overlap. """ if frac == 0: return True start = max(startA, startB) end = min(endA, endB) olen = end - start lenA = endA - startA lenB = endB - startB try: lapA =...
def find_category_name(booleans): """ Find the category name for the list of booleans. """ vals = list(map(lambda val: val == 'True', booleans.split(','))) if all(vals): return 'DBE, MBE, and WBE' elif vals[0] and vals[1]: return 'DBE and MBE' elif vals[1] and vals[2]: ...
def f_3(beta, x): """ implicit definition of the circle """ return (x[0]-beta[0])**2 + (x[1]-beta[1])**2 -beta[2]**2
def delete_keys_from_dict(dict_del): """ Remove unncessary keys from resource definition """ lst_keys = [ 'key', 'version', 'rpc', 'search', 'definitions' ] for k in lst_keys: if k in dict_del: del dict_del[k] for val in list(dict_del.values()): ...
def get_connections(network, user): """Get a user's friends. Keyword arguments: network -- a dictionary containing users' connections and games user -- the name of a person in the network """ try: return network[user]['friends'] except KeyError: return None
def line_to_int_list(line): """ Args: line: A string of integers. Ex: '1 3 5\n' Returns: A list of integers. Ex: [1, 3, 5] """ data = line.split(' ') data = filter(None, data) data = [int(x.strip('\n')) for x in data] return data
def average(channel_sample): """ Get the valid unvisited neighbours for a given point. Arguments: channel_sample {array} -- List of intensity samples of a single image channel. Returns: Int - Rounded average of all intensities. """ return int(round(sum(channel_sample) / len(cha...
def validate_input(start, end): """Convert start and end strings to ints. Args: start: starting value end: ending value Returns: start, end as ints """ try: start = int(start) except ValueError: start = 0 try: end = int(end) except Value...
def sort_colors(array): """ O(n) time O(n) space """ red = [] white = [] blue = [] for elem in array: if elem == 0: red.append(red) if elem == 1: white.append(elem) if elem == 2: blue.append(elem) return red+white+blue
def dt_calc(etime): """Returns an interval of time that increased as the ellapsed time etime increases""" if etime <= 10: return 0.25 elif etime <= 60: return 0.5 elif etime <= 120: return 1.0 elif etime <= 300: return 5.0 elif etime <= 3600: return 10.0 ...
def query(request): """Fixture that return the query for the request.""" return request.param if hasattr(request, 'param') else {}
def _GetListOfNearbyBuildNumbers(preferred_run_build_number, maximum_threshold): """Gets a list of numbers within range near preferred_run_build_number. Args: preferred_run_build_number (int): Assumed to be a positive number. maximum_threshold (int): A non-negative number for how far in either directio...
def indent(spaces, multilinestring): """ Indents a given multilinestring by a given number of spaces. This is used to produce properly formatted LaTeX documents. """ indentation = ' ' * spaces return '\n{}'.format(indentation).join(multilinestring.split('\n'))
def line_points(y1, y2, line): """ Given the slop and intercept of a line returns the points of the line. """ if line is not None: slope, intercept = line if slope > 0 or slope < 0: x1 = int((y1 - intercept) / slope) x2 = int((y2 - intercept) / slope) ...
def scale_temp(value, reverse=False, pcb_version=0): """ Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw value to deg C (if reverse=False), or convert a value in deg C to raw (if reverse=True). For now, raw values are hundredths of a deg...
def build_voice_flags(states): """Returns flags that be used as arguments of voice control commands. The structure of <states> is: {'voice': <state>} <state> is stop, or {'number': <number>, 'repeat': <repeat>}. <number> is voice number to play, 1 - 20. <repeat> is total number of plays. ...
def _get_processing_params(upsampling, downsampling): """ Builds a dictionary of processing parameters for Process API """ processing_params = {} if upsampling: processing_params['upsampling'] = upsampling if downsampling: processing_params['downsampling'] = downsampling retur...
def right_child(n: int) -> int: """Return the right child of a node with non-negative index n.""" return 2 * n + 2
def has_snapshot_with_attributes(snapshots, attrs): """ Test if a snapshot with the given subset of attributes exists """ def dict_contains(a, b): for k in b.keys(): if (a.get(k) != b.get(k)): return False return True for s in snapshots: if (dict_contain...
def enter_is_terminate(x): """This thing makes enter terminate the input.""" if x == 10: return 7 else: return x
def largest_and_smallest(num1, num2, num3): """Return the highest and smallest number between 3 numbers""" if num1 > num2: max_number = num1 min_number = num2 else: max_number = num2 min_number = num1 if num3 > max_number: return num3, min_number elif num3 < m...
def validateClips(cmodel, layers, gmused): """ Ensures coefficients provided in model description are valid and outputs a dictionary of the coefficients. Args: cmodel (dict): Sub-dictionary from config for specific model, for example: .. code-block:: python ...
def unless(predicate, function, value): """Tests the final argument by passing it to the given predicate function. If the predicate is not satisfied, the function will return the result of calling the whenFalseFn function with the same argument. If the predicate is satisfied, the argument is returned as...
def any_list_item(a, b): """Determine whether any item in ``a`` also exists in ``b``. :param a: The first list to be compared. :type a: list :param b: The second list to be compared. :type b: list :rtype: bool """ for i in a: for j in b: if i == j: ...
def cipher(text, shift, encrypt=True): """ Encrypt the text using shift coding. Args: text (str): represent the source text shift (int): the shift size encrypt (bool): True for encrypt and False for decrypt Returns: str: represent the cipher Examples: ...
def order_of_magnitude(x): """Returns the nearest power of 10 less than x x = 0.00345, returns -3, x = 4320.0 returns 3. x = 5.42e+25, returns 25 """ stringx = str(float(x)) # if x is in e form, just return the e multiplier eindex = stringx.find('e') if not eindex == -1: ...
def uncenter_image(img): """ normalize image input """ return ((img + 1.) / 2.) * 255.
def checkDone( visdict, dayspan=0.5 ): """Check for any visits that have been archived/executed/scheduled in the last <dayspan> days, and return a string reporting them to the user. If nothing has been done lately, returns 0. """ daynames = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] archivedTh...
def get_indent(text): """Get text indentation. Args: text: Text to analyze. Returns: Number of leftmost spaces. Notes: Input text must be tab expanded, otherwise indent will be incorrect. """ return len(text) - len(text.lstrip())
def int_to_bytes(data): """ Convert passed data (int) to bytes Return: list of bytes """ # Check if the passed data are 0x0, if yes, return the array with byte representation if(data == 0x0): return [b'\x00'] # Byte coversion is done via the cycle, where the process # is repeat...
def calc_auc(raw_arr): """Summary Args: raw_arr (TYPE): Description Returns: TYPE: Description """ # sort by pred value, from small to big arr = sorted(raw_arr, key=lambda d:d[2]) auc = 0.0 fp1, tp1, fp2, tp2 = 0.0, 0.0, 0.0, 0.0 for record in arr: ...
def FV(PV,i,n,m=1): """ present value interest years optional payments per year """ FV = PV * ((1 + i/m)**(m*n)) return FV
def RGB_to_hex(RGB): """ [255,255,255] -> "#FFFFFF" """ # Components need to be integers for hex to make sense RGB = [int(x) for x in RGB] return "#"+"".join(["0{0:x}".format(v) if v < 16 else "{0:x}".format(v) for v in RGB])
def is_subspan(x, y): """ Return True if x is a subspan of y. """ return y[0]<=x[0] and x[1]<=y[1]
def _var(x, ddof=0): """ Calculate variance for an array Uses Welford's algorithm[1] for online variance calculation. Parameters ---------- x : array-like The data ddof : int Degrees of freedom References ---------- .. [1] https://en.wikipedia.org/wiki/Algorithms_f...
def parse_request(request, listOfSelectedParameter): """ -> Parse result of a request and return only the paramaters present in listOfSelectedParameter. -> Request is a dict generated by a search() operation from the tinyDB package -> listOfSelectedParameter is a list of selected parameters -> return a lis...
def remove_values(the_list, val): """ Remove all items with value `val` from `the_list` """ return [value for value in the_list if value != val]
def _get_normal_name(orig_enc: str) -> str: """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace('_', '-') if enc == 'utf-8' or enc.startswith('utf-8-'): return 'utf-8' if enc in ('latin-1', 'iso-8859-1', 'iso-latin-1')...
def is_point(item): """ Determine if the given list has the structure of a point. This is: it is a list or tuple with two int or float items """ if isinstance(item, list) or isinstance(item, tuple): if len(item) == 2: lon = item[0] if isinstance(lon, int) or isinstance(lon, f...
def set_config_filename(filename): """ Change the "default" filename for the config file from the current value of CONFIG_FILE_NAME to the given filename string. The filename is assumed to be a simple filename (no directory components). Partial directory paths might work, or might not. No sani...
def _parse_port_string_to_rule(port, protocol, fw_partial_uri, is_allow_rule): """ Takes a string argument representing a GCP firewall rule port or port range and returns a dict that is easier to load into Neo4j. Example 1 - single port range: Input: `'0-65535', 'tcp', fw_id, is_allow_rule=True` ...
def count_generator(generator, memory_efficient=True): """Count number of item in generator. memory_efficient=True, 3 times slower, but memory_efficient. memory_efficient=False, faster, but cost more memory. """ if memory_efficient: counter = 0 for _ in generator: counte...
def broize_syllable(p, i): """Given a syllable and its index in an word, return a bro version or None.""" # Try a bunch of heuristics to turn the word into something coherent after # we've crammed a bro in there if p == 'bro' or len(p) < 2: return None if i == 0: if p[1] == 'o' and p...
def get_user_info(auth_version, auth_url, access_key, user_domain_name, secret_key, tenant_name, project_domain_name): """Returns an Swift User with .display_name and .id, or None """ if not (auth_version and auth_url and access_key and secret_key and tenant_name): return None ...
def build_conf_dict(name, bid, qualnames, message, level='MEDIUM'): """Build and return a blacklist configuration dict.""" return {'name': name, 'id': bid, 'message': message, 'qualnames': qualnames, 'level': level}
def make_list_template(elements, cover_data=None, actions=None): """ create carousel list template. reference - `Common Message Property <https://developers.worksmobile.com/jp/document/100500805?lang=en>`_ """ content = {"type": "list_template", "elements": elements} if cover_data ...
def forwards(page_or_revision, data): """Map from boolean and_filtering to three-option tag_filtering. If and_filtering was True (include pages that match all topics tags), set tag_filtering to "all". Otherwise, set it to the default, "any". """ data["tag_filtering"] = ["any", "all"][data.pop("and_...
def variation_string_to_dict(variation_string): """Helper function to convert a list of "="-separated strings into a dictionary Returns ------- dict """ var_data = variation_string.split() variation_dict = {} for var in var_data: pos_eq = var.find("=") var_name = var[0:p...
def simple_merge_handler(previous_props, next_props): """Merge properties if the keys on old and new are disjoint. Return a mapping containing the values from both old and new properties, but only if there is no key that exists in both. """ for name, value in previous_props.items(): if name...
def contig_stats_genome(contigs): """Compute contig statistics within each genome.""" contigs_count_genome = [] contigs_nt_genome = [] contigs_genome_found = True gi = 0 while contigs_genome_found: contigs_genome = [ctg for ctg in contigs if ctg.genome == gi] if len(contigs_genome) == 0: con...
def generate_all_circles(length, circles=[""]): """Recursively generate a set of all circles with given length.""" assert length < 11, "The lengths is too big!" if len(circles[0]) == length: return circles else: new_circles = [] for circle in circles: digits = set("01...
def matrixGrep(matrix, locs, size, uniq=0): """Greps the matrix to get filenames at the given locations""" def getFname(mx, my): """Returns the filename at the given matrix location""" try: return matrix[my][mx] except IndexError: return None mlocs = [(x//size[0], y//size...
def hasException (code): """Prueft ob bei uebergebenen Code eine Exception auftritt""" retval = False try: eval(code) except: return True return False