content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def meters_to_user_units_scale_factor(units: str) -> float:
"""
Return the scale factor to convert meters to user units.
Multiply the meters value by the scale factor to get user units
Args:
units: String containing 'english' or 'meters'
Returns: Scale factor
"""
if units == 'e... | 980cc2eff1f4cc880c9a65eaa98c4cd5b40a1290 | 630,238 |
def execute_query(driver,query):
"""Execute the provided query using the provided Neo4j database connection and driver.
Parameters:
driver A Neo4j bolt driver object
query A Cypher query to be executed against the Neo4j database
"""
with driver.session() as session:
results =... | 9015689fb2bf1674d96de8aee315d002f0f03a9e | 630,239 |
import os
def get_text_path():
"""Gets file path"""
script_dir = os.path.dirname(__file__)
rel_path = "websites.txt"
return os.path.join(script_dir, rel_path) | 150107c3131869103b04ba620477366bdd5a9cd4 | 630,240 |
from datetime import datetime
def mydate():
"""returns current date and time"""
return (datetime.now().strftime("%Y-%m-%d %H:%M:%S")) | 0ecf5fde0d3268cf26bb2a07e65b6ddab03339ef | 630,241 |
def _get_deploy_iso_name(node):
"""Returns the deploy ISO file name for a given node.
:param node: the node for which ISO file name is to be provided.
"""
return "deploy-%s.iso" % node.name | cae34990e5bc0c94408151b69b8562dc5d4c2432 | 630,242 |
def binary_to_string(input_binary: str) -> str:
"""Convert binary string to Ascii string.
:param input_binary: An input binary encoded string.
:return: The Ascii encoded equivalence of the input binary string.
"""
binary_from_str = int(input_binary, 2)
byte_from_binary = binary_from_str.to_byte... | 9aa324b0c041d03ca8e7e85cd8f339bc670beb3b | 630,243 |
def calculate_enrichment(coverage_values):
"""Calculate TSS enrichment value for a dataset
Parameters
----------
coverage_values
iterable of tuples (tss_center_depth, flank_depth) per TSS
Returns
-------
float
the TSS enrichment value
"""
tss_depth, flank_depth... | 673ee0208dca03e10f92463d5d53c1be73341f0d | 630,244 |
def get_interaction_id(question_id):
"""Returns the interaction_id from input question_id."""
rindex = question_id.rfind("_")
if rindex == -1:
return question_id
return question_id[:rindex] | d1e0bf238de9db0185b6db4828a1adc238d8025d | 630,245 |
import argparse
def _parse_args() -> argparse.Namespace:
"""Parse the command line args
Returns:
argparse.Namespace: the created parser
"""
parser = argparse.ArgumentParser(description='Check the status of 5GCN test with DSTester')
# Type
parser.add_argument(
'--type',
... | 245272ea32ff430ea5136c7c2e7959100bd81dbe | 630,246 |
def key_with_maxval(d):
"""Get the key with maximum value in a dictionary
Paramerers:
d (dictionary)
"""
try:
v=list(d.values())
k=list(d.keys())
return k[v.index(max(v))]
except:
return 9999 | bcca37df4154b04befd4e7e66a7f17a2531eac7e | 630,247 |
def expected_node_features():
"""Return the expected node features hexstring for this configuration"""
# features 1, 3, 7, 9, 11, 13, 15, 17 and 55 (0x8000000002aaa2).
return "8000000002aaa2" | 1d40cf2dfefcea2adf57898f583ff395336ea713 | 630,248 |
def merge_config(c1, c2):
"""
Merge 2 configs c1 and c2 (where c1 is the default config and c2 the user defined config).
A config is a python dictionary. The result config takes key:value from c1 if key
is not present in c2, and key:value from c2 otherwise (key is either present both in
in c1 and c... | 32d0315002ac9448b19634652a300960d2e65567 | 630,249 |
import torch
def pseudo_gtmask(mask, cutoff_top=0.6, cutoff_low=0.2, eps=1e-8):
"""Convert continuous mask into binary mask"""
bs,c,h,w = mask.size()
mask = mask.view(bs,c,-1)
# for each class extract the max confidence
mask_max, _ = mask.max(-1, keepdim=True)
mask_max[:, :1] *= 0.7
mask_... | 97c0e6a6dc4b7777b715eac5382dd4145417dad8 | 630,250 |
from pathlib import Path
def read_file(loc: str | Path) -> str:
"""Read test from a file.
:param loc: The file system location of the file.
:return: A :class:str object.
:rtype: str
"""
path = Path(loc)
with open(path) as fh:
contents = fh.read()
return contents | 41ef8e225e2a30ea4df4d90303b089c749607cc7 | 630,251 |
import os
import sys
def make_filename(outdir, prefix, suffix, replace=False):
""" Utility function for command-line interface """
filename = os.path.join(outdir, "{}.{}".format(prefix.strip('.'), suffix.strip('.')))
if os.path.exists(filename) and not replace:
print("Output file {} already exists... | c63c5677b8e66d8a02e517dcb44363645010c733 | 630,252 |
def load_long_description():
"""Parse long description file"""
with open("README.md", "r", encoding="utf-8") as f_readme:
readme = f_readme.read()
return readme | 819dc329e5c512b21d5dc4bfc66846f7d375ddff | 630,253 |
import re
def _normalise_id(raw_id):
"""Reddit IDs start with t1_, t2_, etc. which need to be stripped."""
return re.sub("^t[0-9]_", "", raw_id) | 6d9def895e6aeb60a606849387810050b09f2cd7 | 630,254 |
def group_to_color(group_order, colors):
"""Mapping of groups to colors"""
return dict(zip(group_order, colors)) | 32d14200f4cbc7cc9336f4bebdfb2c2e553e3bee | 630,255 |
def score_num_fev(score):
"""
Fixture for scoring the number of function evaluations that were performed.
"""
def inner(result, cutoff=None, additional_tag=''):
num_fev = sum(res.num_fev for res in result.minimization_results)
score(
num_fev,
tag=additional_tag + ... | dc10f23f47602e49f95fcbab3691f79e3ac2cf47 | 630,256 |
def dist(spectrum, A, B):
"""
Minimum number of steps along ring to get from one pitch to the next
Parameters:
-----------
spectrum: list
user-defined spectrum
A: int
first pitch
B: int
second pitch
"""
length = len(spectrum)
forwa... | 3ecda36a9912f3088949b406f93ccf0654d505c1 | 630,257 |
def get_planet_product_type(img_path):
"""
return if file is scene or OrthoTile"""
split = img_path.stem.split('_')
# check if 4th last imagename segment is BGRN
if split[-4] == 'BGRN':
pl_type = 'OrthoTile'
else:
pl_type = 'Scene'
return pl_type | 70aac7930fb95c0270f4b74a51a09e5d72ea8aeb | 630,258 |
import requests
def shrink(url):
"""
Shrinks the given URL.
"""
return requests.post('http://tinyurl.com/api-create.php', data={'url': url}).text | facf0c6fa34e8663648c177d99895f90a436b0e9 | 630,259 |
def root_to_dict_instrument(root):
"""
Part of parse xml, item_type = Instrument
"""
info = {}
info['InstrumentURN'] = root.find('.//URN').text
if root.findall(".//*[@typeOfUserID='colectica:sourceId']") != []:
info['InstrumentSourceID'] = root.findall(".//*[@typeOfUserID='colectica:sour... | 08e4974d2ed2896fd481a54bc31c1e5cced6caae | 630,261 |
def get_license(j):
"""
By default, the license info can be achieved from json["info"]["license"]
In rare cases it doesn't work.
We fall back to json["info"]["classifiers"], it looks like License :: OSI Approved :: BSD Clause
"""
if j["info"]["license"] != "":
return j["info"]["license"]... | c736967189b170155fe9948ab83c9e54c4ca2719 | 630,262 |
def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_liter... | 14bb312074b06d3b8d5e9e66652050d9247700af | 630,263 |
def decode_params(filename):
"""
Decode the tlusty filenames for the model parameters
"""
model_params = {}
slashpos = filename.rfind("/")
periodpos = filename.rfind(".flux")
# translation of metallicity code
met_code = {"C": 2.0, "G": 1.0, "L": 0.5, "S": 0.2, "T": 0.1}
met_char = ... | c08a13f1aa3bc9d24564085837192264edcf9953 | 630,264 |
import argparse
def init_args():
"""
:return: parsed arguments and (updated) config.cfg object
"""
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--input_dir', type=str,default='./output_fp32',
help='Directory of npu predict output')
parser.add_argument('... | f031873abbe238654576cf1a6efda15e1ba89953 | 630,265 |
def checkpoints(period, total):
"""
A helpful function for individual train method.
to generate checkpoint list with integers
for every PERIOD time steps and TOTAL time steps in total.
"""
ckps = [
period * x for x in range(1, total // period)
]
return ckps | f0bb59f3aa5da73fe6d70ecf7d7788a2b5437551 | 630,267 |
def json_length(msg_body: str) -> str:
""" The robot's JSON API requires the length of the JSON command to be specified before the JSON command. This
function calculates the length of the JSON message body and formats it for the JSON API.
:param msg_body: the JSON message body.
:return: the length of t... | 527b90c42fa055879680b2dbd0511e531a8422fe | 630,268 |
import argparse
def return_parser():
"""Configures and returns argparse ArgumentParser object for command line script."""
parser = argparse.ArgumentParser("Convert raw loglines to ASCII code (minus 30) integer representation.")
parser.add_argument('-datafile',
type=str,
... | dcc8061511f1af27280dc719b367d3866b16aee4 | 630,269 |
import zlib
def inflate(data):
"""Used for deflate Content-Encoding"""
decompress = zlib.decompressobj(
-zlib.MAX_WBITS # see above
)
inflated = decompress.decompress(data)
inflated += decompress.flush()
return inflated | ad51d00f7525becdf4fc9badb46a2d4b1047f35c | 630,270 |
def getxy(a, b):
"""x*a + y*b = gcd(a,b)"""
""" input requirement: a > b """
""" get x for a and y for b"""
remainder = a % b
k = a // b
if b % remainder == 0:
return 1, -k
else:
x1, y1 = getxy(b, remainder)
return y1, y1 * (-k) + x1 | 89da623669fd7515264cf393a10a5feb4a3d178d | 630,271 |
def test():
"""
Test that the website's API is working.
:return:
"""
return 'API works!' | 176a494e2802c699304ef7c35a08ce0d20d9d251 | 630,272 |
from typing import List
def how_many_namefellows(queue: List[str], person_name: str) -> int:
"""
:param queue: list - names in the queue.
:param person_name: str - name you wish to count or track.
:return: int - the number of times the name appears in the queue.
"""
return queue.count(person... | 8364adb4226d0f09bb5a7a90af0aee518d448a95 | 630,273 |
def file_type(filename):
"""returns the type of the file"""
magic_dict = {
"\x1f\x8b\x08": "gz",
"\x42\x5a\x68": "bz2",
"\x50\x4b\x03\x04": "zip"
}
max_len = max(len(x) for x in magic_dict)
with open(filename) as f:
file_start = f.read(max_len)
for magic, filetype... | e3c4829023c2a76466c39cdcee29136f5815e819 | 630,274 |
def extract_capabilities(text):
"""Extract a capabilities list from a string, if present.
Args:
text: String to extract from
Returns: Tuple with text with capabilities removed and list of capabilities
"""
if b"\0" not in text:
return text, []
text, capabilities = text.rstrip().spl... | 6d974b58275d676d712583a83f08d90e3e2186df | 630,275 |
def parse_bool(f):
"""
Parse boolean from string.
:param f:
:return:
"""
def inner(*args, **kwargs):
r = f(*args, **kwargs)
if not r:
return None
return r.lower() == 'true'
return inner | 3e678b8e93c2a629b07309659e581bd7db4d650a | 630,277 |
import torch
def extract_ampl_phase(fft_im):
"""
Extracts amplitude and phase from the image
Args:
fft_im (Tensor): size should be bx3xhxwx2
Returns:
tuple: (amplitude, phase)
"""
# fft_im: size should be bx3xhxwx2
fft_amp = fft_im[:, :, :, :, 0]**2 + fft_im[:, :, :, :, 1]*... | 59d14c950530228262a712427496be9d99840a1c | 630,278 |
import os
def get_token_from_env():
"""
See README.md for details on creating a token
"""
return os.getenv("ATHERA_API_TOKEN") | a880c058227f58a9df8f9e73f2aa560953ba5d13 | 630,279 |
def cli(ctx, deleted=False):
"""Get a list of quotas
Output:
A list of dicts with details on individual quotas.
For example::
[{u'id': u'0604c8a56abe9a50',
u'model_class': u'Quota',
u'name': u'test ',
u'url': u'/api/quotas/0604c8a56abe9a50'},
... | f30d5dc21ebc33a46ce5c81c76dad786ae449606 | 630,280 |
def __float2str(value: float) -> str:
"""Convert a float into a human readable string representatoin."""
if value == 0.0:
return "0.0"
return "{0:.5f}".format(value) | 87f315f71ef97a6974e5d9b2ece9f911a209a944 | 630,281 |
def transform_metadata(record):
"""Format the metadata record we got from the database to adhere to the response schema."""
response = dict(record)
response["id"] = response.pop("datasetId")
response["name"] = None
response["description"] = response.pop("description")
response["assemblyId"] =... | 5a1299acb2f41db7f9c213419cffc29ef09b133f | 630,282 |
def get_sha(s: str, mode: int = 256, encoding='utf-8', to_bin: bool = False) -> str:
"""
获取shaX的加密内容
:param s: 加密前字符串
:param mode: 可以加密的模式: sha1 sha224 sha256 sha384 sha512 只需要传入数字即可 默认: 256
:param encoding: 字符串的编码方式 默认 utf-8
:param to_bin: 是否返回二进制串 默认 False --> 返回十六进制
:return: 加密后字符串
... | c68af4f76177145e4908ee7e648d989e231ba1a3 | 630,283 |
import tempfile
import os
import shutil
def new_html_temp(src):
"""
Create a tmp directory, copy `src` into it, and return the tmp directory
"""
tmpdir = tempfile.mkdtemp()
parentdir = os.path.dirname(__file__)
shutil.copytree(os.path.join(parentdir,src), os.path.join(tmpdir,src))
return ... | 1178fae7517e1af8583bae1bbfaad3ae66516bc3 | 630,284 |
def query_create_rels_unwind(start_node_labels, end_node_labels, start_node_properties,
end_node_properties, rel_type, property_identifier=None):
"""
Create relationship query with explicit arguments.
UNWIND $rels AS rel
MATCH (a:Gene), (b:GeneSymbol)
WHERE a.sid = rel.... | 3ed096d0d9f8bc11c07bf0b0d1c9e1a2d2f5d349 | 630,285 |
def _mass_range(name, mass, width, degen, boson):
"""
Determine the mass thresholds of a resonance for truncating its
Breit-Wigner distribution.
"""
# Masses of decay products, rounded up so that the minimum threshold is
# slightly larger than the actual total mass of the decay products.
PI... | 54d2c7f5ce29fd69be5768fc14e2b56dbdce8ed7 | 630,286 |
import numpy
def transform_mat(xform, mat):
"""
Transform a matrix by another matrix.
:param mat: 4x4 matrix
:param xform: 4x4 matrix
:return:
"""
return numpy.matmul(xform, mat) | 97b5b45fa7b85da369a13239423f1669f8297fd0 | 630,287 |
import os
def check_root():
""" This function returns False if the user does not have root privileges.
Caution: Only works on Unix systems """
return (os.getuid() == 0) | 9069b2f4035af25518dca9af8ef0f2515215feb5 | 630,289 |
def set_prior(kind = 'scale',
logbeta_max=-1,
logbeta_min=-6,
M_max=20, r_max=30,
scale_max=25,
mu_ol_max=25,
r_min_min=0.3,
r_max_max=1.5,
delta_r_min=0.2):
"""
Setup prior transforms for models... | d3a5bb7f6a195947cd5df5db345bdeb12a5dc488 | 630,291 |
def tested_function(x):
"""
Testovaci funkce
"""
return x**2 + 2 * x - 20 | 16ad23ac142cb1d3fba69d66012ba4c3b5d8a6df | 630,292 |
import yaml
def load_algo_config(config):
"""Loads algo specific config from algo config files, based on config['algo']"""
algo = config['algo']
if type(algo) == dict: # most likely algo={'grid_search':[...]}
algo = 'general'
if algo not in config["algo_config_files"].keys():
algo = '... | d9823c3b53faf9f81aafc0304decf6e9f2ddefd0 | 630,293 |
def findDuplicates(fileNames):
"""findDuplicates"""
seen = {}
duplicates = []
if fileNames:
for x in fileNames:
if x not in seen:
seen[x] = 1
else:
if seen[x] == 1:
duplicates.append(x)
seen[x] += 1
... | 3e352ecc0b4976209646f508af91c8b4c3e8e441 | 630,294 |
import typing
def get_word_transform(name: str) -> typing.Callable[[str], str]:
"""Gets a word transformation function by name."""
if name == "upper":
return str.upper
if name == "lower":
return str.lower
return lambda s: s | 1dde1f9aed0b44e47ee429a778afcf111eb01471 | 630,295 |
def make_query(user_id=None, tenant_id=None, resource_id=None,
user_ids=None, tenant_ids=None, resource_ids=None):
"""Returns query built from given parameters.
This query can be then used for querying resources, meters and
statistics.
:Parameters:
- `user_id`: user_id, has a prio... | 6ec0197f1a9071ecd4381542d323997a12bc55ee | 630,296 |
import os
import pickle
def import_data(data_name):
"""
Import pickled coordinate and travel time data if it exists
Args:
data_name (str): name of pickled data
Return:
lats (list): destination latitudes
lngs (list): destination longitudes
travel_times (list): time tak... | 9038833aed2493f2fee9403f09592f0e7699ba23 | 630,297 |
def get_model_pk_column(model_class):
"""
Get the primary key Column object from a Declarative model class
:param Type[DeclarativeMeta] model_class: a Declarative class
:rtype: Column
"""
primary_keys = model_class.__mapper__.primary_key
assert len(primary_keys) == 1, "Nested object must h... | c73cd31beb9a7609e020c278d0f9703f541c7eeb | 630,298 |
def countIntersectionForTwoSets(list1, list2):
"""计算两个集合的交集的模"""
count = 0
for i in range(len(list1)):
m = list1[i]
for j in range(len(list2)):
if list2[j] == m:
count = count + 1
break
return count | 18c50c94b9b09a585e50ff5e14dc2911d55f7f06 | 630,299 |
import functools
def capture_exceptions(async_result):
"""Return a new decorated function that propagates the exceptions of the
wrapped function to an async_result.
:param async_result: An async result implementing :class:`IAsyncResult`
"""
def capture(function):
@functools.wraps(functio... | 6ad9342673a34ea6148309a90211a0b38e1f03b3 | 630,300 |
def fold(dots, axis, line):
"""Return the dots folded along line, given axis x or y."""
if axis == 'x':
return {(line - abs(line - x), y) for (x, y) in dots}
else:
return {(x, line - abs(line - y)) for (x, y) in dots} | 9a7d3f4d790aeb208d1223578c181226d922fb84 | 630,301 |
def lgfCoord(point, lgfOrigin, trf2lgfMatrix):
"""
Determines the coordinates of a point in a Local Geodetic Frame.
:param point: Coordinates of the point of interest expressed in ECEF
:param lgfOrigin: Coordinates of the LGF origin expressed in ECEF
:param lgf2trfMatrix: Rotation matrix from
:... | 9d0cd25a17aaeca360f25b2e789bb27412bcedf4 | 630,302 |
import math
def poh_from_hydronium(concentration):
"""Returns the pOH from the hydronium ion concentration."""
return 14 + math.log(concentration) | 5772099bfb75b0b1e056f4274c2e09e7c887e193 | 630,303 |
def __ror__(self, x):
"""Allows piping input to :class:`torch.nn.Module`, to match same style as
the module :mod:`k1lib.cli`. Example::
# returns torch.Size([5, 3])
torch.randn(5, 2) | nn.Linear(2, 3) | cli.shape()"""
return self(x) | 2994a3dce0e9d3d8b1de85a3b25166b9514d868f | 630,304 |
def permutations(L):
"""permutation implementation, just for fun
should be the same as itertool.permutations
"""
if not L:
return [()]
ans = []
for i, item in enumerate(L):
sub_L = L[:i] + L[i + 1 :]
perms_sub_L = permutations(sub_L)
for x in perms_sub_L:
... | 48c6b822bd079b27d3a48508348f46d93bcaf8ff | 630,306 |
def reverse_match(seq: str, recog: list) -> (bool):
"""
Match the sequence with a recognition sequence in reverse.
:param seq: the sequence to search in
:param recogn: a list with bases that should be
matched subsequently
:return: True if the sequence matches the
rec... | 7686d8d727ac360dc655f80605b20f19f6d2e25c | 630,307 |
def format_diff_int(new, old):
""" returns difference as a string """
diff = abs(new - old)
sign = "+" if new >= old else "-"
return " {} {}".format(sign, diff) | ced8adac831444c819104883e58a4c7dd9c0494c | 630,309 |
import base64
def encode_bytes(bytes_):
""" Encodes some given bytes into base64 using utf-8.
:param bytes bytes_: The bytes to encode
:return: The bytes encoded base64 string
:rtype: str
"""
return base64.encodebytes(bytes_).decode("utf-8") | c434c4cec4a235546ba0ff985d82ddac0d2bf05d | 630,310 |
from typing import List
from typing import Tuple
import re
def split_on_references(lines: List[str], max_refs_fraction: float = 0.5) \
-> Tuple[List[str], List[str]]:
"""
Mark the start of the references.
Does this by looking for the last occurrence of the word "Reference" or
"Bibliography".
... | 8c45f535e4ef2b07c1dcb0cc2edca34989a01a37 | 630,312 |
def transaction_str_to_int(transaction_dict: dict):
"""转换交易格式
Args:
transaction_dict: 交易字典
Returns:
dict:转换后的交易字典
"""
for key, value in transaction_dict.items():
if key in ["value", "gasPrice", "gas", "nonce", "chainId"]:
transaction_dict[key] = int(value)
... | 8e19be97ca6ef013c689f4e97bebd0591de2c1f6 | 630,313 |
def get_auth_data(server, share, workgroup, username, password):
"""
auth callback method for smb context
this method is called by libsmbclient whenever it needs auth information
epson printers accept any user/pass combination
"""
user = "default"
password = "default"
workspace = "WORKGR... | fc94cc1d0f93de0c133052e5fd05e76c6b1e3f46 | 630,314 |
import torch
def max(dat, dim=None):
"""Maximum element (across an axis) for tensors and arrays"""
if torch.is_tensor(dat):
return dat.max() if dim is None else dat.max(dim=dim).values
else:
return dat.max(axis=dim) | 9fc000bd9635129a448fa00926cf21b648048b49 | 630,315 |
def compare_transs(tdata):
"""Compare translation words and return data."""
data = {
'eng_fullparse': 0,
'eng_TAM': '',
'eng_TAMsimp': '',
'eng_agree': 0,
'eng_simp_agree': 0,
}
# add features based on both translations
niv_tam, esv_tam = tdata['niv_TAM'], t... | 72ac9482a3d6a5904231e7d84a03c27501380461 | 630,316 |
def select_from_list(
master_list,
first=None,
last=None,
skip=[],
only=[],
loose=True,
):
"""
Select only part of a list.
"""
sorted_list = sorted(master_list,key=lambda s: s.lower())
sub_list = []
if first is not None:
before_first = True
else:
... | 601f9b103c0105a3a08d9fa0e53ea25489da9fa0 | 630,317 |
from unittest.mock import Mock
def fix_mock_results_pho_3(problem):
""" Create a mock class to replace results."""
resul = Mock()
resul.count = [1]
resul.fob_center = [-20]
resul.fob_star = [-40]
resul.fap_center = [-25]
resul.fap_star = [-35]
resul.x_center = problem.nominal[0]
re... | 49a8a9732f04e64b6bd684046f0dbcc208f84595 | 630,319 |
import re
def temperature_out(value:float, dims:str):
"""
"""
_value = value
if re.match(r"\bfahrenheit\b", str(dims), re.IGNORECASE):
dims = dims.replace('fahrenheit', 'kelvin')
_value = (_value * 9/5 - 459.67)
elif re.match(r"\bcelsius\b", str(dims), re.IGNORECASE):
... | 06da2999d3a82ec5679fc7e5e59987ec1e06887a | 630,320 |
def merge_from_cfg(cfg, base_cfg):
"""
merge the cfg to base cfg
"""
for k, v in cfg.items():
if base_cfg.get(k) and isinstance(v, dict):
base_cfg.update({k: merge_from_cfg(v, base_cfg.get(k))})
else:
base_cfg.update({k: v})
return base_cfg | 00a424448a457ea636d84b7081d388726a7b1aa0 | 630,321 |
import os
def needs_updating(target, dependencies):
"""
Does the file `target` need to be updated, in light of the collection `dependencies`?
Return True if target doesn't exist, has zero size, or is older than any dependency.
Otherwise, return False.
"""
if not os.path.exists(target):
... | f32af8e914fcdf67c13f3de6836dfd238e9025c4 | 630,322 |
import heapq
def dijkstra(connections,start, goal=None):
"""
Requires a dict with as values a LIST of tuples (neighbor, weight)
Or a function returning a list of tuples with neighbors and weights per node
Returns
if goal == None: return all paths from start
elif goal found: returns path... | eafe5930f603efc8071be58ce2dca09970b2c4c8 | 630,324 |
def payload_to_str_base(payload):
"""
Converts a given payload to its str_base representation.
A str_base payload is for example: "0xFF 0xFF 0xFF 0xFF".
:param payload: The payload to be converted.
:return: Returns the str_base representation of the payload.
"""
result = ""
for i in ran... | aa414aca57f3743cb270c3affbd7f9a6bbbda1de | 630,325 |
import struct
def applyDPFSLevel(selector, data, dataBlockSize):
""" Reconstructs active data of a DPFS level using the previous level """
dataPos = 0
selectorPos = 0
output = bytearray()
dataLen = len(data[0])
while True:
u32, = struct.unpack('<I', selector[selectorPos: selectorPos + ... | df29e6a994d227e38a0f2dff539b785bf4a7a36c | 630,326 |
def player_marker():
"""
Function do define the marker of the two players
:param: none
:return: tuple (Player 1, Player 2)
"""
marker = input('Player 1, choose your marker (X/0): ').strip().upper()
# Validation
while marker != 'X' and marker != '0':
marker = input('Typing error,... | c8e8e84adcc99a94a59f0295d37a9bc0f4f14c56 | 630,327 |
def change_weight_of_others(others_factor):
"""
A function that changes the votes for the "others"
"""
def fct(key, votes):
if key != "person":
return votes
else:
return int(others_factor*votes)
return fct | ba64dbfc026bd5d4ac89d3bdda2e6de7289afee0 | 630,328 |
def _next_regular(target):
"""
Find the next regular number greater than or equal to target.
Regular numbers are composites of the prime factors 2, 3, and 5.
Also known as 5-smooth numbers or Hamming numbers, these are the optimal
size for inputs to FFTPACK.
Target must be a positive integer.
... | 3cfd3975ad71904283054c3b5b1721b8f409cfb3 | 630,329 |
def break_list_into_parts(LIST, parts):
"""For example:
.. doctest::
>>> break_list_into_parts([1,2,3,4,5], [3,2])
([1, 2, 3], [4, 5])
:param LIST:
:param parts:
:return:
"""
start = 0
RET = tuple()
for p in parts:
RET += (LIST[start:start+p],)
star... | a570c6e5e2806afdc982797655cd0dffaa11bda1 | 630,330 |
import os
def tokenLocalStoreUtil(token_store, customer_id="customer",
client_id="client"):
"""
Summary: Utility function to reuse for store and load access token for
local storage type
Returns:
fullName(str path): path to the file in local file system where token
... | 9e8b1bdd3dbcf8f8b78f5f7615ff9ca46c2bfa92 | 630,331 |
def __decode_lens__(lens_package):
""" decode the lens_package tuple into its constituents
Args:
lens_package: a tuple or a |ParaxialModel|. If it's a tuple:
- the first element is a |ParaxialModel|
- the second element is a tuple with the begining and ending
... | acdd08577362845c6c95b59feb63f90ec9ef65ce | 630,332 |
from pathlib import Path
import subprocess
def get_phylum_cli_version(cli_path: Path) -> str:
"""Get the version of the installed and active Phylum CLI and return it."""
cmd = f"{cli_path} --version"
version = subprocess.run(cmd.split(), check=True, capture_output=True, text=True).stdout.strip().lower()
... | 2de3d14fd7dfca8b81d21fc144e807c52aaadf7b | 630,334 |
def euclidean_algorithm(a: int, b: int) -> int:
"""
Finds the greatest common divisor of two natural numbers.
If n or k is less than or equal to 0, it raises ValueError.
>>> euclidean_algorithm(6,9)
3
>>> euclidean_algorithm(8, 20)
4
>>> euclidean_algorithm(19, 17)
1
>>> euclidea... | 20dfb1521cc1703a978aa20ea37d2673f648cc39 | 630,335 |
def setdiff(list1, list2):
"""
returns list1 elements that are not in list2. preserves order of list1
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']... | 19fb7a44b2796432404f80f46b9650996b45248c | 630,336 |
from functools import reduce
def createLookup(B):
"""Process B to create a reverse lookup scheme that is appropriate for
any of the libraries in pyncomb that allow for one or more base sets to
be specified.
Let rev(K) be the reverse lookup dictionary of a list K, i.e. if
K[i] = j, then rev(K)[j] ... | 6bb2f907fa71cbd7fa4a2ab1482b0457acd61b36 | 630,337 |
def _cache_original_loads(case):
"""
Stores the original value of all of the load records from the seed case.
:param case: The :class:`Case` that is synchronized with the current loaded case.
:type case: :class:`Case`
:return: The original load values
:rtype: dict{(int, str): dict{str: float}}
... | 76cf28bfead57b059b332ae9f6d3121a835a166b | 630,338 |
def __makenumber(value):
"""
Helper function to change the poorly formatted numbers to floats
Examples:
> value is an integer / float data type -> float type returned
> value = '1,000', then the float value is 1000
> value = '1 000 000.00' then the float value is 1000000
... | 6f1b9c718cb0cce1c9a058ff533c603aad2948e0 | 630,339 |
def request_add_host(request, address):
"""
If the request has no headers field, or request['headers'] does not have a Host field, then add address to Host.
:param request: a dict(request key, request name) of http request
:param address: a string represents a domain name
:return: request after add... | 0ae2eb267e5042b3a662fb8f8b6bb4ec03c56b37 | 630,340 |
import re
def replace_template_vars(string, dictionary):
"""Replaces template variables like {{SOME}} in the string
using the dictionary values."""
orig_string = string
for key, value in dictionary.items():
string = string.replace("{{"+key+"}}", value)
if string == orig_string:
rai... | da1f054360ca906d960588d7ca6edb6c4245bf35 | 630,341 |
def classif_accuracy(labels, preds):
"""Gets the percentage of correct classified predictions.
Parameters
----------
labels : torch.tensor
The true labels.
preds : torch.tensor
The prediction.
Returns
-------
float
Percentage of correct classified labels.
"... | 557aac48865b2d7c942be71bd4ec73ba75e380d6 | 630,343 |
import os
def generate_master_key():
"""
Generate a new 256-bit (32 bytes) AES key to be used for symmetric encryption of secrets.
"""
return os.urandom(32) | a45f3df69e660ea9d9b8aced8b2c40653edc2acb | 630,344 |
def indexing(pair):
"""
The indexing method receives a pair of user X and followed users by X.
for example it receives (X, Fi) as a pair which X follows Fi.
This method returns (Fi, X) and (X, -Fi).
:param pair: (X, Fi) as a pair which X follows Fi.
:return: is a list of pairs [(Fi, X), (X, -Fi)... | bdb96f5f8e23a81dc4f2f90cbe3e0a2dfeb134ad | 630,346 |
import uuid
import json
import time
def execute_later(redis, queue, delayqueue, name, args, delay=0):
"""
:param redis: 唯一标识符
:param queue: 处理任务队列的名称
:param delayqueue: 延迟队列
:param name: 处理任务的回调函数的名字
:param args: 传给回调函数的参数
:param delay: 延迟时间
:return:
"""
identifier = str(uuid... | 3e3c1e25ac34478a0f343868e445bd8802fef195 | 630,347 |
def sanitize_single_id(value: str | int) -> str:
"""
Update `value` to a sanitized sql-friendly name.
Force to string and then scrub out: space, slash, dash, comma
e.g. "Food/Drink" -> "fooddrink"
Arguments:
value (str | int): unique ID value for a POI
Returns:
str: POI value ... | e273f2e9c8e9d19990351d1b71be293f41ce7690 | 630,348 |
import os
def get_filenames(is_training, data_dir):
"""Returns a list of filenames."""
assert os.path.exists(data_dir), (
"Run cifar100_download_and_extract.py first to download and extract the "
"CIFAR-10 data."
)
if is_training:
return [os.path.join(data_dir, "train.bin")]
... | 3380a9ba07d82ac6164e45adc570a2dd06c96c5b | 630,349 |
def model_list(sm_client, model_name):
"""API call to get available models inside Sagemaker."""
try:
response = sm_client.list_models(NameContains=model_name)
recent_models = response["Models"]
return recent_models
except Exception as error:
raise Exception(f"Error listing models: {error}") | 53fd8dcc2171bc6b409e0acac8b781b918020c90 | 630,350 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.