content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def set_parallel(n_core): """ Set parallel. This helper function decides whether the analysis should be run in parallel based on the number of cores specified. :param n_core: An integer; specifies the number of cores to use for this analysis. :return: A boolean; whether analysis should be run in parallel or not. """ n_core = int(n_core) if n_core == 1: parallel = False elif n_core > 1: parallel = True else: raise ValueError return parallel
92d6ae54c7620303a4c6b644b81b3bcc16e185cd
546,431
def lower(tokens): """Lower-case all tokens of a list""" return [token.lower() for token in tokens]
1488a793ad74cc200c810fff47e068a00a762e0d
338,841
import yaml def load_repositories(repos_file): """ Load repository yaml """ if repos_file: try: file_descriptor = open(repos_file, 'r', encoding='utf-8') except IOError as error: print("Error: open file {} failed", repos_file, error) return None repos = yaml.load(file_descriptor.read(), Loader=yaml.Loader) return repos['repositories'] return None
d3f1ae60407f3c9eeebc9ca5326fa753e166c2ba
638,425
from pathlib import Path def get_output_filepath(filepath): """Returns a new output filepath based on a given filepath. Given filepath: /Users/max/Desktop/video.mp4 Returned filepath: /Users/max/Desktop/video_blurred.mp4 Args: filepath (str): Path to an existing file Returns: str: Path to a not yet existing file """ path = Path(filepath) suffix = path.suffix filename = path.stem counter = 0 while True: if counter == 0: new_name = filename + '_blurred' + suffix else: new_name = filename + '_blurred_' + str(counter) + suffix new_path = path.with_name(new_name) if not new_path.exists(): output_filepath = str(new_path) break counter += 1 return output_filepath
f63bc2ae127647e8cb3b8a9a969f87077262540d
258,898
def _extract_hostname(url: str) -> str: """Get the hostname part of the url.""" if "@" in url: hn = url.split("@")[-1] else: hn = url.split("//")[-1] return hn
316310e703954dc6b3a995e8b523dbb549a3e9ca
309,193
def eval_acc(results, is_print=False): """ :param results: np.array shape of (N, 2) [pred, label] :param is_print: print eval score :return: score """ acc = (results[:, 0] == results[:, 1]).sum() / results.shape[0] * 100 if is_print: print('*****************') print('ACC Pos') print('{:.2f} {}'.format(acc, int(results[:, 0].sum()))) print('*****************') return acc
2071437521ce8a13d1efc5618b9ca745b6664bf7
492,414
def identity(*args): """ Identity function :param args: Splat of arguments :type args: ```tuple``` :return: First arg if len(args) is 1 else all args :rtype: Union[Tuple[Any, Tuple[Any]]] """ return args[0] if len(args) == 1 else args
565efa7ab8994accdbc0d4cd27e7762818ab953f
393,241
def package_time(date_dict): """Package a time/date statement in a standardised form.""" return {"time_value": date_dict}
6c4097e162091e3992fa6ef57e83093cf0788c46
670,688
def create_pair(n): """ Create a pair of n-digit integers, from 1-up and from 9-down. """ one = 0 two = 0 up = 1 down = 9 num_digits = 0 while num_digits < n: one = 10 * one + up two = 10 * two + down up += 1 if up == 10: up = 1 down -= 1 if down == 0: down = 9 num_digits += 1 return [one, two]
04ab585ef8ddaa113aafd958cfefe9ad4778aba7
485,047
def sql2dict(queryset): """Return a SQL alchemy style query result into a list of dicts. Args: queryset (object): The SQL alchemy result. Returns: result (list): The converted query set. """ if queryset is None: return [] return [record.__dict__ for record in queryset]
c55fa18773142cca591aac8ed6bdc37657569961
707,916
import difflib def diff_output(expected: str, actual: str) -> str: """ Compares the expected and actual outputs of a command Args: expected: desired output actual: STDOUT captured from command Returns: str: diff output """ # files read in are converted to "universal" newlines so convert captured output too actual = actual.replace("\r\n", "\n") return "".join( difflib.unified_diff( expected.splitlines(keepends=True), actual.splitlines(keepends=True), fromfile="expected", tofile="actual", ) )
cce18472d064196739fcfa0ea7a6a98256c5c20d
576,436
def uniqify(name: str, other_names: list) -> str: """Return a unique name with .xxx suffix if necessary. Example usage: >>> uniqify('hey', ['there']) 'hey' >>> uniqify('hey', ['hey.001', 'hey.005']) 'hey' >>> uniqify('hey', ['hey', 'hey.001', 'hey.005']) 'hey.002' >>> uniqify('hey', ['hey', 'hey.005', 'hey.001']) 'hey.002' >>> uniqify('hey', ['hey', 'hey.005', 'hey.001', 'hey.left']) 'hey.002' >>> uniqify('hey', ['hey', 'hey.001', 'hey.002']) 'hey.003' It also works with a dict_keys object: >>> uniqify('hey', {'hey': 1, 'hey.005': 1, 'hey.001': 1}.keys()) 'hey.002' """ if name not in other_names: return name # Construct the list of numbers already in use. offset = len(name) + 1 others = (n[offset:] for n in other_names if n.startswith(name + '.')) numbers = sorted(int(suffix) for suffix in others if suffix.isdigit()) # Find the first unused number. min_index = 1 for num in numbers: if min_index < num: break min_index = num + 1 return "{}.{:03d}".format(name, min_index)
2fcbe5180b2206e7fcab3540126bdf50d2fd16d2
280,308
import collections def parse_bv_keywords(section): """Grab the keywords in a BrainVision section, and create a dictionary. Args: section: a section starts with [xxx], and contains lines of key=value Returns: A dictionary of keys and values from this section. """ section = section.split(']', 1)[1] # Use OrderedDict so the channel list stays in order section_dict = collections.OrderedDict(()) for key_value in section.split('\n'): if not key_value or key_value[0] == ';': continue if '=' in key_value: key, value = key_value.split('=', 1) key = key.strip() value = value.strip() try: value = int(value) if value.isdigit() else float(value) except ValueError: # Leave value as a str. pass section_dict[key] = value return section_dict
72e4423ae4f87fddc34e695c99bb3e83dc8b9512
337,577
import torch def _compute_stacked_offsets(sizes, repeats): """Computes offsets to add to indices of stacked tensors (Tensorflow). When a set of tensors are stacked, the indices of those from the second on must be offset in order to be able to index into the stacked tensor. This computes those offsets. Args: sizes: A 1D `Tensor` of the sizes per graph. repeats: A 1D `Tensor` of the number of repeats per graph. Returns: A 1D `Tensor` containing the index offset per graph. """ sizes = torch.tensor(sizes[:-1]).type(torch.long) offset_values = torch.cumsum(torch.cat([torch.zeros(1).long(), sizes], 0), dim=0) return torch.repeat_interleave(offset_values, repeats.long())
4f981d196adc4462acfc8428e0d781b15f80756a
289,432
def ib_error(code): """Given an error code, return the error text. """ error_strings = [ \ "System error", \ "Function requires GPIB board to be CIC", \ "No Listeners on the GPIB", \ "GPIB board not addressed correctly", \ "Invalid argument to function call", \ "GPIB board not System Controller as required", \ "I/O operation aborted (timeout)", \ "Nonexistent GPIB board", \ "DMA error", \ "", \ "Asynchronous I/O in progress", \ "No capability for operation", \ "File system error", \ "", \ "GPIB bus error", \ "", \ "SRQ stuck in ON position", \ "", \ "", \ "", \ "Table problem", \ "Interface is locked", \ "Ibnotify callback failed to rearm", \ "Input handle is invalid", \ "", \ "", \ "Wait in progress on specified input handle", \ "Event notification was cancelled due to a reset of the interface", \ "The interface lost power" \ ] return error_strings[code]
3531c21efbe293f1bc15a786d9a64b7c4f9744d8
277,224
import random def get_sampled_frame_number(total_frame_number: int, sample_rate: int): """ Sample frame numbers randomly according to the sample rate. :param total_frame_number: total frame number of target video :param sample_rate: sampling rate for frame :return: list of sampled frame number """ frame_number_list = [] # sample target frame number start_idx = 0 for start_idx in range(1, total_frame_number, sample_rate): end_idx = start_idx + sample_rate sampled_frame_number = random.randint(start_idx, end_idx) frame_number_list.append(sampled_frame_number) return frame_number_list
037c1e131a66869918965f3034933dea36c5531b
521,500
def convert_metadata(old_metadata): """ Convert model metadata from old format (with camel-case parameter group names) to new format. Args: old_metadata (dict): Model metadata in old format Returns: new_metadata (dict): Model metadata in new format """ model_metadata = old_metadata['ModelMetadata'] model_parameters = model_metadata['ModelParameters'] training_dataset = model_metadata['TrainingDataset'].copy() new_metadata = { "model_uuid": old_metadata['model_uuid'], "time_built": old_metadata['time_built'], "training_dataset": training_dataset, "training_metrics": [] } map_keys = [ ("external_export_parameters", "ExternalExportParameters"), ("dataset_metadata", "DatasetMetadata"), ] for (nkey, okey) in map_keys: value = training_dataset.pop(okey, None) if value is not None: training_dataset[nkey] = value map_keys = [ ("model_parameters", 'ModelParameters'), ("ecfp_specific", 'ECFPSpecific'), ("rf_specific", 'RFSpecific'), ("autoencoder_specific", 'AutoencoderSpecific'), ("descriptor_specific", 'DescriptorSpecific'), ("nn_specific", "NNSpecific"), ("xgb_specific", "xgbSpecific"), ("umap_specific", "UmapSpecific"), ] for (nkey, okey) in map_keys: value = model_metadata.get(okey) if value is not None: new_metadata[nkey] = value # Get rid of useless extra level in split params split_params = model_metadata.get('SplittingParameters') if split_params is not None: splitting = split_params.get('Splitting') if splitting is not None: new_metadata['splitting_parameters'] = splitting return new_metadata
18a5b62dbf361bb414f04853cee61d1920467785
332,413
def max_or_none(iterable): """ Returns the max of some iterable, or None if the iterable has no items Args: iterable (iterable): Some iterable Returns: max item or None """ try: return max(iterable) except ValueError: return None
6d123df136e427d54525306439930dc560a0cf05
577,604
def get_random_elements(faker, elements): """ Generate random unique sorted elements using elements :param faker: Faker Library :param elements: List of elements :return: Random unique elements value sorted """ result = faker.random_elements( elements=elements, unique=True, ) return sorted(result)
7008d2aea430f720bf34ed217f2ed88ca677c106
565,576
def _find_sub_list(sublist, full_list): """ Args: - sublist is a list of words that are supposed to be found in the full list. - full list is a list of words that is supposed to be searched in. Returns: - List of tuples with the form (first_index_of_occurence, last_index_of_occurence) This function finds all occurences of sublist in the full_list. """ # this is the output list results = [] sublist_len = len(sublist) # loop over all ind if the word in full_list[ind] matches the first # word of the sublist for ind in (i for i, word in enumerate(full_list) if word == sublist[0]): # check that the complete sublist is matched if full_list[ind:ind+sublist_len] == sublist: # then append this to the results results.append((ind, ind+sublist_len-1)) return results
2f3c0ba416a4f1beaf03681f0361b766823667fb
258,698
def mean_hr_bpm(num_beats, duration): """Average heart rate calculation This is a simple function that converts seconds to minutes and divides the total number of beats found by the total minutes in the strip. :param num_beats: a single integer of the number of total beats in a strip :param duration: a single float for the time duration of the strip :returns: a single float of the average heart rate in the strip """ minutes = duration/60 mean_hr_bpm = num_beats/minutes return mean_hr_bpm
83eb5433cec77f9294e1310410e3e06ed1b1eda9
677,402
def ff_decimal_rounder_uncommon(ls_fl_num2format=[0.0012345, 0.12345, 12.345, 123.45, 1234.5, 123456.789], dc_round_decimal={0.1: 4, 1: 3, 100: 2, float("inf"): 0}, verbose=False): """Decimal rounding function with conditional formatting by number size Given an array of numbers, format and return as a list of string, with different decimal formatting given different number sizes. Parameters ---------- ls_fl_num2format : list of float list of numbers of approximate to decimals dc_round_decimal : dict dict incremental formatter. For example, for the default, if below 0.1 keep 4 decimals, If below 1 keep 3, if below 100 keep 2, if otherwise above, then keep 0 decimals Loop over formatter. Returns ------- list of str Decimal formatted string outputs """ ls_st_numformated = [] for fl_num2format in ls_fl_num2format: for fl_threshold, it_decimals in dc_round_decimal.items(): if fl_num2format < fl_threshold: st_float_rounded = f'{fl_num2format:.{it_decimals}f}' ls_st_numformated.append(st_float_rounded) if verbose: print(f'{fl_num2format=}, {st_float_rounded=}, {fl_threshold=}, {it_decimals=}') break else: continue return ls_st_numformated
b83472401c401332e7c727cb95cebaa74973e4b1
454,830
def memoize(func): """A decorator to cache the return value of func. Args: func: function to decorate Returns: wrapper: decorated function """ cache = {} def wrapper(args): try: return cache[args] except KeyError: cache[args] = func(args) return cache[args] return wrapper
c3068fa4b723dc8e8ee767433fc55f078c8acb63
260,714
import math def ssr(precinct, seed): """ Sum of Square Roots (SSR) pseudorandom function from Rivest, 2008: http://people.csail.mit.edu/rivest/Rivest-ASumOfSquareRootsSSRPseudorandomSamplingMethodForElectionAudits.pdf Input: precinct number (as an integer) and seed (a string of 15 digits) >>> ssr(23951, "279016755606125") 0.93591273640868167 0.93591273640868167 vs from paper: xi = 0.93591273640858040364659219 """ if not seed or len(seed) < 15: return "" p = "%06d" % precinct return math.modf(math.sqrt(int(p[0:2] + seed[ 0: 5])) + math.sqrt(int(p[2:4] + seed[ 5:10])) + math.sqrt(int(p[4:6] + seed[10:15])) )[0]
c180cd2725474f2b2a9cea0e4747a19952dd4d9a
208,844
from typing import Dict from typing import Any def can_local_namespace_access_route( local_namespace: str, route_obj: Dict[str, Any], ) -> bool: """Can this local namespace access the given route?""" for protection in route_obj['namespace-access']: if protection['namespace'] == local_namespace: return bool(protection['access']) return route_obj['default-access'] is True
a12447621a803e0bc0cdf208c0870548aef65d74
357,429
def numfmt( num, fmt="{num.real:0.02f} {num.prefix}", binary=False, rollover=1.0, limit=0, prefixes=None, ): """Formats a number with decimal or binary prefixes num: Input number fmt: Format string of default repr/str output binary: If True, use divide by 1024 and use IEC binary prefixes rollover: Threshold to roll over to the next prefix limit: Stop after a specified number of rollovers prefixes: List of (decimal, binary) prefix strings, ascending """ # SPDX-SnippetComment: Originally from https://github.com/rfinnie/rf-pymods # SPDX-SnippetCopyrightText: Copyright (C) 2020-2021 Ryan Finnie # SPDX-LicenseInfoInSnippet: MIT class NumberFormat(float): prefix = "" fmt = "{num.real:0.02f} {num.prefix}" def __str__(self): return self.fmt.format(num=self) def __repr__(self): return str(self) if prefixes is None: prefixes = [ ("k", "Ki"), ("M", "Mi"), ("G", "Gi"), ("T", "Ti"), ("P", "Pi"), ("E", "Ei"), ("Z", "Zi"), ("Y", "Yi"), ] divisor = 1024 if binary else 1000 if limit <= 0 or limit > len(prefixes): limit = len(prefixes) count = 0 p = "" for prefix in prefixes: if num < (divisor * rollover): break if count >= limit: break count += 1 num = num / float(divisor) p = prefix[1] if binary else prefix[0] ret = NumberFormat(num) ret.fmt = fmt ret.prefix = p return ret
837b271860e065bfd1e811e5f3ca16040f3ea663
470,305
def datetime_to_iso(date): """ convert a datetime object to an ISO_8601 formatted string. Format of string is taken from JS date to string """ return date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
29768984b64f1c66c5d9ee809058d352927c5658
593,660
def interpret_field(data): """ Convert data to int, if not possible, to float, otherwise return data itself. Parameters ---------- data : object Some data object Returns ------- data : int, float or same data type as the input Return the data object casted as an int, float or return data itself. """ try: return int(data) except ValueError: try: return float(data) except ValueError: return data
4e32d7a7574c5564a0a76fc4ce0dc600bcaceded
520,858
def pluralize(count, item_type): """Pluralizes the item_type if the count does not equal one. For example `pluralize(1, 'apple')` returns '1 apple', while `pluralize(0, 'apple') returns '0 apples'. :return The count and inflected item_type together as a string :rtype string """ def pluralize_string(x): if x.endswith('s'): return x + 'es' else: return x + 's' text = '{} {}'.format(count, item_type if count == 1 else pluralize_string(item_type)) return text
1e980ca625f93611b37de797efcfb4f3afb8c7ea
245,310
def stringToLengthAndCombo(combo_string): """Creates a tuple of (attribute, value) tuples from a given string. Args: combo_string: string representation of (attribute, value) tuples. Returns: combo_tuple: tuple of (attribute, value) tuples. """ length = len(combo_string.split(';')) combo_list = [] for col_vals in combo_string.split(';'): parts = col_vals.split(':') if len(parts) == 2: combo_list.append((parts[0], parts[1])) combo_tuple = tuple(combo_list) return length, combo_tuple
51a71a967e5c14df10c3df848bf8655ee853334f
300,761
def polygonArrayToOSMstructure(polygon): """ polygonArrayToOSMstructure(polygon) With a polygon array gets structure of poly for OSM sql. Parameters ---------- polygon : Array Array that contains the poligon separated [[lat,long], [lat', long'], [lat'', long''], ...] same as [[y,x],[y',x'], [y'',x''], ...] representation of OSM return. Returns ------- String Returns the string asociated for OSM sqls (poly: ...). """ s = '(poly:"' for y, x in polygon[:-1]: s += str(x)+ ' '+ str(y)+' ' s += str(polygon[-1][1])+' '+str(polygon[-1][0]) +'")' return s
61c3debcf4b8ff47eca574fd1bb94a0cde52dbf5
86,512
def fpr(fp: int, tn: int) -> float: """False Positive Rate computed from false positives and true negatives.""" return fp / (fp + tn) if fp + tn else 0.0
455610e45cad46e56dae87a71f0ec842763cbc05
645,046
def ifN(v, d): """Return value if value is not None else default""" return v if v is not None else d
fb3ccd6def31f35a53e968510141e4d389a21f5d
146,604
import torch def make_target(label, label_to_ix): """Turn target labels into a numeric vector where each label has a unique index""" return torch.LongTensor([label_to_ix[label]])
33b8f92868d1de685154cda236de4bbe53a9df70
623,030
from pathlib import Path def res_get(res, attr: Path, **kw): # pylint: disable=redefined-outer-name """ Get a node's value and access the dict items beneath it. The node value must be an attrdict. """ val = res.get("value", None) if val is None: return None return val._get(attr, **kw)
eeb5615b253d2a55333714f328e7245bb8a202b7
344,312
def ngrams(seq, min_n, max_n): """ Return min_n to max_n n-grams of elements from a given sequence. """ text_len = len(seq) res = [] for n in range(min_n, min(max_n + 1, text_len + 1)): for i in range(text_len - n + 1): res.append(seq[i: i + n]) return res
af71c95d5c240da78061f481e8068619a4071393
268,727
from typing import Any def get_full_name(obj: Any) -> str: """Returns identifier name for the given callable. Should be equal to the import path: obj == import_object(get_full_name(obj)) Parameters ---------- obj : object The object to find the classpath for. Returns ------- The object's classpath. """ if callable(obj): return obj.__module__ + '.' + obj.__qualname__ else: return obj.__class__.__module__ + '.' + obj.__class__.__qualname__
6f83f808f8c4d226b1d26365adc75f5cb6c4e28f
15,087
def flip_keypoints(keypoints): """ Flipped keypoints horizontally (x = -x) """ for i, k in enumerate(keypoints): keypoints[i, 0] = -keypoints[i, 0] return keypoints
2da5e0b3fc2fde35a49b8615fd3fbe8f63fec3f3
101,178
def create_kmers(seq,kmer_size): """ Create a set of kmers from a sequence. """ return [seq[i:(i+kmer_size)] for i in range(len(seq)-kmer_size+1)]
5fbdcf9c7e9802eed2d491c7b1c40f2c7c7a9f2e
353,057
def json_parts(json_line): """ Checks for "label" and "description" components of Json command. PArameters: json_line (str): The Json command being passed into the function. Returns: Arr [Bool, Bool]: Is there a label command? Is there a description command? """ labF, desF = False, False if "\"label\"" in json_line: labF = True if "\"description\"" in json_line: desF = True return [labF, desF]
168f6cd064b7f443539b3cd8a187a7234085ef7b
692,084
def udfize_lambda_string(expression: str): """Given an expression that uses 'input' as a parameter, return a lambda as a string.""" return "lambda input: ({})".format(expression)
bdcc542568702e91f60400ef25f86df9d4847563
91,889
def noop(value, param=None): """A noop filter that always return its first argument and does nothing with its second (optional) one. Useful for testing out whitespace in filter arguments (see #19882).""" return value
babd4941efdff8fa67df07a5dd3d86da210b91c2
101,677
import torch def add_gaussian_noise(tensor, mean=0.1, std=1., device='cpu'): """Function that add noise to a given tensor. Args: tensor: An input tensor mean: Gaussian noise mean std: Gaussian noise std device: device used to store tensor Returns: tensor: A new tensor with added noise """ return tensor + torch.randn(tensor.size()).to(device) * std + mean
2e3cd8c500d064497ffbc0aa2476a670d2179043
339,960
def _create_gauss(*, mu, sigma, numspikes, prng): """Create gaussian inputs (used by extgauss and evoked). Parameters ---------- mu : float The mean time of spikes. sigma : float The standard deviation. numspikes : float The number of spikes. prng : instance of RandomState The random state. Returns ------- event_times : array The event times. """ return prng.normal(mu, sigma, numspikes)
6c0e6b1c9bbd778e8b447baf5524dfd5f56778ee
308,394
def div_scaler(X, divider): """ Divides the input by the divider """ return X.astype("float32") / divider
53dd469ac2d988eadd048af21cb452418c7fc111
498,552
def strip_hash_bookmark_from_url(url): """Strip the hash bookmark from a string url""" return (url or '').split('#')[0]
c31f569b147d4e9bd74e932856b1a2e168e05bb3
666,194
def getClassLabel(file): """ This method extracts the class label from a given file name or file path. The class label should either be the file name without ending numbers or the folder in which the file is located @param file: The file name or the file path @returns the class label as string """ return file.split('.')[0].strip("0123456789")
cc604a09aed4067fc8e9a71d774822dbc409a736
55,099
def make_object(row, names, constructor): """Turns a row of values into an object. row: row of values names: list of attribute names constructor: function that makes the objects Returns: new object """ obj = constructor() for name, val in zip(names, row): func = constructor.convert.get(name, int) try: val = func(val) except: pass setattr(obj, name, val) obj.clean() return obj
36755906bfa415c09b3cf738c1c9873d61d03fe3
264,097
import six def equals_lf(line): """ Return True if line (a text or byte string) equals '\n'. """ return line == ('\n' if isinstance(line, six.text_type) else b'\n')
4a70e39970f0869319346806ae95159b3293e549
135,739
def mul_point(p, m): """ multiply point p by m """ sp = [] for i in range(3): sp.append(p[i]*m) return sp
6f9cbe000476ee46d8cce842112d463f8e70ef92
354,569
def to_hsl(color: tuple) -> tuple: """Transforms a color from rgb space to hsl space. Color must be given as a 3D tuple representing a point in rgb space. Returns a 3D tuple representing a point in the hsl space. Saturation and luminance are given as floats representing percentages with a precision of 2. Hue is given as an angle in degrees between 0 and 360 degrees with a precision of 0. """ rf = color[0] / 255 gf = color[1] / 255 bf = color[2] / 255 maximum = max(rf, gf, bf) minimum = min(rf, gf, bf) delta = maximum - minimum l = (maximum + minimum) / 2 s = 0 if delta == 0 else delta / (1 - abs(2 * l - 1)) if delta == 0: h = 0 elif maximum == rf: h = 60 * (((gf - bf) / delta) % 6) elif maximum == gf: h = 60 * ((bf - rf) / delta + 2) else: # max is bf h = 60 * ((rf - gf) / delta + 4) return (round(h), round(s, 2), round(l, 2))
725cd35cb9ae83d635ba5d2b477afdeb3c1bd37c
110,922
def switch(*args): """:yaql:switch Returns the value of the first argument for which the key evaluates to true, null if there is no such arg. :signature: switch([args]) :arg [args]: mappings with keys to check for true and appropriate values :argType [args]: chain of mapping :returnType: any (types of values of args) .. code:: yaql> switch("ab" > "abc" => 1, "ab" >= "abc" => 2, "ab" < "abc" => 3) 3 """ for mapping in args: if mapping.source(): return mapping.destination()
c0d152b4004866826c4892a1340865b79feefa2c
696,194
def calc_bin_cov(scaffolds, cov): """ calculate bin coverage """ bases = sum([cov[i][0] for i in scaffolds if i in cov]) length = sum([cov[i][1] for i in scaffolds if i in cov]) if length == 0: return 0 return float(float(bases)/float(length))
19b23824a96afd287a5a2bc55f249b624b81781a
363,968
from pathlib import Path def is_subpath(parent_path: str, child_path: str): """Return True if `child_path is a sub-path of `parent_path` :param parent_path: :param child_path: :return: """ return Path(parent_path) in Path(child_path).parents
6852efb5eede8e16871533dca9d0bf17dd7454bb
683,030
def calc_last_time_active(xml_element, filename): """ Calculate the absolute time (in EPOCH) when an event was active for the last time. :param xml_element: The element containing an lastTimeActive attribute :param filename: A filename where the name contains digits only, representing the creation time in EPOCH. :return: The EPOCH representation of the time an event was active for the last time. """ if 'lastTimeActive' in xml_element.keys(): relative_last_time_active = int(xml_element.attrib['lastTimeActive']) # Some events show the last_time_active as EPOCH already, which is indicated by starting with a minus sign if relative_last_time_active < 0: last_time_active = abs(relative_last_time_active) # Otherwise we need to add the filename (which is the start time in EPOCH) # to the relative time (represented in ms) else: last_time_active = int(filename) + relative_last_time_active # time from ms to s since epoch return last_time_active/1000
8b084647e0cf09eeec99230ac7fcac18d62ac047
472,170
def get_cum_returns(returns, compound=True): """ Computes the cumulative returns of the provided returns. Parameters ---------- returns : Series or DataFrame, required a Series or DataFrame of returns compound : bool True for compounded (geometric) returns, False for arithmetic returns (default True) Returns ------- Series or DataFrame """ if compound: cum_returns = (1 + returns).cumprod() else: cum_returns = returns.cumsum() + 1 cum_returns.index.name = "Date" return cum_returns
89b39cdae9e1cd8e0ebd5547c46a6795a2d45954
469,216
def create_sample_db(ntables): """ Create a python description of a sample database """ rv = {} for i in range(1, ntables + 1): rv["table%s" % i] = { "columns": [ { "name": "id", "type": "integer", "use_sequence": "table%s_id_seq" % i, }, {"name": "data", "type": "text"}, ], } return rv
c49f583b4e7f58f1bbb7ad05902c1fc9010bd35c
7,242
def _request_meta(request): """ Extract relevant meta information from a request instance """ meta = {"ip_address": request.META["REMOTE_ADDR"]} if "HTTP_USER_AGENT" in request.META: meta["user_agent"] = request.META["HTTP_USER_AGENT"] if hasattr(request, "session") and request.session.session_key: meta["session"] = request.session.session_key return meta
7dcb84a16513902ceeba415ff7b0870fee4dc3c7
141,476
def sanitize(string): """Sanitizes the string Args: string (str): input string Returns: str: sanitized string """ sanitized = string.replace('"', '').replace("'", "") return sanitized
b96845220d376fd278a63118f77a27b78f568565
78,662
def parse_story_file(content): """ Remove article highlights and unnecessary white characters. """ content_raw = content.split("@highlight")[0] content = " ".join(filter(None, [x.strip() for x in content_raw.split("\n")])) return content
350774af9ba5341f8869039fb99018be951365af
81,545
def getFiducialPositions(fiducialNode): """ Extracts positions from input fiducial node and returns it as array of positions Parameters ---------- fiducialNode : vtkMRMLMarkupsFiducialNode FiducialNode from which we want the coordinates Returns ------- List of arrays[3] of fiducial positions """ positions = [] for i in range(fiducialNode.GetNumberOfFiducials()): pos = [0, 0, 0] fiducialNode.GetNthFiducialPosition(i, pos) positions.append(pos) return positions
9f42c8bf3208400b1ee6a85506e63f1f14f2def5
451,036
def get_cu_mask(total_count, active_cu): """ Returns a compute-unit mask as a binary string, with a single compute unit set. """ a = ["0"] * total_count a[active_cu] = "1" return "".join(a)
8a5190959993f56bcc6e29f76329014d25218899
246,923
def get_need_types(app): """ Returns a list of directive-names from all configured need_types. **Usage**:: from sphinxcontrib.needs.api import get_need_types all_types = get_need_types(app) :param app: Sphinx application object :return: list of strings """ needs_types = getattr(app.config, 'needs_types', []) return [x['directive'] for x in needs_types]
db3b74b43bb09fe70038b2c0707fa76219c0f565
415,906
import difflib def elements_equal(e1, e2, ignore={}, ignore_trailing_whitespace=False, tidy_style_attrs=False, exc_class=ValueError): """ Recursively compare two lxml Elements. Raise an exception (by default ValueError) if not identical. Optionally, ignore trailing whitespace after block elements. Optionally, munge "style" attributes for easier comparison. """ if e1.tag != e2.tag: raise exc_class("e1.tag != e2.tag (%s != %s)" % (e1.tag, e2.tag)) if e1.text != e2.text: diff = '\n'.join(difflib.ndiff([e1.text or ''], [e2.text or ''])) raise exc_class("e1.text != e2.text:\n%s" % diff) if e1.tail != e2.tail: exc = exc_class("e1.tail != e2.tail (%s != %s)" % (e1.tail, e2.tail)) if ignore_trailing_whitespace: if (e1.tail or '').strip() or (e2.tail or '').strip(): raise exc else: raise exc ignore_attrs = ignore.get('attrs', set()) | ignore.get('tag_attrs', {}).get(e1.tag.rsplit('}', 1)[-1], set()) e1_attrib = {k:v for k,v in e1.attrib.items() if k not in ignore_attrs} e2_attrib = {k:v for k,v in e2.attrib.items() if k not in ignore_attrs} if tidy_style_attrs and e1_attrib.get('style'): # allow easy comparison of sanitized style tags by removing all spaces and final semicolon e1_attrib['style'] = e1_attrib['style'].replace(' ', '').rstrip(';') e2_attrib['style'] = e2_attrib['style'].replace(' ', '').rstrip(';') if e1_attrib != e2_attrib: diff = "\n".join(difflib.Differ().compare(["%s: %s" % i for i in sorted(e1_attrib.items())], ["%s: %s" % i for i in sorted(e2_attrib.items())])) raise exc_class("e1.attrib != e2.attrib:\n%s" % diff) s1 = [i for i in e1 if i.tag.rsplit('}', 1)[-1] not in ignore.get('tags', ())] s2 = [i for i in e2 if i.tag.rsplit('}', 1)[-1] not in ignore.get('tags', ())] if len(s1) != len(s2): diff = "\n".join(difflib.Differ().compare([s.tag for s in s1], [s.tag for s in s2])) raise exc_class("e1 children != e2 children:\n%s" % diff) for c1, c2 in zip(s1, s2): elements_equal(c1, c2, ignore, ignore_trailing_whitespace, tidy_style_attrs, exc_class) # If you've gotten this far without an exception, the elements are equal return True
061c3de64f118c54d2e09d5e990c36d952b59237
279,994
def getGridMarker(location, grid): """Return marker in grid at given location""" return grid[location[0]][location[1]]
28952b0e179534809ea6fa08b977a596312655fc
603,977
def get_src_attrs(placeholder, image, slick=False): """ :param placeholder: url of static image :param image: url of real image :param slick: slick carousel requires `data-LAZY`, semantic-ui uses `data-SRC` attribute :return: src attribute with temporary static placeholder image, real image will be fetched later from data-attr """ lazy_attr_name = 'lazy' if slick else 'src' return f'src={placeholder} data-{lazy_attr_name}={image} type={lazy_attr_name}'
ba749518c0a98ff220fa820783c2ac7f5657274a
252,323
def bitwise_and_2lists(list1, list2): """ Takes two bit patterns of equal length and performs the logical inclusive AND operation on each pair of corresponding bits """ list_len = len(list2) return_list = [None] * list_len for i in range(list_len): return_list[i] = list1[i] & list2[i] return return_list
832b9a745eb157d2ae97c620994337c6f44b734e
615,037
def object_belongs_to_module(obj, module_name): """ Checks if a given object belongs to a given module (or some sub-module). @param obj: Object to be analysed @param module_name: Name of the module we want to check @return: Boolean -> True if obj belongs to the given module, False otherwise """ return any(module_name == x for x in type(obj).__module__.split('.'))
9528c6be37c5cc4b067d95131c0ee0b376c455cc
372,374
def interpreted_value(slot): """ Retrieves interprated value from slot object """ if slot is not None: return slot["value"]["interpretedValue"] return slot
513e27b42d3762694fc4d9a1f0456b2ea6790724
298,980
def _make_rv_params_variable(rv, **params): """ Wraps the random variable rv, allowing it to accept time-dependent parameters. """ if any(callable(x) for x in params.values()): return lambda t: rv( **{k: (x(t) if callable(x) else x) for k, x in params.items()}) else: return rv(**params)
a497962b67f88a9bc01855e695d17a0aceaa8958
49,124
def readable_timedelta(days): """To get the number of weeks and days in given nuber of days""" number_of_weeks = days // 7 #To get number of weeks number_of_days = days % 7 # To get number of days return('{} week(s) and {} day(s)'.format(number_of_weeks, number_of_days))
5be929ebb108192540648dbd2af980a009437ad7
91,138
def add_frame(img, c, b=40): """Add a colored frame around an image with color c and thickness b """ img = img.copy() img[:, :b] = img[:b, :] = img[:, -b:] = img[-b:, :] = c return img
63b00fd6e47347baf49c28a38b74829aef158b98
104,330
import configparser def parse_prep(prepname, prepfile): """Gets parameters from specified prep name and config file.""" preps = configparser.ConfigParser() preps.read(prepfile) return preps[prepname.upper()]
c7e6dca45c8bb544f87ffcecb23e247a7940e194
374,805
def countPxlsPerClass(data, label_col = "Label"): """ Counts amount of pixels per class label Parameters ---------- data: numpy.dataframe dataframe containing data label_col: str ( optional) name of label column Examples --------) >>> countPxlsPerClass(data, "Label_nr") Returns ------- list list of absolute value counts per class """ return data[label_col].value_counts()
c23fbb1e11a816297fa577b701288903c93791af
561,088
import re def camel_to_snake_case(in_str): """ Convert camel case to snake case :param in_str: camel case formatted string :return snake case formatted string """ return '_'.join(re.split('(?=[A-Z])', in_str)).lower()
a905bd2007fcaafed1e811a48c5fe14831e77631
686,249
def remote_raw_val_from_db_val(db_val: bytes) -> str: """Retrieve the address where a grpc server is running from a remote db value Parameters ---------- db_val : bytes db value assigned to the desired remote name Returns ------- str IP:PORT where the grpc server can be accessed. """ raw_val = db_val.decode() return raw_val
05bbe6397e0fdbd4b04a79c5ecc697f9b3a759fb
195,768
def get_seq_middle(seq_length): """Returns relative index for the middle frame in sequence.""" half_offset = int((seq_length - 1) / 2) return seq_length - 1 - half_offset
a5c115627b71dd1e3de9d1a57ab2d37cba972e7f
546,572
import json import requests def sendTelegramMessage( body: str, apiKey: str, chatId: str, disableNotifications: bool = True ) -> bool: """ Send a Telegram message using the REST api. Docs: https://core.telegram.org/bots/api#sendmessage """ headers = {"Content-Type": "application/json"} data_dict = { "chat_id": chatId, "text": body, "parse_mode": "HTML", "disable_notification": disableNotifications, } data = json.dumps(data_dict) url = f"https://api.telegram.org/bot{apiKey}/sendMessage" response = requests.post(url, data=data, headers=headers, timeout=1) return response.ok
49358ce9d626e9f4beceeff963b3294f8727a932
468,552
def get_col(model, attribute_name): """Introspect the SQLAlchemy ``model``; return the column object. ...for ``attribute_name``. E.g.: ``get_col(User, 'email')`` """ return model._sa_class_manager.mapper.columns[attribute_name]
a2e81d77e3f0b7c796b3cbc65b0b792049dcf8af
71,200
def parse_ls_tree_line(gitTreeLine): """Read one line of `git ls-tree` output and produce filename + metadata fields""" metadata, filename = gitTreeLine.split('\t') mode, obj_type, obj_hash, size = metadata.split() return [filename, mode, obj_type, obj_hash, size]
0c32b850ed5951bcf888194894682ad9aab10e2c
341,539
def parent(n: int) -> int: """Return the index of the parent of the node with a positive index n.""" return (n - 1) // 2
b2b9451d00124665fd7443b6fe663f24ba6d7fc7
680,812
def determine_paired(args) -> bool: """ Determine whether we should work in paired-end mode. """ # Usage of any of these options enables paired-end mode return bool( args.paired_output or args.interleaved or args.adapters2 or args.cut2 or args.pair_filter or args.untrimmed_paired_output or args.too_short_paired_output or args.too_long_paired_output or args.quality_cutoff2 )
3a79f44fe6bfc59f15b81bb765745abba3ca1277
570,697
def is_number(s): """ Returns True if the string s can be cast to a float. Examples: is_number('1') is True is_number('a') is False is_number('1a') is False is_number('1.5') is True is_number('1.5.4') is False is_number('1e-6') is True is_number('1-6') is False Parameter s: The string to test Precondition: s is a string """ try: x = float(s) return True except: return False
a3249fc4ff413353894e7dd2153d2428e5f8b405
511,477
import math def latlon2tms(lat,lon,zoom): """ Converts lat/lon (in degrees) to tile x/y coordinates in the given zoomlevel. Note that it doesn't give integers! If you need integers, truncate the result yourself. """ n = 2**zoom lat_rad = math.radians(lat) xtile = (lon+ 180.0) / 360.0 * n ytile = (1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n return (xtile, ytile)
f4c238ad3af7635f6a812021cc38744a73a0a437
631,003
import re def get_thesis_description(thesis): """ The description exists in two parts: one that is shown and one that is hidden (must be expanded to see). The structure of the second part varies, and thus we must make the way of extraction generic. Return: The entire description of a given master thesis. """ desc_first_part = thesis.find("p").text desc_second_part = "" # Not every thesis has a hidden description try: desc_second_part_raw = thesis.find_all("div")[1] # Remove the "Skul besrkivelse" anchors desc_second_part_raw = desc_second_part_raw.find_all()[:-2] desc_second_part = [tag.text.strip() for tag in desc_second_part_raw] desc_second_part = [re.sub(r"[\n]", ". ", text) for text in desc_second_part] except IndexError: pass desc = desc_first_part + " " + " ".join(desc_second_part) return desc
46db952a928b85767cde573830e7808f9af20276
170,533
import torch def calculate_dihedrals(p, alphabet): """Converts the given input of weigths over the alphabet into a triple of dihederal angles Args: p: [BATCH_SIZE, NUM_ANGLES] alphabet: [NUM_ANGLES, NUM_DIHEDRALS] Returns: [BATCH_SIZE, NUM_DIHEDRALS] """ sins = torch.sin(alphabet) coss = torch.cos(alphabet) y_coords = p @ sins x_coords = p @ coss return torch.atan2(y_coords, x_coords)
381add4de653ba30b1049248666296520530a539
625,103
def _getHierBenchNameFromFullname(benchFullname): """ Turn a bench name that potentially looks like this: 'foodir/bench_algos.py::BenchStuff::bench_bfs[1-2-False-True]' into this: 'foodir.bench_algos.BenchStuff.bench_bfs' """ benchFullname = benchFullname.partition("[")[0] # strip any params (modName, _, benchName) = benchFullname.partition("::") if modName.endswith(".py"): modName = modName.partition(".")[0] modName = modName.replace("/", ".") benchName = benchName.replace("::", ".") return "%s.%s" % (modName, benchName)
c9bbc6882f2c702a110d1b81b8c47eace72409b9
60,731
def splitIssue(str, delim): """ Converts issue string (separated by delimiter) into issue array """ if((str == str) & (str is not None)): return(str.split(f"{delim} ")) else: return([])
f8b2062ffa76ee940ce17f208cae5a2226778c14
514,594
def get_localized_name(name): """Returns the localizedName from the name object""" locale = "{}_{}".format( name["preferredLocale"]["language"], name["preferredLocale"]["country"] ) return name['localized'].get(locale, '')
efa32f51bf89d1f2262a225dcfb13ea3ae2fedbc
648,509
def parse_team_links(response): """Parse the links to individual teams from a franchise page to get injury reports.""" years = response.css('th[data-stat=year_id] a::text').getall() links = response.css('th[data-stat=year_id] a::attr(href)').getall() # Injury reports are only available from 2009 onwards. return [link for year, link in zip(years, links) if int(year) >= 2009]
a12b90e69330c977c6f4ab2e0313c80238ab1967
595,765
def url_file_name(url: str) -> str: """ Extract file name from url (last part of the url). :param url: URL to extract file name from. :return: File name. """ return url.split('/')[-1] if len(url) > 0 else ''
38ea970f26f439119ad8bb8312ff9e393bf7e431
629,384
def arrayCheck(nums): """ Function to find a sequence 1, 2, 3. Given a list of integers, return True if the sequence of numbers 1, 2, 3 appears in the list somewhere. Args: nums (Array): Array of integer """ for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3: return True return False
22b871e12e49fbd215ca517ff1071d38f06c26cc
625,685
def traverse_map(input_map, right=3, down=1): """Travel down the input map by heading right and down a fixed amount each iteration. The map consists of clear ground '.', and trees '#'. The map repeats to the right infinitely. Get the number of trees that would be encountered travelling from the top left at the specified slope. :param input_map: A list of lines consisting of '.'s and '#'s. :param right: The number of grid spaces to move right each iteration :param down: The number of grid spaces to move down each iteration :return: int """ tree_count = 0 x_axis = 0 for line in input_map[::down]: if line[x_axis % len(line)] == "#": tree_count += 1 x_axis += right return tree_count
9844c795581e285f26e81258f19381efb0a705ba
636,047
def _custom_formatargvalues( args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value)): """Copied from inspect.formatargvalues, modified to place function arguments on separate lines""" def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): return formatarg(name) + formatvalue(locals[name]) specs = [] for i in range(len(args)): specs.append(convert(args[i])) if varargs: specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) result = '(' + ', '.join(specs) + ')' if len(result) < 40: return result else: # Put each arg on a separate line return '(\n ' + ',\n '.join(specs) + '\n)'
644568f56f51f1287790b472693dd08b80f8728f
128,850
def wrap_lines(lines, width=80, sep=' ', ellipsis="...", force_ellipsis=False, rjust_ellipsis=False): """ Wraps given list of lines into a single line of specified width while they can fit. Parts are separated with sep string. If first line does not fit and part of it cannot be displayed, or there are other lines that that cannot be displayed, displays ellipsis string at the end (may squeeze line even more to fit into max width). If rjust_ellipsis=True, puts ellipsis at the rightest possible position, filling gaps with spaces. Otherwise sticks it to the text. Returns pair (<number of lines displayed>, <result full line>). If first line does not fully fit and some part of it cannot be displayed, first number in the pair will be negative and it's abs will be equal to amount of characters that are displayed. """ if not lines: return 0, None if not force_ellipsis and len(lines) == 1 and len(lines[0]) <= width: return 0, lines[0] result = lines[0] if len(result) + len(ellipsis) > width: result = result[:width-len(ellipsis)] + ellipsis return -(width - len(ellipsis)), result to_remove = 1 while len(lines) > to_remove and len(result) + len(sep) + len(lines[to_remove]) + len(ellipsis) <= width: result += sep + lines[to_remove] to_remove += 1 if not force_ellipsis and len(lines) == to_remove: to_remove = 0 if to_remove: if rjust_ellipsis: result = result.ljust(width-len(ellipsis)) result += ellipsis return to_remove, result
ecf2dac1c693687b19c058f13187ba1a4968c0de
54,911
def calculate_weight_per_week(data) -> float: """Reads a list that stores a week's worth of data to calculate and return average weight per week""" total = 0 day = len(data) for index, weight in enumerate(data): total += weight[2] return total / day
5a5cd9adc1a127deba9d8fe46fbcbe4ba365f5e5
373,292
def _get_ipaddr(req): """ Return the ip address for the current request (or 127.0.0.1 if none found) based on the X-Forwarded-For headers. """ if req.access_route: return req.access_route[0] else: return req.remote_addr or '127.0.0.1'
5f9d2af65428f752aa998346c6eb10b359ad8032
85,765
def substr_match(a, b): """ Verify substring matches of two strings. """ if (a is None) or (b is None): return False else: return a in b
9b98d14b6ec5f2ab433eea92d377b5e1477fef64
13,535
from typing import Callable from typing import Any import inspect async def maybe_coroutine(func: Callable, *args, **kwargs) -> Any: """Allows running either a coroutine or a function.""" if inspect.iscoroutinefunction(func): return await func(*args, **kwargs) else: return func(*args, **kwargs)
8ac38b41863aa73fdd4534032d45d3a2f56770d2
259,412
def _footer(settings): """ Return the footer of the Latex document. Returns: tex_footer_str (string): Latex document footer. """ return "\n\n\end{tikzpicture}\n\end{document}"
a1d8d884e1a5e028ec2139f68f8a499b460785b6
547,682