content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def sign(input, *args, **kwargs): """ Returns a tree of new tensors with the signs of the elements of input. Examples:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.sign(ttorch.tensor([12, 0, -3])) tensor([ 1, 0, -1]) >>> ttorch.sign(ttorch.tensor({ ... 'a': [12, 0, -3], ... 'b': {'x': [[-3, 1], [0, -2]]}, ... })) <Tensor 0x7f1c81d02d30> β”œβ”€β”€ a --> tensor([ 1, 0, -1]) └── b --> <Tensor 0x7f1c81d02a60> └── x --> tensor([[-1, 1], [ 0, -1]]) """ return torch.sign(input, *args, **kwargs)
768b4a6a4d12d4f7de5854c060fe1d7a494e8e6a
21,396
def _get_included_folds(folds, holdout_index = None): """ Returns a list that contains the holds to include whe joining. If a holdout index is specified, it will not be included. :param folds: the folds to join :param holdout_index: an index to holdout :return: the folds to use when joining """ return [folds[index] for index in range(len(folds)) if index != holdout_index]
f6715734620d3acbb43fc1146b84d312199ad741
21,398
def determine_colors(percentage): """ Determine the color of the duplicated section. The color depends on the amount of code duplication. """ colors = [] if 3 >= percentage > 0: colors.append("rgb(121, 185, 79)") elif 5 >= percentage > 3: colors.append("rgb(255, 204, 5)") elif 20 >= percentage > 5: colors.append("rgb(251, 135, 56)") else: colors.append("rgb(204, 5, 5)") colors.append("rgb(121, 185, 79)") return colors
3b9aa1071476a34c30fef274fb2a0d86f3eeb687
21,399
def equal_near(item_1: float, item_2: float, thresold: float = 0.1) -> bool: """Is two item close to equl? Return True is difference less than thresold. Args: item_1 (float): First item. item_2 (float): Second item. thresold (float, optional): Thresold for compare. Defaults to 0.01. Returns: bool: Return True if difference less than thresold. """ return abs(1 - (item_1 / item_2)) < thresold
e9d61f1e14d7c09a42444d32da19e0d81be56af2
21,403
import itertools def reject(iterable, conditional=None): """ Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter. params: iterable, conditional iterable -> list, sequenece, set, dictionary, generator etc conditional -> a lambda or function that takes one or two inputs, first is element from iterable, second is index (optional) Examples: >>> odds = _.reject([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0) >>> list(odds) >>> [1,3,5] """ return itertools.filterfalse(conditional, iterable)
02baa409454d20c07e328b669014768fdd971e5c
21,407
def build_msg(request, msg_type, name, drink): """Personalize SMS by replacing tags with customer info""" msg = request.form.get(msg_type) msg = msg.replace('<firstName>', name) msg = msg.replace('<productType>', drink) return msg
2a22f1b48717d9a874e2397791f734fce483e703
21,410
def _pascal_case_to_underscore_case(value: str) -> str: """ Converts a pascal case string (e.g. MyClass) into a lower case underscore separated string (e.g. my_class). """ result = "" state = "initial" partial = "" for char in value: if "A" <= char <= "Z": if state == "initial": state = "upper" elif state == "upper": state = "multi-upper" else: if result: result += "_" result += partial partial = "" state = "upper" partial += char.lower() else: if state == "multi-upper": if result: result += "_" result += partial partial = "" partial += char state = "lower" if result: result += "_" result += partial return result
540d4b7525424d3e2f40f52d357fcb6c94b77d52
21,416
import struct def read_uint32(fp, pos): """Read 4 little-endian bytes into an unsigned 32-bit integer. Return value, position + 4.""" fp.seek(pos) val = struct.unpack("<I", fp.read(4))[0] return val, pos + 4
2b2f4fa99bc480aae5eb8bc8602f1c11aa775031
21,418
import collections def process_types(mrsty_file): """Reads UMLS semantic types file MRSTY.2019.RRF. For details on each column, please check: https://www.ncbi.nlm.nih.gov/books/NBK9685/ """ cui_to_entity_types = collections.defaultdict(set) with open(mrsty_file) as rf: for line in rf: line = line.strip() if not line: continue # Each line is as such: # 'C0000005|T116|A1.4.1.2.1.7|Amino Acid, Peptide, or Protein|AT17648347|256| # CUI|TUI|STN|STY|ATUI|CVF # Unique identifier of concept|Unique identifier of Semantic Type|Semantic Type tree number|Semantic Type. The valid values are defined in the Semantic Network.|Unique identifier for attribute|Content View Flag line = line.split("|") e_id = line[0] e_type = line[3].strip() # considering entities with entity types only if not e_type: continue cui_to_entity_types[e_id].add(e_type) return cui_to_entity_types
b20b26f5015abb2ee5ce718eaa83895d4cb4f5e2
21,422
def week_of_year(date): """ Our weeks starts on Mondays %W - week number of the current year, starting with the first Monday as the first day of the first week :param date: a datetime object :return: the week of the year """ return date.strftime("%W")
6de546b23e5cc717b3b0fc357da3af6b4fa1305b
21,425
def append_hostname(machine_name, num_list): """ Helper method to append the hostname to node numbers. :param machine_name: The name of the cluster. :param num_list: The list of nodes to be appended to the cluster name. :return: A hostlist string with the hostname and node numbers. """ hostlist = [] for elem in num_list: hostlist.append(machine_name + str(elem)) return '%s' % ','.join(map(str, hostlist))
d2ff25273a21682ec31febc1e63fbc2f562017c3
21,430
def objsize(obj): """ Returns the size of a deeply nested object (dict/list/set). The size of each leaf (non-dict/list/set) is 1. """ assert isinstance(obj, (dict, list, set)), obj if not obj: return 0 if isinstance(obj, dict): obj = obj.values() elem = next(iter(obj)) if isinstance(elem, (dict, list, set)): return sum(objsize(v) for v in obj) else: return len(obj)
66c792c4799df530cded59c5a006ae251032a2b9
21,433
def reduceDictionary(data: dict): """ This function reduce a dictionary in the case of one only element dict. Eg. a = {"key": value} -> value """ if len(data) == 1: return data[list(data.keys())[0]] else: return data
9165a12bf04601d903fb1b6caed120a193279e30
21,435
from typing import Dict from typing import Any def merge_dict(dict1: Dict[str, Any], dict2: Dict[str, Any] ) -> Dict[str, Any]: """Merge two dictionaries into a third dictionary. Args: dict1: First dictionary to be merged. dict2: Second dictionary to be merged. Returns: A dictionary by merging the two dictionaries. Note that if the two dictionary has the same keys the value of the latter dictionary will be used. """ res = dict1.copy() res.update(dict2) return res
baa64359ab740fcf9689305d091a75fb7c7a0cbc
21,436
def normalise_error_asymptotic(absolute_error: float, scaling_factor: float) -> float: """ Given an error in the interval [0, +inf], returns a normalised error in [0, 1] The normalised error asymptotically approaches 1 as absolute_error -> +inf. The parameter scaling_factor is used to scale for magnitude. When absolute_error == scaling_factor, the normalised error is equal to 0.5 """ if absolute_error < 0: raise ValueError(f'Error to be normalised must be non-negative ' f': {absolute_error}') scaled_error = absolute_error / scaling_factor return scaled_error / (scaled_error + 1)
a3a2a99390acf65b334fc7b2b1d0792c042582fd
21,439
def inverse_clamp(value, liveband): """ Ensures value is in (-∞, -liveband] βˆͺ [liveband, ∞) liveband must be a positive value """ if value > 0: value = max(value, liveband) if value < 0: value = min(value, -liveband) return value
07b0b617e1658bf6534b92360087bd0b150ef731
21,443
import math def normalize_value(x, exponent_min, exponent_max): """ Normalize the input value. Note that this assumes that `allocation: lg2` is used for the color space in the OpenColorIO configuration. :param x: Input value :param exponent_min: Smallest exponent for the input values :param exponent_max: Largest exponent for the input values :return: Normalized value """ return (math.log2(x) - exponent_min) / abs(exponent_max - exponent_min)
808f70446a2e450fd7dfe1df480c696ed38163dd
21,447
def first_word(str): """ returns the first word in a given text. """ text=str.split() return text[0]
73f1efc24c6c68e92b2af824358b0656cfbe278b
21,448
import torch def sinc(x: torch.Tensor): """ Implementation of sinc, i.e. sin(x) / x __Warning__: the input is not multiplied by `pi`! """ return torch.where(x == 0, torch.tensor(1., device=x.device, dtype=x.dtype), torch.sin(x) / x)
2b7fd194a0e5ef8449b88f711312fce9a2d0ba84
21,455
def collisions(distance_list, distance_cutoff): """ Determine if there are any collisions between non-bonded particles, where a "collision" is defined as a distance shorter than 'distance_cutoff'. :param distance_list: A list of distances. :type distance_list: List( `Quantity() <https://docs.openmm.org/development/api-python/generated/simtk.unit.quantity.Quantity.html>`_ ) :param distance_cutoff: The distance below which particles will be considered to have "collisions". :type distance_cutoff: `Quantity() <https://docs.openmm.org/development/api-python/generated/simtk.unit.quantity.Quantity.html>`_ :returns: - collision (Logical) - A variable indicating whether or not the model contains particle collisions. """ collision = False if len(distance_list) > 0: for distance in distance_list: if distance < distance_cutoff: collision = True return collision
cab45e8a2da21b9096656cce7eedce74fdae4d76
21,462
def _get_comparable_seq(seq_i, seq_j, start_phase, end_phase): """ Return the residues of the exon/subexon that can be shared. It takes into account that first/last residue could be different if the start/end phase is different from 0 or -1. >>> _get_comparable_seq("ASMGSLTSSPSSL", "TSMGSLTSSPSSC", 1, 2) ('SMGSLTSSPSS', 'SMGSLTSSPSS') """ if start_phase in [1, 2]: seq_i = seq_i[1:] seq_j = seq_j[1:] if end_phase in [1, 2]: seq_i = seq_i[:-1] seq_j = seq_j[:-1] return seq_i, seq_j
0d309f2c2081e84f7285485577b4edd84aba9635
21,463
from typing import Dict def csv_pep_filter(p, **kwargs) -> Dict[str, str]: """ CSV PEP filter, that returns Sample object representations This filter can save the CSVs to files, if kwargs include `sample_table_path` and/or `subsample_table_path`. :param peppy.Project p: a Project to run filter on """ sample_table_path = kwargs.get("sample_table_path") subsample_table_path = kwargs.get("subsample_table_path") sample_table_repr = p.sample_table.to_csv(path_or_buf=sample_table_path) s = "" if sample_table_repr is not None: s += sample_table_repr if p.subsample_table is not None: subsample_table_repr = p.subsample_table.to_csv( path_or_buf=subsample_table_path ) if subsample_table_repr is not None: s += subsample_table_repr return {"samples.csv": s}
8cadf3f1cf292e6b511bf7d2489ffaa0edf22191
21,464
import torch def onehot_labels(labels: torch.Tensor, n_classes: int): """Convert loaded labels to one-hot form. :param labels: tensor of shape (batch_size x n_cells) with integers indicating class :param n_classes: number of classes :return: tensor of shape (batch_size x n_cells x n_classes) with one-hot encodings """ onehot = torch.zeros((*labels.shape[:2], n_classes), device=labels.device) onehot.scatter_(-1, labels.unsqueeze(-1), 1.0) return onehot
3e27693b62eacf19d1bd996a79e18b82addc91e6
21,465
def list_encoder_factory(type_callable): """ Creates a function encoder that iterates on the elements of a list to apply the specified type_callable format. :param type_callable: type to apply to data :return: function that applies type_callable to a supplied list of data """ def inner(data): return [type_callable(x) for x in data] return inner
6a892956d94e88e24ad738de6a19e2394aa34842
21,470
def hex_to_rgb(value): """Given a color in hex format, return it in RGB.""" values = value.lstrip('#') lv = len(values) rgb = list(int(values[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) return rgb
274725a7f6695e190d3590565c935fbe1f6c7676
21,471
def determine_input_arg(arg_val, default_arg_val): """ if arg_val exists, use it, else return default_arg_val """ if arg_val: return arg_val else: return default_arg_val
c15500b7869a5b4c5a0c687228c926bfa4568f74
21,474
def _dict_depth(d): """ Get the nesting depth of a dictionary. For example: >>> _dict_depth(None) 0 >>> _dict_depth({}) 1 >>> _dict_depth({"a": "b"}) 1 >>> _dict_depth({"a": {}}) 2 >>> _dict_depth({"a": {"b": {}}}) 3 Args: d (dict): dictionary Returns: int: depth """ try: return 1 + _dict_depth(next(iter(d.values()))) except AttributeError: # d doesn't have attribute "values" return 0 except StopIteration: # d.values() returns an empty sequence return 1
0c6fd91ed64b25ff023edbfbf210c6b354cd3af8
21,478
def inherit_function_doc(parent): """Inherit a parent instance function's documentation. Parameters ---------- parent : callable The parent class from which to inherit the documentation. If the parent class does not have the function name in its MRO, this will fail. Examples -------- >>> class A(object): ... def do_something(self): ... '''Does something''' >>> >>> class B(A): ... @inherit_function_doc(A) ... def do_something(self): ... pass >>> >>> print(B().do_something.__doc__) Does something """ def doc_wrapper(method): func_name = method.__name__ assert (func_name in dir( parent)), '%s.%s is not a method! Cannot inherit documentation' % ( parent.__name__, func_name) # Set the documentation. This only ever happens at the time of class # definition, and not every time the method is called. method.__doc__ = getattr(parent, func_name).__doc__ # We don't need another wrapper, we can just return the method as its # own method return method return doc_wrapper
0d22610e66118363fdeda6139eab0a8065e6c354
21,481
import re def check_files(files, count_limit, size_limit): """ Check if uploaded files are conforming given requirements. """ if len(files) == 0: return False, "No file was uploaded" elif len(files) > count_limit: return False, "Limit on amount of files exceeded" for file in files: if file.size > size_limit: return False, "Limit on file size exceeded" if re.search(r'[^a-zA-Z0-9_\-\.]', file.name): return False, "File name contains invalid characters" return True, None
25ccb7641b9f4b8b3f71f25dbcbf5f73be8de6b0
21,484
import math def distance_between_points(p0, p1): """ Distance between two points (x0, y0), (x1, y1) Parameters ---------- p0 : tuple Point 0 p1 : tuple Point 1 Returns ------- distance : value Distance """ return math.sqrt((p0[1] - p1[1])**2+(p0[0] - p1[0])**2)
58ee3b4536c912846704c581fa42065cd1b2f0a1
21,487
def _stocknames_in_data_columns(names, df): """Returns True if at least one element of names was found as a column label in the dataframe df. """ return any((name in label for name in names for label in df.columns))
30eee497f7a21755eda7e1915bf84dc800a09abc
21,488
import six def to_bytes(value, encoding='utf-8'): """ Makes sure the value is encoded as a byte string. :param value: The Python string value to encode. :param encoding: The encoding to use. :return: The byte string that was encoded. """ if isinstance(value, six.binary_type): return value return value.encode(encoding)
c4f0e24d39ee565135326550006a3d5311adbb40
21,491
import requests def get_team(team_id, gw): """ Get the players in a team Args: team_id (int): Team id to get the data from gw (int): GW in which the team is taken Returns: (tuple): List of integers, Remaining budget """ res = requests.get( 'https://fantasy.premierleague.com/api/entry/' + f'{team_id}/event/{gw}/picks/').json() # Scrape GW before FH to get the team from GW prior if res['active_chip'] == 'freehit': res = requests.get( 'https://fantasy.premierleague.com/api/entry/' + f'{team_id}/event/{gw-1}/picks/').json() # Adjust the player id with fplreview indices return [i['element'] for i in res['picks']], res['entry_history']['bank']
295c46628c14ad64715ee4a06537598878a8ef2e
21,495
def get_indexes(start_index, chunk_size, nth): """ Creates indexes from a reference index, a chunk size an nth number Args: start_index (int): first position chunk_size (int): Chunk size nth (int): The nth number Returns: list: First and last position of indexes """ start_index = nth * chunk_size stop_index = chunk_size + nth * chunk_size return([start_index,stop_index])
a8dba6fef788b542b502e1e0ce52ce57f2372485
21,498
def _get_request_wait_time(attempts): """ Use Fibonacci numbers for determining the time to wait when rate limits have been encountered. """ n = attempts + 3 a, b = 1, 0 for _ in range(n): a, b = a + b, a return a
91e4c165fee5b821e8654468e954786f89ad1e0b
21,502
def GetProblemIndexFromKey(problems, problem_key): """Get a problem's index given its key and a problem list. Args: problems: Iterable of problems in the current contest. problem_key: String with the problem key that must be searched. Returns: The index of the requested problem in the problem list. If the problem is not found this method returns None. """ # Look at all the problems and return position of the first problem whose # key matches the looked key. for i, problem in enumerate(problems): if problem['key'] == problem_key: return i return None
08e84afe65695c0d0aedb391975b37c7b42f22af
21,508
from typing import List from pathlib import Path def get_core_paths(root: str) -> List[str]: """Return all the files/directories that are part of core package. In practice, it just excludes the directories in env module""" paths = [] for _path in Path(root).iterdir(): if _path.stem == "envs": for _env_path in _path.iterdir(): if _env_path.is_file(): paths.append(str(_env_path)) else: paths.append(str(_path)) return paths
96b9e6391fa8aabbec947a88c4f142b8007eaddc
21,509
import re def get_symbol_name(module, symbol_id): """Return a pretty printed name for the symbol_id if available. The pretty printed name is created from OpName decorations for the symbol_id if available, otherwise a numerical ID (e.g. '%23') is returned. Names are not unique in SPIR-V, so it is possible that several IDs have the same name in their OpName decoration. This function will return that name for the first ID found, and the rest will get a numerical name.""" if symbol_id in module.id_to_symbol_name: return module.id_to_symbol_name[symbol_id] for inst in module.global_instructions.name_insts: if inst.op_name == 'OpName' and inst.operands[0] == symbol_id: name = inst.operands[1] # glslang tend to add type information to function names. # E.g. "foo(vec4)" get the symbol name "foo(vf4;" # Truncate such names to fit our IL. regex = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*') match = regex.match(name) if match is None: return '%' + str(symbol_id.value) new_name = match.group(0) symbol_name = '%' + new_name if symbol_name in module.symbol_name_to_id: # This name is already used for another ID (which is # possible, as the decorations we are using for symbol # names are not guaranteed to be unique). Let the first # ID use this name, and use a numerical name for this ID. symbol_name = '%' + str(symbol_id.value) break else: symbol_name = '%' + str(symbol_id.value) module.id_to_symbol_name[symbol_id] = symbol_name module.symbol_name_to_id[symbol_name] = symbol_id return symbol_name
b82ec2e06e289a58d1a4dc6ebd858a74a4c07ca6
21,510
import struct def unpack_uint32(byte_stream, endian="<"): """Return list of uint32s, (either endian) from bytes object. Unpack a bytes object into list of 32-bit unsigned integers. Each 4 input bytes decodes to a uint32. Args: byte_stream (bytes): length is a multiple of 4 endian (char, optional): "<" means little-endian unpacking, and ">" means big-endian unpacking Returns: list: unpacked uint32 numbers """ num_uint32 = len(byte_stream) // 4 out_uint32s = struct.unpack(endian + "I" * num_uint32, byte_stream) return out_uint32s
87f7bd12607e9be193098a407b51cbc01bdbe3c4
21,511
def tag_to_rtsip(tag): """Convert tag to relation type, sense, id, and part.""" rel_type, rel_sense, rel_id, rel_part = tag.split(":") return rel_type, rel_sense, int(rel_id), rel_part
38237836cd16d34a594296c5077eee062600d899
21,519
def _clean_name(s: str) -> str: """ >>> _clean_name("Residual x ") 'residual_x' """ return str(s).strip().lower().replace(" ", "_")
15bce66826a7caa76f4f25810369047de451c276
21,520
import torch def sample_points(rays_o, rays_d, near, far, num_samples, perturb=False): """ Sample points along the ray Args: rays_o (num_rays, 3): ray origins rays_d (num_rays, 3): ray directions near (float): near plane far (float): far plane num_samples (int): number of points to sample along each ray perturb (bool): if True, use randomized stratified sampling Returns: t_vals (num_rays, num_samples): sampled t values coords (num_rays, num_samples, 3): coordinate of the sampled points """ num_rays = rays_o.shape[0] t_vals = torch.linspace(near, far, num_samples, device=rays_o.device) t_vals = t_vals.expand(num_rays, num_samples) # t_vals has shape (num_samples) # we must broadcast it to (num_rays, num_samples) if perturb: rand = torch.rand_like(t_vals) * (far-near)/num_samples t_vals = t_vals + rand coords = rays_o.unsqueeze(dim=-2) + t_vals.unsqueeze(dim=-1) * rays_d.unsqueeze(dim=-2) return t_vals, coords
28adc68aa8a6d8cf0fd54fa62d23bc2e7a1dc296
21,529
def html(html_data): """ Builds a raw HTML element. Provides a way to directly display some HTML. Args: html_data: The HTML to display Returns: A dictionary with the metadata specifying that it is to be rendered directly as HTML """ html_el = { 'Type': 'HTML', 'Data': html_data, } return html_el
898100fe5eef22fb7852b5991b1927ac4b3bf8f6
21,530
def distance_sqr_2d(pt0, pt1): """ return distance squared between 2d points pt0 and pt1 """ return (pt0[0] - pt1[0])**2 + (pt0[1] - pt1[1])**2
23820a4e5f396ddda9bea0a0701c26d416e6567b
21,532
def wlv_datetime(value): """Default format for printing datetimes.""" return value.strftime("%d/%m/%Y %H:%M:%S") if value else ""
c8bf50d239c7bad195e65f6036c7bcf522d38feb
21,533
def get_diff_sq(a, b): """ Computes squared pairwise differences between a and b. :param a: tensor a :param b: tensor b :return: squared pairwise differences between a and b """ aa = a.matmul(a.t()) bb = b.matmul(b.t()) ab = a.matmul(b.t()) diff_sq = -2 * ab + aa.diag().unsqueeze(1) + bb.diag().unsqueeze(0) return diff_sq
fcaec3db6316c8872c24a89ee56e1b6e6b83787b
21,535
from typing import List def D0_dd( phi: List[float], s: List[float] ) -> float: """ Compute the central difference approximation of the second order derivative of phi along the same dimension, as in [3]. :param phi: List of the 3 upwind-ordered phi values (i.e. [\phi_{i-1}, \phi_i, \phi_{i+1}]). :param s: List of the 2 distances along the d dimension between the upwind-ordered phi values (i.e. [s_{i-1}, s_{i+1}]). :return: D^0_{dd}\phi_i. """ return 2.0 / sum( s[:2] ) * ( ( phi[2] - phi[1] ) / s[1] - ( phi[1] - phi[0] ) / s[0] )
20c012098827e929b08770fe159d87cf29eb15c2
21,537
def separate_categories(data): """ Separate the rows concerning "script-identifiable edits" from those concerning "other edits". Also, in each categry, and for each line, calculate the sum of levenshtein distances across all edits for that line. Return two separate DataFrames. """ # Line 6 should have an entry in both other and script. data = data.groupby(["category", "line"], axis=0).sum() other = data.loc["other", :].reset_index()\ .astype(int).sort_values(by=["line"]) script = data.loc["script-identifiable", :]\ .reset_index().astype(int).sort_values(by=["line"]) # print(script.head(), other.head()) return other, script
6d7b844bd69402fc32c2deb4c0ee3df131fdf6aa
21,538
import math def calculate_distance(coord1, coord2, box_length=None): """ Calculate the distance between two 3D coordinates. Parameters ---------- coord1, coord2 : list The atomic coordinates [x, y, z] box_length : float, optional The box length. This function assumes box is a cube. Returns ------- distance: float The distance between the two atoms """ #Do periodic boundary corrections if given a box_length if box_length is not None: #Distance = sqrt(sum of square differences of each dimension) #initialize the sum of square differences to 0 sum_square_diff = 0 #Iterate through dimensions for i in range(len(coord1)): #Find the raw distance between the two coordinates in this dimension dim_dist_uncorrected = math.fabs(coord1[i] - coord2[i]) #Periodic boundary corrections #If raw distance is less than half the box_length, no corrections are needed if dim_dist_uncorrected <= box_length / 2: dim_dist_corrected = dim_dist_uncorrected #If raw distance is greater than half the box length and less than one whole box length, correct accordingly elif (dim_dist_uncorrected > box_length / 2 and dim_dist_uncorrected <= box_length): dim_dist_corrected = box_length - dim_dist_uncorrected #If raw distance is greater than one whole box length, correct accordingly else: dim_dist_corrected = dim_dist_uncorrected - box_length * round(dim_dist_uncorrected / box_length) #Add the square difference to the total sum sum_square_diff += (dim_dist_corrected)**2 #Calculate distance after finding the sum of square differences distance = math.sqrt(sum_square_diff) #Otherwise assume no periodic boundaries else: sum_square_diff = 0 for i in range(len(coord1)): sum_square_diff += (coord1[i] - coord2[i])**2 distance = math.sqrt(sum_square_diff) return distance
954bdf6dc66ca4edf58b1b96aa63343930e1a604
21,539
def practice_problem2a(sequence, delta): """ What comes in: -- A sequence of integers, e.g. ([2, 10, 5, -20, 8]) -- A number delta What goes out: -- Returns a new list that is the same as the given list, but with each number in the list having had the given delta added to it (see example below) Side effects: None. Example: Given the list [2, 10, 5, -20, 8] and the number 6, this problem returns [8, 16, 11, -14, 14] Type hints: :type sequence: [int] :type delta: int """ #################################################################### # DONE 3. Implement and test this function. # The testing code is already written for you (above). #################################################################### # DIFFICULTY AND TIME RATINGS (see top of this file for explanation) # DIFFICULTY: 5 # TIME ESTIMATE: 5 minutes. #################################################################### seq = [] for k in range (len(sequence)): seq = seq + [sequence[k] + delta] return seq
31cc3f1272f5563db0f2edcb5c1f5f7052b10751
21,542
import torch def compute_tv_norm(values, losstype = "l2"): """Returns TV norm for input values. Source: regnerf/internal/math.py Args: values: [batch, H, W, *]. 3 or more dimensional tensor. losstype: l2 or l1 Returns: loss: [batch, H-1, W-1, *] """ v00 = values[:, :-1, :-1] v01 = values[:, :-1, 1:] v10 = values[:, 1:, :-1] if losstype == "l2": loss = ((v00 - v01)**2) + ((v00 - v10)**2) elif losstype == "l1": loss = torch.abs(v00 - v01) + torch.abs(v00 - v10) else: raise ValueError(f"Unsupported TV losstype {losstype}.") return loss
34088d342cac0f1d4ee0ec4946f73aec9cc92639
21,543
import re def is_sale(word): """Test if the line is a record of a sale""" cattle_clue = r'(bulls?|steers?|strs?|cows?|heifers?|hfrs?|calf|calves|pairs?|hc|sc)' price_clue = r'[0-9,]+' has_cattle = any(bool(re.search(cattle_clue, this_word, re.IGNORECASE)) for this_word in word) has_price = any(bool(re.search(price_clue, this_word)) for this_word in word) return has_cattle & has_price
f4b53e28b18f7f7fdffeebf8884076224660ae48
21,545
import re def word_count(text: str) -> int: """ Counts the total words in a string. Parameters ------------ text: str The text to count the words of. Returns ------------ int The number of words in the text. """ list_words = re.split(' |\n|\t', text) #Splits along spaces list_words = list(filter(str.strip, list_words)) return len(list_words)
869afd06172c9ffb61430489804cac20706ca245
21,551
def tobin(i): """ Maps a ray index "i" into a bin index. """ #return int(log(3*y+1)/log(2))>>1 return int((3*i+1).bit_length()-1)>>1
a32bf5895071ac111bbd0c76a3fa8b630feb252d
21,552
def get_model_path(model): """Return the qualified path to a model class: 'model_logging.models.LogEntry'.""" return '{}.{}'.format(model.__module__, model.__qualname__)
ab6b631aa4fb3acac0355c587f792441ecf25702
21,553
def get_image_data(image): """ Return a mapping of Image-related data given an `image`. """ exclude = ["base_location", "extracted_to_location", "layers"] image_data = { key: value for key, value in image.to_dict().items() if key not in exclude } return image_data
684cd2a358599b161e2311f88c3e84c016ad2fef
21,558
def proceed() -> bool: """ Ask to prooceed with extraction or not """ while True: response = input("::Proocced with extraction ([y]/n)?") if response in ["Y", "y", ""]: return True elif response in ["N", "n"]: return False else: continue
6d4c93ee7a216d9eb62f565657cf89a2e829dd30
21,559
def clean_input(text): """ Text sanitization function :param text: User input text :return: Sanitized text, without non ascii characters """ # To keep things simple at the start, let's only keep ASCII characters return str(text.encode().decode("ascii", errors="ignore"))
974a24e4d516faac650a9899790b66ebe29fc0a2
21,560
import requests def get_player_stats_from_pfr(player_url, year): """ Function that returns the HTML content for a particular player in a given NFL year/season. :param player_url: URL for the player's Pro Football Reference Page :param year: Year to access the player's stats for :return: String containing all content of the player's gamelogs for the given year """ get_url = player_url + year response = requests.get(get_url) return response.content
d6e4b34de9498dd8dff80bf5e6bd0bdc9f44255b
21,564
def euclidean_rhythm(beats, pulses): """Computes Euclidean rhythm of beats/pulses From: https://kountanis.com/2017/06/13/python-euclidean/ Examples: euclidean_rhythm(8, 5) -> [1, 0, 1, 0, 1, 0, 1, 1] euclidean_rhythm(7, 3) -> [1, 0, 0, 1, 0, 1, 0] Args: beats (int): Beats of the rhythm pulses (int): Pulses to distribute. Should be <= beats Returns: list: 1s are pulses, zeros rests """ if pulses is None or pulses < 0: pulses = 0 if beats is None or beats < 0: beats = 0 if pulses > beats: beats, pulses = pulses, beats if beats == 0: return [] rests = beats - pulses result = [1] * pulses pivot = 1 interval = 2 while rests > 0: if pivot > len(result): pivot = 1 interval += 1 result.insert(pivot, 0) pivot += interval rests -= 1 return result
c1ded4891dfc658a4ba1e92db7b736c70f25f4f5
21,566
import csv def get_device_name(file_name, sys_obj_id, delimiter=":"): """Get device name by its SNMP sysObjectID property from the file map. :param str file_name: :param str sys_obj_id: :param str delimiter: :rtype: str """ try: with open(file_name) as csv_file: csv_reader = csv.reader(csv_file, delimiter=delimiter) for row in csv_reader: if len(row) >= 2 and row[0] == sys_obj_id: return row[1] except OSError: pass # file does not exist return sys_obj_id
3074dffc5274d882bb99c13a0e642b05fd68cb9c
21,568
def get_replaces_to_rule(rules): """Invert rules dictionary to list of (replace, rule) tuples.""" replaces = [] for rule, rule_replaces in rules.items(): for replace in rule_replaces: replaces.append((replace, rule)) return replaces
de3fd8235eb8926682544def49de500412ee3084
21,569
def query_epo_desc_table(src_table: str): """ Return the query generating the aggregate table to compute descriptive statistics on the EPO full text database :param src_table: str, table path to EPO full-text database on BigQuery e.g. 'project.dataset.table' :return: str """ query = f""" WITH tmp AS ( SELECT publication_number AS publication_number, publication_date, title.text IS NOT NULL AS has_title, title.LANGUAGE AS title_language, abstract.text IS NOT NULL AS has_abstract, abstract.LANGUAGE AS abstract_language, description.text IS NOT NULL AS has_description, description.LANGUAGE AS description_language, claims.text IS NOT NULL AS has_claims, claims.LANGUAGE AS claims_language, amendment.text IS NOT NULL AS has_amendment, amendment.LANGUAGE AS amendment_language, url.text IS NOT NULL AS has_url, url.LANGUAGE AS url_language, FROM `{src_table}`) SELECT family_id AS family_id, tmp.* FROM tmp, `patents-public-data.patents.publications` AS p WHERE tmp.publication_number = p.publication_number """ return query
20f114cc4c54e03261362458140b2f7bc7318ea4
21,570
def _get_metadata_map_from_client_details(client_call_details): """Get metadata key->value map from client_call_details""" metadata = {metadatum[0]: metadatum[1] for metadatum in (client_call_details.metadata or [])} return metadata
1d0b843b41f2777685dad13b9269410033086b02
21,571
def snake_to_camel_case(name: str, initial: bool = False) -> str: """Convert a PEP8 style snake_case name to CamelCase.""" chunks = name.split('_') converted = [s.capitalize() for s in chunks] if initial: return ''.join(converted) else: return chunks[0].lower() + ''.join(converted[1:])
1669c0a1065da8133771d83ebbc7ed4c393d4a8f
21,572
def filter_default(input_dict, params_default): """ Filter input parameters with default params. :param input_dict: input parameters :type input_dict : dict :param params_default: default parameters :type params_default : dict :return: modified input_dict as dict """ for i in params_default.keys(): if i not in input_dict.keys(): input_dict[i] = params_default[i] return input_dict
5cae639c2a18c6db7a858ebe4ce939bf551088c2
21,577
def is_even(n): """Determines whether `n` is even """ # even = n % 2 == 0 even = not(n & 1) return even
cfb0d961bf456fe84b99ba3dd81ec34b2bdd4f2f
21,579
import time def minutesTillBus(busTimepoint, nowTime = None): """ given a bus timepoint record from getTimepointDepartures, return the number of minutes until that bus, as a float. nowTime is the current time since unix epoch, but leave it out to just use the system time. """ t = busTimepoint["DepartureTime"] if nowTime is None: nowTime = time.time() secondsFromNow = float(t[6:-2].split('-')[0])/1000.0 - nowTime return secondsFromNow / 60.0
b26f194fd07160a2e7b2d5a059a6242af636d1fe
21,580
import base64 def read_file_as_b64(image_path): """ Encode image file or image from zip archive to base64 Args: image_path (bytes or str): if from a zip archive, it is an image in bytes; if from local directory, it should be a string specifying the filepath Returns: b64_string (str): encoded image file ready to be sent to server """ # If input is from zip archive, it will be in bytes if type(image_path) is bytes: b64_bytes = base64.b64encode(image_path) else: # Or it is from a directory with open(image_path, "rb") as image_file: b64_bytes = base64.b64encode(image_file.read()) b64_string = str(b64_bytes, encoding='utf-8') return b64_string
516200ba2c7a129f236c92dbf7952592f449b6e3
21,581
from typing import Iterable import functools def prod(iterable: Iterable[int]) -> int: """ Calculates the product of an iterable. In Python 3.8 this can be replaced with a call to math.prod """ return functools.reduce(lambda x, y: x * y, iterable)
219aec67b87fb1b4b16e6d4e70f8d1deca3a4388
21,582
def return_int(user_input): """Function to check and return an integer from user input""" try: user_int = int(user_input) except ValueError: print("Oops! Not a valid integer format.") else: return user_int
01dccefb92e3b854029ec6100a11d02bc51af240
21,585
def get_clusterID(filename): """given a file name return the cluster id""" return filename.split(".")[0]
43de7ab212d41d4e7c1d40e6dadb988c178db1f4
21,586
import json def to_json(value): """A filter that outputs Python objects as JSON""" return json.dumps(value)
386a27290c2f9e1f0a926143bc7e54e2ca98912b
21,594
def get_mac_addr_from_dbus_path(path): """Return the mac addres from a dev_XX_XX_XX_XX_XX_XX dbus path""" return path.split("/")[-1].replace("dev_", '').replace("_", ":")
a8603f2f7b6202ab9bafe5f911606efd8dc54358
21,599
import typing def compute_parent( tour_edges: typing.List[int], ) -> typing.List[typing.Optional[int]]: """Compute parent from Euler-tour-on-edges. Args: tour_edges (typing.List[int]): euler tour on edges. Returns: typing.List[typing.Optional[int]]: parent list. the tour root's parent is None. Examples: >>> tour_edges = [0, 1, 4, -5, 2, -3, -2, 3, -4, -1] >>> compute_parent(tour_edges) [None, 0, 1, 0, 1] """ n = len(tour_edges) >> 1 parent: typing.List[typing.Optional[int]] = [None] * n st = [tour_edges[0]] for u in tour_edges[1:]: if u < 0: st.pop() continue parent[u] = st[-1] st.append(u) return parent
5887a22faf42fae32b81fab902de9490c5dc4b00
21,600
from typing import Optional def build_netloc(host: str, port: Optional[int] = None) -> str: """Create a netloc that can be passed to `url.parse.urlunsplit` while safely handling ipv6 addresses.""" escaped_host = f"[{host}]" if ":" in host else host return escaped_host if port is None else f"{escaped_host}:{port}"
56e44584b2f5e76142c40b639919951772f75aed
21,602
def error404(e): """ 404 error handler. """ return ''.join([ '<html><body>', '<h1>D20 - Page Not Found</h1>', '<p>The only endpoint available on this entropy micro-service is <a href="/api/entropy">/api/entropy</a>.</p>', '<p>For more information including the complete source code, visit <a href="https://github.com/AgalmicVentures/D20">the D20 repository</a>.</p>', '</body></html>', ]), 404
35ab121b88e84295aaf97e2d60209c17acffd84d
21,607
import string import random def id_generator( size=6, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits ): """ Creates a unique ID consisting of a given number of characters with a given set of characters """ return ''.join(random.choice(chars) for _ in range(size))
9a6bf02c63e5ad933340be70e95c812683a69dee
21,609
def convert_hubs_to_datastores(hubs, datastores): """Get filtered subset of datastores as represented by hubs. :param hubs: represents a sub set of datastore ids :param datastores: represents all candidate datastores :returns: that subset of datastores objects that are also present in hubs """ hubIds = [hub.hubId for hub in hubs] filtered_dss = [ds for ds in datastores if ds.value in hubIds] return filtered_dss
14e7231f9c6a1e273c217bf77b8a7d3b3632709c
21,611
def inspect_chain(chain): """Return whether a chain is 'GOOD' or 'BAD'.""" next_key = chain.pop('BEGIN') while True: try: next_key = chain.pop(next_key) if next_key == "END": break except KeyError: return "BAD" if len(chain) > 0: return "BAD" return "GOOD"
083886aa31fa81cc90d4c7bd30149c5575a5a675
21,613
def hex(string): """ Convert a string to hex. """ return string.encode('hex')
66ff8fe8797c840d5471dbb4693e0ae6ef32fb8e
21,624
import ast def literal(str_field: str): """ converts string of object back to object example: $ str_literal('['a','b','c']') ['a', 'b', 'c'] # type is list """ return ast.literal_eval(str_field)
25d23f55e52cdb4727f157a3db13614932bcbec7
21,626
def tail_logfile(logfile=''): """Read n lines of the logfile""" result = "Can't read logfile: {}".format(logfile) lines = 40 with open(logfile) as f: # for line in (f.readlines()[-lines:]): # print(line) result = ''.join(f.readlines()[-lines:]) return result
61a4046d2a7bfb8be907a325253424b2d425b410
21,627
from typing import Dict from typing import Any from typing import Optional import requests def request_data(url: str, params: Dict[str, Any]) -> Optional[str]: """Request data about energy production from Entsoe API. Args: url (str): Entsoe API url. params (Dict[str, str]): Parameters for the API get requests. Returns: Optional[str]: If response status is ok returns xml response as a string. """ headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:83.0) Gecko/20100101 Firefox/83.0' } r = requests.get(url, params=params, headers=headers) if r.status_code == 200: return r.text return None
187d134f3457616d830ec5c78b02a11f880c981e
21,629
def minimum_katcp_version(major, minor=0): """Decorator; exclude handler if server's protocol version is too low Useful for including default handler implementations for KATCP features that are only present in certain KATCP protocol versions Examples -------- >>> class MyDevice(DeviceServer): ... '''This device server will expose ?myreq''' ... PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 1) ... ... @minimum_katcp_version(5, 1) ... def request_myreq(self, req, msg): ... '''A request that should only be present for KATCP >v5.1''' ... # Request handler implementation here. ... >>> class MyOldDevice(MyDevice): ... '''This device server will not expose ?myreq''' ... ... PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 0) ... """ version_tuple = (major, minor) def decorator(handler): handler._minimum_katcp_version = version_tuple return handler return decorator
bcaefb29af78400cd283895fef0d4fd94f175112
21,631
def newick_to_json(newick_string, namestring = "id", lengthstring = "branch_length", childrenstring = "children", generate_names=False): """Parses a newick string (example "((A,B),C)") into JSON format accepted by NetworkX Args: newick_string: The newick string to convert to JSON. Names, branch lengths and named internal nodes accepted. If no names are given, an ID is generated for the name if generate_names=True. namestring: The label for node name to use in the JSON (default "id"). lengthstring: The label for branch length to use in the JSON (default "branch_length"). childrenstring: The label for children arrays to use in the JSON (default "children"). generate_names: Whether or not to generate names if none are given """ def __split_into_children(children_string): """ Helper function for splitting a newick string into siblings """ string = children_string opened = 0 closed = 0 pieces = [] last_stop = 0 for i, s in enumerate(string): if s == "(": opened += 1 if s == ")": closed += 1 if s == "," and opened == closed: pieces.append(string[last_stop:i]) last_stop = i+1 pieces.append(string[last_stop:]) return(pieces) newick_string = newick_string.strip(";") node = dict() info = newick_string[newick_string.rfind(")")+1:] info = info.split(":") name = info[0] node[namestring] = name length = "" if len(info) > 1: length = info[1] node[lengthstring] = float(length) children_string = newick_string[0:newick_string.rfind(")")+1] if children_string != "": if children_string[-1] == ")": children_string = children_string[1:-1] children_string = __split_into_children(children_string) child_nodes_JSON = [] for child_string in children_string: child_JSON = newick_to_json(child_string, namestring, lengthstring, childrenstring, generate_names) if (not name) and generate_names: node[namestring] += child_JSON[namestring] child_nodes_JSON.append(child_JSON) node[childrenstring] = child_nodes_JSON return node
b116869f46467390b6dd2463bf2b982f01a95a13
21,633
def __str2key(_): """Make string a valid jinja2 template key e.g. dictionary.key Ref: https://jinja.palletsprojects.com/en/3.0.x/templates/#variables """ return _.replace('.', '')
7980e8d38576211f9bd02bcedd817c5d0087e415
21,635
import re def compile_re(pattern): """ Compile a regular expression with pattern Args: pattern (str): a string representing the pattern e.g. "NoviPRD-.*" means strings that start with "NoviPRD-" e.g. ".*\.csv" means strings that end with ".csv" e.g. ".*xxx.*" means strings that contain "xxx" in the middle Returns: regular expression object """ return re.compile(pattern)
f5fa043b9472bf19e350c880bbaf6200739234f5
21,636
import warnings def check_args(parsed_args): """ Function to check for inherent contradictions within parsed arguments. For example, batch_size < num_gpus Intended to raise errors prior to backend initialisation. Args parsed_args: parser.parse_args() Returns parsed_args """ if 'resnet' not in parsed_args.backbone: warnings.warn('Using experimental backbone {}. Only resnet50 has been properly tested.'.format(parsed_args.backbone)) return parsed_args
160f4bacc40d6187191c6b8ec18e0bc214856d4d
21,640
def email_associated(env, email): """Returns whether an authenticated user account with that email address exists. """ for row in env.db_query(""" SELECT value FROM session_attribute WHERE authenticated=1 AND name='email' AND value=%s """, (email,)): return True return False
4f5ff9954cf7a73eca17529f74f3004835c6a07d
21,641
def _ListOpToList(listOp): """Apply listOp to an empty list, yielding a list.""" return listOp.ApplyOperations([]) if listOp else []
1c6aefacdbadc604a2566b85483894d98d116856
21,644
def calc_rectangle_bbox(points, img_h, img_w): """ calculate bbox from a rectangle. Parameters ---------- points : list a list of two points. E.g. `[[x1, y1], [x2, y2]]` img_h : int maximal image height img_w : int maximal image width Returns ------- dict corresponding bbox. I.e. `{ 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax }` """ lt, rb = points xmin, ymin = lt xmax, ymax = rb xmin = min(max(0, xmin), img_w) xmax = min(max(0, xmax), img_w) ymin = min(max(0, ymin), img_h) ymax = min(max(0, ymax), img_h) return { 'xmin':xmin, 'ymin':ymin, 'xmax':xmax, 'ymax':ymax }
45be9537c80d54e26a54dc4a04ece3759d988feb
21,646
def __en_omelete(soup): """ Helper function to get Omelete News :param soup: the BeautifulSoup object :return: a list with the most read news from a given Omelete Page """ news = [] anchors = soup.find('aside', class_='c-ranking c-ranking--read').find_all('a') for a in anchors: link = 'http://www.omelete.com.br' + a['href'] title = a.find('div', class_='c-ranking__text').string news.append(dict(title=title, link=link)) return news
3c18168ca3f4656182e09c5dbde98ce1665b425d
21,647
def trailing_zeros(n): """Count trailing zero bits in an integer.""" if n & 1: return 0 if not n: return 0 if n < 0: n = -n t = 0 while not n & 0xffffffffffffffff: n >>= 64; t += 64 while not n & 0xff: n >>= 8; t += 8 while not n & 1: n >>= 1; t += 1 return t
dd25d3f855500ae4853130c3b84601c51b64d9f0
21,651
def extract_node_attribute(graph, name, default=None): """ Extract attributes of a networx graph nodes to a dict. :param graph: target graph :param name: name of the attribute :param default: default value (used if node doesn't have the specified attribute) :return: a dict of attributes in form of { node_name : attribute } """ return { i : d.get(name, default) for i, d in graph.nodes(data=True) }
5ec1b7124ecbe048107d4d571c18fe66436d0c7b
21,653
import struct def Rf4ceMakeFCS(data): """ Returns a CRC that is the FCS for the frame (CRC-CCITT Kermit 16bit on the data given) Implemented using pseudocode from: June 1986, Kermit Protocol Manual https://www.kermitproject.org/kproto.pdf """ crc = 0 for i in range(0, len(data)): c = ord(data[i]) q = (crc ^ c) & 15 #Do low-order 4 bits crc = (crc // 16) ^ (q * 4225) q = (crc ^ (c // 16)) & 15 #And high 4 bits crc = (crc // 16) ^ (q * 4225) return struct.pack('<H', crc)
81add4f980ded4e26b78252257933a191be8721c
21,654
def _best_streak(year_of_commits): """ Return our longest streak in days, given a yeare of commits. """ best = 0 streak = 0 for commits in year_of_commits: if commits > 0: streak += 1 if streak > best: best = streak else: streak = 0 return best
3d0f042dc9565d5ef7002b6729550a76d01d3b00
21,655
def labels_to_clusters(X, labels): """Utility function for converting labels to clusters. Args: X (ndarray[m, n]): input dataset labels (ndarray[m]): labels of each point Returns: clusters (list, ndarray[i, n]): list of clusters (i denotes the size of each cluster) """ return [X[labels==i] for i in range(labels.max() + 1)]
d3e316f8563d0e8c4853754bddb294b51462d724
21,661
import requests def get_page(url): """ Get a single page of results. """ response = requests.get(url) data = response.json() return data
d7d31ea8abbaa13523f33aa9eb39fca903d5cb21
21,662
def lst_to_ans(ans_lst): """ :param ans_lst: list[str], contains correct guesses the user entered and undeciphered character. :return: str, turns the list into string. """ ans = '' for i in range(len(ans_lst)): ans += ans_lst[i] return ans
b1f0c196a53dc88e76967481d573bdff591597b9
21,665