content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import logging def SafeList(ctx, url): """Get a GS listing with details enabled. Ignore most any error. This is because GS flake can trigger all sorts of random failures, and we don't want flake to interrupt a multi-day script run. It is generally safe to return [] since any files that would have been disc...
03577bf448fe4ae026bbfce2ca19a67b7ebf941d
612,908
import re def convert_RL_name(name): """Switch R-L or L-R presceding, following or in-between underscores Args: name(str): String to operate on Returns: str: Switched name Example: _L -> _R / _L0_ -> _R0_ / L_ > R_ ... """ # If the input is just L or R return the co...
1010e3049afffd0ff1a745d8a92dd78fa8d0adcc
612,913
def train_and_predict(train_x, train_y, val_x, model_cls, return_model=False, **model_params): """Convenience function that trains a model on one dataset and predicts on another, given a model class and a set of parameters. Parameters ---------- train_x, val_x: pd.DataFrame, The datasets to...
03f21bf00c24fa9047fafd402d3f7b69ae8f17c2
612,914
def get_count(text, func=sum): """ Performs `func` (default is `sum`) on the list of all peer char totals """ return float(func([peer.count for peer in text.peers.values()]))
d58d590dc760397e1a7000d4404a3b1e27f2fbe1
612,916
import re def EnumToCssProperty(enum_name): """Converts a camel cased enum name to the lower case CSS property.""" # The first group also searches for uppercase letters to account for single # uppercase letters, such as in "ZIndex" that need to convert to "z-index". # Special case total page measured for bac...
dab6d2650c16d2d57d70159fa380c1ae8425fc49
612,917
def severe_validations(results): """Filter `results` to only include validations with low or higher signing severity.""" return (result for result in results if (result['signing_summary']['high'] > 0 or result['signing_summary']['medium'] > 0 or result...
a95af0e7ca056ace3266a239b8d8c27cc0a7cff8
612,918
from typing import Any from datetime import datetime def datetime_encoder(data: Any) -> Any: """ A datetime encoder for `msgpack` Usage: ``` from datetime import datetime from scalpel import datetime_encoder import msgpack data = {'fruit': 'apple', 'date': datetime.utcnow()} pac...
4c5c7d0bd7187b1f5268f419ff66715b390d1a55
612,924
def get_cosine_distance(arr1, arr2): """Calculate the cosine distance of two vectors. Arguments: arr1 {list} -- 1d list object with int or float arr2 {list} -- 1d list object with int or float Returns: float -- cosine distance """ numerator = sum(x1 * x2 for x1, x2 in zip(arr...
79b78b8cbe77873905597938506fd395d0124a3e
612,925
def get_rb_file_as_string(fid): """Read Rainbow File Contents in data_string Parameters ---------- fid : object File handle of Data File Returns ------- data_string : str File Contents as data_string """ try: data_string = fid.read() except Exception: ...
2c87b47d2214f8b15fd6d60a8cc4eb1a9108c11b
612,931
def lowercase_and_make_unique(in_list): """ Takes a collection of strings, and returns it with all strings lowercased and with duplicates removed. Args: in_list (List[str]): the collection of strings to operate on Returns: set[str]: the lowercased unique set of strings. """ ret...
a73fa54fbbf17d230617b17b1913cbb3eb9ca8a7
612,932
def generate_gon_ring(gon_side: int, perm: list[int]) -> list[int]: """ Generate a gon_side-gon ring from a permutation state The permutation state is the ring, but every duplicate is removed >>> generate_gon_ring(3, [4, 2, 3, 5, 1, 6]) [4, 2, 3, 5, 3, 1, 6, 1, 2] >>> generate_gon_ring(5, [6, 5...
7d880a098e911d69448fa4b92fc69a500e2d97e4
612,937
import re def find_col(df, regex_str): """Return column names that satify regex d condition Parameters ---------- df : pd.DataFrame DataFrame to folter columns regex_str : str regex condition Returns ------- list list of column names that satisfy condition ...
dd855bb7fd83ce8a95b6a665a14d713677c094ea
612,940
def get_spatial_size(x): """ :param x: an input tensor with shape [batch_size, ..., num_channels] :return: The spatial shape of x, excluding batch_size and num_channels. """ return x.get_shape()[1:-1]
ce6593a45713029437c12973076556b16116f6d2
612,947
from typing import Callable import functools def create_patch_proxy(target: Callable, new: Callable): """ Creates a proxy that calls `new` but passes as first argument the target. """ @functools.wraps(target) def proxy(*args, **kwargs): return new(target, *args, **kwargs) return prox...
b582439bb54c3315705e5e0a1ca23cd5784f5708
612,949
import torch def huber_loss(error, delta=1.0): """ Args: error: Torch tensor (d1,d2,...,dk) Returns: loss: Torch tensor (d1,d2,...,dk) x = error = pred - gt or dist(pred,gt) 0.5 * |x|^2 if |x|<=d 0.5 * d^2 + d * (|x|-d) if |x|>d Author: Charles R. Qi ...
8a70a7bd2b1d60f336d71440697dc51face3b7b9
612,952
def isfloat(x): """Return True if can convert `x` to float, return False otherwise. https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python """ try: float(x) return True except ValueError: return False
4dcabf96be145c819a2072f8393f63b59c3cb699
612,953
from typing import List def chunkify_string(string: str, max_length: int) -> List[str]: """Returns a list of strings of a particular maximum length Original solution taken from https://stackoverflow.com/a/18854817 Parameters ---------- string : str The string to slice max_length ...
ca4de01cc9bff8844da488c26511d57f02fc67e1
612,955
from typing import Iterable def have_differences_by_keys(dict1: dict, dict2: dict, keys: Iterable): """Check if two given dictionaries have differences in values of given keys.""" for name in keys: try: value1 = dict1[name] except KeyError: if name in dict2: ...
153bcff810b213bad7ed226c2e0d0f274c2b53e3
612,956
from typing import Iterable def _list_of_digits_to_number(list_of_digits: Iterable[int]) -> int: """Convert a list of digits to a number.""" return int(''.join([str(digit) for digit in list_of_digits]))
b234d27babc439fe76607df4766ec43cfaa1fab8
612,958
import json def read_json(f): """ Read a json file. """ r = {} with open(f) as fd: r = json.load(fd) return r
4308b2528d6292acfd8f7e9509ce742ad7239786
612,962
def is_linear(cigar_tuple): """ Whether end of alignment segment is a linear end Parameters ----- cigar_tuple : tuple of cigar Returns ----- int 1 for linear end, 0 for ambiguous end """ if cigar_tuple[0] == 0 and cigar_tuple[1] >= 5: return 1 else: ...
0cf563714bc4753ba870a2213efbb41346189457
612,965
def avg(nums, weights=None, default=0): """Calculates the average of a list of numeric types. If the optional parameter weights is given, calculates a weighted average weights should be a list of floats. The length of weights must be the same as the length of nums default is the value returned if nums ...
1ffb9316f9b1a0662330e5b63ac2cf9eae1199bf
612,971
def compute_net_dimensions(weights): """ Computes the network dimensions from the its weights :param weights: networks weights :type weights: `numpy.ndarray` :return: network dimensions :rtype: `list` """ new_dims = [] for i in range(1, len(weights), 2): new_dims.append(weigh...
4b082ca0f4951b52d6ed1cc10362d9bcd73d012f
612,972
import re def findLastAssignment(lines, row, attrName): """Finds the most recent assignment of `attrName' before `row'. Returns everything after the '=' sign or None, if there was no match.""" contRegex = re.compile(r'[^#]*?' + # Don't search in comments. attrName + ...
990be2fda6463a62f3aa2d12d956a690883d8c60
612,973
from functools import reduce import operator def get_from_dict(dataDict, mapList): """Given a list of keys retrieve data from a nested dictionary.""" return reduce(operator.getitem, mapList, dataDict)
31a37f844487e493d48af3af0bbc0344f33a4f1a
612,978
import pytz def _ParseTimezone(timezone): """Try to parse a timezone string (e.g. 'America/Los_Angeles').""" try: return pytz.timezone(timezone) except pytz.exceptions.UnknownTimeZoneError: return None
28a82865173653f5212a41bd1104235e50159139
612,986
def get_aparc_aseg(files): """Return the aparc+aseg.mgz file""" for name in files: if 'aparc+aseg.mgz' in name: return name raise ValueError('aparc+aseg.mgz not found')
836ef199a42f4ca8daaa6eff5b6f06fb41cfb7f1
612,988
import torch def ln_mul_addTH(x : torch.Tensor, alpha : torch.Tensor, beta : torch.Tensor) -> torch.Tensor: """ out = x * alpha[None, :, None] + beta[None, :, None] """ return x * alpha[None, :, None] + beta[None, :, None]
30028c86c1c7bf5875254ab806564d778194842d
612,998
def mean(distribution): """Computes the mean of a distribution in the [[point, instances]] syntax """ addition = 0.0 count = 0.0 for point, instances in distribution: addition += point * instances count += instances if count > 0: return addition / count return float(...
deb7473339ad8877d341c04088561610ee271fbf
613,001
from pathlib import Path def get_version() -> str: """ Return the BlurWal version from the version module. :return: The BlurWal version """ base_dir = Path(__file__).parent version_file = base_dir / 'blurwal/_version.py' version = {} exec(version_file.read_text(), version) return...
627988550febfe0180f29db0e2a62305eaadc589
613,003
import re def is_isin(isin: str) -> bool: """ Checks whether a string is a valid ISIN or not. :param isin: the string to be checked :return: true if the given string is a valid ISIN, otherwise false """ if re.match("^[A-Za-z]{2}[A-Za-z0-9]{10}", isin): return True else: re...
4c2d20d7b93c279a9fb6eb6a903824f1533f9a89
613,004
def RevisionKeyName(rev_id, repository_name): """Compute the keyname for a revision. We use a keyname. This allows faster lookups. But more importantly, it enforces uniqueness. Each revision in a Repository exists at most once. This is useful, because otherwise we'd have a race condition. Args: rev_...
225e8cbe814c3afc6c2ff1f9fb5779d733debc98
613,010
import hashlib def file_to_md5(path, blocksize=65536): """Return a hash of the file at filepath as an MD5 hex string.""" fd = open(path, 'rb') hasher = hashlib.md5() buf = fd.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = fd.read(blocksize) return hasher.hexdigest...
1fe20f12622d1c16f49c16696ab20741949da2fc
613,017
from typing import Callable from typing import Any def _apply_constraints(method: Callable[..., Any]) -> Callable[..., Any]: """Decorator for (re)applying constraint after updating hfun spec This function is a deocrator that takes in a callable and assumes the callable is a method whose first argument is...
8d0942d6fbb99aaf4c8db4aef2bbd031885b71e9
613,018
def mirror_grid(X, Y): """Find the mirrored grid (above/below major-axis) Args: X (array): Y (array): input grid (numpy arrays) Returns: X, -Y """ return X, -Y
c4301d50ff3f77daeb3840858c908fe298521527
613,022
def sky_brightness(Dh, m, I_0): """ :param Dh: the horizontal diffuse irradiance :param m: the relative optical airmass :param I_0: the extraterrestrial irradiance :return: the sky's brightness noted as Delta """ return Dh * m / I_0
82759c8ed4466c50189cb6b471767f6376dbc8a4
613,026
def group_by(objects, attrs): """Groups `objects' by the values of their attributes `attrs'. Returns a dictionary mapping from a tuple of attribute values to a list of objects with those attribute values. """ groups = dict() for obj in objects: key = tuple(getattr(obj, attr) for attr i...
270085200b5b471afef54395a8130d1addbf1695
613,027
def get_env_prefix(instrument): """Return the environment variable prefix (IRAF prefix) for `instrument`.""" return "crds://"
1aa81f85edbf3258030276d72afcaf02739a6724
613,029
from typing import List def list_voices(client) -> List[str]: """ Lists the available voices. """ return [voice.name for voice in client.list_voices().voices]
c33347e1502ac3c1db492e3493a1733b3cded456
613,030
def add_attrs(**attrs): """Makes a function that adds attributes to a function. Used in it's normal context, it looks something like this: >>> @add_attrs(my_special_attr='my special value', another=42) ... def foo(x): ... return x + 1 >>> >>> foo(10) # checking that this great functio...
143320f7f088a1f3652fe41185e54c245e60a6f6
613,037
def truncate_end(list_of_ids, id_end): """Removes the end of the list starting from the first id_end token""" list_trunc = [] for idx in list_of_ids: if idx == id_end: break else: list_trunc.append(idx) return list_trunc
221b70ba4d3916bbd7776497bc6bcf3ce744e2b6
613,038
def reduce_multiline(string): """ reduces a multiline string to a single line of text. args: string: the text to reduce """ string = str(string) return " ".join([item.strip() for item in string.split("\n") if item.strip()])
b4b84b986c5d7eff8a09b6c9c23aa2a1291281d9
613,040
def get_branch_condition(branch): """ Extract branchCondition_GuardedBranchTransition from specification, e.g. "type.VALUE == &quot;graphical&quot;" -> "#graphical" :param branch: "branches_Branch" :return: extracted condition string """ branch_condition = branch.find("./branchCondition_Guar...
6a8bb3dc05fce391e19a05abc01a3fca370bb33b
613,044
def deduplicate(mylist): """Remove duplicates while otherwise maintaining order""" return list(dict.fromkeys(mylist))
474d145aa1b22a21733b7cd2ee1050b2ede32d36
613,045
def parse_custom_params(data, misc_keys): """Parse customParameters into a list of <name, val> pairs.""" params = [] for p in data.get('customParameters', []): params.append((p.pop('name'), p.pop('value'))) for key in misc_keys: try: val = data.pop(key) except KeyErr...
e45833b81cc0a1c7a458c2b13d06257171c9f005
613,050
import itertools def args_with_default(names, defaults, fillvalue=None): """ Iterate over pairs of (argument, default) values. """ rnames = reversed(names) rdefaults = reversed(defaults) pairs = itertools.zip_longest(rnames, rdefaults, fillvalue=fillvalue) return reversed(list(pairs))
6e3528f7ebb506e6a81f7302f608694006278a8c
613,051
def is_exp_summary_editable(exp_summary, user_id=None): """Checks if a given user may edit an exploration by checking the given domain object. """ return user_id is not None and ( user_id in exp_summary.editor_ids or user_id in exp_summary.owner_ids or exp_summary.community_owned...
4fa83ef1a8fba6e92a4f405fc85dbc2f92ddee7b
613,052
def split(m): """ Splits message into separate topic and content strings. :param m: a ZeroMq message containing the topic string and JSON content :return: a tuple containing the topic and JSON content """ ndx = m.find('{') return m[0:ndx - 1], m[ndx:]
c2f04814671e62edeae962ca8f6af089559a1120
613,059
def _zero_state(input, state_shape): """ Returns a nested structure of zero Tensors with the same structure and shape as `state_shape`. The returned Tensors will have the same dtype and be on the same device as `input`. Arguments: input: Tensor, to specify the device and dtype of the returned tensors. ...
ff2b1bea41f282f69126c107db7afd936d7f741e
613,063
from typing import Dict from typing import Any import json def get_entry_dict_from_json(save_file: str) -> Dict[str, Any]: """ Gets an dictionary from a JSON file, using the latest values if met with a list. Useful for analyzing latest log data. :param save_file: A str representing the file p...
5ca0c874e7859e3821d91a7545d76d4477dda0fb
613,068
def compare_pivot(pivot1, pivot2): """ Compare pivot1 and pivot2 regardless of the sequence """ if pivot1 == pivot2 or pivot1 == [pivot2[-1], pivot2[0]]: return True else: return False
abb0e83d84c5ceaae3a6df8e86393ff2b563d49c
613,071
def lag_id(port): """ Calculates the lag id to use for the given port. Max lag id is 32, using all 8 100G ports as separate lags leaves 1..24 for 25G ports """ if port<=24: # 25G ports on IXR-D2 return port elif port>=49: # 8x 100G ports on IXR-D2 return 25 + (port-49) else...
c0dd253e0447fa0fd8c12daf639f3ee108d139bf
613,072
def convert_seconds_to_video_time_string(seconds): """ Converting elapsed seconds from the beginning of a video to video time's string representation Arguments: seconds (int): Time for the beginning of a video. Examples: >>> convert_seconds_to_video_time_string(16) ...
3404947268f90cb459dcc6b2f5e60bb008dea69a
613,074
def empty_vector(size): """ return an empty vector of given size """ return [0] * size
19fa8e3148e9d8f68dbee53a149800be0ceecbb5
613,075
import toml def toml_parsing(toml_string): """ Parses the "toml" string and return dictionary format :param toml_string: String that is a "toml" file format. :return: Return dictionary format """ parsed_toml = toml.loads(toml_string) return parsed_toml
e716335264ba7df10066744a697561e34c83d2bd
613,076
from typing import Callable from typing import Iterable import collections def groupby(func: Callable, values: Iterable) -> dict: """Return mapping of key function to values.""" groups = collections.defaultdict(list) # type: dict for value in values: groups[func(value)].append(value) return g...
2d78cbd005079388e793062b3f56308d5d0e38f6
613,077
def per_longest(total, x, y): """Divides total by max(len(x), len(y)). Useful for normalizing per-item results from sequences that are zipped together. Always returns 0 if one of the sequences is empty (to avoid divide by zero error). """ longest = max(len(x), len(y)) if not longest: ...
a91d73210740805969d42c5d8a90a4ce540e4400
613,079
def filter_seq_dict(key_lst, rec_dic): """ Returns filtered dictionary element from rec_dic according to sequence names passed in key_lst """ return { key: rec_dic[key] for key in key_lst }
ccf43339a99411ee494736913e81f26634a5daa0
613,085
def noam_step(iter_count: int, warmup_steps: int, dimensionality: int, scaling_factor: float): """ Computes the learning rate at a given step of the noam learning rate scheduler. :param iter_count: The number of iterations (optimizer steps) taken so far. :param...
5fd8cfba76a69bf70595a57a6f63752f2e63b3ac
613,087
def priority(value): """Decorate a function to be executed with higher or lower priority. :param str value: one of ``high``, ``medium``, or ``low``; defaults to ``medium`` The priority allows you to control the order of callable execution, if your plugin needs it. """ def...
ef7b24886e5fdebc8eb2b20bc2a217cc1f5d77a2
613,088
def remove_nones(params): """Removes None values from optional arguments in a parameter dictionary. :param params: The dictionary of parameters to be filtered. :type params: dict :return: A filtered copy of the parameter dictionary. :rtype: dict """ return { key: value for ...
0b6e7ad7700f56bdb7c8cf030951aa59b30ffc7c
613,090
def plotOnTwoScales(ax, arrX, arrY1, arrY2, label1, label2, col1, col2, linewidth = 1, arrX2 = None): """ plot two time-series with two different y-axis scales (with two different colors), one scale on the left and the other on the right side of the graph @param ax: the graph canvas @param arrX: the shared...
ac9e0138af4d53e16b1eecc936a4558de8405c5a
613,092
import functools def unif_segmented(x, segments): """Define indicative function of union of intevals in [0, 1]. Parameters ---------- x : float in [0, 1] function variable segments : list of intervals in [0, 1] ex: [[0.1, 0.2], [0.5, 1.]] Returns ------- 0 or 1 : valu...
7104507b7d4b0ffa04589227fe8e9598dba1a1bd
613,094
from pathlib import Path def check_pem_files(keys_path): """Check *_public.pem and *_private.pem is exist.""" pub_file = Path(keys_path + "_public.pem") pri_file = Path(keys_path + "_private.pem") return bool(pub_file.is_file() and pri_file.is_file())
646b91f7e3875f2b693c1c220ee6a896b0ae5c1c
613,097
def unescape(name): """Reverses escaping of forward slashes in a node name.""" return name.replace('//', '/')
f96c5aa12d7296b0826fc0b0d4b44df5419afebc
613,099
import math def entropy(U, N, weight=None): """ Returns information entropy of the assignment Args: U: assignment {class_id: [members,],} N: number of objects weight: weight factor {object_id: weight},] """ H = 0 for class_id, members in U.items(): size = len(membe...
5437b3dd843fbc82b3f26852f3525f02fb1e95ae
613,104
import json def job_list_as_json(job_list): """ Serializes a job list into JSON """ return json.dumps(job_list, indent=2)
a64e92e2384e1491a8e2443af6dc40e086f89d51
613,106
import math def measurement_reward(old_measurements, new_measurements): """Computes the reward based on action, old and new frame rate and bit rate. Parameters ---------- old_measurements : dict A dictionary of the previous measurements new_measurements : dict A dictionary of the ...
c1fe51aa2074364f3dbd29c6ba660ff4ec274350
613,107
from typing import Dict from typing import Any import pkgutil import json def _get_schema_for_protocol(version_num: int) -> Dict[Any, Any]: """ Retrieve the json schema for a protocol schema version """ if version_num > 3: raise RuntimeError( f'JSON Protocol version {version_num} is no...
959cc95e8a116b1cd82a5165a6b8bff4d7dcad48
613,108
from typing import Any from typing import Optional from typing import Union from typing import Dict from typing import List def resolve(document: Any, pointer: str) -> Optional[Union[Dict, List, str, int, float]]: """Implementation is adapted from Rust's `serde-json` crate. Ref: https://github.com/serde-rs/j...
fcc46563bef98ffc2c8d0909812efa956604e1d3
613,110
def custom_metric(metric_type): """Generate custom metric name. :param metric_type: name of the metric. :type metric_type: str :returns: Stacdriver Monitoring custome metric name. :rtype: str """ return "custom.googleapis.com/{}".format(metric_type)
2ed56f7269407a181df04b5a046b52057af9e33f
613,119
import io import yaml def generate_openstack_conf(params): """ Generate an openstack.conf file-like given the supplied params dict. :param params: A dictionary containing parameters to use. See utils.populate_params. :return: StringIO populated with the generated openstack configuration. """ o...
414fa2016c45b3a4b91fe2c38b706ed9b1b94fa7
613,122
def get_indent(op): """Get indentation for given level.""" ret = "" for ii in range(op): # Would tab be better? ret += " " return ret
38b8cc3dce8acc8c4ff1f7d6d53db586322d36c8
613,133
def fahrenheit_to_celsius(fahrenheit: float, interval: bool = False) -> float: """Convert a temperature in Fahrenheit to Celsius.""" if interval: return fahrenheit / 1.8 return (fahrenheit - 32.0) / 1.8
0e03e21fdc5eccd5b5f7c0876f5521779461ac5f
613,134
import math def get_distance(vec1: list, vec2: list) -> float: """Return Euclidean distance of 2 vectors""" return math.sqrt(sum([pow(i - j, 2) for i, j in zip(vec1, vec2)]))
2f0a705e0319e3daa28360c6575737e6cb67d2d1
613,136
import re def _df_to_dict(t, prefix='', d=None): """Convert a table to a dict. Arguments: t (pd.DataFrame): table prefix (str): string to prefix to each column name d (dict): a dictionary to insert keys into """ if d is None: d = {} if prefix is not '': p...
82260a5f14b6b7ed8b0784b7d65a259723ab405b
613,141
def calculate_identity(sequenceA, sequenceB): """ Returns the percentage of identical characters between two sequences. Assumes the sequences are aligned. """ sa, sb, sl = sequenceA, sequenceB, len(sequenceA) matches = [sa[i] == sb[i] for i in range(sl)] seq_id = (100 * sum(matches)) / sl ...
4fc5495a8299936f1da6421c5c0968958ee2f841
613,142
def convert_pixel_wcs(ccd_image, lon_or_ra, lat_or_dec, is_pix=True, origin=0): """ Takes either pixel or World Coordinate System (RA/Dec) coordinates and converts to the other type. Parameters ---------- ccd_image: CCDData object Image which has the coordinates to...
885a13633a7ddb1dc09122476a18a4c199035d39
613,144
def FeAt8MgO(FeOT: float, MgO: float) -> float: """ To account for differences in the slopes and curvature of liquid lines of descent as a function of parental magma composition [#ref_1]_ [#ref_2]_ (after [#ref_3]_). Parameters ------------- FeOT : :class:`float` Iron oxide content. ...
a7da5bc03caf7488198a50b243c7dd670f426831
613,145
def get_turtle_state(turtle): """ Return turtle's current heading and position. """ return turtle.heading(), turtle.position()
7f0d9379c192ce7379f96844df71b671082258cf
613,151
def jaccard_distance(set1, set2): """Calculate Jaccard distance between two sets. Parameters ---------- set1 : set Input set. set2 : set Input set. Returns ------- float Jaccard distance between `set1` and `set2`. Value in range `[0, 1]`, where 0 is min ...
1041d2b24180e96cc76c3342d5e02ca8171ffa93
613,152
def rms_normalize(samples): """Power-normalize samples Taken from: https://github.com/asteroid-team/torch-audiomentations/blob/master/torch_audiomentations/utils/io.py Parameters ---------- samples : (channel, time) Tensor Single or multichannel samples Returns ------- sample...
46812cc4b2f2c1287399cb19b67d9b56e91e2115
613,153
from typing import Dict from typing import Any def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]: """ Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys. """ result = {} # type: Dict[str, Any] for k, v in d.items(): result[pre...
94bf9d8b164b4da7d62c34ba2aa7a021318e568e
613,154
def is_string(obj): """ Return True if *obj* is a string """ if isinstance(obj, str): return True return False
5af0378c0bd1c597f97bc76a90708a8eea968913
613,155
def get_unique_ngrams(sequence, n): """ Creates a list of all unique ngrams found in a given sequence. Example --------- >>> sequence = [2,1,1,4,2,2,3,4,2,1,1] >>> ps.get_unique_ngrams(sequence, 3) #doctest: +NORMALIZE_WHITESPACE [[2, 1, 1], [1, 1, 4], [1, 4, 2], [4, 2, 2], [2, 2, 3], [2, 3, 4], [3...
199a6984952c0964181a5d57741e0287911dc978
613,156
def create_encoded_array(index, size, numeric_type=int): """ Creates a one-hot encoded array with a one at the given index and zeroes everywhere else, up to the given size. :param index: The index to set to one. :param size: The size of the encoded array. :param numeric_typ...
b7b93c93ac8e9c057f63f74be512076009177562
613,158
def arr_any(iterable, fn): """ :return: True if fn(item) for any item else False """ for item in iterable: if fn(item): return True return False
c3f1822dafb9db52f318f1b56953f6c6bf0573d3
613,160
import string import random def random_string(n): """ Generates a random string. """ random_str = "" for x in range(n): rand = string.ascii_letters + string.digits random_str += random.choice(rand) return random_str
081d526a3d08f786fe19fe85a9b226e0b8f0c22d
613,161
import pickle import glob def get_num_examples(data_dir, mode): """ Get the number of examples in directory. :param data_dir: str - data directory :param mode: str - `training`, `test` or `validate` (must match folder names) :return: int - number of examples """ with open('{}/labels.pickle...
b505a310e371b1da76fc3893a937f597b5ae673f
613,162
def avroTypeToSchema(avroType): """Convert a titus.datatype.AvroType into an Avro schema. :type avroType: titus.datatype.AvroType :param avroType: AvroType object :rtype: avro.schema.Schema :return: schema object for the Avro library """ return avroType.schema
b1b7e61186d965ac2976fa43afe1f35e8eb86b8d
613,163
def indexed_view(indx, ndarray, axis): """Return last view along specified axis E.g. ndarray[:,:,indx,:] if axis=2 :indx: :ndarray: :axis: :returns: ndarray """ n=ndarray.ndim pretuple=[slice(None)]*ndarray.ndim pretuple[axis]=indx return ndarray[tuple(pretuple)]
b89036ef2cf4c7ef06a3d44c8406c5077bbc3964
613,164
def strclass(cls): """Generate a class name string, including module path. Remove module '__main__' from the ID, as it is not useful in most cases. """ if cls.__module__ == "__main__": return cls.__name__ return f"{cls.__module__}.{cls.__name__}"
d2ca0f6e4dcdb737c67935172fa977a529fc9f80
613,166
def delcastillo_katz_model(l, emax, kd, tau): """Del Castillo-Katz model of receptor-response. The Del Castillo-Katz model corresponds to a two-state receptor activation model with a linear effect response: L + R <--kd--> LR <--tau--> LR* ---> Effect, Here tau represents the ratio of active rece...
aa0ac5881ba688dc46077fea9bac4172e79857fc
613,167
def looks_like_image(path): """Returns True if the given path looks like a NIFTI/ANALYZE image. """ return any((path.endswith('.nii'), path.endswith('.nii.gz'), path.endswith('.img'), path.endswith('.hdr'), path.endswith('.img.gz'), ...
093277d2c850cae785ea455d0c194302781e397c
613,168
def _split(data, labels, chunk_size, fraction): """Return two tuples of couple (data, labels). Each tuple containing a multiple of <chunk_size> elements. Firts tuple represents an approximative proportion of 1 - <fraction>, while second tuple represents a proportion of <fraction>. """ n_1 = chunk_s...
973b2d4edb128eb3642a845deaddcd9085e2b518
613,169
from typing import Dict def parse(path: str) -> Dict: """Parses any file from http://www.math.uwaterloo.ca/tsp/world/countries.html. The files are in a format where there are two sections. The first section has metadata about the country, including the name, number of cities and comments. The second ...
3500597a0e0df69fe32a2858d5a674a290ec9f9b
613,174
from typing import Union def read_field(dictionary: dict, key: str) -> Union[str, None]: """ Read field value from dictionary. If there is no `key` in `dictionary` or value is equal to `N/A` return `None` :param dictionary: container to read from :param key: key to look up :return: value or N...
a2a03c65d6cf9acb423e9fff20367ba9d6642873
613,175
def get_standard_parallels(srs): """ Get all standard parallels for a given map projection Parameters ---------- srs : object OSR spatial reference system Returns ------- : list of standard parallels """ parallels = [None, None] for i in range(2): ...
562bffa1312f4b59f881ff0ea54ffdf51444cb37
613,176
def transpose(matrix): """ function to transpose a matrix """ return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
166bc8b786b08d1d235923c4ee9d3a7da1c49b59
613,181
from datetime import datetime def ordinal_to_date(ordinal: int) -> str: """Convert ordinal dates to date strings in ISO-8601 format. Defaults to the current date if a bad value is passed as the argument. :param ordinal: the ordinal date to convert. :return: the ISO-8601 date representation of the pa...
6b6d385247393ba823cbeb4583c0de9b324e2eea
613,186