content
stringlengths
42
6.51k
def get_server_pull_config(config:dict): """ takes a config dictionary and returns the variables related to server deployment (pull from intersections). If there is any error in the configuration, returns a quadruple of -1 with a console output of the exception """ try: server = config["Data...
def convert_meV_to_GHz(w): """ Convert an energy from unit meV to unit GHz. Parameters ---------- w : float / array The energy in the old unit. Returns ------- w_new_unit : float / array The energy in the new unit. """ # 1 meV = 1.0/4.1357e-3 GHz w_GHz = w /...
def is_url(checkpoint): """Check whether the checkpoint is a url or not. """ is_url = ('https://storage.googleapis.com' in checkpoint) return is_url
def lol_tuples(head, ind, values, dummies): """List of list of tuple keys Parameters ---------- head : tuple The known tuple so far ind : Iterable An iterable of indices not yet covered values : dict Known values for non-dummy indices dummies : dict Ranges of...
def flux_mag_ratio(mag1: float, mag2: float) -> float: """Calculate the flux ratio between two magnitudes. Using the equation f1/f2 = 10**(-0.4 * (mag1 - mag2)). A common approximation is the equation f1/f2 approx 2.512**(m2 - m1), but is not here. Parameters ---------- mag1 float Magn...
def command(cmd, *parameters): """ Helper function. Prints the gprMax #<cmd>: <parameters>. None is ignored in the output. Args: cmd (str): the gprMax cmd string to be printed *parameters: one or more strings as arguments, any None values are ignored Returns: s ...
def parse_arg(x): """ Parse a string argument and attempt to turn numbers into actual number types. Parameters ---------- x : str A string arg. Returns ------- str, float, or int x type converted. """ if x.replace('.', '').isdigit(): if ...
def get_linknames(dic): """ Gets the names of links from links block so references can be made in properties list """ out = [] links = dic['links'] if links: for link in links: if type(link) == dict: try: out.append(link['name']) ...
def log_level_to_num (level): """converts a log level string to a number strings are used instead of numbers directly so it's easier to read and also easier to add more levels in between old ones Args: level (string): the level in string form Returns: level in number form """ i...
def print_aunit_human_alerts(console, alerts): """A helper method printing out alerts not linked to any test case and returning number of critical errors. """ errors = 0 for alert in alerts: console.printout(f'* [{alert.severity}] [{alert.kind}] - {alert.title}') errors = errors...
def get_first_non_none_parsed_value(parsed_values): """ Gets the first non-`None` parsed value. Parameters ---------- parsed_values : `None`, `list` of `Any` The parsed value. Returns ------- value : `None`, `Any` The parsed value if any. """ if (parsed_valu...
def get_question(resource_id): """Returns a question by id.""" return {"data": resource_id}
def _table_error(show, subcorpora, updating): """ Check for problems with table """ if updating: return "" errors = [] if not show: errors.append("No choice made for feature to use as columns.") # this is now allowed ... can probably remove this function if # we don't do ...
def parse_stage_name(stage): """ Determine the name of a stage. The stage may be provided already as a name, as a Stage object, or as a callable with __name__ (e.g., function). :param str | pypiper.Stage | function stage: Object representing a stage, from which to obtain name. :return ...
def S_gradient_filter(_data_list, _diff=0.1): """ Returns data samples where points with same gradient are discarded. """ g_data = [] ds = len(_data_list) pgrad = 0 for i in range(ds-1): grad = _data_list[i+1]-_data_list[i] d = abs(pgrad-grad) lv = abs(max(pgrad...
def filter_compatible_patch_sizes(perturb_patch_sizes: list, img_size: int) -> list: """Remove patch sizes that are not compatible with input size.""" return [i for i in perturb_patch_sizes if img_size % i == 0]
def get_coords(line): """Input: pdbline Output: [x,y,z] (list of floats)""" x_val = line[30:38] y_val = line[38:46] z_val = line[46:54] return [float(x_val), float(y_val), float(z_val)]
def top_k_frequent(words, k): """ Input: words -> List[str] k -> int Output: List[str] """ # Your code here new_map = {} # count = 0 for word in words: if word in new_map: new_map[word] += 1 else: new_map[word] = 1 print(new_map) ...
def final(i, p): """Return last integer greater or equal to initial index, i, such that condition, p, holds.""" return i - 1 if not p(i) else final(i+1, p)
def get_default_settings(cfg): """Get default configuration settings.""" cfg.setdefault('all_data_label', 'all') cfg.setdefault('confidence_level', 0.66) cfg.setdefault('merge_identical_pred_input', True) cfg.setdefault('savefig_kwargs', { 'bbox_inches': 'tight', 'dpi': 600, ...
def get_unique_id(home_id: str, value_id: str) -> str: """Get unique ID from home ID and value ID.""" return f"{home_id}.{value_id}"
def timeTuple_to_float(secs, usecs): #todo delete? """Converts a time tuple from (secs, usecs) to float.""" return float(secs) + (float(usecs) / 1000000.0)
def pop_keys_from_dict(dict_to_pop, keys): """ Removes a set of keys from a dict and returns a dict of all the removed key-value pairs. Ex. usage: pop_keys_from_dict({'a': 1, 'b': 2, 'c': 3}, ['a', 'c']) #> {'a': 1, 'c': 3} Args: dict_to_pop (dict): A dictionary keys (li...
def get_field_type(field_name): """Grab old style (ENCODE) data field type.""" try: return field_name.split(":")[1] except IndexError: return "string"
def collect_expected(dataset): """ Peel of the target values from the dataset """ expected = [] for sample in dataset: expected.append(sample[0]) return expected
def disjoint_bounds(bounds1, bounds2): """Returns True if bounds do not overlap Parameters ---------- bounds1: rasterio bounds tuple (xmin, ymin, xmax, ymax) bounds2: rasterio bounds tuple """ return (bounds1[0] > bounds2[2] or bounds1[2] < bounds2[0] or bounds1[1] > bounds2[3]...
def convert_integer(inpt): """Return integer value from input inpt >>> convert_integer('1.0') 1 """ return int(float(inpt))
def fake_census_metadata_runner(fake_metadata_runner): """Generate a set of claims required for runner using census parameters instead of schema_name""" del fake_metadata_runner["schema_name"] fake_metadata_runner["survey"] = "CENSUS" fake_metadata_runner["form_type"] = "I" fake_metadata_runner["re...
def MatchesAny(channels, channel): """Whether any channels' id is a prefix of channel.id.""" for chan in channels: if channel.id.startswith(chan.id): return True return False
def make_int_list(val): """Check if the item is a string, and if so, apply str.split() to make a list of ints. If it's a list of ints, return as is. Used as a conversion function for apply_conversions above. Inputs: val: value, either string or list of ints Outputs: ...
def cast_int(string, invalid_value=None): """a helper method for converting strings to their integer value Args: str: a string containing a number Returns: the integer value of the string given or None if not an integer """ try: string_as_int = int(string) if string...
def indicator(prediction, label): """Returns one if the prediction doesn't match the label, else zero. Args: prediction : int Prediction of a data point by a classifier. label : int Actual label of a data point by a classifier. """ return 1 if prediction != lab...
def put_condition_on_query(query, condition): """ To generate a query that wraps the output of some query with some given conditions :param query: (str) base query :param condition: (str) where condition :return: (str) new query """ query = query.strip() if query[-1] == ";": ...
def parse_query(query, exact_taxon=False): """Return the query based on if Taxon ID or BioProject/Study accession.""" import re try: taxon_id = int(query) if exact_taxon: return ['taxon', f'tax_eq({taxon_id})'] else: return ['taxon', f'tax_tree({taxon_id})'] ...
def ext_euclid(a: int, b: int) -> tuple: """Extended euclidean algorithm Return the gcd of a and b, and pair of x and y such that ax + by = gcd(a, b)""" if b == 0: return 1, 0, a else: x, y, q = ext_euclid(b, a % b) x, y = y, (x - (a // b) * y) return x, y, q
def is_exchange_token_protected(f): """Is the given view function exchange token protected?""" return getattr(f, 'is_exchange_token_protected', False)
def seconds_in_nano(seconds): """Convert seconds to nanoseconds :param seconds: (int) The number of seconds. """ return seconds * (10 ** 9)
def make_file_key(profile, filename, file_id): """Make unique key for file storage on s3""" return 'user/{}/{}/{}'.format(profile, file_id, filename)
def spam(a, b, c): """The spam function Returns a * b + c""" return a * b + c
def get_drive_identification(servo, subnode=None): """Gets the identification information of a given subnode. Args: servo: Instance of the servo Class. subnode: subnode to be targeted. Returns: int, int: Product code and revision number of the targeted subnode. """ prod_cod...
def merge_dicts(*dict_args): """Merge dictionaries. Given any number of dicts, shallow copy and merge into a new dict. Precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def insertSort(array, begin=0, end=None): # in-place | stable """ Best O(n) Time | O(1) Space Average O(n^2) Time | O(1) Space Worst (On^2) Time | O(1) Space """ if end == None: end = len(array) for i in range(begin, end): j = i while j > begin and array[j - 1] > ar...
def convert(char, counters): """Convert counters to graphical chart""" return "".join(["#" for _ in range(counters.get(char, 0))])
def air_viscosity(temperature, verbose=False): """define""" out = 0.00001708 * ((temperature / 273.15) ** 1.5) * ((393.396) / (temperature + 120.246)) if verbose: print('air_viscosity: %s' % out) return out
def returns(a_0, a_1): """linear returns formula""" return (a_1 - a_0) / a_0
def filter_lines_with_settings(lines): """ filters the lines and returns only strings that contain required or optional setting """ def is_setting(line): skipped_prefixes = ["# ", "#-", "##", "#WHERE", "#in"] return len(line) > 2 and not [p for p in skipped_prefixes if line.startswith(p)] ...
def remove_xml(rid): """ Removes the .xml from a resource or spec id. """ if '.xml' in rid[-4:]: return rid[:-4] else: return rid
def flatten(nasted_list): """ input: nasted_list - this contain any number of nested lists. ------------------------ output: list_of_lists - one list contain all the items. """ list_of_lists = [] for item in nasted_list: list_of_lists.extend(item) return list_of_lists
def _sort_population(populate: str) -> int: """ Used to sort population list by level (.) into populate value. Args: populate (str): Populate value. Returns: int: Return the number of . (level) into populate value. """ return populate.count('.')
def get_shasta_name(name, mapper): """Parse mapper to get Shasta name.""" for node in mapper: shasta_name = node[1] if shasta_name in name: return shasta_name
def whole(value, exception = ValueError): """Casts to whole (integer) if possible""" newvalue = int(value) #The exception may get raised here by the int function if needed if newvalue < 0: raise exception return newvalue
def tasktrapper_view(request): """Display Task trapper Detail.""" message = "Hello" return {'message': message}
def sign(x): """ Objective: take the sign of x e.g., >>>sign(-1.2) -1 >>>sign(5) 1 """ if x>0: return 1 elif x<0: return -1 else: return 0
def _correct_registry_paths(registry_paths): """ parse_registry_path function recognizes the 'item' as the central element of the asset registry path. We require the 'namespace' to be the central one. Consequently, this function swaps them. :param list[dict] registry_paths: output of parse_registry_pat...
def validate_jobfile_format(jobfile): """Takes a jobfile dictionary and returns it if formatted properly. Args: jobfile: dictionary after file ingestion Returns: jobfile dictionary Raises: ValueError """ first_level_fields = [ 'job_name', 'job_type', 'creative_source_type', 'crea...
def _generate_indeces_from_options(opts): """ list of indeces, this method will support index ranges :param opts: :return: """ res = [] for opt in opts: if "-" in opt: start, end = opt.split('-') res.extend(range(int(start), int(end) + 1)) else: ...
def _detect_skipped_track(remaining_duration: float, end_of_track_buffer: float, track: dict, prev_track: dict) -> bool: """Performs the detection logic for whether a track was skipped Args: remaining_duration: The remaining duration of the track in m...
def uniform_cdf(x): """returns the probability that a uniform random variable is less than x""" if x < 0: return 0 # uniform random is never less than 0 elif x < 1: return x # e.g. P(X < 0.4) = 0.4 else: return 1
def pretty_format_memory(nbytes): """Utility to return memory with appropriate unit.""" if nbytes < (1 << 10): return f'{nbytes} bytes' elif (1 << 20) > nbytes > (1 << 10): return f'{nbytes / (1 << 10)} KB' elif (1 << 30) > nbytes > (1 << 20): return f'{nbytes / (1 << 20)} MB' ...
def mapmuse_addr_parse(address): """hardcoded parser for mapmuse address format""" try: aparts = address.split(",") addr_line = " ".join(aparts[:-1]) city_state = aparts[-1].strip() city, state = city_state.split(' ', maxsplit=1) d = { "line":[addr_line], ...
def remove_duplicate_field(event, field_to_keep, field_to_discard): """ Remove a field when both fields are present :param event: A dictionary :param field_to_keep: The field to keep if both keys are present and the value is not None :param field_to_discard: The field to discard if the field_to_keep i...
def parse_number(string): """Parse a string as a number. This is just a short-hand for int(string, 0) suitable for use in the |type| parameter of |ArgumentParser|'s add_argument() function. An improvement to just using type=int is that this function supports numbers in other bases, e.g. "0x1234". ...
def base(x: int, k: int) -> str: """ Converts the integer `x` to its string representation in base `k`. :Example: >>> base(323, 3) '102222' """ if x == 0: return '0' rep = "" while x != 0: rep += str(x%k) x //= k return rep[::-1]
def extract_content_type_encoding(content_type_string): """ Extract the content type and encoding information. """ charset = "" content_type = "" for part in content_type_string.split(";"): part = part.strip().lower() if part.startswith("charset"): charset = part.spli...
def _version2int(v: str) -> int: """ X.X.X => X0X0X """ if '-' in v: v = v.split("-")[0] if v.endswith(".*"): v = v.replace(".*", ".0") # X.X.* => X.X.0 v_list = v.split(".") if len(v_list) < 3: v_list.append('0') v_new = "" for i, value in enumerate(v_list):...
def parse_extreme(starter, minim, maxim, mintext, maxtext): """ Check if floor/ceiling value is OK. :param starter: Minimum/maximum OS version. :type starter: int :param minim: Minimum value for starter. :type minim: int :param maxim: Maximum value for starter. :type maxim: int :...
def get_orthogonal_vector(vector_one, vector_two): """Get orthogonal vector by simple method for R^2""" aux_vector = ( vector_two[0] - vector_one[0], vector_two[1] - vector_one[1] ) orthogonal_vector = [0, 0] orthogonal_vector[0] = -aux_vector[1] orthogonal_vector[1] = aux_vector...
def _normalize_longitude(lon: float) -> float: """Normalize longitudes between [-180, 180]""" return ((lon + 180.0) % 360.0) - 180.0
def aggregate(data): """Aggregates keys and data as a dict.""" keys = ['mid', 'sid', 'aid', 'msg'] return dict(zip(keys, data))
def preamble(file_info): """ Return the list of preamble strings. """ vim_modeline = "(* vim: set syntax=ocaml: *)" generated_by = "(* Automatically generated by gen_part_nv.py *)" return [vim_modeline, file_info, generated_by]
def total_descent(geo_data): """return the total descent in meters """ sum_descent = 0.0 for ascent in geo_data["differential_descent"]: sum_descent += ascent return sum_descent
def mangle_name(name): """make a name Like<This,and,That> look Like__lt__This_and_That__gt__""" s = name.replace('<', '__lt__').replace('>', '__gt__').replace(',', '_') s = s.replace(' ', '_').replace('&', '__amp__').replace('*', '__star__') s = s.replace(':', '_') s = s.replace('(', '_lp_').replace...
def float_or_int(v): """ cast to int if possible or to float """ vf = float(v) try: vi = int(vf) if vi == vf: return vi except: return vf
def optParameterDomain(longName, shortName): """ Returns a list that you can use in your L{usage.Options}'s C{optParameters} list. """ # Automatically setting document.document based on a GET # parameter or by looking at parent's URL is insecure (because # some browsers will allow setting document.domain to 'com...
def create_encoded_array(index, size, numeric_type=int): """ Creates a one-hot encoded array with a one at the given index and zeroes everywhere else, up to the given size. :param index: The index to set to one. :param size: The size of the encoded array. :param numeric_typ...
def tag_text(unique_fonts: list, doc: dict) -> list: """ Categorizes each text into L, M, or S. :param unique_fonts: a list of unique fonts in the powerpoint :type unique_fonts: list :param doc: a list of blocks per each document page :type doc: dict :rtype: list :return: a list of dict...
def facebook_recon(email): """Find facebook account if linked via email.""" if not email: return None return {'site': 'Facebook', 'url': 'https://www.facebook.com/search/people?q={}'.format(email) }
def get_readable_distance_from_metres(distance): """We'll generally read distances in kilometres, unless it's less than .95 of a kilometre.""" if distance < 950: return str(round(distance)) + 'm' else: return str(round(distance / 1000)) + 'km'
def any (pred, seq): """any takes a one argument predicate function and a sequence. Returns true if any element in seq returns true for predicate, else returns false. The predicate function should return true or false. """ for i in seq: if pred(i): return 1 return 0
def _validate_parameters(parameters, parameters_name): """ Validates the given subdomain. Parameters ---------- parameters : `None` or `dict` of (`str`, `Any`) items or (`set`, `tuple`, `list`) of `tuple` (`str`, `Any`) Initial parameters to add to the route. Returns ------- pa...
def check_ascii_compliance(plaintext): """Returns true if all the characters of plaintext are ASCII compliant (ie are in the ASCII table).""" return all(c < 128 for c in plaintext)
def rst_section(title, symbol="="): """ title ===== """ stroke = symbol * len(title) return "\n".join([title, stroke])
def get_dep_dist(elem1, elem2): """ Get the dependency distance between two list of indices. """ ret = None return max([abs(x - y) for x in elem1 for y in elem2])
def form_tweets(sentences): """Create a tweet, or multiple tweets if the tweets are too long, out of the sentences.""" tweet = "" tweets = [] while sentences: if len(tweet) + len(sentences[0]) > 139: tweets.append(tweet) tweet = "(cont'd.):" else: if l...
def serie(fim): """Dado n, calcule o valor de s = 1 + 1/2 + 1/3 + 1/4 + ... + 1/n """ s = 0 for i in range(1,fim+1): s += 1/i return round(s,2)
def reverse(S, start, stop): """ Reverse elements in implicit slice S[start:stop] -- LINEAR RECURSION """ if start < stop - 1: # if at least 2 elements: S[start], S[stop - 1] = S[stop - 1], S[start] # swap first and last. reverse(S, start + 1, stop - 1) return S
def my_view(database): """A very simple function.""" return 'Value: {}'.format(database['value'])
def repression(val, Kd, power): """Function takes a value and Kd. Function fits the value to a hill function with n=power and Kd and returns the fraction bound.""" new_val = val**power / (Kd**power + val** power) return new_val
def split_tag(tag): """ Returns (chain_id, res_num, insert). Empty chain_id=" " and empty insert="". """ words = tag.split(":") if len(words) > 2: raise Exception("Too many : in res tag %s" % tag) res_num = words[-1] insert = "" while not res_num[-1].isdigit(): insert += res_num[-1] res_n...
def letters_numbers_equals(A): """ Here, I'm trying to outputs the sub-array that its numbers and letters equals: [1, 1, 2, 's', 7, 's', 'b', 5, 'q'] -> 1,8 (4 int and 4 str) O(N^2) :param A: :return: """ max_size = 0 start = 0 end = 0 for i in range(len(A)): letters...
def not_success(status): """ Whether the GitHub status is not a success. :param dict status: a GitHub API status. :return bool: whether the status isn't a success """ return status['state'] != u'success'
def merge_2_into_1(res1, res2): """ merges 2 dictionaries together the second dictionary is merged in the first one (the second remains unchanged / is copied) @param res1: a dictionary in which the second dict will be merges @param res2: second dict will remain unchanged @return: the first dict ...
def list_pairs(validation_dates): """ For a set of ndates dates, return a list of indexes and IDs for all possible unique pairs. For example, for ndates=3 -> [(0, 1), (0,2), (1,2)] """ ndates = len(validation_dates) indexes = [] pair_ids = [] for k1 in range(ndates): for k2 in r...
def app_url(version, model, name): """ /v1/welcome/get_welcome_data """ name = "/%s/%s%s" % (version, model, name) # name = '/{}/{}{}'.format(version, model, name) return name
def get_key_from_rot(rotation): """ Yeah I know it's ugly code... """ if rotation < -67.5: return -90 elif rotation < -22.5: return -45 elif rotation < 22.5: return 0 elif rotation < 67.5: return 45 else: return 90
def fill_slicer(slicer, in_len): """ Return slice object with Nones filled out to match `in_len` Also fixes too large stop / start values according to slice() slicing rules. The returned slicer can have a None as `slicer.stop` if `slicer.step` is negative and the input `slicer.stop` is None. This ...
def z2a(z): """ converts from redshift to scale factor """ return 1.0 / (1.0 + z)
def circular_permuted(x): """ Args: x (iterator) Returns: list: All cicular permutations of x """ return([x[i:] + x[:i] for i in range(len(x))])
def deduce_loop_size(subject: int, public_key: int) -> int: """ Deduce the loop size for ``public_key`` by transforming the ``subject``. :return: The loop size, or -1 if no success """ value = 1 for loop_ct in range(100000000): if value == public_key: return loop_ct ...
def reshape_by_field_to_by_sent(results_by_field, num_fields=5): """ Input is list of length num_fields, where each inner list is of sentences, with num words Output needs to be list of length num_sentences, where len(output[i]) == num_fields :param results_by_field: :param num_fields: :re...