content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def transpose_callable(f): """Returns a callable whose output is the transposed of the input callable.""" def transposed(x): return f(x).T return transposed
5a3caa3b5f7b98f1cdfe0271ecd8dd6607f1dd66
670,329
from typing import List def unsentencise(ts: List[str]) -> str: """Join a list of sentences into a string""" return ". ".join(ts)
40521539359a08f5544d3fb9bc0a7d58c45ebbb7
670,330
import yaml def load_yaml(config_path): """Tries to load a config file from YAML. """ with open(config_path) as f: return yaml.load(f, Loader=yaml.FullLoader)
a24328da04e4a7c42aff5a3eaa7ff552b5e96d85
670,331
def eval_median_spend(simulation): """median spend metric for current trial Returns: float: Median real spending for current trial """ return simulation.latest_trial.trial_df['spend'].median()
063efe44b8daf0357a99a6c41d565144745084f7
670,332
from datetime import datetime import json def sfn_run(session, arn, input_={}): """Start executing a StepFunction Args: session (Session): Boto3 session arn (str): ARN of the StepFunction to execute input_ (Json): Json input data for the first state to process Returns: st...
d47b84ce707e6d7d2ead95be078e879860c23731
670,334
from typing import List from typing import Dict from typing import Any import itertools def chain(*configs: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Chain given iterable config dictionaries.""" chained_configs: List[Dict[str, Any]] = list() for instance in itertools.product(*configs): mer...
bc1f087a8212b8071c345c1594d6324f2531cd0b
670,337
import torch def batch_randint(start, batch_end): """ Sample k from start to end (both inclusive) Return the same shape as batch_end """ return start + (torch.rand_like(batch_end.float()) * (batch_end - start + 1).float()).long()
e2591aae46618223724d4b1560f7c287fa51cffb
670,339
def extract_email(msg): """Extract all the interesting fields from an email""" msg_obj = {} msg_obj["from"] = msg.getheaders('From')[0] msg_obj["to"] = msg.getheaders('To')[0] msg_obj["subject"] = msg.getheaders('Subject')[0] msg_obj["date"] = msg.getheaders('Date')[0] msg_obj["contents"] = ...
1ed737fb280fd999beade57a46202380d4e9fa6a
670,350
import re def has_timestamp(text): """Return True if text has a timestamp of this format: 2014-07-03T23:30:37""" pattern = r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}' find = re.findall(pattern, text) return bool(find) pass
d17aeae04061feb5aacb60e946912d08914a3339
670,353
def get_words(message): """Get the normalized list of words from a message string. This function should split a message into words, normalize them, and return the resulting list. For simplicity, you should split on whitespace, not punctuation or any other character. For normalization, you should conver...
e365e5b2ff4dad072eba66bcbd299d704272f9cf
670,356
def book_name_strings(bk): """Returns a list of the named range names in as workbook. Arguments: bk {xw.Book} -- Workbook to retrieve list from. Returns: list -- named range names. """ return [nm.name for nm in bk.names]
7fb4f35018d840e7fc1369993fcecf54e594cf83
670,360
def get_text(elem, name, default=None): """Retrieve text of an attribute or subelement. Parameters ---------- elem : xml.etree.ElementTree.Element Element from which to search name : str Name of attribute/subelement default : object A defult value to return if matching a...
a17a92b16831ac7ff793cab59f2588eb6130afc4
670,362
def harmonic_mapping(fg): """Get all peaks from a FOOOFGroup and compute harmonic mapping on the CFs.""" f_mapping = [] for f_res in fg: cfs = f_res.peak_params[:, 0] if len(cfs) > 0: f_mapping.append(list(cfs / cfs[0])) return f_mapping
1878e3cfd3e99d688ec20f5b294a8fe9faaa240c
670,363
def intersect(a, b): """ Return the intersection of two lists. Args: a (list): A list. b (list): Another list. Returns (list): The intersection of the two lists. """ # NOTE: Binary operator '&' is built in and returns the intersection of 2 sets. ret...
b0e0ac8160ed9fc16c27a8352992e64e1612d642
670,366
def bgr_to_rgb(bgr): """Converts Blue, Green, Red to Red, Green, Blue.""" return bgr[..., [2, 1, 0]]
27e359732cfac4fdf553e1e2445c25fe1d5d8e89
670,367
def torchcrop(x, start_idx, crop_sz): """ Arguments --------- x : Tensor to be cropped Either of dim 2 or of 3 start_idx: tuple/list Start indices to crop from in each axis crop_sz: tuple/list Crop size Returns ------- cropped tensor """ dim = len(x.s...
f7a3ef0eb2e81bb77d194b0e04d8c504979475d7
670,369
def round_int(x, *, ndim=0): """ 先四舍五入,再取整 :param x: 一个数值,或者多维数组 :param ndim: x是数值是默认0,否则指定数组维度,批量处理 比如ndim=1是一维数组 ndim=2是二维数组 >>> round_int(1.5) 2 >>> round_int(1.4) 1 >>> round_int([2.3, 1.42], ndim=1) [2, 1] >>> round_int([[2.3, 1.42], [3.6]], ndim=2) [[2...
36bb8dfe22bc1a14c0c882b5b30453ab37890b37
670,377
def get_river_config(fileName, noisy=False): """ Parse the rivers namelist to extract the parameters and their values. Returns a dict of the parameters with the associated values for all the rivers defined in the namelist. Parameters ---------- fileName : str Full path to an FVCOM R...
5751456eda34c8f9fc2c134515cc420b156c2d17
670,378
from typing import Union from typing import List def list_over(obj: Union[list, str], n: int) -> List[str]: """ Return a list of strings of length greater than n in obj, or sublists of obj, if obj is a list. If obj is a string of length greater than n, return a list containing obj. Otherwise retu...
c6e26a948ad8decb98c68c0d9cc7f42afea7e7cd
670,383
def prune(d): """If possible, make the multi-valued mapping `d` single-valued. If all value sets of `d` have exactly one member, remove the set layer, and return the single-valued dictionary. Else return `d` as-is. """ if all(len(v) == 1 for v in d.values()): return {k: next(iter(v)) f...
b0c60b00a5bd47d248f558db6d96b8569b9e94bb
670,384
def fn_check_missing_data(df): """check for any missing data in the df (display in descending order)""" return df.isnull().sum().sort_values(ascending=False)
831bf7fca1e1a3863f32cb0dbd169064d85f81e2
670,386
def rotate_square_counter(block, count): """ Return a square block after rotating counterclockwise 90° count times """ for _ in range(count): block = [[block[j][i] for j in range(len(block))] for i in list(reversed(range(len(block))))] block = [''.join(i) for i in block] return block
f15e39891a2f71c5b65881e57bbe844ef2056ebd
670,387
def Finish_to_c(self): """Syntax conversion for breaking a loop.""" return f"goto break_{self.targetID};"
0ca45ac96bbeae75c0bbeead4383efa96d3ee00a
670,389
def key_by_id(mapping): """ Converts arrays to hashes keyed by the id attribute for easier lookup. So [{'id': 'one', 'foo': 'bar'}, {'id': 'two', 'foo': 'baz'}] becomes {'one': {'id': 'one', 'foo': 'bar'}, 'two': {'id': 'two', 'foo': 'baz'}} """ if isinstance(mapping, list) and isins...
87a6af2e2d0662ce58cc00ad5025acd9359e7f42
670,392
def _match_tags(repex_tags, path_tags): """Check for matching tags between what the user provided and the tags set in the config. If `any` is chosen, match. If no tags are chosen and none are configured, match. If the user provided tags match any of the configured tags, match. """ if 'any' ...
b9434c29679b98810f357282c2b42e4b318a62df
670,393
import string def isalphanum(word): """ This function returns true if a word contains letters or digits :param word: A string token to check :return: True if the word contains letters or digits """ for char in word: if char not in string.ascii_letters and char not in string.digits: ...
ca65885ae38437cb22c68ca1b360467fe00e9a84
670,396
def read_fp(filename, dtype=int): """ read fingerprint from file Args: filename: <type 'str'> Return: chembl_id_list: <type 'list'>, a list of str fps_list: <type 'list'>, a list of dict. """ chembl_id_list = [] fps_list = [] infile = open(filename, "r") line_num = 0 for line in infile: ...
29ebee689937a8954aa9f3130bd8b9ee3b0c18fc
670,398
def stmt_from_rule(rule_name, model, stmts): """Return the source INDRA Statement corresponding to a rule in a model. Parameters ---------- rule_name : str The name of a rule in the given PySB model. model : pysb.core.Model A PySB model which contains the given rule. stmts : lis...
1defd6b6f4f013c3ae5fc41bbda6e271fb6b4d0d
670,400
import string import random def get_alphanumeric_string(str_length, **kwargs): """Get random alpha numeric string, default is lowercase ascii chars Available kwargs (in order of precedence*): uppercase_only = default is False mixed_case = default is False digits_only = default is Fals...
0242a3ad9c7fec2a9a1b068d9ebccf3db1fa5a5a
670,402
import mpmath def mode(p, b, loc=0, scale=1): """ Mode of the generalized inverse Gaussian distribution. The mode is: p - 1 + sqrt((p - 1)**2 + b**2) loc + scale ------------------------------- b """ p = mpmath.mpf(p) b = mpmath.m...
7091cf76ba01c8c7e388f82a112fc207f5cdeae7
670,403
import torch def kl_divergence_mc( q_distrib: torch.distributions.Distribution, p_distrib: torch.distributions.Distribution, z: torch.Tensor ): """Elementwise Monte-Carlo estimation of KL between two distributions KL(q||p) (no reduction applied). Any number of dimensions works via broadcasting and correc...
1a1c0a14f13f4ed705608f37b2c4f00f67a1cbaa
670,406
def _get_test_type(item): """ Gets the test type - unit, functional, integration, based on the directory that the test is in. """ return item.nodeid.split('/')[1]
54e01a182042d9a3db9942843ee85108a4d27547
670,407
def _dummy_get_parameter(tree_info, extra_config): """ Dummy function used to return parameters (TreeEnsemble converters already have parameters in the right format) """ return tree_info
9d30a08177d04de84070db0778772b23efa15e2a
670,409
def bubble_sort(a: list): """Optimized Bubble sort that return sorted list with O(n^2) complexity""" a, n = a.copy(), len(a) for _ in range(n): is_swap = False for i in range(1, n): if a[i-1] > a[i]: is_swap = True a[i-1], a[i] = a[i], a[i-1] ...
da200df35cad0856c2b290a1119a1ccea9f6ce03
670,410
def calc_bfdp(bf, prior): """ Calculate BFDP for a single gene per Wakefield, AJHG, 2007 """ # Wakefield phrases prior as probability of no effect, so we need to invert prior = 1 - prior po = prior / (1 - prior) bftpo = bf * po bfdp = bftpo / (1 + bftpo) return bfdp
d2da81abb009b70c45b7fdcc43ee48220f25526a
670,411
def fnsplit(fn): """/path/fnr.x -> (/path/fnr, x) when possible. Non-str treated as None.""" if not (isinstance(fn, str) and fn): return (None, None) fn = fn.strip() if not fn: return (None, None) x = fn.rfind('.') if x == -1: return fn, None return (fn[:x], fn[x:])
c2813b4ded84d7121ad45532e36c97dbd8463aaa
670,413
def pluralize(s, count): #=============================================================================== """ Return word with 's' appended if the count > 1. """ if count > 1: return '%ss' % s return s
2587ee2fe4ea7d8405345572acd9d0fe01a6aa15
670,414
def isfile_s3(bucket, key: str) -> bool: """Returns T/F whether the file exists.""" objs = list(bucket.objects.filter(Prefix=key)) return len(objs) == 1 and objs[0].key == key
e5ded8c24764a0d8d0c9b84aa96ee16db688c8c1
670,416
def filepaths(filesets): """ Return a list of filepaths from list of FileSets """ filepaths = [] for fs in filesets: filepaths += fs.files return filepaths
4fa6efea0ebf9bc49ababf050fa38d549770045b
670,419
def agent_slot(occupants, a_id, t): """Return the slot agent with id a_id occupied in round t, or -1 if a_id wasn't present in round t""" agents = occupants[t] if a_id in agents: return agents.index(a_id) else: return -1
c38b0e77276cdc35d1dfbd99a306cd31af5f7704
670,420
def __ensure_suffix(t, suffix): """ Ensure that the target t has the given suffix. """ tpath = str(t) if not tpath.endswith(suffix): return tpath+suffix return t
392bf04404e2d739c676ede578410db34d232789
670,424
def _numlines(s): """Returns the number of lines in s, including ending empty lines.""" # We use splitlines because it is Unicode-friendly and thus Python 3 # compatible. However, it does not count empty lines at the end, so trick # it by adding a character at the end. return len((s + 'x').splitline...
440f4b2ae03e4b77d057bc01443e6c8f1c83c318
670,430
def get_second_offset(time): """ Get second offset from time. @time: Python time object in 24 hour format. """ return time.hour * 3600 + time.minute * 60 + time.second
80ead4d1a7ca4942eb5ce0980488880f60b32b75
670,436
def num(s): """ convert a string to integer or float :param s: a string of number :return: an int or float type number """ try: return int(s) except ValueError: return float(s) else: raise ValueError('Expected integer or floating point number.')
8d2585ae0c53dfd27f75edef59bab67e68293fc2
670,440
def normalize_typename(typename: str) -> str: """ Drop the namespace from a type name and converts to lower case. e.g. 'tows:parks' -> 'parks' """ normalized = typename if ":" in typename: normalized = typename.split(":")[1] return normalized.lower()
360b0341e9c7adc3741466855b15925b8ca191ba
670,442
def xyzw2wxyz(xyzw): """Convert quaternions from XYZW format to WXYZ.""" x, y, z, w = xyzw return w, x, y, z
6a092c0f6075c5d14198a7d092cb6b30a1fb0754
670,443
def check_related_lot_status(tender, award): """Check if related lot not in status cancelled""" lot_id = award.get('lotID') if lot_id: if [l['status'] for l in tender.get('lots', []) if l['id'] == lot_id][0] != 'active': return False return True
6b4aeb76ee938de434f646913a196162e903df8e
670,445
def decode_rle(input): """ Gets a stream of data and decompresses it under a Run-Length Decoding. :param input: The data to be decoded. :return: The decoded string. """ decode_str = "" count = "" for ch in input: # If not numerical if not ch.isdigit(): # ...
25de4f7756aefdfedfd3779040918f8b58c14d19
670,446
import itertools def flatten(list_of_lists): """Flatten one level of nesting.""" return itertools.chain.from_iterable(list_of_lists)
1019d7f084e7d01db5e49e455123811dfae1ee2f
670,450
import six def get_model_label(model): """ Take a model class or model label and return its model label. >>> get_model_label(MyModel) "myapp.MyModel" >>> get_model_label("myapp.MyModel") "myapp.MyModel" """ if isinstance(model, six.string_types): return model else: ...
3031b8facf621b266328917dc5cd49c94856e6a9
670,451
def fst(ls): """returns the 0th element of a list""" return ls[0]
a44d5b883be2117f9dc26be3cedac8f8e4356471
670,453
def get_camera_from_topic(topic): """ Returns the camera name given the image topic. """ topic_split = topic.split('/') return topic_split[2]
63e773b45457e99c911941b39be1854668f877df
670,460
from pathlib import Path import json def read_parameters(parameters_file: Path): """This function reads the config file containing the parameters needed for filtering datasets.""" if parameters_file.exists(): with open(parameters_file) as fout: parameters = json.load(fout) else: ...
6f7c1e1fb5a97504669f1c2414505507dc74ad74
670,462
def extract_parts(usage): """Extract individual components from a usage string""" opp = {'{': '}', '[': ']', '(': ')'} cur_word = [] tokens = [] stack = [] for c in usage: if c.isspace() and not stack: if cur_word: tokens.append(''.join(cur_word)) ...
de4040207d06fd309bea14260f2ef03ac5dc2e5a
670,464
def array_chunk(array, size): """ Given an array and chunk size, divide the array into many subarrays, where each subarray is of length size. array_chunk([1,2,3,4], 2) --> [[1,2], [3,4]] array_chunk([1,2,3,4,5], 2) --> [[1,2], [3,4], [5]] """ counter = 0 outer_list = [] inner_lis...
7ec1e40c8306dc256387292421474ee9e037568b
670,466
def time_minutes(dt): """Format a datetime as time only with precision to minutes.""" return dt.strftime('%H:%M')
93288a8f0204dd56c59b18b75c62a5c1e059e159
670,469
import re def offset(text): """Returns index of first non-whitespace character. Args: text (str): string to be analyzed for whitespaces. Returns: index (int): index of first non-whitespace character; -1 if none found. """ index = 0 # Assume first character is not a whitespace ...
4dc17c73dd5098e56c12781f1aafc7816ddba0a5
670,470
def WithChanges(resource, changes): """Apply ConfigChangers to resource. It's undefined whether the input resource is modified. Args: resource: KubernetesObject, probably a Service. changes: List of ConfigChangers. Returns: Changed resource. """ for config_change in changes: resource = co...
4e0db8a71b24146e0ef5d18c65e71ac12e500fef
670,472
import binascii def encode(bs): """Given a bytes object, return a Base64-encoded version of that object, without newlines.""" return binascii.b2a_base64(bs, newline=False).decode("utf-8").rstrip()
c19d4c93df608ec1656c846e163cbfe726bbb219
670,476
import re def is_tns_name(name: str): """ Checks if a string adheres to the TNS naming scheme """ return re.match("^AT|SN(19|20)\d\d[a-z]{3,4}$", name)
5d003431aa35946b4dcf4ab918a4e2d92428af75
670,477
def normalize_wiki_text(text): """ Normalizes a text such as a wikipedia title. @param text text to normalize @return normalized text """ return text.replace("_", " ").replace("''", '"')
ec3855b8661ae67abc6ca84d03634ff48437ad58
670,483
from typing import Any from typing import Union def try_parse_int_float_str(candidate: Any) -> Union[float, int, str]: """ Tries to parse the given value as an int or float. If this does not work simply the string-representation of the candidate will be returned. Examples: >>> res = try_parse...
2a356253cf55c429e1ac9cfdfd31eaaef54037e9
670,484
def find_edf_events(raw): """Get original EDF events as read from the header. For GDF, the values are returned in form [n_events, pos, typ, chn, dur] where: ======== =================================== ======= name description type ======== ================...
6015da7468ae92b4a12a13122682a3d47db3d831
670,485
def buildup_function(p, E_max, p_half): """Calculate asymptotic buildup curve Args: p (array): power series E_max (float): maximum enhancement p_half (float): power at half saturation Returns: ndarray: buildup curve .. math:: f(p) = 1 + E_{max} * p / (p_{1/2} +...
bdc43e2fd12336ee0b415c4d574f2a62a5555217
670,486
def plot_hsu(hst, models, max_speed, pressure_charge, max_pressure): """ For the given HST computes the sizes, efficiencies and plots the efficiency map. Returns: --- fig: plotly figure object """ hst.compute_sizes() hst.compute_speed_limit(models['pump_speed']) hst.add_no_load((180...
0e2b5db439ce4c102d06a58f02c2483e00d3263d
670,487
def format(dt, fmt = "dt", simplified = True): """Format a datetime object. Use a python :py:class:`datetime.datetime` object and convert it to a string, wrapping the :py:meth:`datetime.datetime.strftime` method. For convenience, enable the interpretation of a simpler syntax for common and default ...
8b5f86b91f9d617bcc931c2f6e43aee9f3921915
670,489
import mpmath def _fmod(x, y): """ returns x - n * y, where n is the quotient of x / y, rounded towards zero to an integer. """ fquot = mpmath.mpf(x) / y if fquot < 0: n = -mpmath.floor(-fquot) else: n = mpmath.floor(fquot) return x - n * y
51ba5b89ba0f0409ae70c39e31e7cbacdbfcd3c2
670,490
def count_in_list(my_list, count_for=1): """ Gets the count of a certain value in a list. Args: my_list (list of obj): The list to search through. count_for (obj): The object to count. Returns: int: The number of that object """ count = 0 for item in my_list...
6cd59227fc7f6a08f254970a5495bd705d464597
670,497
def pool_sku(config, lower=False): # type: (dict, bool) -> str """Get Pool sku :param dict config: configuration object :param bool lower: lowercase return :rtype: str :return: pool sku """ sku = config['pool_specification']['sku'] return sku.lower() if lower else sku
6049ac4ec80e452bf2f6c8405e1d0085e230c668
670,504
def filter_latest_builds(builds): """Filters Build objects to include only the latest for each builder. Args: builds: A collection of Build objects. Returns: A list of Build objects; only one Build object per builder name. If there are only Builds with no build number, then one is ...
e1ecc4a5bb8ced67a6913c1a7662d52ad03fc84e
670,506
def checksum(number, alphabet='0123456789'): """Calculate the Luhn checksum over the provided number. The checksum is returned as an int. Valid numbers should have a checksum of 0.""" n = len(alphabet) number = tuple(alphabet.index(i) for i in reversed(str(number))) return (sum(nu...
a40fb8175bbd8aa4d1185e3ad3765f62db89df95
670,508
def racks_for_replica_list(replicas, pos=None): """ Returns a set of racks for each of the given replicas in the list Skip the replica at position pos, if specified :params replicas: a list of Broker objects :params pos: a replica position to skip, or None to not skip a replica :returns: a list...
830d3e9ba1072d6e54bed5c1328f6d20a5346d0b
670,510
def tbody( trContent=""): """ *Generate a table body - TBS style* **Key Arguments:** - ``trContent`` -- the table row content **Return:** - ``tbody`` -- the table body """ tbody = """<tbody class="">%(trContent)s</tbody>""" % locals() return tbody
c4fd63b07aba144205a39e7fd841459bbdbba39f
670,515
def sample_width_to_string(sample_width): """Convert sample width (bytes) to ALSA format string.""" return {1: 's8', 2: 's16', 4: 's32'}[sample_width]
5a08a08d845a1727f206e822045a5619db33347a
670,516
import hashlib def sha256(payload): """This function returns the sha256 of the provided payload""" return hashlib.sha256(payload).digest()
05e5fef168521265c0fdfa0b82ca18930baadef6
670,517
def _generate_snitch_text(cluster): """Generate the text for the PropertyFileSnitch file""" i=1 contents = [ "# Auto-generated topology snitch during cluster turn-up", "#", "# Cassandra node private IP=Datacenter:Rack", "#", "" ] for z in cluster.keys(): contents.append("# Zo...
a37d30101f8588ebc4b32c665834504455b5b93c
670,519
from collections import OrderedDict def readResult(fname): """ Open results file, extract and return minimum point as OrderedDict and return raw list of all other lines for further processing. """ RES=[] OTH=[] with open(fname) as f: for line in f: l=line.strip() ...
81fb8aa081a42a10691e0fedfcb4b727dce407db
670,520
import re def _identifier_for_name(name, *reserveds): """Makes an identifier from a given name and disambiguates if it is reserved. 1. replace invalid identifier characters with '_' 2. prepend with '_' if first character is a digit 3. append a disambiguating positive integer if it is reserved :p...
e75089624367e2f6bde9a6e7ac1f8657222efc2d
670,521
import mpmath def var(lam): """ Variance of the Poisson distribution. """ return mpmath.mpf(lam)
601c5e800bdb94e2c30c51eab84e8569b378b000
670,524
def scale_to_range(min_max_old, element, min_max_new=[0, 10]): """Scale element from min_max_new to the new range, min_max_old. Args: min_max_old: Original range of the data, [min, max]. element: Integer that will be scaled to the new range, must be within the old_range. min...
263f08a7247af4feea9f498bd2ac2a129f949556
670,526
def output_file_version() -> str: """A suffix that is added to output files, denoting a version of the data format""" return 'v5'
713162ae39175fd8cd57ea8cb176c5970cf758b9
670,528
def _GetBrowserPID(track): """Get the browser PID from a trace. Args: track: The tracing_track.TracingTrack. Returns: The browser's PID as an integer. """ for event in track.GetEvents(): if event.category != '__metadata' or event.name != 'process_name': continue if event.args['name'] =...
1e9a5900a4cd9930f8c634c8f0a932eae4873764
670,531
def mean(x1, x2): """Integer average.""" return (x1 + x2)/2
a4f8a0df5d90bd8cde5b37682c7ca2a2e7e8a602
670,532
def get_time(seconds): """Returns human readable time format for stats.""" m, s = divmod(seconds, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) return "%dd:%dh:%02dm:%02ds" % (d, h, m, s)
1a1c5439dabcfbde4d78c6aeccff4472a9b45f0a
670,533
def manage_time(timestamp): """ Given the string representation of a the time using the "minutes:seconds[:miliseconds]" representation, returns the number of seconds using double precision """ time_strip = timestamp.split(":") seconds = int(time_strip[0]) * 60 + int(time_strip[1]) # Ad...
8782a2c49c70cfd6a3c4f2869c71f86a3576c2ec
670,536
import json def parse_genres(movie): """ Convert genres to a dictionnary for dataframe. :param movie: movie dictionnary :return: well-formated dictionnary with genres """ parse_genres = {} g = movie['genres'] with open('genre.json', 'r') as f: genres = json.load(f) for k...
079221e858868fdc4db250bb8b2fc7046efb213d
670,538
def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(2...
d77bbd977777960650b06ee804dd30891cb665b9
670,543
import math def distance(point_a, point_b): """ Returns the distance between two points given as tuples """ x0, y0 = point_a x1, y1 = point_b return math.hypot(x0 - x1, y0 - y1)
d41cec3978ea62b3b93e1e64b1f1103bce88d231
670,544
def estimate_clipping_rect(projector, size): """ Return: rect -- NSRect style 2d-tuple. flipped (bool) -- Whether y-axis is flipped. """ # lt -> rt -> lb -> rb image_corners = [(0, 0), (size[0], 0), (0, size[1]), size] x_points = [] y_points = [] for corner in image_corners: ...
10ba33b415913b72dd46a9a367ebe0fcf377789a
670,545
def flatten(nested): """ flattens a nested list >>> flatten([['wer', 234, 'brdt5'], ['dfg'], [[21, 34,5], ['fhg', 4]]]) ['wer', 234, 'brdt5', 'dfg', 21, 34, 5, 'fhg', 4] """ result = [] try: # dont iterate over string-like objects: try: nested + '' except(TypeError): pass else:...
3634057e2dbae0ef98fd215cd810ff314667dc80
670,552
from typing import Tuple from typing import Callable import hashlib from typing import Union def _hash( tpl: Tuple, hash_function: Callable = hashlib.sha1, as_int: bool = True ) -> Union[str, int]: """Deterministic hash function. The main use here is providing a `commit_hash` for a Dataset to compare acro...
35d52babd68f6b79b929fac2d9b113c599fc2ba7
670,553
def generate_sequence(lst: list[int]) -> list[int]: """Return a new list that contains the sequence of integers between the minimum and maximum of lst, inclusive. When the minimum and maximum of lst are the same, the list should only contain one element. Assume that len(lst) >= 1. >>> generate_se...
86a84dfe0825550d2b227e29e9906cd361c592a4
670,558
import math def euclidean_distance(p, q): """ Computes the distance between two points p and q. """ return math.sqrt((p[0] - q[0])**2 + (p[1] - q[1])**2)
6e460743b8171e1ca8ca780e26c3b5e440dd4b79
670,561
def _normalize_image_id(image_id): """ The image IDs we get back from parsing "docker build" output are abbreviated to 12 hex digits. In order to compare them to the ids we get from "docker.Client.images()" calls, we need to normalize them """ if image_id is None: return None if ima...
5f64666ab15273e3853f8978918effeab12c9c89
670,566
import torch def mask_fill( fill_value: float, tokens: torch.Tensor, embeddings: torch.Tensor, padding_index: int, ) -> torch.Tensor: """ Function that masks embeddings representing padded elements. :param fill_value: the value to fill the embeddings belonging to padded tokens. :param...
e89e2a0f807765694ff68109b7d1a5adfec0297b
670,567
def _average(value_a: float, num_a: int, value_b: float, num_b: int) -> float: """Compute a weighted average of 2 values with associated numbers.""" divisor = num_a + num_b if divisor == 0: return 0 else: return float(value_a * num_a + value_b * num_b) / divisor
c2326ae7e17c556abfd2de493707b88e528effbf
670,571
def average(lst): """ Calculates the average of a given list :param lst: list of numbers :return: average value """ return sum(lst) / len(lst)
aa84f1de98cca31d84ab0e3e2a77a22d46ad622f
670,574
def getChunks(dsets,nbchunks): """ Splits dataset object into smaller chunks Parameters: * dsets (dict): dataset * nbchunks (int): number of data chunks to be created Returns: * dict: chunks from dataset stored as dictionaries """ ret = [] for ichunk in range(nbchunks): datagrp = {} f...
d693ad68b142816b5d43bde37f01d757ced60298
670,579
def from_rgb(rgb): """translates an rgb tuple of int to a tkinter friendly color code """ r, g, b = rgb return f'#{r:02x}{g:02x}{b:02x}'
7bf6494dfc98b43912c2f44cf97801da86b21b1d
670,580
import math def printAngle(angle): """Generate angle line Parameters ---------- angle : Angle Object Angle Object Returns ------- angleLine : str Angle line data """ k0 = angle.K0*8.3680 angle0 = math.radians(angle.angle0) return '<Angle class1=\"%s\...
ce6f32021fb99faeb8a344e4da00cfab938658ce
670,585