content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import argparse from sys import version def cmdLineHandler(): """ Command Line Handler @param return: Instance of class argparse.Namespace containing all the parsed command line arguments. """ parser = argparse.ArgumentParser(description="Run Leo-Babel Tests", usage='%(prog)s [options] tests re...
b672e6b035fae7eb2cca816b6eb6e47b55ecc7d2
657,585
import math def entropy(features): """ Calculates the entropy of all the categories for every feature. Parameters ---------- features : dictionary a dictionary of features with keys as feature name and values as objects of feature class. Returns ------- featu...
232cee07ca9983c6ba0651dab945a8a08534b33f
657,586
import json def get_keys_and_secrets(): """ Function to aggregate all keys and secrets for simplicity and return an easy tuple to parse """ ## Need to add your own details.json with your keys and secrets ## credentials = {} with open("details.json",'r') as file: credentials = json.load...
9e557d54e587ad737a6d7cb962ee505cdc885529
657,587
import re def get_life_range(source): """ Return the birth and death year from _source (as a tuple). Return empty strings if not available. """ years = [] for event in ["from", "to"]: if source["lifespan"].get(event): date = source["lifespan"][event].get("date", "") ...
c85e9446ebcf8ed6f8019f84a61c07989ad1c8f0
657,589
def reverse_and_add(n): """Returns n + reversed(n).""" return n + int(str(n)[::-1])
67052b91a66d921dc13e6d481c83180d388a90ca
657,590
def one(s): """Get one element of a set""" return next(iter(s))
45ce1607e5d4b6bf2fc53cfc2da5602ccdc83910
657,591
def empty_string(): """Return string.""" return ''
316ebc6dfb4db887397a5655e58fcc90a8944c1f
657,592
def boxes_to_geojson(boxes, class_ids, crs_transformer, class_map, scores=None): """Convert boxes and associated data into a GeoJSON dict. Args: boxes: list of Box in pixel row/col format. class_ids: list of int (one for each box) crs_transformer: CRSTransformer use...
ddf258d8a25a227ff00b7d036149408e7a2afe59
657,593
def perturb(x, prn): """ Randomly perturb an integer point. Parameters ---------- x : tuple of int Point to be perturbed prn : prng.MRG32k3a object Returns ------- tuple of float The perturbed point """ q = len(x) return tuple(x[i] + 0.3*(prn.random() - ...
ea3156b3b6ca2993d7d6c9c713d9f5ae93b0d9cd
657,594
def create_input(afferetntFiringRate,time): """ Load previously computed affarent inputs """ afferents = {} afferents['GM'] = {} dtUpdateAfferent = 5. afferents['GM']['Iaf'] = [afferetntFiringRate]*(int(time/dtUpdateAfferent)+1) afferentsInput = [afferents,dtUpdateAfferent] return afferentsInput
09b8b93def996e728182c8ce1c4be3138326546f
657,595
import re def generate_content_type(type, version=2): """ Generate the Content-Type header, including a version number Content-Types look like: application/vnd.ozp-iwc+json;version=1 """ try: version = re.findall(r'version=(\d+)', type)[0] # version number found already - just use...
7aa9669f9c567a4526de45da3b57bf952cb22011
657,596
def dimension_constraint(): """ A helper function to restric dimensions """ def _dim_check(attrs): if len(attrs['pool_size']) in [1, 2, 3]: return True return False return _dim_check, "Only 1d, 2d, 3d kernel supported."
ce53b088b596bfd4cd9f122ecc80028e35848934
657,597
def compute_P(new_h, past_observations): """Computes weighting factor. Parameters ---------- new_h : float Altitude of current observation. past_observations : list List of past ``Observation`` objects of the same source. """ if len(past_observations) == 0: P = 1 ...
7cdc27ab3ad917e63ed651a3a6b4c67c177bf79b
657,598
import os def output_path_concat(path, im_path): """Creates a file path of an image Returns an output file path for the resized images Parameters ---------- path: a path (str) a string that lead to an existing file path im_path: an image path (str) a string that leads to an e...
659ae45d30b84dad8e28d18d0840303edfde9132
657,599
import six def greedy_max_inden_setcover(candidate_sets_dict, items, max_covers=None): """ greedy algorithm for maximum independent set cover Covers items with sets from candidate sets. Could be made faster. CommandLine: python -m utool.util_alg --test-greedy_max_inden_setcover Example0...
2545990e0a74102d9137bc37a12e661d0e184a0c
657,600
def LogFiles(log_prefix): """Determines the filenames for the instmake log and the make output log by using an arbitrary prefix. Returns a tuple of the two filenames (instmake_log, make_log).""" imlog = log_prefix + ".imlog" mklog = log_prefix + ".make.out" return (imlog, mklog)
f96644abdf557a4300226200b130a42093a84add
657,601
import os def parse_pres_pipes(pres_desc_str): """ Parse presentation structure. This function separates the code of the different slides of the presentation. """ # remove comment lines pres_desc_lines = pres_desc_str.splitlines() pres_desc_lines_nocomment = [] for line in pres_des...
fea466d6f0a5945de9f22741927f300041e56c56
657,602
import json def to_json(response): """" Convert response to JSON """ return json.loads(response.content.decode("utf-8"))
41e06b184c354b9ea8f7e56dea5ea968529d02ba
657,603
def scalar_ne(x, y): """Implement `scalar_ne`.""" return x != y
de68a171645f65d34c32d6c4869c5c219cdf02ed
657,604
def test_apply(plane): """Test whether the apply method works with numpy functions.""" def return_array(image): return image def return_scalar(image): return 123 assert plane.apply(return_array) == plane assert plane.apply(return_scalar) == 123
1847b08a9b24e0e4568f6e887a75c3dbf662406c
657,605
import os def make_local_filename(out_path: str, url: str) -> str: """ Choose a local filename for a given URL. """ filename = os.path.join(out_path, url).replace(":", "") if filename.endswith("/") or os.path.isdir(filename): filename += "index.html" elif not filename.endswith(".html...
225f6b38df81920d9b125a7f3089e57fe1170b56
657,607
def mapVal(inputPos, in_min, in_max, out_min, out_max): """ This function will linearly scale an incoming value belonging to a certain range (in_max - in_min) to a new value in the out range (out_max - out_min). """ scale = ((out_max - out_min) / (in_max - in_min)) return float(((in...
ce360266bd061ed82771e08b2480300b4c64ec8e
657,608
from typing import Union from typing import AnyStr from typing import Iterable def is_blank(obj: Union[AnyStr, Iterable, None]) -> bool: """ True if line is empty string, None, string that contains only spaces and space like characters, or line is iterable that contains only these kinds of strings/obj...
9d93ce0eccaa65a10302a13111bcb8ca94d39b1e
657,609
def _convert_to_transformer_inputs(question, answer, tokenizer, max_sequence_length): """Converts tokenized input to ids, masks and segments for transformer (including bert)""" def return_id(str1, str2, truncation_strategy, length): inputs = tokenizer.encode_plus(str1, str2, add_specia...
4d1835b53a10b2fe80db82af60d066576e9261fd
657,610
import re def parse_requirements(*filenames): """ We generate our install_requires from the pip-requires and test-requires files so that we don't have to maintain the dependency definitions in two places. """ requirements = [] for f in filenames: for line in open(f, 'r').read().spl...
2b3f95c6f36b09285b3b6a774fa92d2cda12b587
657,611
from pathlib import Path import re from typing import Dict def find_latest_xml_file(dir_name: Path) -> Path: """ Find the latest timestamped xml files, with un-timestamped files as a fallback if no timestamped file is found :raise FileNotFoundError: if either file can't be found """ name_pattern ...
ebfa9496ac46714092fe9b5dd35ea2b5a890197e
657,612
def translate(text, conversion_dict, before=lambda _: _): """ Translate words from a text using a conversion dictionary @brief text The text to be translated @brief conversion_dict The conversion dictionary @brief before A function to transform the input """ # if empty: if not text: return ...
d597246ed74205e5911d1a2d6a8485546e390c8d
657,613
def prune_by_tum_detect(iqms): """Prunes to only contain IQMs for imgs with identifiable tumour Parameters ---------- iqms : dict The dict of IQMs for one beamformer Returns ------- pruned_iqms : dict The dict of the IQMs for all images which had an identifiable tum...
ebddbc482190b420d9ae1fad8be4d3e35b07aaad
657,614
import logging from datetime import datetime def log_time(target, message, log_method=None, target_args=None, target_kwargs=None): """Execute target and log the start/elapsed time before and after execution""" logger = logging.info if log_method is not None: logger = log_method start_time = datetime.now() lo...
9a7387338fea9c26807ab71f40caebc0b378adbe
657,615
def extract_exposed_seqeunces(sequence, distlist, cutofffreq): """(str,[float, str], float) ->[str,str...] 2013-12-02 18:51 WEV this should index the dotbrackets and then pull the sequences from the components """ minimumnumberofbases = 1 #print sequence #print distlist listofstartstop =...
4228316b2b5d2db5781b7dec535bf0b5b1bc3f07
657,616
def lowercase_f(x): """ Returns all strings in a Pandas Series `x` in lowercase. """ return x.str.lower()
6573cc1d0b5d28ea916ff9a4632ed89fa0038456
657,617
from typing import Any def invert_results_dict( results: dict[str, dict[str, dict[str, dict[str, list]]]] ) -> list[dict[str, Any]]: """ Flatten the results nested dictionary into a CSV-writable format. Results has the following nested structure as input: dict[directory, dict[trial, dict[cut, dict...
99fdfad9a8d72ee155f2e50168d9e71220c7e85f
657,618
def get_neighbor_verts(vertex): """ Return the neighbor vertices of a vertex! """ edges = vertex.link_edges[:] relevant_neighbour_verts = {v for e in edges for v in e.verts[:] if v != vertex} return relevant_neighbour_verts
3163e2471d0bc6493cbb5b29a0c14a8e2432f783
657,619
import os def read_register_result(resultpath, id1, id2): """ Read the registration result of {id1} & {id2} from the resultpath Return values contain the inlier_number, inlier_ratio, flag(indicating whether this pair is a ground truth match). """ # cloud_bin_s = f'Hokuyo_{id1}' # cloud_bin_t =...
4765db0fc5746a5aa6c373d20f619658de7a936f
657,620
def _construct_grounding_map(rows): """Construct grounding map from rows in a grounding_map csv file Parameters ---------- rows : list List of rows from a grounding map csv file. File should contain seven columns, the first of which is an agent text. The remaining columns contai...
54b6dfdba6b2e9dd9ece2bb8c902efc4e0e33aad
657,621
def check_password_format(password, username, email): """ Checks that the password adheres to the rules defined by this function. See `password_requirements`. :param password: :param username: :param email: :return: True if ok """ if not ((any(s.isupper() for s in password)) and (any...
e1de73447fdc55ad978edab75e36e27267d2669f
657,622
from typing import Optional def get_next_id(current_id: int, size: int, total: int) -> Optional[int]: """Get next id. Assumes a simple list. Args: current_id: Current element index. size: Size of a page. total: Total elements. Returns: ``None``, if there is no next p...
bfaf133973f34383e335b85693170905035c3e04
657,624
def _parse_offset_limit(request): """Parse offset and limit values from a given Flask request and return a tuple containing both. """ offset = request.args.get("offset", default=0, type=int) limit = request.args.get("limit", default=None, type=int) if limit is not None: limit = offset + ...
61ac9d1ed69b82cade39754612d08749a4566d3b
657,625
def calcDailyTravelDistance(self): """ :return: Returns daily travel distance per household """ dailyDistances = self.data.loc[:, ['hhPersonID', 'tripDistance']].groupby(by=['hhPersonID']).sum() return dailyDistances.mean()
4a432bd20dd1ce14514a3d3fd9b07456b9d6dada
657,626
def split_to_sections(text) -> list[str]: """ "Return the list of text sections. The separator of the sections is '--\n' line in the original text """ lines = text.split("\n") sections = [] section_lines = [] for line in lines: if line == "--": section = "\n".join(sectio...
1560105b33fbed329f4812513838e85509152b46
657,627
import torch def trans_imu_smooth(trans_params, imu_trans): """ :param trans_params: :param imu_trans: :return: """ trans_diffs = torch.norm(trans_params[:-1,:] - trans_params[1:, :], dim =1) imu_diffs = torch.norm(torch.tensor(imu_trans[:-1,:] - imu_trans[1:, :], dtype = torch.float, devi...
ff8e549ca3c0c85de39e36a551f0dd0b375e8bd6
657,628
import numpy def _sample_over_ranges(rngs, nsamp): """ randomly sample over several ranges """ nrng = len(rngs) samp_mat = numpy.random.rand(nsamp, nrng) for i, (start, stop) in enumerate(rngs): samp_mat[:, i] = samp_mat[:, i] * (stop - start) + start return tuple(map(tuple, samp_mat))
b48f2813b51535b1c7d293e69d1dc1a54a4c36be
657,629
def pk_intersection_finder(query_1, query_2): """This takes two querysets and finds the intersection between the two queries pks. One query needs a dog.pk attribute and the other .pk) Returns a list.""" query_1_pks = set() for item in query_1: query_1_pks.add(item.dog.pk) query_2_pks = ...
8458b0ea18a93c9fcb396e244a4f9968c760cbaf
657,630
import re def sectionRecursive(configtree, section): """ parse configtree recursively and return config with the desired matches in dict section """ ret = dict() branchkeys = configtree.keys() if len(section) == 0: # no more section matches available, return whole subtree return co...
278a08c8b2794d2a09ced638261940099fb1989f
657,631
def decode_core(device, corefile, result_file='', timeout=300): """ Function to decode the given corefile """ cmd = "/auto/mcp-project1/decoder/decode.py --noemail {cf}".format( cf=corefile) decode_output = '' try: decode_output = device.api.execute("{command}".format(command=cmd), ...
213bc526addc2c79550851d7f70653cf894644e0
657,632
def location(self) -> str: """Get the raw location inside the document :returns: The location inside the document """ return self.url.split("#")[1]
191a0041645ecd4179dd901d111b863daec908ab
657,633
def ucfirst(string): """ Convert the first character of a string to uppercase. """ return string[:1].upper() + string[1:]
95b495be087e4a779713626ea22628e558c6c6a7
657,634
import re def is_reinstate_line(op): """Tell if line is one of the legal lines to exist within entry push.""" # Zeroing. match = re.match(r'\s*xor.*\s+%(\S+)\s?,.*', op, re.IGNORECASE) if match: return True # Moving labels into registers. match = re.match(r'\s*mov\w\s+\$[a-zA-Z_]\S*,\s+%\w+$', op, re....
b6e45a6aa218d284ee0fa9daa31182524d331d1a
657,635
def define_tuner_hparam_space(hparam_space_type): """Define tunable hparams for grid search.""" if hparam_space_type != 'ga': raise ValueError('Hparam space is not valid: "%s"' % hparam_space_type) return { 'population_size': [10, 25, 50, 100, 500], 'crossover_rate': [0.2, 0.5, 0.7, 0.9, 0.95], ...
ab9d3d11a664d0526945fe16ca9173d80e6454f9
657,636
def create_demo(ec2): """Create EC2 Node Demo >>> from ec2demo import get_ec2, create_demo >>> ec2 = get_ec2() >>> node = create_demo(ec2) >>> node <Node: uuid=9d1..., name=i-7b1fa910, state=3, public_ip=[''], ...> And to destroy the node: >>> node.destroy() If you've accidentall...
7d9fd9fb830cf7b483b452de20828204799b2beb
657,637
def reverse_mac(rmac): """Change LE order to BE.""" if len(rmac) != 12: return None return ( rmac[10:12] + rmac[8:10] + rmac[6:8] + rmac[4:6] + rmac[2:4] + rmac[0:2] )
83c2be1df99524250f4419aabcbe16ab4bebd94e
657,638
import csv def read_lun_file(filename): """Read lun csv file and return the list.""" lunlist = [] with open(filename, 'r') as cvsfile: filereader = csv.reader(cvsfile, delimiter=',') for row in filereader: lunlist.append(row) del lunlist[0] return lunlist
4ad633dcb673c50fc43d9ee81edb88d34c4b2f89
657,639
def IC_NIS(ic_cc, ic_ca, ic_pp, ic_pa, p_nis_a, p_nis_c): """ Calculates the predicted binding affinity value based on the IC-NIS model. """ return -0.09459*ic_cc + -0.10007*ic_ca + 0.19577*ic_pp + -0.22671*ic_pa \ + 0.18681*p_nis_a + 0.13810*p_nis_c + -15.9433
8b4d549cd2eb9162c33a8f984c295a516cb88ad3
657,641
import random def select_j_rand(i, m): """ takes 2 values: the index of our first alpha, and the total number of alphas. A value is randomly chosen, as long as it isn't i """ j = i while(j == i): j = int(random.uniform(0, m)) return j
1a2c348ba036c9509e84de7e734618ceae5cb2a7
657,642
def cga(geoact, geoacs, subff2): """ GEOACT: GA CENTER POINT GEOACS: GA AREA C/SUB 0=None 1=Quest 2=<I2 3=<O2 4=<1/2 DA 5=<1DA 6=<2DA 7=>2DA 8=CG Returns: 0, 1, 88 """ if geoact == 2 or (geoact == 1 and 2 <= geoacs...
4cfe79d76f7c7e0fe2e5ebc136b5d772627fba72
657,643
import re def omitCommas(row): """ Locates data parts with double quotes and removes commas within them. Parameters: row (str): The csv string to be searched for double quotes. Returns: (str): The same string without double quotes and extra commas. """ cases = re.findall('"[^"]+"', row) replaced = [re....
014d90a3d0fa373a58e767a1b8efdb845720737b
657,645
def get_session_workbook(project_path, date_info): """ """ session_path = project_path+"Observations/dss28/%4d/%03d/" % (date_info[1],date_info[4]) wb_name = "%4d-%03d.xlsx" % (date_info[1],date_info[4]) wb_file = session_path+"/"+wb_name return wb_name, wb_file
682749ccfe83efb9512a90998e134610a556b5f2
657,647
def clip(value, minimum=-float("inf"), maximum=float("inf")): """Signal hard clipping""" if value < minimum: return minimum if value > maximum: return maximum return value
d8171e2660960c99e32f3f91c0654c6ee7fdeeeb
657,648
def extract_property(search_str, str): """ This function extracts the first string that matches a given search string from Psi-Mi formatted table's cell :param search_str: A Psi-Mi property that needs to be extracted from a Psi-Mi cell :type search_str: string :param str: A cell of the Psi-Mi format...
78875bed65c465dd70b557d56d8a80cf94a29897
657,649
import os def getFilename(RECORDS_DIR='myo_data'): """ Function to allow user to pick filename of CSV to load in the input records directory. Filename is picked by its index within the directory which is output to the user along with the associated filename. If an inval...
144f2ed40aaa4d9d86aa4ba3a5ad9119313c8bc3
657,650
def d8n_get_all_images_topic_bag(bag): """ Returns the (name, type) of all topics that look like images. """ tat = bag.get_type_and_topic_info() consider_images = [ 'sensor_msgs/Image', 'sensor_msgs/CompressedImage', ] all_types = set() found = [] topics = tat.t...
1093cb8bb13946a170acf2333bcae1617db163d9
657,652
from typing import Dict from typing import Any from pathlib import Path from typing import Optional import json def check_source(pmfpconf: Dict[str, Any], sourcepackdir: Path, template_string: str, env: Optional[str] = None, language: Optional[str] = None) -> Dict[str, Any]: """校验组件所在模板库的信息,通过的话返回模板库信息""" wit...
aeaed36a985803cf58c5865ddd681cbe77d1e127
657,653
def get_window_content(center, whole_context, windows_size): """given whole context, center then return window's content in range windows_size by character Args: center(str): center word whole_context(str): whole context windows_size(int): window size Returns: list: window'...
bcc4dfda2fd7344a92d8315717df339e7784fc4f
657,654
def estimatePublishedYear(authorYearOfBirth, authorYearOfDeath): """ @param authorYearOfBirth: @param authorYearOfDeath: @return: @rtype text """ estimatedPublishedYear = '' if authorYearOfBirth > 1800: estimatedPublishedYear = (authorYearOfBirth + authorYearOfDeath) // 2 ...
21d5db682db4650424474880b424940dcecb4ffd
657,655
from functools import reduce import operator def extract_key_paths(d, key_paths, field_naming='full', use_default=False, default_val=None): """ getting with a key list or "."-separated string :param d: dict :param key_path: list or "."-separated string of keys :param field_naming: 'full' (default)...
8a9cf629e5ba6e89943c46a072b2503c147629e7
657,656
from typing import Optional from pathlib import Path import os def get_access_token(tokenfile=None, log=None) -> Optional[str]: """Determine the access token from the mounted configmap (nublado2), secret (nublado1), or environment (either). Prefer the mounted version since it can be updated, while the en...
fe9678530bf10fa89ec3ac277f9afcb950235b90
657,657
from typing import Any def is_zero_or_mod_zero(mod: int, counter: int, *, ret: Any = True, alt: Any = False) -> Any: """ test if mod is zero or if counter % mod is 0 if any of the tests are true return ret else return alt :param mod: :param counter: :param ret: :param alt: :retu...
338654d073624076093bd9452046d36889d3971e
657,658
from typing import Optional def validate_text(text: str) -> Optional[int]: """ Validate text message. :param text: text to validate """ if text.lower().startswith('sprint '): sprint, sprint_number = text.split(' ', 1) try: sprint_number = int(sprint_number) exc...
c1dbfafdb90faa1b1eba109edf54b18ce84a2e69
657,659
import re def sanitize_filename(filename, allow_spaces=False): """Strips invalid characters from a filename. Considers `POSIX "fully portable filenames" <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_282>`__ valid. These include: A-Z a-z 0-9 ._- Filename...
a239c4488c97a6c1af1a4531a2cec1723353ce1f
657,661
def get_zip_filename(book_id): """ Get the filename for a zip document with the book identifier. """ return book_id + ".zip"
2919ca946c887a4c51a98af2d7abea1c74816161
657,662
def eta1_Vargaftik_and_Yargin(TK): """Dynamic viscosity of Li monomers Dynamic viscosity of the monomers as a function of temperature. Parameters ---------- TK K, temperature Returns ------- η, Pa s References ---------- Vargaftik, N B, and V S Yargin. Ch 7.4:...
f8c08b3f59d9b0ed97ade08f89928e58c0d546a8
657,663
def _char_police(string): """If a string has bad chars, ignore it. Unclear how a NUL would get in profile data, but Postgres does not allow them in strings. """ if not string: return None if string.find('\x00') > -1: return None return string
4125542a797ab5e0f14dc79e64d901366d8200dd
657,664
import logging import os import subprocess def RunPoolStatsR(poolfile_fp, genes_table_fp): """ inp_d: (dict) contains R_fp (str) Path to R script 'PoolStats.R' output_fp (str) (pool_fp) finished pool file genes_table_fp (str) genes table file path nMapped (int) R_op_fp...
13a0e975b3cdcc997eebab30c910801b75314832
657,666
def leap_year(leap): """ Help on function leap_year in module a1_akmijares: leap_year(leap) -> int leap_year() determines if the year is a leap year which will return as True or False e.g: leap_year(2016) -> True leap_year(2015) -> False (END) """ l_year = leap if l_yea...
0b5f9c4aa16e2b5f241fc4ec3af5b3c73f88e88b
657,667
import re def extract_statuses(raw_html): """Given a dump of HTML data, extract the timestamp and return it as a string value. :param raw_html: Dump from the ticket page. """ re_status = r'<input type="radio" [^<]+name="action" value="([^"]+)' return re.findall(re_status, raw_html)
357c8ebe6e90df25e230c2dec23539feaa89a948
657,668
def ra_dec_prefix(ra_arr, dec_arr, band, prefix): """Get the output file name based on (RA, Dec).""" return [ "{:s}_{:s}_{:s}_{:s}".format( prefix, "{:8.4f}".format(ra).strip(), "{:8.4f}".format(dec).strip(), band.lower().strip() ) for (ra, dec) in zip(ra_arr, dec_arr...
3e9ceee097ad245635b78e0564ad0939ceb88611
657,669
def composeMap(fun1, fun2, l): """ Returns a new list r where each element in r is fun2(fun1(i)) for the corresponding element i in l :param fun1: function :param fun2: function :param l: list :return: list """ # Fill in new = [] for i in l: t = fun2(fun1(i)) ...
f063444936dcdf06059cd89a85bbcf69dc0ded4f
657,671
import argparse def add_atac_args(): """ Arguments for ATAC-seq pipeline """ parser = argparse.ArgumentParser( description='ATACseq pipeline') parser.add_argument('-b', '--build-design', dest='build_design', action='store_true', help='Create design for fastq files') par...
f2b50d9703f013f49556a6f19c27707fd4354f90
657,672
def indented(text, level, indent=2): """Take a multiline text and indent it as a block""" return "\n".join("%s%s" % (level * indent * " ", s) for s in text.splitlines())
8de1460106745de2c33fdba4baacb2d0141340ee
657,673
def _test_data(**overrides): """Returns a valid set of test data to use during API integration tests overrides allows the caller to replace one or more items in the returned dictionary without having to specify the entire thing every time. """ test_data = { 'sender': 'someemail@somedomain.c...
10a8d7eae8547b2d95d4f2baca31a14e1e65e21b
657,674
def get_fixture_or_param_value(request, fixture_or_param_name): """ Returns the value associated with parameter or fixture named `fixture_name`, in provided request context. This is just an easy way to use `getfixturevalue` or `getfuncargvalue` according to whichever is available in current pytest versi...
476b267ff7b0c1b7d0f9a1643d3adca8a3223992
657,675
def list_to_dict(l): """Turn a l of tuples into a dictionary.""" return {k: v for v, k in l}
85ac67fabd89e8ff95ddd833dd85e25722ca276c
657,676
def _denumpy(x): """ Try using the numpy.tolist() to convert to native python type. DBI's can't typically handle numpy vals.""" try: return x.tolist() except: return x
9c39e3a7f637cd8e9a86d4d7250e69df4eeb6cd8
657,677
def copy_file(origin, destination): """ Copy a file from a given origin to a given destination """ return True
69b6e7472f330ca9a8f343dcc80e6920830d9185
657,678
def make_range_partition(min_val, max_val): """ Returns a new partitioning function that partitions keys in the range *[min_val:max_val]* into equal sized partitions. The number of partitions is defined by the *partitions* parameter """ r = max_val - min_val f = "lambda k, n, p: int(round(f...
a86cae26fc79e73974fa05def8a4db531f31a829
657,679
import os def get_files(directory): """ Get the list of .mhd files in the given directory. :param directory: Directory to search through for .mhd files. :return: List of filenames (without directory prefix). """ return [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('...
3472b630e8e13c1489dcbe8210e83425c247855e
657,680
def load_alist(path): """Read `alist`-file [MacKay]_ and return nested list describing the parity-check matrix of a code. Many code examples can be found in [UniKL]_. Input ----- path:str Path to file to be loaded. Output ------ alist: list A nested list containing...
08579269ae33eb00f6c41b511f201531eb34f9c7
657,681
import random def sample_cloud (numpy_cloud, sample_divisor, deterministic_sampling=False ): """Samples a numpy cloud by a given divisor. If sample_divisor=4, cloud is 4 times as small after sampling.""" previous_length = numpy_cloud.shape[0] # deterministic sampling if (deterministic_sampling ): ...
c06aaec3b88c8a7c3ef92af397c4792db14d4f51
657,682
import itertools def jaccard(str1, str2): """Implements Jaccard N-Grams metric for n=[2,3]. str1, str2: str Input values in unicode. Returns ------- float A similarity score normalized in range [0,1]. """ str1 = " " + str1 + " " str2 = " " + str2 + " " a = list(it...
31a5c31e48362909bcf11ad9ce796244a8bee020
657,683
from typing import Optional def set_latest_version_state(version: str, state_file: Optional[str]) -> Optional[int]: """ Set version in state file """ if not state_file: return 0 if version: with open(state_file, "w") as file: return file.write(version) raise ValueEr...
332bd7d522cf1ea579e2ab42426685a34bfd8270
657,684
def CreateLocalSsdMessage(resources, messages, device_name, interface, zone=None): """Create a message representing a local ssd.""" if zone: disk_type_ref = resources.Parse('local-ssd', collection='compute.diskTypes', ...
b7bec14dbdd68314c0b6f1e24663a5130067326c
657,685
def get_fixture_value(request, name): """Get the given fixture from the pytest request object. getfuncargvalue() is deprecated in pytest 3.0, so we need to use getfixturevalue() there. """ try: getfixturevalue = request.getfixturevalue except AttributeError: getfixturevalue = re...
d50ef248dd63d64c0927f80ae5a86928dd975105
657,687
def put_genomicsCounts(db, counts): """ Insert each document in list into 'genomicsCounts' collection. """ return db, counts
45ca251754f151dc30535e75408fc5191cf7f934
657,688
def hex_to_rgb(color): """Convert the color from HEX coordinates to RGB coordinates.""" color = color.lstrip('#') size = 1 if len(color) == 3 else 2 factor = 2 if len(color) == 3 else 1 return tuple(int(color[i * size:i * size + size] * factor, 16) for i in range(3))
d17d1144d44fdbb37b26279c22b8bbcac4f3a984
657,689
def convert(char, counters): """Convert counters to graphical chart""" return "".join(["#" for _ in range(counters.get(char, 0))])
bd01bd69dba351f8860521f0d9bd45f24840640a
657,690
import torch def prevent_clip(wav, mode='rescale'): """ different strategies for avoiding raw clipping. """ assert wav.dtype.is_floating_point, "too late for clipping" if mode == 'rescale': wav = wav / max(1.01 * wav.abs().max(), 1) elif mode == 'clamp': wav = wav.clamp(-0.99, ...
67a6d0d4a4c77a0502bafc1ebc6d9687a38884d2
657,691
def parse_spotify_url(url): """ Parse the provided Spotify playlist URL and determine if it is a playlist, track or album. :param url: URL to be parsed :return tuple indicating the type and id of the item """ if url.startswith("spotify:"): print("gib meh spotify limk.") parsed_url =...
388b6ef45703c392bacb153e725dd69a21855e0a
657,692
def perc_unaligned(n_items, n_aligned, n_targs, **kwargs): """ Calculates the percent of items that are unaligned Args: n_items: ndarray (same dims as n_targs) n_aligned: ndarray (same dims as n_targs) n_targs: ndarray (same dims as n_items) Returns: perc: float ...
7d58aaa8911cc711396f7c282b7d39948875ec8d
657,693
def domain(): """Provide a domain for the tests.""" return "abc.com"
b686f649670ea5b5450c3865fd98ab75deadf671
657,694
def str_strip(str_in): """ strip whitespace at right of string. Wrap string rstrip method into function """ return str(str_in.rstrip())
9b2ee0a61fd5351d64b5bd727484114bc38f4418
657,695