content
stringlengths
42
6.51k
def roundToNearest(value, roundValue=1000): """ Return the value, rounded to nearest roundValue (defaults to 1000). Args: value (float): Value to be rounded. roundValue (float): Number to which the value should be rounded. Returns: float: Rounded value. """ if roundValu...
def format_network_speed(raw_bps=0): """ Formats a network speed test to human readable format """ fmt = ['b/s', 'Kb/s', 'Mb/s', 'Gb/s'] index = 0 speed = raw_bps while speed > 1024: index += 1 speed /= 1024 return "%0.2f %s" % (speed, fmt[index])
def dict_adapter(values, names): """Adapter returns name-values dict instead of pure tuple from iteration scheme. """ return dict(zip(names, values))
def get_unique_item(lst): """ For a list, return a set of the unique items in the list. """ return list(set(lst))
def string_to_list(s: str) -> list: """ :param str s: A serialized list. :return list: The actual list. """ return s.split(', ')
def no_similar_images(similar_image): """return bool""" return similar_image["target path"] == ""
def pluralize_pl(value, arg=u's'): """ pluralize_pl is fully compatible with Django's "pluralize" filter. Works exactly the same as long as you are giving it up to 2 comma-separated arguments. The difference is you can provide it with a third argument, which will be used as a second plural form and ...
def find_scan_node(scan_node): """ utility function to find the parent node of "scan" type, meaning some of its children (DAQ_scan case) or co-nodes (daq_logger case) are navigation axes Parameters ---------- scan_node: (pytables node) data node from where this function look for its navi...
def _check_coordinate_precision(coord, precision): """Coordinate precision is <= specified number of digits""" if '.' not in coord: return True else: return len(coord.split('.')[-1]) <= precision
def calculate_velocity(mom1,mom2,mom3,dens): """Calculates the 3-vector velocity from 3-vector momentum density and scalar density.""" v1 = mom1/dens v2 = mom2/dens v3 = mom3/dens return v1,v2,v3
def make_field(name: str, value: str) -> str: """ Return an ADIF field/value, like "<adif_ver:5>value" """ return f"<{name}:{len(value)}>{value}"
def get_links_for_pages(link): """ retrieve pagnation link for the category """ # 5 pages for each category return [link + '?page=' + str(i) for i in range(1, 6)]
def daybounds( season ): """Input is a 3-character season, e.g. JAN, JJA, ANN. Output is bounds for that season in units of "days since 0". In most cases the bounds will be like [[lo,hi]]. But for DJF it will be like [[lo1,hi1],[lo2,hi2]]. The noleap (365 day) calendar is required.""" # This i...
def compare_dict(dict1, dict2): """Compare two dictionaries. This function checks that two objects that contain similar keys have the same value """ dict1_keys = set(dict1) dict2_keys = set(dict2) intersect = dict1_keys.intersection(dict2_keys) if not intersect: return False ...
def tokenize_char(sent): """ Return the character tokens of a sentence including punctuation. """ return list(sent.lower())
def filter_git_files(files): """Remove any git/datalad files from a list of files.""" return [f for f in files if not (f.startswith('.datalad/') or f == '.gitattributes')]
def approx2step(val, x0, dx): """Approximate value, val, to closest increment/step, dx, starting from x0.""" while True: if x0 > val: break x0 += dx return x0
def formalize_table_neural_experiments(name, d): """ Takes the data from find_best_f1 and parses it, and returns an array with name + performance. """ if (d is None): return [name, 0, 0, 0, 0] best_f1, best_acc, best_prc, best_rc = d["f1"], d["acc"], d["precision"], d['recall'] best_f1, bes...
def compress_dna(text: str) -> int: """Compress a DNA string into a bit string Arguments: text {str} -- DNA string to compress Returns: int -- integer bit-string representing DNA Example: >>> compress_dna("ACGT") 283 """ bit_string = 1 for nt in text...
def union(interval1, interval2): """ Given [0, 4] and [1, 10] returns [0, 10] Given [0, 4] and [8, 10] returns False """ if interval1[0] <= interval2[0] <= interval1[1]: start = interval1[0] end = interval1[1] if interval2[1] <= interval1[1] else interval2[1] elif interval1[0] <=...
def find_even_index(arr): """Return the index where sum of both sides are equal.""" if len(arr) == 0: return 0 for i in range(0, len(arr)): sum1 = 0 sum2 = 0 for j in range(0, i): sum1 += arr[j] for k in range(i + 1, len(arr)): sum2 += arr[k]...
def map_wrapper(x): """For multi-threading""" return x[0](*(x[1:]))
def sum_attributes(triplet): """ return the sum of the attributes of a triplet ie: triplet = (((2, 2, 2, 2), (3, 3, 3, 3), (1, 2, 3, 1))) returns [6, 7, 8, 6] <- [2+3+1, 2+3+2, 2+3+3, 2+3+1] """ return [sum(a) for a in zip(*triplet)]
def genomic_del1_rel_37(genomic_del1_37_loc): """Create test fixture relative copy number variation""" return { "type": "RelativeCopyNumber", "_id": "ga4gh:VRC.2_BewkjhJtvj8J814SE0RVxp-OdYxJSo", "subject": genomic_del1_37_loc, "relative_copy_class": "copy neutral" }
def map(func, data, processes=4): """ This maps the data to func in parallel using multiple processes. This works fine in the IPython terminal, but not in IPython notebook. **Arguments**: *func*: Function to map the data with. *data*: Data sent to func....
def select_to_text_compact(caption, choices): """ A function to convert a select item to text in a compact format. Format is: [question] 1:[choice1], 2:[choice2]... """ return "%s %s." % (caption, ", ".join(["%s:%s" % (i+1, val) for i, val in \ ...
def kwargs_to_string(kwargs): """ Given a set of kwargs, turns them into a string which can then be passed to a command. :param kwargs: kwargs from a function call. :return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise. """ outstr = '' for ...
def strip(value): """ Strip all leading and trailing whitespaces. :param value: The value :type value: str :return: The value with all leading and trailing whitespaces removed :rtype: str """ return value.strip()
def get_stream_fps(streams): """ accepts a list of plex streams or a list of the plex api streams """ for stream in streams: # video stream_type = getattr(stream, "type", getattr(stream, "stream_type", None)) if stream_type == 1: return getattr(stream, "frameRate", ge...
def append_bias(vector): """ Takes a list of n entries and appends a 1 for the bias Args: vector - a list Returns: a list """ temp_vector = [x for x in vector] temp_vector.append(1) return temp_vector
def repeat_list_elements(a_list, rep): """ Creates a list where each element is repeated rep times. """ return [element for _ in range(rep) for element in a_list]
def calc_section_data(size, num_parts): """ Calculates info about each part of a file of given size separated into given number of parts. Returns a list of dicts having 3 pieces of information: - 'start' offset inclusive - 'end' offset inclusive - 'size' """ # Changing this vital f...
def getTimeZone(lat, lon): """Get timezone for a given lat/lon """ #Need to fix for Python 2.x and 3.X support import urllib.request, urllib.error, urllib.parse import xml.etree.ElementTree as ET #http://api.askgeo.com/v1/918/aa8292ec06199d1207ccc15be3180213c984832707f0cbf3d3859db279b4b324/query...
def _remove_pronominal(verb): """ Remove the pronominal prefix in a verb """ if verb.split()[0] == 'se': infinitive = verb.split()[1] elif verb.split("'")[0] == "s": infinitive = verb.split("'")[1] else: infinitive = verb return infinitive
def x_in_y(query, base): """Checks if query is a subsequence of base""" try: l = len(query) except TypeError: l = 1 query = type(base)((query,)) for i in range(len(base)): if base[i:i+l] == query: return True return False
def read_file_to_list(filename): """Returns a list of (stripped) lines for a given filename.""" with open(filename) as f: return [line.rstrip('\n') for line in f]
def _flatten_nested_keys(dictionary): """ Flatten the nested values of a dictionary into tuple keys E.g. {"a": {"b": [1], "c": [2]}} becomes {("a", "b"): [1], ("a", "c"): [2]} """ # Find the parameters that are nested dictionaries nested_keys = {k for k, v in dictionary.items() if type(v) is dic...
def indent(indent): """Indentation. @param indent Level of indentation. @return String. """ return " "*indent
def union(value: list, other: list) -> list: """Union of two lists. .. code-block:: yaml - vars: new_list: "{{ [2, 4, 6, 8, 12] | union([3, 6, 9, 12, 15]) }}" # -> [2, 3, 4, 6, 8, 9, 12, 15] .. versionadded:: 1.1 """ return list(set(value).union(other))
def SurrRateMult(t): """Surrender rate multiple (Default: 1)""" if t == 0: return 1 else: return SurrRateMult(t-1)
def trim_item(item): """Trims unnecessary fields in the track item""" track = item['track'] if 'album' in track: to_delete = ['album_type', 'available_markets', 'external_urls', 'href', 'images', 'uri'] for key in to_delete: try: del track['al...
def str2num(size, s): """Convert a string of decimal digits to an integer.""" i = 0 n = 0 while i < size: n = n | (ord(s[i]) << (i*8)) i = i + 1 return n
def generic_response(status_code, success, message, data=None): """ This function handles all the requests going through the backend :rtype: object """ response = { "success": success, "message": message, "data": data } return response, status_code
def inst_attributes(obj,of_class=None): """ Find all instance attributes of obj that are instances of of_class and return them as dictionary. """ d = {} if of_class: for k,v in obj.__dict__.items(): if isinstance(v,of_class): d[k] = v else: d.upd...
def cal_trans(ref, adj): """ calculate transfer function algorithm refering to wiki item: Histogram matching """ table = list(range(0, 256)) for i in list(range(1, 256)): for j in list(range(1, 256)): if ref[i] >= adj[j - 1] and ref[i] <= adj[j]: table...
def _pop(inlist): """ make a list of lists into a list """ if isinstance(inlist, (list, tuple)): return inlist[0] return inlist
def move_right_row(row, debug=True): """move single row to right.""" if debug: print(row) row_del_0 = [] for i in row: # copy non-zero blocks if i != 0: row_del_0.append(i) #print(row_del_0) row = row_del_0 i = 0 j = len(row_del_0) - 1 while i < j: # com...
def _instance_overrides_method(base, instance, method_name): """ Returns True if instance overrides a method (method_name) inherited from base. """ bound_method = getattr(instance.__class__, method_name) unbound_method = getattr(base, method_name) return unbound_method != bound_method
def linear_search(array, val): """Linear search.""" length = len(array) for i in range(length): if array[i] == val: return i return None
def resample_factor_str(sig_sample_rate_hz: float, wav_sample_rate_hz: float) -> str: """ Compute file string for oversample and downsample options :param sig_sample_rate_hz: input signal sample rate :param wav_sample_rate_hz: wav sample rate; supports permitted_wav_fs_values ...
def get_intermixed_trials(trials, n, n_user_suggestions): """Filters the exploration trials for intermixed ensemble search.""" return [ trial for trial in trials if trial.id % n != 0 or trial.id <= n_user_suggestions ]
def get_spacing_dimensions(widget_list): """ will be further developed """ space_dimensions = space_label = 0 for widg in widget_list: space_d = widg.get('dimensions', '') space_l = widg.get('label', '') if space_d: space_d_new = len(list(space_d)) if...
def parse_trans_table(trans_table): """returns a dict with the taxa names indexed by number""" result = {} for line in trans_table: line = line.strip() if line == ";": pass else: label, name = line.split(None, 1) # take comma out of name if it is t...
def removeall(item, seq): """Return a copy of seq (or string) with all occurences of item removed. >>> removeall(3, [1, 2, 3, 3, 2, 1, 3]) [1, 2, 2, 1] >>> removeall(4, [1, 2, 3]) [1, 2, 3] """ if isinstance(seq, str): return seq.replace(item, '') else: return [x for x in...
def product(l): """Get the product of the items in an iterable.""" t = 1 for i in l: t *= int(i) return t
def prime_test(i, j=2): """ Cases: Return False if i is not prime Return True if i is prime Caveat: cannot test 1. Caveat 2: Cannot test 2. It is fortuitous that these tests both return true. """ if j >= i: # i used greater than to cover 1 return True if i % j == 0: # th...
def camel_case_to_upper(name): """ :Examples: >>> camel_case_to_upper('squareRoot') 'SQUARE_ROOT' >>> camel_case_to_upper('SquareRoot') 'SQUARE_ROOT' >>> camel_case_to_upper('ComputeSQRT') 'COMPUTE_SQRT' >>> camel_case_to_upper('SQRTCompute') 'SQRT_COMPUTE' >>> camel_case_to_...
def solve(n, coins, k): """ Solution for count_change :param n: money :param coins: List of coins. :param k: coins[k] :return: Count of combinations. """ # print("n: %d, k: %d" % (n, k)) if k < 0 or n < 0: return 0 if n == 0: # Change for 0 is only empty one. ...
def threshold_predictions(predictions, thr=0.999): """This method will threshold predictions. :param thr: the threshold (if None, no threshold will be applied). :return: thresholded predictions """ if thr is None: return predictions[:] thresholded_preds = predictions[:]...
def is_uniform(x, epsilon=0.000000001): """Determine if the vector is uniform within epsilon tolerance. Useful to stop a simulation if the fitness landscape has become essentially uniform.""" x_0 = x[0] for i in range(1, len(x)): if abs(x[i] - x_0) > epsilon: return False return True
def float2int_ensure_precision(value, scale): """Cast a float to an int with the given scale but ensure the best precision.""" # Round it to make sure we have the utmost precision return int(round(value * pow(10.0, scale)))
def setup(): """Sets paths and initializes modules, to be able to run the tests.""" res = True # # Make available to configure.py the top level dir. # scarlett_os_dir = get_scarlett_os_dir() # sys.path.insert(0, scarlett_os_dir) # # NOTE: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # SUPER IMPORT...
def gnome_sort(a): """ Sorts the list 'a' using gnome sort >>> from pydsa import gnome_sort >>> a = [5, 6, 1, 9, 3] >>> gnome_sort(a) [1, 3, 5, 6, 9] """ i = 0 while i < len(a): if i != 0 and a[i] < a[i-1]: a[i], a[i-1] = a[i-1], a[i] i -= 1 el...
def full_name_with_qualname(klass: type) -> str: """Returns the klass module name + klass qualname.""" return f"{klass.__module__}.{klass.__qualname__}"
def remove_root(field): """Replace txt.""" return field.replace("/media", "media").replace("<p>","").replace("</p>","")
def is_empty(s): """Is this an empty value? None or whitespace only counts as empty; anything else doesn't. @param s: value to test @return: True if the value is empty """ return (s is None or s == '' or str(s).isspace())
def transform_shape(shape): """ Transforms a shape to resize an image after that. Shape size must be equal to 2 or 3, otherwise it raises a ValueError. Returns: A tuple of the same size. Raises: A ValueError if the shape size is not equal to 2 or 3. Example: >>> shape...
def jacobianDouble(Xp, Yp, Zp, A, P): """ Double a point in elliptic curves :param (Xp,Yp,Zp): Point you want to double :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :ret...
def get_customized_ini_name(env: str) -> str: """ get customized service config ini file name :return: """ return f'{env}.ini'
def split_long_lat(long_lat): """ Takes in a string that looks like "-02398470+09384779" in order to obtain the first value and the second value of the string. In this case, the longitude is -02398470 and the latitude is +09384779. This function is needed because the TIGER/Line files have the long...
def next_power_of_2(x): """ Returns the first power of two >= x, so f(2) = 2, f(127) = 128, f(65530) = 65536 :param x: :return: """ # NOTES for this black magic: # * .bit_length returns the number of bits necessary to represent self in binary # * x << y means 1 with the bits shifted to...
def notice(title, text, style="info"): """ A notice panel. :param title: Notice title :param text: Notice information :param style: Notice style (info, danger, success, default) """ return { "class": "notice", "title": title, "text": text, "style": style }
def sigref(nod1, nod2, tsys_nod2): """ Signal-Reference ('nod') calibration ; ((dcsig-dcref)/dcref) * dcref.tsys see GBTIDL's dosigref """ return (nod1-nod2)/nod2*tsys_nod2
def card(id, title, s): """Build a card by ID.""" return """<card id="%(id)s" title="%(title)s"><p>%(s)s</p></card>""" % \ {'id': id, 'title': title, 's': s}
def calc_nbar(n_0, n_curr): """ Calculate the n2o concentration average between the historical n2o and current n2o concentrations Parameters ---------- n_0 : float Historical n2o concentration, in ppm n_curr : float Current n2o concentration, in ppm Return ...
def remove_non_datastore_keys(form_data): """Remove keys not relevant to creating a datastore object.""" form_dict = {k: v[0] for k, v in form_data.items()} for key in ["csrfmiddlewaretoken", "name", "type", "owner"]: form_dict.pop(key, None) return form_dict
def series1_proc_func(indep_var, dep_var, xoffset): """Process data 1 series.""" return (indep_var * 1e-3) - xoffset, dep_var
def validate_placement(placement): """ Validate placement policy """ for item in placement: if item not in ['requirements', 'preferences']: return (False, 'invalid item "%s" in placement policy' % item) if 'requirements' in placement: for item in placement['requirements'...
def test_cab (archive, compression, cmd, verbosity, interactive): """Test a CAB archive.""" return [cmd, '-t', archive]
def try_convert_to_aggregation_function(token): """ This method tries to convert the given token to be an aggregation function name. Return None if failure. Args: token (str): the given token to be converted. Returns: Return the converted aggregation function name if the conversion...
def _is_sunder(name: str) -> bool: """Return True if a _sunder_ name, False otherwise.""" return name[0] == name[-1] == "_" and name[1:2] != "_" and name[-2:-1] != "_" and len(name) > 2
def find_role_from_parents(team_roles, team_parents, team_id): """Searches for the first parent with defined role >>> find_role_from_parents({42: 'member'}, {1: 2, 2: 42}, 1) 'member' """ if team_roles.get(team_id) is not None: return team_roles[team_id] current_team_id = team_id v...
def _parse_seq_body(line): """ Ex: {()YVPFARKYRPKFFREVIGQEAPVRILKALNcknpskgepcgereiDRGVFPDVRA-LKLLDQASVYGE()}* MENINNI{()----------FKLILVGDGKFFSSSGEIIFNIWDTKFGGLRDGYYRLTYKNEDDM()}* Or: {(HY)ELPWVEKYR... The sequence fragments in parentheses represent N- or C-terminal flanking regions...
def get_iterable(input_var): """ Returns an iterable, in case input_var is None it just returns an empty tuple :param input_var: can be a list, tuple or None :return: input_var or () if it is None """ if input_var is None: return () return input_var
def _create_primes(threshold): """ Generate prime values using sieve of Eratosthenes method. Parameters ---------- threshold : int The upper bound for the size of the prime values. Returns ------ List All primes from 2 and up to ``threshold``. """ if threshold =...
def getSizeTable(cursor, tableName): """ Get the size in MB of a table. (Includes the size of the table and the large objects (LOBs) contained in table.""" tableName = tableName.upper() try: if type(tableName) == str: tableName = [tableName, ] queryArgs = {}...
def parallel_variance(mean_a, count_a, var_a, mean_b, count_b, var_b): """Compute the variance based on stats from two partitions of the data. See "Parallel Algorithm" in https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance Args: mean_a: the mean of partition a count_a: th...
def _postprocess_feature(feature): """Make a feature compatible with graph tuples""" # always return an iterable if not hasattr(feature, "__len__"): feature = (feature,) # transparently convert bools etc. to float return [float(value) for value in feature]
def allPointsBetween_int(x1, y1, x2, y2, accuracy): """Does not use allPointsBetween() Requires extra parameter accuracy (1=default) Returns in integer.""" # slope = dy/dx (rise/run) dy = y2 - y1 dx = x2 - x1 currXadd = 0 # x2 # int currYadd = 0 # y2 # int pointGraphArr = [(x1, y...
def oauth_url(client_id, permissions=None, server=None, redirect_uri=None): """A helper function that returns the OAuth2 URL for inviting the bot into servers. Parameters ----------- client_id : str The client ID for your bot. permissions : :class:`Permissions` The permissions y...
def extract_state(x): """ Extracts state from location. """ split = x.split(', ') if len(split) != 2: return '' return split[1]
def calculate_octant(vector): """Calculates in which octant vector lies and returns the normalized vector for this octant. :param vector: given vector :type vector: array :rtype: normalized vector """ #Small offset between octants epsilon = 30 if epsilon > vector[0] and vector[0] > ...
def get_new_classes(update_records): """ """ relabeled_classes = [] for rec in update_records: relabeled_classes += [rec.relabeled_class] return set(relabeled_classes)
def norm(value): """ Convert to Unicode """ if hasattr(value,'items'): return dict([(norm(n),norm(v)) for n,v in list(value.items())]) try: return value.decode('utf-8') except: return value.decode('iso-8859-1')
def apply_transform(service, t, x): """Apply a transformation using `self` as object reference.""" if t is None: return x else: return t(service, x)
def is_retryable_error(error): """ Determines whether the given error is retryable or not. :param error: (:class:`~hazelcast.exception.HazelcastError`), the given error. :return: (bool), ``true`` if the given error is retryable, ``false`` otherwise. """ return hasattr(error, 'retryable')
def is_duplicate_policy(link_contents, domain, policy_dict): """ Since the crawler does its work automatically, it is not immune to gathering duplicate policies (sometimes from different initial sources). This function will compare the current policy with the previously verified policies to see if i...
def caesar_cipher_decode(n: int, text: str, p: str) -> str: """ Returns a string where the characters in text are shifted left n number of spaces. The characters in text are only decrypted if they exist in p. If they don't exist in p, they will remain unchanged. Ex. str = 'def45' n = 3 ...
def cell_associate(pathloss_matrix, users, basestations): """Associate a user with a basestation that provides the minimum pathloss. Args: pathloss_matrix: (list) of numpy arrays users: (obj) list of users! basestations: (obj) list of basestations! Ret...
def drop_none(arr): """ Drop none from the list :param arr: :return: """ return [x for x in arr if x is not None]