content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def reverse_geometric_key(string): """Reverse a geometric key string into xyz coordinates.""" xyz = string.split(',') return [float(i) for i in xyz]
4ca34a6c5f3607f3c1ea38642309e0ef988a61d9
669,685
def chooseSize(string): """ Determines appropriate latex size to use so that the string fits in RAVEN-standard lstlisting examples without flowing over to newline. Could be improved to consider the overall number of lines in the string as well, so that we don't have multi-page examples very often. ...
4b1eee8ce1a768ee320f4b78fac16df42db19eca
669,686
import binascii def shinglify(clean_text): """ Generates list of 'shingles': crc sums of word subsequences of default length :param clean_text: cleaned text to calculate shingles sequence. :return: shingles sequence """ shingle_length = 3 result = [] for idx in range(len(clean_text) - ...
aedd17f3eed48aaf1cbeb0bbe34103d594d6428b
669,687
def plot_arrow(ax, x1, y1, x2, y2, shrink_a=1, shrink_b=1, connectionstyle="arc3,rad=0", arrow_style="<-"): """ This function plots arrows of the task schematic :param ax: Axis object :param x1: x-position of starting point :param y1: y-position of starting point :param x2: x-position of end point ...
f731a96dc253db03eeeb16ee2594a96969b01219
669,688
def writeResults(Patterns, df): """ utility function to write patterns in a pandas dataframe Parameters ---------- Patterns : list list of patterns df : pandas dadaframe input dataframe Returns ------- pandas dadaframe updated dataframe """ for pat i...
a079e9614c1000e22af5b4a1050adc303bae7c9d
669,689
from typing import List from typing import Tuple def split_weights( weights: List[float], num_features: int, num_hidden: int ) -> Tuple[List[List[float]], List[float], List[float]]: """Splits the input vector into the the NN bias weights and layer parameters.""" # Check weights is the right length ...
c7761fa95641d17dbf702ec3bb1483df610ea02a
669,690
def is_ip_per_task(app): """ Return whether the application is using IP-per-task. :param app: The application to check. :return: True if using IP per task, False otherwise. """ return app.get('ipAddress') is not None
7de05a7db5eb886bea2687492585b554f898fc41
669,691
def map_atoms(indices, nres_atoms=1): """ Map the indices of a sub-system to indices of the full system :param indices: indices of atoms to map with respect to full system :param nres_atoms: number of atoms per residue :type indices: list :type nres_atoms: int :return: dictionary of mapped in...
b49487cb2926b9529330a01b11164ba871af85e2
669,692
def match_token(token, tok_type, tok_str=None): """Returns true if token is of the given type and, if a string is given, has that string.""" return token.type == tok_type and (tok_str is None or token.string == tok_str)
5486eb439c15a15116f417c641c936e981c43c71
669,693
import time def wait_until(somepredicate, timeout, period=0.1, *args, **kwargs): """Waits until some predicate is true or timeout is over.""" must_end = time.time() + timeout while time.time() < must_end: if somepredicate(*args, **kwargs): return True time.sleep(period) ret...
b8744afdd052146a01c0280550974ace83718063
669,694
def get_permissions(user): """ Get permission bits that are required across all/most views. Currently just a placeholder. """ permission_dict = {} return permission_dict
dce899b3953e5191e945c1ead1b83f06aabaac24
669,695
import pickle def serialize(jid, huc_ids, np_array, name_temp, section): """ Returns pickle to be sent to Mongo server. :param np_array: :param name_temp: :param section: :return: """ return pickle.dumps({ "jid": jid, 'output': np_array, 'huc_ids': huc_ids }...
99d64a1063fed0987e1aff5d69d2b6da480ec3f4
669,696
import re def rangelist_to_set(rangelist): """Convert '1-3,7,9-12' to set(1,2,3,7,9,10,11,12)""" result = set() if not rangelist: return result for x in rangelist.split(','): if re.match(r'^(\d+)$', x): result.add(int(x)) continue m = re.match(r'^(\d+)-(...
f58fd8929f25a7edf156a1402b6d9c61620c823d
669,697
def crop_to_subarray(data, bounds): """ Crop the given full frame array down to the appropriate subarray size and location based on the requested subarray name. Parameters ---------- data : numpy.ndarray Full frame image or ramp. (x,y) = (2048, 2048) May be 2D, 3D, or 4D ...
0327e996c96664c6a40be03ee1c9f121c10d656f
669,698
def get_sparsity_train(config, train_kwargs, train_dataloader, robustness_testing_datasets): """ Converts training data set created by sparsity into dataloader object. Uses same config settings as original training data. Args: train_kwargs (dict): Training dataset config train_dataloade...
93728ccf222729e2988e3d43a91cd51594c77cb1
669,701
def getTitles(docs): """ retrieving titles for all documents """ documentData = [] for d in docs: temp = {} temp['id'] = d['_id'] #temp[] if 'title' in d['_source'].keys(): temp['title'] = d['_source']['title'] elif 'html_title' in d['_source'].keys(): temp['title'] = d['_source']['html_title'] e...
546a468a430666f609ef95dacb21442da956ad1d
669,702
def get_data(): """Creates a set of data for use in the sample""" values = [] values.append({"pressure": 346, "temperature": 91, "time": "2017-01-11T22:21:23.430Z"}) values.append({"pressure": 0, "temperature": 0, "time": "2017-01-11T22:22:23.430Z"}) values.app...
0597792e0f01b7bb424a67524f3669b1b35cc2fc
669,703
def get_rpath_deps(pkg): """Return immediate or transitive RPATHs depending on the package.""" if pkg.transitive_rpaths: return [d for d in pkg.spec.traverse(root=False, deptype=('link'))] else: return pkg.spec.dependencies(deptype='link')
1664fd2e54b2b29cf615a365131c057d7eb261b7
669,704
def threeSum_faster(nums): """ This skips the duplicates directly """ result = [] nums.sort() for index, value in enumerate(nums): if not index or (index and nums[index]!=nums[index-1]): target = -1 * value left = index + 1 right = len(nums) - 1 ...
806ffb1564a04b81242bf1ca848aa4d2cb918795
669,705
import re def checkURI(uri): """Validate tcp:// regex""" regex = re.compile( r"""(?xi) # "verbose" mode & case-insensitive \A # in the beginning... tcps?:// # tcp or tcps protocol (?: # hostname / IP address (?: ...
c279434b4077ef4ea59814d784bfbf208e470a51
669,706
import inspect def concat_docs(cls): """Does it look like I'm enjoying this?""" attributes = [] def get_docs(parent): nonlocal attributes if parent.__name__ == 'object': return docs = parent.__doc__.splitlines() if " Attributes" in docs: attribu...
c4314d3eb84e401083902ca9e278f520259cfe44
669,707
def double_factorial(n: int) -> int: """ Compute double factorial using recursive method. Recursion can be costly for large numbers. To learn about the theory behind this algorithm: https://en.wikipedia.org/wiki/Double_factorial >>> import math >>> all(double_factorial(i) == math.prod(rang...
085ba77f7fc27d2e7438b44f9e815d760527ff8b
669,708
def ProcessGainsData(inF, delim=',', idCol=0, gainCol=1): """ reads a list of ids and info gains out of an input file """ res = [] inL = inF.readline() for line in inF.xreadlines(): splitL = line.strip().split(delim) res.append((splitL[idCol], float(splitL[gainCol]))) return res
b60e2af96b58fd34194505257bc47248900ca1fc
669,709
def is_internal(ip_address): """Determine if the address is an internal ip address Note: This is super bad, improve it """ # Local networks 10.0.0.0/8, 172.16.0.0/12, '192.168.0.0/16 local_nets = '10.', '172.16.', '192.168.', '169.254', 'fd', 'fe80::' return any([ip_address.startswith(local) ...
830948997cc5916a28189ffda0e5b4881a0fc6cb
669,711
def is_even(value: int) -> str: """Return 'even' or 'odd' depending on if the value is divisible by 2.""" if value % 2 == 0 or value == 0: return 'even' else: return 'odd'
2fd9b0bcbfa75852de61371d88b27e6e6e522864
669,712
def dtool_lookup_config(dtool_config): """Provide default dtool lookup config.""" dtool_config.update({ "DTOOL_LOOKUP_SERVER_URL": "https://localhost:5000", "DTOOL_LOOKUP_SERVER_TOKEN_GENERATOR_URL": "http://localhost:5001/token", "DTOOL_LOOKUP_SERVER_USERNAME": "testuser", "DTOO...
d9c81e9e04b709ec5d3c5ea0f27d1198317673b5
669,713
def unpack_object_id(object_id): """Return ``(table_name, id)`` for ``object_id``:: >>> unpack_object_id(u'questions#1234') (u'questions', 1234) >>> unpack_object_id(u'questions#*') (u'questions', None) """ parts = object_id.split('#') try: parts[1] = i...
110743cf35d1cc49bbe0d23b43e60fa79edf6123
669,714
def update_minmax(array, val_min, val_max, matrix, il, xl, ilines_offset, xlines_offset): """ Get both min and max values in just one pass through array. Simultaneously updates (inplace) matrix if the trace is filled with zeros. """ maximum = array[0] minimum = array[0] for i in array[1:]: ...
fea1b825ba15342f6d3d15ff8d0c9f12e1f06534
669,715
import math def circunference(rad) -> float: """Returns the surface length of a circle with given radius.""" return 2 * math.pi * rad
1051c9f5f0fa4b80d1bbc3395c871de3fa7ce010
669,716
def _create_cummin_perm(axis, x_shape): """Insure axis is in [-len(x_shape),len(s_shape)-1]""" len_axis = len(x_shape) if not isinstance(axis, int): raise TypeError(f"The date type of 'axis' should be Int, but got {axis}.") if axis < -len_axis or axis > len_axis: raise ValueError(f"The v...
ad9f42c781378c285b70e7fe8a10f9a279f0f548
669,717
def known_words(word_list, lm_vocab): """ Filters out from a list of words the subset of words that appear in the vocabulary of KNOWN_WORDS. :param word_list: list of word-strings :return: set of unique words that appear in vocabulary """ return set(filter(lambda word: word in lm_vocab, word_lis...
adbd120072ec1b75b89e091a2f7897a2fba4f479
669,719
def minSize(split, mined): """ Called by combineCheck() to ensure that a given cleavage or peptide is larger than a given minSize. :param split: the cleavage or peptide that is to have its size checked against max size. :param mined: the min size that the cleavage or peptide is allowed to be. :re...
d89c330bc69c9e39a6887e5d8e114a87a072e12c
669,720
def simple_substitute(text, alphabet, code): """ Used to encode or decode the given text based on the provided alphabet. PARAMS: plaintext (string): The message you want to encode alphabet (dictionairy[char] = char): Key is plaintext char, value is the substitute. Enter the same alphabet for...
e34643ef45eb6ceb493c35c43a302e661e0933a9
669,721
def read_input_file(input_file): """ Reads the input file. """ ids = set() with open(input_file, 'r') as input_f: for line in input_f: fields = line.strip().split('\t') if fields[0] == '': continue else: ids.add(fields[0]) ...
666129c9ebb3677b120fb64b9a080813a35bb7ea
669,722
def GetMetaData(metadata,wrfinput=False): """Help on built-in function print_namelist in module GetMetaData: GetMetaData(...) GetMetaData([wrfinput]) This is a helper function to populate the metadata dictionary for the wrf post processed file. Automatically called when...
23ca45ae645edc786e8ddb47ab7219a42ed93ce5
669,723
def func_ideal_length(target_position, no_probe_sites): """Finds the optimum length between insertion sites, based on the nucleotide length""" length = target_position[-1] - target_position[0] #length of sequence available for probe sites no_intervals = no_probe_sites - 1 #number of intervals between probe ...
efc51c0cb2572c521dc141daf632bd5e0152fef3
669,724
def var_replace(eq, var, new): """ Replace all instances of string var with string new. This function differs from the default string replace method in that it only makes the replace if var is not contained inside a word. Example: eq = "-1j*kx*v*drho -drhodz*dvz -1.0*dz(dvz) - drho" var...
892bef29250fd57aa304f7ce099a684ac9df61d6
669,725
def postprocess_result(out): """ 后处理结果,比如需要返回哪个层的结果 param: out, 网络前向预测的结果 return: 自定义需要的返回值 """ prob = out["prob"].copy() rets = [] for p in prob: label = p.argsort()[::-1][0] score = p[label] rets.append((label, score)) return rets
390d905f1b87655f0ac9666dc123873f93bec72b
669,727
def initialize(): """Returns PIC starting code.""" code = "TRISB = %00000000\nTRISC = %00000000\nTRISD = %00000000\n" return code
7af438e3b02475d4c35e6ce1315fcf2439d21ff9
669,728
def extract_detailed_address(raw_content): """ :param raw_content: :return: return list address, such as 'lists/1752913' """ try: point_one_index = raw_content.index('href') except: return '' left_colon_index = raw_content[point_one_index:].index( '"') + point_one_ind...
2fba429c4f283f06343609f6fee44119f445cf49
669,730
def get_subarray(A, ind): """Extract a subarray For a :class:`numpy.ndarray`, the function **get_subarray** extracts a subset of the array. The portion of the original array being extracted is defined by providing the indices along each axis. Parameters ---------- A : numpy.ndarray ...
e57fadcd40a47b3aafaf26fd9883df1392ba0db6
669,731
from typing import Tuple def xgcd(a: int, b: int) -> Tuple[int, int, int]: """Extended Euclidean algorithm. Finds :code:`gcd(a,b)` along with coefficients :code:`x`, :code:`y` such that :code:`ax + by = gcd(a,b)`. Args: a: first number b: second number Returns: gcd(a,b),...
6d8764e21511b473b968b24d6783ac97ead0a180
669,732
def spectrum_accelerate_spec(): """ Return arguments spec for AnsibleModule """ return dict( endpoints=dict(required=True), username=dict(required=True), password=dict(no_log=True, required=True), )
bd0acf5f0175e04051a88de6ad9419e2c6de1bdc
669,733
def get_line_starts(s): """Return a list containing the start index of each line in s. The list also contains a sentinel index for the end of the string, so there will be one more element in the list than there are lines in the string """ starts = [0] for line in s.split('\n'): sta...
3f88d8bfb5ab63662c7c4dbc0ef3fe4253be3291
669,734
import random def generate_positive_detections(): """ Generate random inputs for the test cases. :return: Dictionary mimicking the structure of the inferrer output. """ detections = [] for i in range(10): detections.append({ "classId": int(random.choice(range(15))), ...
7612605c4a23e1dc17731fd2dbc03527fb43b68f
669,735
import sys def get_generator() -> str: """Returns cmake generator based on platform.""" if sys.platform == 'linux' or sys.platform == 'linux2': return 'Unix Makefiles' if sys.platform == 'win32': return 'Visual Studio 16 2019' if sys.platform == 'darwin': return 'Xcode' sy...
57120e249d4156cd8bd7f246ba4c9dcd394c8ffd
669,736
import re def get_bash_cases(): """Setup module.""" re_split = re.compile(r'><><><><') with open('tests/brace-results.txt', 'r') as r: # Split by test cases results = re_split.split(r.read()) results.pop() # Split by line within test case wanted = [x.split('\n') f...
bfeff4868977de5268572c42c5fad9fb42b00da4
669,737
def _calculate_graduation_year(x): """Calculate the cohort year for an enrollment record""" if x["Grade"] == "K": return int(x["Year"]) + 5 elif x["Grade"] == "1": return int(x["Year"]) + 4 elif x["Grade"] == "2": return int(x["Year"]) + 3 elif x["Grade"] == "3": retu...
0a01fbf0481b15cc757c69eb433bef071bd18ca1
669,738
def find_ns_subelements(element, subelement_name, ns_dict): """ retuns list of subelements with given name in any given namespace Arguments: - element (ElementTee.Element): main element to search in - subelement_name (string): searched name of element - ns_dict: dict of ...
1bbd87025ba9cac503b4ceb7523485a9b33d5637
669,739
def get_trivy_scan_source(data): """Returns repo name of scan source, if found.""" for d in data: repo_uri = d['locations'][0]['physicalLocation']['artifactLocation']['uri'] try: return repo_uri.split('/')[1].split(':')[0] except IndexError: continue return '*...
9d443225f8b7364b488f2b34aa0c5a62e5a35558
669,741
def FSphere(x): """ Sphere function range: [np.NINF, np.inf] """ return (x ** 2).sum()
90755faee5c9f6788ca7c05d6eba760acd4e636f
669,742
import bz2 import pickle def load(filename): """ Loads a Calibration Object into a file using gzip and Pickle :param filename: Calibration filemane *.fco :return: object """ with bz2.BZ2File(filename, "rb") as f: obj = pickle.load(f) return obj
647584f24a9275f39ee8fabe954bcf5dd2357bc8
669,743
def all_params(params, funcs): """ Combined list of params + funcs, used in the test """ return params + funcs
d5f93e52201f57c31b16e10c5f45a16ebaee0813
669,744
from operator import mul def text_color(bg): """ Determine text color based off background color. Parameters ---------- bg : tuple[int] Background RGB color. Returns ------- tuple[int] Foreground RGB color. """ luminance = sum(map(mul, (0.299, 0.587, 0.114), b...
4e99e9c06ab5a8574f735d98db0b0b12c69a35a5
669,745
def net_formatNET(self): """Return the netlist formatted as a KiCad .net""" return self.tree.formatNET()
f9c63f03eeaf95a6920d48c80d2e125cc296f55e
669,746
import io def LeerAgentes(): """[summary] Returns: [type]: [description] """ F = io.open("../data/processed/internal/admisiones/agents_names/agentes_sh.txt", mode = "r") Agentes_F = F.read().splitlines() F.close() G = io.open("../data/processed/internal/admisiones/agents...
3a47c2205e8c969051aa4998e08fcc8c7a49dc4f
669,747
def regex_escape(val): """ A custom Jinja filter function which helps to handle Windows FilePaths and escaping""" return val.replace('\\', r'\\')
dc5b80677d662172253d2fa704ddd5cef3ea6513
669,748
import random def propose_flip_every_district(partition): """Proposes a random boundary flip for each district in the partition. :param partition: The current partition to propose a flip from. :return: a proposed next `~gerrychain.Partition` """ flips = dict() for dist_edges in partition["cu...
0d7cbd9a767b5a8ddb99edd46fee119d97c165ad
669,749
import re def is_valid_input(service_name): """ Validate the input. Args: service_name (str): the name of the service. given as an argument to the module Returns: bool: True if the input is valid, else False. """ if re.match("^[A-Za-z0_]*$", service_name): return True...
f42e37e6e26bd0b64c1cc45a295d47b49cd8e9c4
669,750
def min_reconstruction_scale(ls_min, ls_max): """ Calculate the smallest scale in phi that can be reconstructed successfully. The calculation is given by Eq. (9) in Cooray et al. 2020b. Parameters ---------- ls_min : float Lower limit of lamdba squared in the observed spectrum...
d13fc138b7f3c1bd02bda03f1add307d5e0b1733
669,752
def make_header_text(avl_object): """This function writes the header using the template required for the AVL executable to read Assumptions: None Source: None Inputs: avl_object.settings.flow_symmetry.xz_plane [-] avl_object.settings.flow...
8b179bcd9e7dbd3c0f586f71d7c2ea7e164e8007
669,753
import random def generate_code(code_len=4): """ 生成指定长度的验证码 :param code_len: 验证码的长度(默认4个字符) :return: 由大小写英文字母和数字构成的随机验证码 """ all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' last_pos = len(all_chars) - 1 code = '' for _ in range(code_len): inde...
83fa7934cb740e291543cc5e5e0f1848d05346fb
669,754
import numpy def isLatestFormat(filename): """ Returns True if the calibration file is the latest format. This is mostly used for testing. """ data = numpy.load(filename, allow_pickle = True) return (len(data) == 5) and (data[4] == 2)
eba4c04eb7051acdb2c061cad25af6eb69803c15
669,757
def nogil(request): """nogil keyword argument for numba.jit""" return request.param
9d5f53c0636f8af6d5196c71f8f5e40bbab99769
669,758
def applies_to_product(file_name, product): """ A OVAL or fix is filtered by product iff product is Falsy, file_name is "shared", or file_name is product. Note that this does not filter by contents of the fix or check, only by the name of the file. """ if not product: return True r...
3b816fec99a6353b69dc61629aaa91adbc949488
669,759
def compare_payloads(modify_payload, current_payload): """ :param modify_payload: payload created to update existing setting :param current_payload: already existing payload for specified fabric :return: bool - compare existing and requested setting values of fabric in case of modify operations if b...
9461ff15c4687ab1a48d57358283cd18ac006eec
669,761
def get_table_7(): """表 7 照明区画݅に設置された照明設備の特殊条件による補正係数 Args: Returns: list: 表 7 照明区画݅に設置された照明設備の特殊条件による補正係数 """ table_7 = [ 1.0, 0.5, 1.0, 1.0, 0.8, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0,...
8d928e3f60c1e164c1943e099287ab203badbc01
669,762
def _root_name_comps(): """Return the name components of the root module.""" # This assumes `rewrite` is a top-level submodule of `fun_mcmc`. # If we move it, we'd change the `-1` to equal the (negative) nesting level. return __name__.split('.')[:-1]
09cb6978deee4cc8371ebc705c140e50e070ebe4
669,763
def seg_dict(event_dict): """ :param event_dict: :return: """ keys, values = list(), list() for k, v in event_dict.items(): keys.append(k) if str(v).isdigit(): values.append(str(v)) else: values.append("'" + str(v) + "'") return ','.join(keys...
1851ef5272e3586d79d924c9b5a83b2b358a5431
669,764
def getDicoIdx(dico, val): """Maps an entry val with a number""" if val not in dico: dico[val] = len(dico) return dico[val]
ab805a3605315e2913c46124ea064603da125169
669,765
def drop_cols(data_frame, columns): """ Remove columns from data frame """ for col in columns: data_frame = data_frame.drop([col], axis=1) return data_frame
244f7910e960de51a5b585fbb891b5a94f5eba3f
669,766
def gen_variants(text): """return a number of common variants to naming conventions""" low_str = text.lower() # all lowercase up_str = text.upper() # all uppercase return [low_str, up_str, f"{low_str}s", f"{up_str}S"]
7dea8ee539364cf6e6fa4708c90ea16b457503fd
669,767
def help_flag_present(argv: list[str], flag_name: str = 'help') -> bool: """ Checks if a help flag is present in argv. :param argv: sys.argv :param flag_name: the name, which will be prefixed with '-', that is a help flag. The default value is 'help' :return: if the help flag is present """ ...
a804ec64702e6173d94c50f024373f67d9893344
669,769
def get_fraction(lsnp1, lsnp2): """Return the fraction of reads supporting region1.""" reg1_fraction = [] for index in range(len(lsnp1)): sumdepth = lsnp1[index] + lsnp2[index] if sumdepth == 0: reg1_fraction.append(0) else: reg1_fraction.append(float(lsnp1[in...
27f7740ea214dc438b22e730110f770c3e3a061a
669,770
def sort_datasets(datasets): """This method reorders the list so that datasets that have dataset data sources are ingested after there dependent data source. """ ingested = [] output = [] remaining = [] while len(datasets) > 0: for dataset in datasets: if dataset.__xmlrpc...
80296cbf47f6526e62aa056052591891ec731c65
669,771
def bool_eval(token_lst): """token_lst has length 3 and format: [left_arg, operator, right_arg] operator(left_arg, right_arg) is returned""" return token_lst[1](token_lst[0], token_lst[2])
990588c9ea1ebb0ef743bcd31c43b80332238df8
669,773
import logging def basic_logger(name, level): """ Returns a basic logger, with no special string formatting. Parameters ---------- name : str The name of the logger. level : int An integer, such as `logging.INFO`, indicating the desired severity level. As in the `loggi...
c1440c1dc1a4ee68eede0975b9cb6f6e19f13fd5
669,774
import string def is_pangram(text, alphabet=string.ascii_lowercase): """ Checks if text is a pangram. :param text: string :param alphabet: string :return: boolean """ return set(text.lower()) >= set(alphabet)
486872cd3f22e698ade2332de9e07a53ffaa6ddf
669,775
import os def log_loading(log_path, region): """ This function takes the log file where the region of previous training are written and check if the model has already seen this region. """ list = [] with open(os.path.join(log_path, 'transfer_log.txt'), 'r') as filehandle: for line in f...
03ed369f3c769191e266bf5651d4ff55a47a9248
669,776
def get_headers(data, extra_headers=None): """ Takes the response data as well as any additional headers and returns a tuple of tuples of headers suitable for passing to start_response() """ response_headers = { "Content-Length": str(len(data)), } if extra_headers: response_...
d00c8315b21dd697b3a7ba1689b4b858af616fc6
669,777
from typing import Iterable def recall(pred: Iterable, ref: Iterable) -> float: """% of correct retrieved: R = TP / (TP + FN) """ # True Positive = the number of (unignored) reference mappings that are Positive tp = len(set(pred).intersection(set(ref))) # False Negative = the number of (un...
df6937730dd7ebd27b6db1be2527ea99a4ab2717
669,778
def unfold(vc: set, folded_verts: list): """ Compute final vc given the partial vc and list of folded vertices (unreversed) :param vc: partial vc as a set :param folded_verts: list of folded vertices as 3-tuples :return: final vertex cover as a set """ final_vc = set(vc) for u, v, w in f...
89fd6852548bb5e133b7a9d07accfdb51fbf74c5
669,780
import inspect def add_state_features(*args): """ State feature decorator. Should be used in conjunction with a custom Machine class. """ def _class_decorator(cls): class CustomState(type('CustomState', args, {}), cls.state_cls): """ The decorated State. It is based on the State class used...
aab443cc448279968a24d5d18c7f5fa19573a038
669,781
def get_delta_from_interval(data_interval): """Convert interval name to number of seconds Parameters ---------- interval : str interval length {day, hour, minute, second, tenhertz} Returns ------- int number of seconds for interval, or None if unknown """ if data_in...
bd264a8aab1c1cd3dd1121ca0ed74faae450f39d
669,782
def find_shops(index: dict, products: list) -> set: """ Find all the shops that contain all the products :param index: Index of products :param products: Products to match :return: Set of all shops that sell all mentioned products """ try: final_set = index[products[0]] # Initial in...
04716a4178392075767632d2f1762215fdaec601
669,783
def jsonify(record): """ Fetch some useful values from the alignment record """ # Blast records are pretty deeply nested alignment = record.alignment hsp = alignment.hsp # Information about the hit data = { 'score': hsp.score, 'expect': hsp.expect, 'positives...
faa2559fd2b0df6ac393008e1952a08f0f7a9ef0
669,784
def get_budget_report( client, customer_id, *args, **kwargs): """ Get report from AdWords account 'customer_id' and save to Redshift 'target_name' table """ include_fields = kwargs.pop('include_fields', []) exclude_fields = kwargs.pop('exclude_fields', ['ConversionTypeName']) exclude_ter...
de2d54e201b075ef520e45768fee1c8b7b50c32a
669,786
import re def sanitize_filename(filename: str) -> str: """ Make the given string into a filename by removing non-descriptive characters. :param filename: :return: """ return re.sub(r'(?u)[^-\w.]', '', filename)
859249f3d2a70c7413e92c5df7cee9b7bccb7ecc
669,787
def df_variant_id(row): """Get variant ID from pyvcf in DataFrame""" if row['ID'] != '.': return row['ID'] else: return row['CHROM'] + ':' + str(row['POS'])
460868e501b5e4683fc88d80cee363b5778d7623
669,788
def get_hd_domain(username, default_domain='default'): """Returns the domain associated with an email address. Intended for use with the OAuth hd parameter for Google. Args: username: Username to parse. default_domain: Domain to set if '@suchandsuch.huh' is not part of the username. Defaults to ...
adae35610ef1452de0dfac3980cccd91a7f7e41f
669,789
def generate_term(n): """Generates nth term in the Fibonacci sequence""" assert n >= 1 if n == 1: return 1 elif n == 2: return 2 else: return generate_term(n-1) + generate_term(n-2)
92073b38f74c70099eb64671ecaf4e9ad6307470
669,791
def abbr(name): """ Return abbreviation of a given name. Example: fixed-effect -> f10t per-member -> p8r """ return name if len(name) <= 2 else f"{name[0]}{len(name) - 2}{name[-1]}"
3bbddbad6372f0dfa17b3e5e1b0c30fcf3c401d7
669,792
def is_isogram(string): """Checks whether a given string is isogram or not. Returns a boolean.""" string = string.lower().replace(' ', '').replace('-', '') return len(string) == len(set(string))
33202ce21f0e333471dab3453d1b0cd6d000ec26
669,793
def parse_one_column_table(data_table): """Parse tables with only one column""" output_list = [] data_rows = data_table.find_all("tr")[1:] for data_row in data_rows: data_cells = data_row.find_all("td") for data_cell in data_cells: try: output_list.append(data...
53d703050a89fd8f3fb12575405c332eecb4dd19
669,794
import shelve def read_net_cp(namefile): """Read pre-computed network cp assignation.""" db = shelve.open(namefile) cps = db['cps'] net = db['net'] methodvalues = db['methodvalues'] db.close() return cps, net, methodvalues
bbf5f2c798af398b85e5f949ab8e45325d768755
669,795
def dh_number_digest(g_val: int, p_val: bytes) -> int: """Determine hash value for given DH parameters. Arguments: g_val: the value g p_val: the value p Returns: a hash value for the given DH parameters. """ return hash((g_val, p_val))
9a107af56a82a57cd6c91758194102675f8bc528
669,797
from unittest.mock import patch def mock_scan_fixture(): """Mock pyatv.scan.""" with patch("homeassistant.components.apple_tv.config_flow.scan") as mock_scan: async def _scan(loop, timeout=5, identifier=None, protocol=None, hosts=None): if not mock_scan.hosts: mock_scan.ho...
bd7080868c0a335e44a6c643a16bf9d04a829b13
669,798
def get_public_params(pp, base=16): """ Returns a dictionary of small values (integers) and large values (strings). """ # small_values = {} small_values['n'] = pp.mmap.params.n small_values['rhof'] = pp.mmap.params.rhof small_values['eta'] = pp.mmap.params.eta small_values['etaq'] = pp.mmap.params.etaq small...
8aa2e43feedacc3e42e2c6ad8c483c8309d810f3
669,799
def wait_for_job(dataproc, project, region, job_id): """Wait for job to complete or error out.""" print('Waiting for job to finish...') while True: job = dataproc.get_job(project, region, job_id) # Handle exceptions if job.status.State.Name(job.status.state) == 'ERROR': r...
689395501cafad6519521f39ca861f270b7b1fba
669,800
import numpy def ortho(arr1, arr2): """ This function orthogonalises arr1 with respect to arr2. The function then returns orthogonalised array arr1_orth. PARAMETERS ---------- arr1 : numpy array A numpy array containing some data arr2 : numpy array A numpy array containin...
e8b5aa696c81ac94990e5d665dff203932af3a8a
669,801