content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import math def make_divisible(x, divisor): """taken from https://github.com/ultralytics/yolov5/blob/master/utils/general.py""" # Returns x evenly divisible by divisor return math.ceil(x / divisor) * divisor
723f7877018f457b98f30eb6c1b9f20ecfcbba31
573,215
import torch from typing import List def topk_accuracy(output: torch.Tensor, target: torch.Tensor, topk=(1,)) -> List[torch.FloatTensor]: """ Computes the accuracy over the k top predictions for the specified values of k In top-5 accuracy you give yourself credit for having the right answer if the rig...
3af04978fc79e54450a3dfbb55f3163c49e34325
573,221
def ascii_lower(string): """Lower-case, but only in the ASCII range.""" return string.encode('utf8').lower().decode('utf8')
db1dd559463a4c11f8a66355fec3dc17cabf15a2
573,222
def to_enum_member(name: str) -> str: """Maps an enum member name to a python safe enum member name. """ try: int(name[0]) except ValueError: return name else: return f"_{name}"
397762098f480a47dcbdf25a2efb368e997711d6
573,224
def _vipsParameters(forTiled=True, defaultCompression=None, **kwargs): """ Return a dictionary of vips conversion parameters. :param forTiled: True if this is for a tiled image. False for an associated image. :param defaultCompression: if not specified, use this value. Optional parameters...
7b1ce612ce6ba156b266a470e95c10b084029cde
573,232
import torch def swish(x): """Swish activation. This is suggested in arXiv:1710.05941 Args: x (Tensor): input Returns: Tensor """ return x * torch.sigmoid(x)
9e0f49a68aa3a46a3755fcbfa0f563aad097a05f
573,236
import json def load_settings(settings_file: str) -> dict: """Load settings in the script. Return them as a dictionary.""" with open(settings_file, "r") as read_file: settings = json.load(read_file) return settings
fc794b26340f994378f90cb5356cd1cbcc9fc601
573,239
import re def clean_data(filename): """ Opens the data file, deletes all entries, that do not belong to class cp or im, and returns a list of lists with the respective entries""" with open(filename) as input_file: raw_data = input_file.readlines() data = [] for line in raw_data...
9570067140815b991258f8e6ecc2a0ab859f8855
573,241
from typing import List from typing import Dict from typing import Counter def get_category_id_dict_from_dataset(data_dict: List[Dict]) -> Dict: """ Get a dictionary with how many times each category appears in all annotations in a given data_dict Args: data_dict: Data dictionary as returned by Da...
fa08d2be17a1286174909a48326b328256dc6583
573,242
def get_python_exec(py_num: float, is_py2: bool = False) -> str: """ Get python executable Args: py_num(float): Python version X.Y is_py2(bool): for python 2 version, Set True if the returned result should have python2 or False for python. Returns: str: python executable """ ...
b6c816e97c6e1d6d57c6570662c9afc0ac1683a1
573,243
import re def parse_show_interface(raw_result): """ Parse the 'show interface' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'admin_st...
43a56be455e5fef269065ab40d01d205dd13be1b
573,250
def define(name: str, value: str = "") -> str: """ Return C++ macro-string #define name value Used for header defines. Parameters ---------- name : str Name of macro to be defined value : str, optional Value of defined macro (if any), Returns ------- str: ...
444bdf60f6a8e3daae0ad5358ccd397e882d8aca
573,252
import re def note_str_to_num(note, base_octave=-1): """Convert note pitch as string to MIDI note number.""" patt = re.match('^([CDEFGABcdefgab])([b#]*)(-?)(\d+)$', note) if patt is None: raise ValueError('invalid note string "{}"'.format(note)) base_map = {'C': 0, 'D': 2, ...
47a4f2c265f78ba4cf03f8b7bae879d566e50d11
573,253
import re def to_varname(string): """Converts string to correct Python variable name. Replaces unavailable symbols with _ and insert _ if string starts with digit. """ return re.sub(r'\W|^(?=\d)','_', string)
39ae3b91946e1c818f8efbee8a1356c4d7fd00b1
573,255
def format_assumption(step): """Format a proof assumption.""" pred = step['detail']['predicate'] return 'assumption: {}'.format(pred)
e83725e2cc15e885da346aacddb8b8ce4e718d8b
573,256
def sql_ts_agg_stmt(table, groupby_cols, date_col, values_cols, resample_code, period=1, fun='mean', val_round=3, where_lst=None): """ Function to create an SQL statement to pass to an SQL driver to resample a time series table. Parameters ---------- table : str The SQL table name. grou...
eec7e209e447799a7b31ad1fa03ffec65a7fbe1c
573,259
async def monero_get_creds(ctx, address_n=None, network_type=None): """ Credentials derivation method. In the emulated setup (no trezor environment) this fallbacks to retrieving credentials from the context (trezor lite). :param ctx: :param address_n: :param network_type: :return: "...
f5d7368ac23a5b1af5d81ece8d835c4906c67022
573,262
import torch from typing import Tuple def remove_pairs_from_same_domain( batch_domain_indices: torch.Tensor, a_pair_info: torch.Tensor, b_pair_info: torch.Tensor ) -> Tuple[torch.Tensor,torch.Tensor]: """ In training, we want only pairs from different domains. We enforce that their featu...
8ff37febae3084fc1e0a399e1840b5a8903ec1a3
573,263
def unexpected_response_error(api, response, query=None): """format error message for reponse not matching expectations""" msg = "calling: %s: unexpected response %s" % (api, repr(response)) if query: msg += " for query: %s" % repr(query) return response, msg
5e77e7c000e0e590446f0ba3541944863d1732b7
573,264
def SecondsToDuration(value): """Convert seconds expressed as integer to a Duration value.""" return '%ss' % int(value)
ff04b7ef2cf277843e724deac96a70a8d2143aca
573,268
from typing import Optional def validate_ref_dataset_optional(ref_dataset: Optional[int]) -> Optional[int]: """ Validates the reference to a dataset of an object. :param ref_dataset: The reference to a dataset of the object. :return: The validated reference to a dataset. """ if ref_dataset is...
5dfc234d8fd2efa5e203af6334aea6db1f8a2f67
573,273
from typing import Dict import torch def move_to_device(data: Dict[str, torch.Tensor], device: torch.device) -> Dict[str, torch.Tensor]: """Move the data dict to a given torch device :param data: the torch dict :param device: the device where to move each value of the dict :return: the torch dict on ...
6405ac06ce7d42a9004e8c39c1ad5a1fcd036a91
573,274
from typing import Union def avg(items: Union[list, tuple, set]): """Average between items in list/tuple/set.""" return sum(items) / len(items)
caa75d648e4f044961104b26e1c5abbfe5e294e4
573,276
from typing import Union from typing import Callable def decode_with(x, decoder: Union[str, bool, Callable] = False): """Decode ``x`` with specified decoder :param x: Input to decode :param decoder: How to decode (if at all). Could be: bool: If ``False``, leaves ``x`` as is, if ``True`` uses defa...
6bfe648ead5c90cab2aaf7519c9138335a18e4d6
573,277
from typing import List import json def from_json(json_input_file: str) -> List[List[List]]: """Get phonemes from JSON format.""" data = json.load(open(json_input_file)) data = [[list(n.values()) for n in list(m.values())] for m in list(data.values())] return data
48d655b3aac6bb47df3ce551c2ff67d300d74b9f
573,278
def unflatten_like(vector, likeTensorList): """ Takes a flat torch.tensor and unflattens it to a list of torch.tensors shaped like likeTensorList Arguments: vector (torch.tensor): flat one dimensional tensor likeTensorList (list or iterable): list of tensors with same number of ele- ...
ae121ac963df5352d346fb59f8c9560b919e2bb4
573,280
def build_kwargs_write(spec: dict, ext: str) -> dict: """Builds up kwargs for the Pandas to_* functions.""" col_arg_names = {'.parquet': 'partition_cols', '.xls': 'columns', '.xlsx': 'columns', '.csv': 'columns'} kwargs = {} if 'columns' in...
9470b3a138d95dc9a81351480c4677525e4cc3be
573,284
def clamp(frm, to, value): """ Clamps an ordinable type between two others. Complexity: O(1) params: frm: the lower end to: the upper end value: the value returns: the clamped value """ if frm > to: raise ValueError("frm cannot be bigger than to in clamp") ...
cc6c6237fcdcfe0b6340cf50696086f8d7d6489e
573,286
def create_bins(lower_bound, width, upper_bound): """ Creates bin if given the lower and upper bound with the wirdth information. """ bins = [] for low in range(lower_bound, upper_bound, width): bins.append([low, low + width]) return bins
f01fe25d9706d852b5672e6dceca011e73836aaa
573,288
def load_file(infile): """Read and return text file as string of lowercase characters.""" with open(infile) as f: text = f.read().lower() return text
adaf4232de857c3016102d0244976352bed42180
573,289
def adds_message_to_errors_dict(error_message): """A decorator that asserts the the decorated validator adds a given error message to the `errors` dict. :param error_message: the error message that the validator is expected to add to the `errors` dict :type error_message: string Usage: ...
b30f4240ac5f9dd5073d522d1ed5d8f34def4455
573,290
import re def find_pattern(pattern, text, allow_part_of_word = False, enable_case_sensitive_search = False): """ Generic function to match a regex pattern in our metadata quest. By default, the pattern is surrounded by \\b (word boundary) and is case-insensitive. allow_part_of_word (default False) : a...
29443324f503bba6d8c6cacd43c8c389a051a696
573,291
def sp_add2_array(sp, arr): """ :param sp: sparse matrix p-by-1 (created with :py:meth:`~rlpy.tools.general_tools.sp_matrix`) :param arr: a 1-D iterable type (ndarray, list, matrix) of length p. Returns ret = arr + sp (with type(ret) = type(arr)) """ ind = sp.nonzero()[0] for i in ...
f69e0b8da5a7f4f32d94c6233493d7bd6a8d95a8
573,293
def strip_right(s, pattern): """ Strips a string right (end) of string if found. Otherwise, returns the original string. :param s: str :param pattern: str :rtype: str """ if s.endswith(pattern): return s[:-(len(pattern))] else: return s
39f72ad2c38033a74e5983e325fdd67b702b3405
573,295
import yaml def yaml_load(path): """Returns content of YAML file at `path` as a Python object.""" with open(path, 'r', encoding='utf-8') as f: data_yaml = yaml.load(f, Loader=yaml.FullLoader) return data_yaml
abf0e4501c3963cf86ee2e83ba8b91c9410b7fbb
573,297
def get_interest(ammount): """ Returns the ammount owed for interests """ if ammount > 1000: return ammount - ammount * 0.98 return ammount - ammount * 0.985
e7631b670d1c7ab0f6afabda933388cbdc39caf8
573,300
import hashlib def get_md5_bytes(data: bytes) -> str: """Gets the MD5 hash of a bytes object holding data Args: data: Data as a bytes object Returns: str: MD5 hash of data """ return hashlib.md5(data).hexdigest()
09292b6c75b68cdcd03d8e11c84f916174a8c448
573,303
def clean_tokens(tokens): """Returns a list of lemmas from a list of spaCy tokens Args: tokens (list(spaCy_token)): the list of spaCy tokens to pull lemmas from Returns: list: a list of lemmas corresponding to the tokens passed in """ cleaned_tokens = [] for token in to...
9e6d16dbc1be101ec7d248b8afaa4834df1de3fc
573,307
def _indent_of(s): """Return the prefix of s that is whitespace.""" return s[:len(s) - len(s.lstrip(" \t"))]
a91ec607fd9706128d1db682816b157b22a938b1
573,313
import re def is_strong_pw(text: str) -> bool: """Is strong password Uses three :py:mod:`re` object patterns to check if a given text is at least 8 numbers and characters long, has at least one uppercase and lowercase character, and has at least one digit. Args: text: String containing p...
0184fd8874f6494d6858a2d94cd6e61da89927cf
573,323
def find_substring(content: str, start_pos: int, end_pos: int) -> str: """Metin içerisinde metin arama Arguments: content {str} -- Metin start_pos {int} -- Başlangıç indeksi (dahil) end_pos {int} -- Bitiş indeksi (dahil değil) Returns: str -- Bulunan metin Examles: ...
2d3040dda0aa757da1d12dfdc33e53cfcaa389d3
573,325
def calculate_perplexity(sentence, n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0): """ Calculate perplexity for a list of sentences Args: sentence: List of strings n_gram_counts: Dictionary of counts of n-grams n_plus1_gram_counts: Dictionary of counts of (n+1)-gram...
3e0598054e161819fb69a6a2ad6cc602662f2701
573,336
def scores( mean_utility_arr, statistic_fns): """Evaluate the statisctics of mean utility of a search space and a budget. Args: mean_utility_arr: (x_drawn_num,) shaped array of utilities at x-locations averaged over their y-values. This array is the output of score function. statistic_fns: a ...
9c1b2d80f23ad697799443586baf68733b787d38
573,337
def uniquify(seq, idfun=None): """Deduplicate elements of list based on value of id function idfun.""" # order preserving if idfun is None: idfun = lambda x: x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen...
6bf74dd250855ee10d7e0d322f5e52db6a72f1ab
573,338
import logging def setup_logging(logging_level): """Setup logger with the given logging level.""" logger = logging.getLogger(__name__) logging.basicConfig(level=logging_level, format='%(asctime)-15s %(message)s') return logger
4a124185c5cdbe15d228489c9f0b60fc2eb6ec29
573,340
import math def get_forward_angle(fix1, fix2): """Calculates forward azimuth between two positions in radians.""" lat1 = math.radians(fix1.latitude) lon1 = math.radians(fix1.longitude) lat2 = math.radians(fix2.latitude) lon2 = math.radians(fix2.longitude) y = math.sin(lon2 - lon1) * math.cos(...
d2418db07a5a95e56e9e112722a272bf35fbaf41
573,342
def standardize_tailmen(tailmen): """This function aims at standardizing the household size. The column has mixed types (ints and strings). Args: tailmen (str): household size as recorded, can be category (1 to 4 people) or float (4.0 = there are 4 people in the household). Returns: ...
23b6445a4cff2c7fe80e8fa80ee046627d923bce
573,345
def decode_ids(ids, vocab): """Decode the ids to the corresponding characters. """ out = [] for _id in ids: out.append(vocab[_id]) return out
52ad32716e43cd6e807ccbc0c11bfcda877a5632
573,348
def invertImage(imgarray): """ returns a contrast inverted image """ return -1.0*imgarray
74f52a5500b91306c79320f03d3b6024c6316d08
573,351
def _makefpartparamsizes(nbparams): """return a struct format to read part parameter sizes The number parameters is variable so we need to build that format dynamically. """ return b'>' + (b'BB' * nbparams)
0e6277dd63edd170c80c44f106aff21fd2cf4006
573,352
def sanitize_module_name(modname): """ Sanitizes a module name so it can be used as a variable """ return modname.replace(".", "_")
e8b37c5dbbc00bcb8dbb8ef3458c0a85685d03de
573,363
def parse_time_interval(time_arg): """Parse a simple string representing a time interval and return an integer number of seconds""" try: return int(time_arg) except ValueError: pass if time_arg.endswith('s'): seconds = int(time_arg[:-1]) elif time_arg.endswith('m'): s...
8790a2397b43a017adfdea27bc5dab80742c6cbe
573,364
def get_roi(img, p1, p2): """ extract region of interest from an image. p1, p2: two tuples standing for two opposite corners of the rectangle bounding the roi. Their order is arbitrary. """ x1, y1 = p1 x2, y2 = p2 x_min = min([x1, x2]) y_min = min([y1, y2]) x_max = max([x1,...
488e45be43420010f100ce5b3ee45c480a8f8656
573,366
def splitlines(string: str) -> list[str]: """Splits a newline-delimited string into a list of newline-delimited strings. Suitable for `difflib.Differ.compare`. """ lines = string.splitlines(keepends=False) # `splitlines(keepends=True)` would work, but the last line is problematic. This # manual...
bd046a66e4e31ac4c3f82f3732313459282fed7e
573,368
def pca_reconstruction(x, basis, xmean=None): """Map x in the PCA space back to the original space using the basis and mean of the PCA mapping.""" xrec = x.dot(basis.T) if xmean is not None: xrec += xmean return xrec
e37a42dcd9fe90830a7198c81ae9c29bb0ff01d6
573,369
import pathlib from typing import List def _get_pkgfiles_and_dirs_at_path(path: pathlib.Path) -> tuple: """Utility function to get the tar.gz files and the directories at a given URL. """ packages: List[pathlib.Path] = [] dirs: List[pathlib.Path] = [] if not path.exists(): return pack...
c495076cf055280fd37ef74ffedf7471455260ea
573,371
def get_area_from_bbox(bbox): """ bbox: [x1,y1,x2,y2] return: area of bbox """ assert bbox[2] > bbox[0] assert bbox[3] > bbox[1] return int(bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
19ed3f9a711a9db9c09aeea6f59525a615117899
573,374
def limit_dataset(df,byvar="beacon",id_list=range(0,51,1)): """limits datasets to only including observations from certain participants""" return df[df[byvar].isin(id_list)]
03fb574911dd642a5fa512fb5daa4aa9268ab1ee
573,376
def _node_value(G, node_attr): """Returns a function that returns a value from G.nodes[u]. We return a function expecting a node as its sole argument. Then, in the simplest scenario, the returned function will return G.nodes[u][node_attr]. However, we also handle the case when `node_attr` is None or wh...
6a8b061000c01686e6ead30df70bbec0f0e0957c
573,378
import torch def linear_bezier(params: torch.Tensor, t: torch.Tensor) -> torch.Tensor: """Evaluate a batch of linear bezier curves at different points. This is predominantly for testing, as it would be much more efficient to utilise line segments in a distance transform computation. Args: ...
a33f243d723b540886ee06af2b7805d73650a725
573,379
def find_tag_positions(html: str) -> list: """ Finds the position of HTML opening and closing tag characters ("<", ">"). Args: - html: the HTML string to parse Returns: list of positions. Note that it includes all tags, even those in comments, and they should be ignored. (The extract_active...
c8ad392df9b742cfc94f2f768c4580430af42172
573,382
from typing import List from typing import Optional def get_matching_option(options: List, data: str) -> Optional[str]: """ Extracts the environment or role matching one of those defined in a list. :param options: List of available environments or roles. :param data: Input data. :return: First str...
1784e160c0dd065817c80df9259ed1e212e66d23
573,385
def is_hex(color): """ Method to check if a color code is hexadecimal (HEX) This method returns the value True if the input argument corresponds to an hexadecimal color code. Parameters ---------- color: :obj: Color code Returns ------- bool True if the input colo...
8b8dafa1d59ceba27f423a5dc592c9936b85df54
573,391
import click def validate_positive_int(ctx, param, value): """Callback to validate param passed is a positive integer.""" if isinstance(value, int) and value > 0: return value raise click.BadParameter("Must be a positive integer")
78cf6f677d47e30b58e0e6ac1bdf3caa40134338
573,394
def input_soil(P, Dt, X, soil_upstream_inflow): """Compute the total input to a soil store. Calculate the total rate of input to a single soil store. This comprises the sum of rainfall input, subsurface contribution from upstream cells and the overland contribution from upstream cells. Parameters ...
01dbb16de0b1d296776849b632e65bbc9f052a31
573,400
import base64 def parse_workchain(smc_address: str) -> int: """Parse workchain https://ton.org/docs/#/howto/step-by-step""" decoded_addr = base64.urlsafe_b64decode(smc_address) worckchain_signed_8 = decoded_addr[1] worckchain_signed_8 = (((worckchain_signed_8 >> 7) * 128) ^ worckchain_signed_8) - ( ...
6e8e5f4cac0c9b6658f8fd67003ea4cab6d57953
573,401
def json_ld_get_activities_list_from_rawdata(data): """Return list of processes from raw data.""" return list(data["processes"].values())
8828d6a777875464d5eec710deae2a6b69863a38
573,402
from pathlib import Path def wc(path): """Count lines in the file""" i = 0 with Path(path).open() as f: for line in f: i += 1 return i
349a1c7a4a9faa0020bf71bd4ba2cb127d9d5d35
573,403
def sparse(v): """ Returns the vector with features that have weight 0 removed. """ for f, w in list(v.items()): if w == 0: del v[f] return v
360ab41e0e8efe2e8f1d7b896e491dc82f9947e4
573,405
def commonextent(*args): """ compute the common extent of multiple extent dictionaries. Parameters ---------- args: dict an extent dictionary, see e.g. :attr:`spatialist.vector.Vector.extent` Returns ------- dict: the common extent """ ext_new = {} for e...
a3794ac547ed85e6619a83e3f8c376dd45fca629
573,406
def create_np_dtype(py_obj, h_group, name, **kwargs): """ dumps an numpy dtype object to h5py file Parameters ---------- py_obj (numpy.dtype): python object to dump; should be a numpy dtype, e.g. numpy.float16 h_group (h5.File.group): group to dump data into. name (str): ...
0bc2e2791c38e98a1c65484d42972332740e61a9
573,408
def has_same_clues(puzzle, solution): """Returns true if the cells in puzzle have the same value in solution. Args: puzzle: The original puzzle, expected to have some empty cells. solution: The solved puzzle. Returns: True if every non-empty cell in puzzle has the same value in ...
cd27e1669a64db268fd77e18c62e764c975baa65
573,409
def parse_time_diff(x): """utility function for parsing a time difference to make it nicely readable Parameters ---------- x : float number which will be formatted """ if x >= 60: return "{:.2f} min".format(x / 60) elif x < .5: return "{:.2f} ms".format(x * 1000) ...
bd1572aa995365be4294fc81d087d79d5fc740d4
573,411
def clean_subs(subs): """ Takes messy subs dicts and cleans it up. :param subs: Substitutions dictionary :return: Dict with proper uniting """ cleaned_subs = {} vks = subs.keys() for vk in vks: try: cleaned_subs[vk] = subs[vk].value except: cleaned...
1fc650013906faff57bf46b20deb5e87918b01a5
573,412
def denormalize_images(predictor_matrix, predictor_names, normalization_dict): """Denormalizes images from z-scores back to original scales. :param predictor_matrix: See doc for `normalize_images`. :param predictor_names: Same. :param normalization_dict: Same. :return: predictor_matrix: Denormalize...
32e0d62ac3c68a89fec1403ddccd4d871785891b
573,413
def get_mean(iterable): """ Returns the mean of a given iterable which is defined as the sum divided by the number of items. """ return sum(iterable) / len(iterable)
c1a5a81a7ac9c04991145a8b8245f8cd05af5fcb
573,414
def split_type(line): """Splits off the first word in the line and returns both parts in a tuple. Also eliminates all leading and trailing spaces. Example: split_type('ROW ##.##') returns ('ROW', '##.##') split_type('CLUE (0,1) down: Of or pertaining to the voice (5)') returns ('...
87ec135f5ac5e436a47ae806c189bfeccf19caf6
573,415
def table_publish_format(name, timestamp, table, data): """ Return a dictionary for use in the results publish""" table_key = str(str(name) + '&' + str(timestamp)) return [table_key, [table, data]]
c30b345c0a22d93d41d131e009613d291af1efe5
573,416
import string import random def gen_random_string(len_name=10): """ Generates a random string of the specified length using the ASCII characters excluding special chars :param int len_name: Specifies length of the string to generate. default 10 :return: Random string of specified length :rtyp...
99d6b61755853f35bc5cff8c12a158760f9fd614
573,418
from typing import Dict from typing import Any from typing import Hashable def dict_hashable_values(items: Dict[str, Any]) -> Dict[str, Hashable]: """Return new dictionary where all values are Hashable (value is converted to string when not Hashable)""" return {k: v if isinstance(v, Hashable) else str(v) for ...
ea8cc3436b517d71680be97ac7e0204917d74163
573,419
def is_major_inc(commit): """Returns true if commit.message contains a major inc command""" return "+major" in commit.message
9fc2228c387884ed5827c6c24916a1fed2f9ea57
573,421
import re def camel_to_snake(s): """Convert `CamelCase` to the `snake_case`. Credits: * https://stackoverflow.com/users/1522117 * https://stackoverflow.com/users/3423324/luckydonald References: * https://stackoverflow.com/a/12867228 """ a = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)(?<!_)[A-Z](?=[a-z]))'...
777cb633dcc9a0e10a6c5496f1387ac1aa76b6d4
573,422
def map_number(n, exponent): """Elevate a number to an exponent.""" return n ** exponent
3073dfabe1a984cfecd8825b57f7ba7765cbb4f6
573,430
def _identify_tag_combination(tags_dict, test_tags_dict, true_value=True, none_value=None, **unused): """Test whether there all of a particular combination of tags are in ``tags_dict``. tags_dict : :obj:`dict` Dictionary of tags related to OSM element test_tags_dict : :obj:`dict` Dicti...
c91fad95cb8dcceddc37a129263731ab821100b0
573,432
from typing import AnyStr from typing import Optional def rstrip_min(string: AnyStr, min_len: int, chars: Optional[AnyStr] = None) -> AnyStr: """:meth:`str.rstrip` but keep first ``min_len`` chars unchanged.""" str_copy = string result = string.rstrip(chars) return str_copy[:min_len] if...
91ea90c90450bcb6a3295355837c6a3b2f6a9c40
573,433
def find_root(nodes): """Find the root of the tree :nodes: dict of Node objects :return: root Node""" # pick a node and follow its parent up until we got one without a parent root = next(iter(nodes.values())) while root.parent: root = root.parent return root
46ccf3eaed3bd865d4b005030ed63135b04994f2
573,434
def normalize_to_start_of_day(dt): """ Normalizes a datetime value to the start of it's day Args: dt (datetime.datetime): the datetime to normalize Returns: datetime.datetime: the normalized datetime """ return dt.replace(hour=0, minute=0, second=0, microsecond=0)
be219e0cb058a4d1aa5d32c116da6db3bc8175ce
573,437
def anish_astakh(XYZ, t, u=1.2, n=0.5): """ The Anishenko-Astakhov Attractor. x0 = (0.1,0,0) """ x, y, z = XYZ i = 1 if x >= 0 else 0 x_dt = u * x + y - x * z y_dt = -x z_dt = -n * z + n * i * x**2 return x_dt, y_dt, z_dt
39459c5e4c1269d9b1e76a16d767a573ed397a30
573,439
from re import VERBOSE def phe(pointer, main_stack, aux_stack): """ Phe Put aux stack on top of main stack, preserving its order """ if VERBOSE: print("Phe", main_stack, aux_stack) main_stack += aux_stack aux_stack = [] return(pointer, main_stack, aux_stack)
44ddeda22cdb163765e3e75ed442c71437b34b58
573,441
def unsafe_peek(init): """ Deserialize all the attributes available in the container and pass them in the same order as they come in the container. This is a factory function; returns the actual `peek` routine. Arguments: init: type constructor. Returns: callable: deserializ...
fa6ea263fc9eb8672f1114fc382cdc5644684cbd
573,442
def chalNameToChalID(configFile,chalName,defaultValue=None): """ returns chalID for a given chalName """ v = defaultValue try: v = configFile[chalName]['chal_id'] except: pass return v
c8e633cc63a694f3bad883caa6db4384d34368f9
573,445
def build_azure_signed_url_write_headers(content_length: str, x_ms_blob_type: str = 'BlockBlob', accept: str = '*/*', accept_encoding: str = '*'): """Builds the headers required for a SAS PUT t...
1f4df6eb15e38218f0d2948ce8a121234367a767
573,451
def get_counts_per_label(y_true, n_classes): """ Return a map of {label: number of data points with that label} for the given list of labels Parameters: - y_true: (integer) a list of labels - n_classes: (integer) the number of classes """ label_counts = [0] * n_classes for label...
a6f36900e24b90c6525263e3cd8a7cb71493ae1b
573,454
import posixpath def is_special_file(name): """Returns true if a file is some special Git metadata and not content.""" return posixpath.basename(name) in ['.gitignore', '.gitattributes', '.gitmodules', '.gitftpignore']
94aa516c0e2d0987d1096d6958203884dbf451c5
573,455
import re def get_motif_stats(motifs): """Get the GC content and the length for a list of motifs Parameter: ---------- motifs : list A list of gimmemotifs motif objects. Return: ------- motif_stats : dict A dictionary containing the motif name as key and a list with GC content and motif length as valu...
e691e36bc5723f0b0e6d13b7b00fe55873419f20
573,458
def parse_section(fin): """ Parse a section from the tssv report NOTE: this moves the file pointer forwards """ section = list() # Get the header header = next(fin).strip('\n').split('\t') # Parse the other files for line in fin: # End of section if not line.strip('\n'...
4a0d8738b205676c8dc813c269ee0723e9450c2c
573,460
def get_cost(record): """Parse CDS cost string to extract currency and value.""" SUPPORTED_CURRENCIES = ["EUR", "USD", "GBP", "CHF", "YEN"] # NOTE: We will try to extract and migrate only the most common case, which # comes to the form "EUR 88.40". If it comes in any other form will # store it in no...
93bd22556313db65318b7312c563c29e25335788
573,463
def prepend(string, prefix): """Append something to the beginning of another string. Parameters ---------- string : str String to prepend to. prefix : str String to add to the beginning. Returns ------- str String with the addition to the beginning. Notes ...
31065e7d4121681d89b57b8d954e08713152b9e8
573,464
import networkx def create_subnet(edges): """ Create a subnetwork from an edge list """ subnet = networkx.MultiGraph() for edge in edges: subnet.add_edge(edge.start_node, edge.end_node, edge.key) return subnet
9f8b06fb6538831e2db86df0cea652877d20eac3
573,471
def f(x): """Compute quadratic function.""" return x ** 2
568f3a53024e7598d3e4fae755fd6541e858ed8c
573,474