content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def tag(**tags): """ Takes the given tags and applies them to the token. """ def apply_tags(tokens): for key, value in tags.items(): tokens[key] = value return apply_tags
836f298122837d56942879db777f2b1148441787
661,626
import torch def create_mask_tensor_image(left_indices: torch.Tensor, right_indices: torch.Tensor, threshold: int = 0): """ Creating masking of two tensor. These two tensors are integer tensor Parameters ---------- left_indices: (B1, n1, M1) right_indices: (B, n, M2) threshold: when it is...
72fdf038b634987ad5614369118664b9c72ff04c
661,627
def remove_whitespace(string_to_parse): """remove spaces and tabs""" string_list = string_to_parse.split() return "".join(string_list)
498c94d69826166e3a34fb48b8f1efbc2494bae4
661,628
def fact(n): """Factorial. fact(5) = 5! = 5 * 4! = 5 * 4 * 3 * 2 * 1 = 120""" if n == 1: return 1 return n * fact(n - 1)
8af471f8ef4aeb49606ce864400b968737c97597
661,629
def model_create(module, model_pars=None): """ Create Instance of the model from loaded module model_pars : dict params """ if model_pars is None : model_pars = module.get_pars() model = module.Model(**model_pars) return model
fdaa95619ec27f68c32a2945938749d88c237948
661,630
def extractFieldValueFromGml(gmlString, labelInit,labelFin): """ Returns the value between two labels in a gml. Eliminates spaces at start and end of the returned value """ g=gmlString s1=labelInit s2=labelFin i=g.find(s1) f=g.find(s2) g2= g[i:f] s1=g2.find('>')+1 g3=g2[s...
a4982771caa9d4b2b445049cc3de335aa6b3521a
661,631
def default_account(web3): """Returns the default account which is used to deploy contracts""" return web3.eth.defaultAccount
f3b5e684fd050e04ff46b508ca516b5047914cd4
661,632
def s2b(s): """ String to binary. """ ret = [] if type(s) == type(b''): s = "".join(map(chr, s)) for c in s: ret.append(bin(ord(c))[2:].zfill(8)) return "".join(ret)
f467d4b75a5ab4fa6ab39f59ad8343e6fee29a69
661,633
import argparse def parse_args(): """Parse the args.""" parser = argparse.ArgumentParser( description='Fetch data for analysis') parser.add_argument('--days', type=int, required=True, help='number of days to fetch data') return parser.parse_args()
a1ff0648bf7dce9ca76388b3abea24db35bcc222
661,634
def index_map(idx_lines): """Returns a map from the orbital index to its descriptive quantum numbers :param idx_lines: lines defining the index -> orbital key """ idx_map = dict() for line in idx_lines: row = line.split() row[0] = int(row[0]) idx_map[row[0]] = tuple(row[1...
e274094b9adcbc99ac1b166ee2c54a048d6e0ca3
661,635
def truncate(phrase, n): """Return truncated-at-n-chars version of phrase. If the phrase is longer than, or the same size as, n make sure it ends with '...' and is no longer than n. >>> truncate("Hello World", 6) 'Hel...' >>> truncate("Problem solving is the best!...
f72251162baf220a4cf3555b4b95a7a7ef00aef9
661,636
import os def shortpath(p): """Replace ``$HOME`` in path with ~.""" if not p: return p h = os.path.expanduser(u'~') return p.replace(h, '~')
7bdb3d06f85fdd7d63f621b400a73b9053a932bf
661,637
from typing import Optional from typing import List def trits_from_int(n: int, pad: Optional[int] = 1) -> List[int]: """ Returns a trit representation of an integer value. :param n: Integer value to convert. :param pad: Ensure the result has at least this many trits. References:...
1e823243111486eeeab78ceaa9e2f4d0ead65bbe
661,638
def event_team_object_factory(event_id, team_id): """Cook up a fake eventteam json object from given ids.""" eventteam = { 'event_id': event_id, 'team_id': team_id } return eventteam
b8913a853526a9bee937dfe50b130025b828c69a
661,639
def _GetSetOfAllTestArgs(type_rules, shared_rules): """Build a set of all possible 'gcloud test run' args. We need this set to test for invalid arg combinations because gcloud core adds many args to our args.Namespace that we don't care about and don't want to validate. We also need this to validate args comin...
7f6facc49c6bd98684651079a134eae6b6f759c3
661,640
import subprocess import os def check_jenkins_user(url, username, passwd): """ Check if the jenkins user is present in Jenkins server """ jenkins_url = 'http://' + url + '' # Download the CLI jar from the jenkins server subprocess.call([ 'curl', '-sL', jenkins_url + '/jnlpJars/jenk...
c2832420ba2df3cc6b9da7420a63ced873fa4894
661,641
def example_loss(tensor): """Test loss function. Sum over squared entries. The Hessian of this function with respect to its inputs is given by an identity matrix scaled by 2. """ return (tensor ** 2).contiguous().view(-1).sum()
97fa40247903a4833121ed5936dc045d47c1d2d2
661,642
from typing import Tuple from typing import Optional from typing import Union from typing import Type from typing import Any def split_list_type(ftype) -> Tuple[Optional[Union[Type[list], Type[set]]], Any]: """Checks if the ftype is a List (or Set) type and return the list type and the inner type. Returns: ...
fd6ad37c35bf4a657fd80ae0a343e3bb0819b3f2
661,643
from typing import Any import click def cli_ssh_group_member_id_argument() -> Any: """An argument to specify the ssh group member id. This is effectively the id of a user that is part of the group. """ return click.argument( "ssh_group_member_id", type=str, required=True, ...
07a38d4ee137c007058a2869630a760ed4126de9
661,644
def skip_if(cursor, offset, date_key): """Return True if we want to skip a particular date""" # Useful to skip work that already has been done return int(date_key) < 20191228
342ecc8b17ab4f0d8eb270f75f6ced507c41ce01
661,645
def euler_problem_40(): """ An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following ...
3fa7fc13c8ce8889b9efdddb4284fc592def51e1
661,646
def hello(): """Return a friendly HTTP greeting.""" resp = "Health check" return "Hello World" if resp is True else "%s" % resp
6192b577a955676ca63417554d01de919cb26bfe
661,647
def filter_answers(qa_pairs, min_occurence): """This will change the answer to preprocessed version """ occurence = {} for id, row in qa_pairs.iterrows(): # row:[id,ques,ans] gtruth = row['answer'] gtruth = ' '.join(gtruth.split()) # gtruth = preprocess_answer(gtruth) if...
8094a16f54ad055ee79eaff4a606dfb03159b136
661,648
import math def total_level(source_levels): """ Calculates the total sound pressure level based on multiple source levels """ sums = 0.0 for l in source_levels: if l is None: continue if l == 0: continue sums += pow(10.0, float(l) / 10.0) level =...
3117b92f59e821941ac1d8aa80f32c161d357e71
661,649
def calc_num_character(ttype, text, width): """ Errechnet die maximale Anzahl an Character unter einer gegebenen Breite pro Zeile in Pixeln. :param ttype: Font-Typ :param text: Der Text, der u.U. umgebrochen werden muss :param width: maximale Breite pro Zeile in Pixeln :return: Anzahl an maxim...
13968f3f0152a0ee14c3a08e0e91cdaa2863a787
661,650
def get_padding_2d(in_shape, k_shape, mode): """ H_out = (H_in + pads - K) // s + 1 if "VALID": pads = 0 if "SAME": pads = (h_out - 1) * s + k - H_in s = 1 --> h_out === h_in so, pads = (h_in - 1) * 1 + k - H_in so, pads = (w - 1) + k - w """ def get_padding_1d(w, k): if mode...
6e6804ca461cab4c64099daf5b9d145be0f76f82
661,652
import argparse import textwrap def openfile(): """Input Parsing.""" parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent('''\ The source data file in this example is keyed on US state names including Washington DC...
6437f7e60a85c83390522d581160e5bf6a16f5f2
661,653
def take_nth(n): """Take each nth item from a collection, always start on first (0 idx).""" def generator(coll): for i, item in enumerate(coll): if not i % n: yield item return generator
184d5244172a43b00a17504b379e1b3f8fa436ae
661,654
def check_wordlist_sets(wordlist, book_words): """Return only those words in book_words not in wordlist, in a set wordlist, book_words: dictionaries """ return set(book_words)-set(wordlist)
9e1b46b254036c9380bda6ca70c1321a4746e9ad
661,656
import torch def l2norm(X): """L2-normalize columns of X """ norm = torch.pow(X, 2).sum(dim=-1, keepdim=True).sqrt() X = torch.div(X, norm+1e-10) return X
7517e81e97ec63be085fd2f7f6502e6b3c7541d8
661,657
def m3day2m3sec(value): """ comverts flow rate :param value: flow rate in m3 / day :return: flow rate in m3 / sec """ return value / 86400
dae1767990a6647f12f90dde180edc921acfe8d8
661,658
import colorsys def rgb_to_hsv(r: int, g: int, b: int) -> tuple: """Convert an RGB color (from 0 to 255) to HSV equivalent (from 0 to 1) """ return colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
1389ef4f69e32494aa4b21ed91d9b3aba6d96da5
661,659
def linkers(sequence_descriptors): """Provide possible linker component input data.""" return [ { "component_type": "linker_sequence", "linker_sequence": sequence_descriptors[0] }, { "component_type": "linker_sequence", "linker_sequence": s...
a1201e6dfc9a70d7fd01346a126a1590709a939d
661,660
def _convert(result): """Convert value from pysnmp object to standard python types. Args: result: Named tuple result Returns: converted: converted value. Only returns BYTES and INTEGERS """ # Initialieze key values converted = None value = result.value snmp_type = resu...
f87174a08c07be8c08a649d678818370f50d21a1
661,661
def _update_nested_dict(dict_1: dict, dict_2: dict) -> dict: """ Update `dict_1` with elements from `dict_2` in a nested manner. If a value of a key is a dict, it is going to be updated and not replaced by a the whole dict. Parameters ---------- dict_1 : dict The dictionary to be update...
7c7b617e346c692a0cd77fff862dad7dddf64672
661,662
import os def scan_dir(bin_path): """Scan directory""" out = os.listdir(bin_path) return out
ab1148e4c2a7279332d5bb90e0c71b186a35cf1a
661,663
from pathlib import Path def ensure_dmg_extension(filepath: Path) -> Path: """ Make sure given file have .dmg extension """ if filepath.suffix != '.dmg': return filepath.with_suffix(f'{filepath.suffix}.dmg') return filepath
e5189acaa058edb13cb282fbfaf51238e2af0522
661,664
def _NodeShape(data): """Helper callback to set default node shapes.""" node_type = data.get("type", "statement") if node_type == "statement": return "box" elif node_type == "identifier": return "ellipse" elif node_type == "magic": return "doubleoctagon" else: return ""
856bb7d0f728ee171aca8321da644e9d2243b00e
661,665
import numpy def get_centroid(st, atom_list=None): """ Returns the structure's centroid as a 4-element numpy array:: [x y z 0.0] NOTE: Periodic boundary conditions (PBC) are NOT honored. :type st: structure.Structure :type atom_list: list(int) :param atom_list: A list of 1-based at...
ea3d7a2972d01eef8aacd29cf5086c8c3e82c455
661,666
def find_key_value_in_dict(d, key): """ Searches a dictionary (with nested lists and dictionaries) for the first value matching to the provided key. """ for k, v in d.iteritems(): if k == key: return v elif isinstance(v, dict): r = find_key_value_in_dict(v, ke...
476e5a53b15c9e3049f7f7b9e244481a2174f79f
661,667
def check_pre(v, g, order): """Check if all predecessors have already been placed.""" if order.index(v) > -2: return False for v2 in g.predecessors(v): if order.index(v2) == -2: return False return True
d61b2052bb93098017618ba6ac668712a4a355ce
661,668
import re def find_link(text): """ Finds all links following RST format in a documentation. :param text: text :return: all urls """ url = "https?://[-a-zA-Z0-9@:%._\\+~#=]+?[-a-zA-Z0-9@:%._\\+~#=/&?\\n ]*?" reg = [re.compile("[<](%s)[>]" % url), re.compile("[.]{2} image:: (%s)\...
9bce653073f38fba4f68f5b1cdaf16bcad7876f4
661,669
from pathlib import Path def is_illegal_dir(d: Path): """Refuse to remove directories for some situations, for safety. """ if (d / ".git").exists(): return ".git file found" if d.absolute() == Path.home().absolute(): return "cannot replace home directory" if d.absolute == Path("/")...
7282f629f631f91b4a332d8f8a7420e41afd9a6b
661,670
import traceback import os def put_model_to_device(model, device='gpu', kill=True, error_code=3): """ Tries moving model to device Args: model: model to put to GPU (other other device) device: send model to this device, defult "gpu" kill: whether to exit program on C...
294fd9c426c0557ea5b409c30bea3b4fc4c22b0f
661,671
import argparse def func_parser() -> argparse.Namespace: """ Defines what arguments the program requires, and argparse will figure out how to parse those out of sys.argv :return: an instance of the argparse class that can be used to access command line arguments """ parser = argparse.ArgumentPar...
e03503d60d84bd9099af7c9039a461d64e13cb62
661,672
def FilterByGOIds(gene2go, go2info): """ filter gene_id to go_id lookup by a list of go_ids returns a new gene2go mapping. used to restrict GO terms to GO_slim and remove alternates gene2go # starting set, map of genes to go terms go2info # alt ids are repeats of superceding ids ""...
190d7b2da548b93d8f38091d5c668415a9269461
661,673
import time def time_to_date(timestamp): """ 时间戳转换为日期 :param timestamp : 时间戳,int类型,如:1537535021 :return:转换结果日期,格式: 年-月-日 时:分:秒 """ timearr = time.localtime(timestamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timearr) return otherStyleTime
d815135503b29c2012c9a75d1ffa960f78bb64d8
661,674
import uuid def vault_prefix(): """Random prefix is needed to avoid clashes in parallel runs and reuse the same Vault instance.""" return "secret/team/" + str(uuid.uuid4().hex)
c13362b687c7a884406dd1e067ec8161bbd86880
661,675
def common_advisor(x: int, y: int) -> int: """[summary] Args: x (int): [First Value] y (int): [Second Value] Returns: int: [Common Advisor] """ x_factor = [] y_factor = [] x_factor = set(i for i in range(1, x+1) if x % i == 0) y_factor = set(i for i in range(1,...
aaa54788a9fc2536ee239433ecce667fb6d12a1d
661,676
def _fib_doubling(n): """ Calculate Nth Fibonacci number using the doubling method. Return the tuple (F(n), F(n+1)).""" if n == 0: return 0, 1 else: a, b = _fib_doubling(n >> 1) c = a * ((b << 1) - a) d = a * a + b * b if n & 1: return d, c + d ...
7fb144bdc984a28a2ef013a17bb1a3b76cfc0037
661,677
def shift_to_include_gamma(mp_grid): """ Calculate the shift required to include $\\Gamma$. in the Monkhorst-Pack grid. Parameters: mp_grid (:obj:`list` of :obj:`int`): number of grid points in each reciprocal space direction. Returns: :obj:`list` of :obj:`float`: shift req...
a8892d916df77f21c502ec395c5ae34b24b7ae27
661,678
def get_support(item, item_set): """ Get support of specified item. Args: item (frozenset): The specified item. item_set (list[tuple]): The frequent item set with support. Returns: Support of specified item. """ for key, value in item_set: if frozenset(key) == i...
bb79d757fe07eb7c1880d6f8ac75330e83b1c903
661,679
def liquidThermalConductivity(T, lTCP): """ liquidThermalConductivity(float T, list lTCP) liquidThermalConductivity (W/m/K) = 10**(A + B*(1-T/C)^(2/7)) Parameters T, temperature in Kelvin lTCP, A=lTCP[0], B=lTCP[1], C=lTCP[2] A, B, and C are regression coefficients Returns...
532221136676cfdf01b155e3d3114aafaabbba03
661,680
def fibonacci(n: int) -> int: """Return the nth fibonacci number >>> fibonacci(0) 0 >>> fibonacci(1) 1 >>> fibonacci(10) 55 >>> fibonacci(20) 6765 >>> fibonacci(-2) Traceback (most recent call last): ... ValueError: n must be >= 0 """ if n < 0: ra...
0457893b08ba3646e092789ff7233eac2f4c356f
661,681
def walk_json_dict(coll): """ Flatten a parsed SBP object into a dicts and lists, which are compatible for JSON output. Parameters ---------- coll : dict """ if isinstance(coll, dict): return dict((k, walk_json_dict(v)) for (k, v) in iter(coll.items()) if k != '_io') elif isinstance(coll, bytes)...
b7ac601b222ce0ea9b4c32d17f97c531a9df2074
661,682
def load_stop_words(words): """Load stopwords list, return a set""" with open(words, "r") as lines: set_stop_words = set() for i in lines: set_stop_words.add(i.strip()) return set_stop_words
7f1cb89af7d4cc5b17861af32484cf3c1a2b37f9
661,683
def get_param_value_and_result_list_call(exp_run, val_results_list, **kwargs): """ Callable functions to be used when traversing experiments. Returns dictionary with data organised by environment and agent parameters and their available values in any of the experiments. :param exp_run: Dictionary w...
e6bd19c9a1bfb350757f55070e39ba3414c32c55
661,685
def fitLine(line_points): """ Given 2 points (x1,y1,x2,y2), compute the line equation y = mx + b""" x1 = line_points[0] y1 = line_points[1] x2 = line_points[2] y2 = line_points[3] m = (y2 - y1) / (x2 - x1) b = y1 - m * x1 return (m, b)
c2ae660fbc0f49b868e3f3bbbddea25a6684abed
661,686
def map_items_to_parent(items, parents): """Groups all items into a list based on thier respective parent ex: pages have request, runs have pages """ item_lists = {} if len(parents) > 0: pk = parents.values()[0].pk for p_id in parents: item_lists[p_id] = [] for i...
8d165bae685546662c6be7f86196812e84f6e5a3
661,688
def _check_classifer_response_method(estimator, response_method): """Return prediction method from the response_method Parameters ---------- estimator: object Classifier to check response_method: {'auto', 'predict_proba', 'decision_function'} Specifies whether to use :term:`predict...
10771d4cf3c6bb160f633324c13e2cb61eb62dc9
661,689
import logging def base_func(aggregate_function): """Deals with the possibility of functools.partial being applied to a given function. Allows access to the decorated 'return' attribute whether or not it is also a partial function Args: aggregate_function (callable) Either a raw function or a...
902853a53a5043674b241753d532567d0d6576aa
661,690
def to_rgba_array(arr): """ Convert 2D integer values to RGBA tuples . Parameters ---------- arr: array of input values to split into rgba, will be cast to uint32 Returns ------- array of RGBA tuples: [[[R, G, B, A] ...]] (uint8) """ # from: http://stackoverflow.com/questio...
2a008685ef759a2829ee3c4949a58d3490b95523
661,691
import os def nth_dirname(path, n): """ Find the Nth parent directory of the given path Args: path (str): path name containing at least N components n (int): num of basenames to remove Returns: outpath (str): path with the last n components removed Notes: If n is 0, pat...
b6cf43851fa50a0bf4130d85cd52386a681acee1
661,692
def getTrees(treefile, matchlist): """ Returns list of trees at indices obtained from readSeqs """ focal_trees = [] trees = open(treefile, "r") i = 0 for line in trees: l = line.replace("\n", "") if len(l) > 3: i += 1 if i in matchlist: ...
15a63bb187ccd44e1d2b9e3ee60f95349f3da050
661,693
def klass(orig_class, mocker): """Return the CUT with some networky bits mocked out.""" credential_mock_attrs = { 'from_json_keyfile_name.return_value': "FakeTestCredentials" } driver_mock_attrs = { } orig_class.CREDENTIAL_CLASS = mocker.Mock(**credential_mock_attrs) orig_class.DRIVE...
d68eb921d7d3db1b531c6a9c80739cf197aa7bc0
661,694
def str_fill(i, n): """Returns i as a string with at least n digits. i: int n: int length returns: string """ return str(i).zfill(n)
78fb17307fc477b6f62497c7f07f57b9cfde948a
661,695
import hashlib def filehash(filename, block_size=65536, algorithm='sha256'): """ Computes the hash value for a file by using a specified hash algorithm. :param filename: filename :type filename: str :param block_size: blocksize used to compute file hash :type block_size: int :param algori...
5170bfe997e10159f753693bbc135e0cac5b08c0
661,696
def is_valid_input(ext): """ Checks if input file format is compatible with Open Babel """ formats = ["dat", "ent", "fa", "fasta", "gro", "inp", "log", "mcif", "mdl", "mmcif", "mol", "mol2", "pdb", "pdbqt", "png", "sdf", "smi", "smiles", "txt", "xml", "xtc"] return ext in formats
bb9ca7013470303be4812078b6ec5e7d5092b99c
661,697
def get_exit_code(matches): """ Determine exit code """ exit_code = 0 for match in matches: if match.rule.id[0] == 'W': exit_code = exit_code | 4 elif match.rule.id[0] == 'E': exit_code = exit_code | 2 return exit_code
68bfe810adebf25b1b67af2af10a7ea1404194f6
661,698
def read_param_file(paramfile): """Reads fitted parameters for semivariogram for plotting.""" lines = open(paramfile, "r").readlines() sigma2_gage = None sigma2_back = None L_back = None for line in lines: key, value = line.split(":") value = float(value) if key == "SIGMA...
3bfd6d16daa8bd601ac7448ba04fa7e48cbfb220
661,699
def computa_menor_tamanho_lista(lista_de_listas): """ Recebe uma lista de listas e retorna o tamanho da menor lista """ menor_lista = len(lista_de_listas[0]) for lista in lista_de_listas: if(len(lista) < menor_lista): menor_lista = len(lista) return menor_lista
3694bd9abc4054f258986ab0e68e20f38772b676
661,700
def parseBrowserBase(base_config): """ Parses the given option value into type and base url @param base_config: The option value @type base_config: C{str} @return: The type and the base url @rtype: C{tuple} """ if base_config: tokens = base_config.split(None, 1) ...
dd2b686024d77ca317f8421413d256a9b60199fa
661,701
def is_voiced(sound): """ Check if a sound is voiced or not. """ if sound.obj.phonation == "voiced" or sound.obj.breathiness or sound.obj.voicing: return True return False
b10247bdb942bfe59c9e9b9cb193bf4d678958d3
661,702
def claim_get(transport, request, queue_name, claim_id): """Gets a Claim `claim_id` :param transport: Transport instance to use :type transport: `transport.base.Transport` :param request: Request instance ready to be sent. :type request: `transport.request.Request` """ request.operation = ...
c0235eb249383d54d90f13d617cf58c02fe39ab1
661,703
import os def get_full_path(name): """ This method takes a string "name" and returns the named file's filepath. :param name: The name of the account file :return: The full path of a .txt file """ return os.path.abspath(os.path.join('.', 'lists', name + '.wrds'))
a56951c6f829c197552fbd68799d8316a8ba31b3
661,704
def crossover(parent_genes): """Take each value by alternating between parent genes""" num_parents = len(parent_genes) gene_length = len(parent_genes[0]) return [parent_genes[i % num_parents][i] for i in range(gene_length)]
0de1ea7b7e9be86338b9a4e374684dc579f7e32b
661,705
def dedup(df_in): """ Deduplicate gene sample combinations with >1 mutations and aggregate with additional feature of variant count for gene sample combination. """ df = df_in.copy() counts = df.groupby('case_barcode')['Hugo_Symbol'].value_counts() df = df.drop_duplicates(subset=['case...
3ff029afdb03e9a729ed8cad40b2fce829dd7eaa
661,707
def update_portfolio(returns, withdrawal, stock_allocation, balance): """Update a portfolio based on performance in a single year. Parameters ---------- returns : dict Stock and bond returns for a single year. withdrawal : float Amount to withdraw from the portfolio. The withdrawal ...
1f05bfcb5857473ec2f9e0ea8a65d0a1f9c4a104
661,708
import sys import subprocess def tts(message): """ This function takes a message as an argument and converts it to speech depending on the OS. """ if sys.platform == 'darwin': tts_engine = 'say' return subprocess.call([tts_engine, message]) elif sys.platform == 'linux2' or sys.plat...
ac4139af1c6e0ad7d1e1c3f6127aa9859d78e4e9
661,709
def get_ratio_served(solution): """Returns the ratio of users that have been assigned a video representation. """ nserved = 0 for u in solution["users"]: if "mos" in u: nserved += 1 return nserved/len(solution["users"])
7e609bee5fa4fe1ce0e45fa1a5490ef718e0af80
661,712
import sqlite3 def search_database(dbname,table,field,value): """ @param dbname: name of the database @param table: table to search @param field: field that we are using to search @param value: value that we want to search for @return: True or False if the command was executed correctly and i...
d2de34aef321b078e2c053a2f013e0d2ac248b1f
661,714
def is_form_post(environ): """Determine whether the request is a POSTed html form""" content_type = environ.get('CONTENT_TYPE', '').lower() if ';' in content_type: content_type = content_type.split(';', 1)[0] return content_type in ('application/x-www-form-urlencoded', ...
4b5966c87263161a1cdf182fc215149f850682de
661,715
def find_cmd0(cmd_stream, cmd) -> int: """Returns parameter of the first command in the stream that matches the given command""" for command in cmd_stream: if (command & 0xFFFF) == cmd.value: return (command >> 16) & 0xFFFF assert False, f"Not in command stream: {cmd}"
f2b4abdce13b3d21eafbe87a3920766dd493c7f8
661,716
from typing import Dict import re def parse_header_links(links_header: str) -> Dict[str, Dict[str, str]]: """ Parse a "Link" header from an HTTP response into a `dict` of the form:: {"next": {"url": "...", "rel": "next"}, "last": { ... }} """ # <https://git.io/JcYZi> links: Dict[str, Dict...
5f64f487cf541154c5751e705933cf41e250a03d
661,717
def filter_pattern_group(note_begin_pattern, note_end_pattern, note_metronome_group, note_end_metronome_group): """ The pattern group from dataset contains all notes. This filters it to only notes present in the new map """ for i,p in enumerate(note_begin_pattern): if i not in note_metronome_gro...
ecbf3d49b358c7bac351f83a3d040d25fcc33a90
661,718
def is_numeric(series, max_unique=16): """Flag if series is numeric.""" if len(set(series.values[:3000])) > max_unique: return True return False
8f3b492b8eb7a230f8dd01d628b12b39a517332a
661,719
def countInRange(listOfInts,rangeMin,rangeMax): """ return count of ints >= rangeMin and < rangeMax throw ValueError if listOfInts isn't a list, or contains something that isn't an int """ return -42
690c61c36b98e4ba5e8bc1c4511332be3bd2130b
661,720
def substrings_of_length(length, string): """ Given a string, return a list of all substrings of that string with a given length. For example, substrings_of_len(2, "ABC") returns ["AB", "BC"]. """ # You could also use a generator here, but I don't want to overcomplicate # things. substrings = [] for ...
3f20efbeb11eab840e27d43ea7932480a89f9d55
661,721
def num_pattern(i: int) -> str: """ Tries to make an unique pattern that will not generate collisions """ return f"_.:{i}:._([{i}])_!?{i}?!_"
e3cd48aa445f85e647ec7b435f75cda1d6653a6c
661,722
from datetime import datetime def now_dmy_hm(): """Format date to Year Month Day Hour Minute""" return datetime.now().strftime("%d.%m.%Y kl. %H:%M")
a3678769eb5f6f0b559b160dcf19b64e02d42442
661,725
def get_cfg_var(interp, var): """ Gets the value of a PHP configuration option""" w_value = interp.config.get_ini_w(var) if w_value is None: return interp.space.w_False return w_value
605f13abd8b09cb0316862f9eb0351137246db5c
661,726
def rank_features(explanation): """ Given an explanation of type (name, value) provide the ranked list of feature names according to importance Parameters ---------- explanation : list Returns ---------- List contained ranked feature names """ ordered_tuples = sorted(explanation, ...
f1d14296434f800fc03313cb447a44a2c11ea123
661,727
import random def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 ...
bac96b7562254f7140f4d12badbf2376b4fd9d59
661,728
import os import re def _convert_path(path, name): """Convert resource's path and name to storage's table name. Args: path (str): resource path name (str): resource name Returns: str: table name """ table = os.path.splitext(path)[0] table = table.replace(os.path.sep,...
403dedafea6a17a6fc0fc69567c98bf295f90c5f
661,729
import getpass def get_current_username() -> str: """ >>> assert get_current_username() is not None """ username = getpass.getuser() return username
6617040b9ef363d0ccef5a01e1a6d101a8c8642f
661,730
def _JoinWithOr(strings): """Joins strings, for example, into a string like 'A or B' or 'A, B, or C'.""" if not strings: return '' elif len(strings) == 1: return strings[0] elif len(strings) == 2: return strings[0] + ' or ' + strings[1] else: return ', '.join(strings[:-1]) + ', or ' + strings[...
dd50c410a11fccd05d5fba6797919c553662e924
661,731
def format_Kd(Kd): """Return formatted Kd.""" if Kd < 1e-14: return Kd * 1e15, 'fM' elif Kd < 1e-11: return Kd * 1e12, 'pM' elif Kd < 1e-7: return Kd * 1e9, 'nM' elif Kd < 1e-4: return Kd * 1e6, 'uM' elif Kd < 1e-1: return Kd * 1e3, 'mM' else: ...
5e05375eb4ca56828ca9ff289adbf31b157bb1a4
661,732
def create_ip_dict(): """ Creates a dictionary with all fields of IP-header, TCP-header and an element for the TCP-data IP-options and TCP-options always include padding :return: ip_dict """ ip_dict = { "version": None, "ihl": None, "tos": None, "total_length": ...
3a8d2a0e3f2d114c0998941bfcf8d042e5acd69f
661,733
def convert_coco_category(category_id): """ Convert continuous coco class id to discontinuous coco category id (0..79 --> 0..90) """ match = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, ...
f32b96850acfa59b83c0ab01d01a0f0f9fef9196
661,734
def glyph(x): """Helper routine to document that a glyph name goes in a slot.""" assert isinstance(x, str) return [x]
b507d1d648cfe1aa33d9d19ae03d543e44f73599
661,735