content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import operator
def map_method(*args, **kwargs):
"""
Given a method name and a sequence of models, return a sequence of values
of applying the extra positional and keyword arguments in each method.
Attr:
attr:
Method name. Dotted python names are valid.
models:
A sequence of models.
*args, **kwargs:
Arguments to pass to m.<attr>(*args, **kwargs)
"""
attr, data, *args = args
attr, _, method = attr.partition(".")
if method:
data = map(operator.attrgetter(attr), data)
return map(operator.methodcaller(method, *args, **kwargs), data)
else:
return map(operator.methodcaller(attr, *args, **kwargs), data) | aa2ab34f729c41376e30c9a9b8c6536e14ba8be4 | 694,023 |
def get_cell_genes(cur,cell):
"""
Return the genes expressed in cell
Parameters
----------
cur : MySQLdb cursor
cell : str
Name of cell
"""
sql = ("select genename from WB.association "
"join WB.cells on "
"WB.association.idcell = WB.cells.idcells "
"where WB.cells.name like '%s'"
%cell)
cur.execute(sql)
return [a[0] for a in cur.fetchall()] | 03550cc6a8645b49c86d280d17032b05102b88d3 | 694,027 |
import torch
def test(model, test_loader, device=torch.device("cpu")):
"""Checks the validation accuracy of the model.
Cuts off at 512 samples for simplicity.
"""
model.eval()
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if batch_idx * len(data) > 512:
break
data, target = data.to(device), target.to(device)
outputs = model(data)
_, predicted = torch.max(outputs.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
return correct / total | 2df49a192c144a9300b5cd218b347a55f79da467 | 694,032 |
def isGlideinHeldNTimes(jobInfo, factoryConfig=None, n=20):
"""This function looks at the glidein job's information and returns if the
CondorG job is held for more than N(defaults to 20) iterations
This is useful to remove Unrecoverable glidein (CondorG job) with forcex option.
Args:
jobInfo (dict): Dictionary containing glidein job's classad information
Returns:
bool: True if job is held more than N(defaults to 20) iterations, False if otherwise.
"""
if factoryConfig is None:
factoryConfig = globals()["factoryConfig"]
greater_than_n_iterations = False
nsysholds = jobInfo.get("NumSystemHolds")
if nsysholds > n:
greater_than_n_iterations = True
return greater_than_n_iterations | e608ada46f1571b9e96531bc3cca3692f940846a | 694,035 |
import re
def prepare_whitelist(patterns):
"""Join and compile the re patterns.
Args:
patterns: regex patterns.
Return:
A compiled re object
"""
return re.compile('|'.join(patterns)) | 5c1eb91c2aa534af6b8ff5cc4165095a5eb577e7 | 694,038 |
def _GetVersionIndex(version_str):
"""Returns the version index from ycsb version string.
Args:
version_str: ycsb version string with format '0.<version index>.0'.
Returns:
(int) version index.
"""
return int(version_str.split('.')[1]) | 9c415a55a97adedb6bbc5576d7147d2164651d4e | 694,041 |
import re
def parse_ping_output(ping_output):
"""Parse ping output.
Returns a tuple with the number of packets sent and the percentage of
packet loss from a ping output."""
match = re.search(
'(\d*) packets transmitted, .* ([\d\.]*)\% packet loss',
ping_output)
return match.groups() if match is not None else None | e3af78babdbd21dd6369f18de150a9d453fe7d21 | 694,042 |
def is_transform(str_in):
"""Determines if str_in is the name of a transformation file
"""
return '.ima' in str_in \
or '.trm' in str_in | c7f65ac6c86776c640a0027c94b0cee5afdd8cfb | 694,045 |
def process_resize_value(resize_spec):
"""Helper method to process input resize spec.
Args:
resize_spec: Either None, a python scalar, or a sequence with length <=2.
Each value in the sequence should be a python integer.
Returns:
None if input size is not valid, or 2-tuple of (height, width), derived
from input resize_spec.
"""
if not resize_spec:
return None
if isinstance(resize_spec, int):
# For conveniences and also backward compatibility.
resize_spec = (resize_spec,)
resize_spec = tuple(resize_spec)
if len(resize_spec) == 1:
resize_spec = (resize_spec[0], resize_spec[0])
if len(resize_spec) != 2:
raise ValueError('Unable to process input resize_spec: %s' % resize_spec)
if resize_spec[0] <= 0 or resize_spec[1] <= 0:
return None
return resize_spec | 2850b1f86a62cb35611bcb89a543bb35eb8226bf | 694,046 |
def split_wrap(sql):
"""Split with \n, and strip the ' '. """
sql_list = sql.split('\n')
if sql_list[0] == '':
del sql_list[0]
if sql_list[-1] == '':
del sql_list[-1]
sql_list = list(map(lambda x: x.strip(), sql_list))
return sql_list | 7d8639b99219226b5a29da204a1c7fd8f71acc0e | 694,050 |
def fastpath_dup_rid_input(app):
"""
Access DB directly. Fetch > 1 measurements from fastpath that share the same
report_id and input
Returns (rid, input, count)
"""
sql = """
SELECT report_id, input,
from fastpath
group by report_id, input
HAVING count(*) > 1
LIMIT 1
"""
with app.app_context():
for row in app.db_session.execute(sql):
return (row[0], row[1]) | a09e82cd84483c21722a197ab8f5becae2c1d5a6 | 694,051 |
def get_BM_data(filename):
"""Read the contents of the given file. Assumes the file
in a comma-separated format, with 6 elements in each entry:
0. Name (string), 1. Gender (string), 2. Age (int)
3. Division (int), 4. Country (string), 5. Overall time (float)
Returns: dict containing a list for each of the 6 variables."""
data = {}
f = open(filename)
line = f.readline()
data['name'], data['gender'], data['age'] = [], [], []
data['division'], data['country'], data['time'] = [], [], []
while line != '':
split = line.split(',')
data['name'].append(split[0])
data['gender'].append(split[1])
data['age'].append(int(split[2]))
data['division'].append(int(split[3]))
data['country'].append(split[4])
data['time'].append(float(split[5][:-1])) #remove \n
line = f.readline()
f.close()
return data | c3dce697ed850ed422a5d60fbd08310f04461a82 | 694,052 |
def build_B_spline_higher_degree_basis_fns(
breaks, prev_degree_coefs, degree, x):
"""Build the higer order B spline basis coefficients
N_{i,p}(x) = ((x-u_i)/(u_{i+p}-u_i))N_{i,p-1}(x) \
+ ((u_{i+p+1}-x)/(u_{i+p+1}-u_{i+1}))N_{i+1,p-1}(x)
"""
assert degree > 0
coefs = []
for i in range(len(prev_degree_coefs)-1):
alpha1 = (x-breaks[i])/(breaks[i+degree]-breaks[i]+1e-12)
alpha2 = (breaks[i+degree+1]-x)/(breaks[i+degree+1]-breaks[i+1]+1e-12)
coef = alpha1*prev_degree_coefs[i] + alpha2*prev_degree_coefs[i+1]
coefs.append(coef)
return coefs | a8b732ce519a608ea277aa1c1165be8d674e141b | 694,054 |
def circular_distance(a: int, b: int, C: int) -> int:
"""
Finds the shortest distance between two points along the perimeter of a circle.
arguments:
a: a point on a circle's circumference.
b: another point on the cicrle.
C: the total circumference of the circle.
return:
The shortest distance along the circumference of the circle between the two points
>>> circular_distance(2,5,10)
3
>>> circular_distance(12,3,15)
6
>>> # It even works with numbers >C or <0
... circular_distance(-20, 37, 10)
3
"""
arc = abs(a - b) % C # the distance between these in one direction -- not necessarily the shortest distance
return min(C - arc, arc) | 1b1a54dca54edc18ef4c44a9e54f883410fb7c8f | 694,056 |
def get_proxy_list_size(proxy_list):
""" Return the current Queue size holding a list of proxy ip:ports """
return proxy_list.qsize() | 982240d8225f7c79327c661c91d6741311c1dd4e | 694,058 |
def find_toolchain(ctx):
"""Finds the first rust toolchain that is configured.
Args:
ctx (ctx): The ctx object for the current target.
Returns:
rust_toolchain: A Rust toolchain context.
"""
return ctx.toolchains["@io_bazel_rules_rust//rust:toolchain"] | 2c003b40529dec403c17cf02d7bf97f0e1d427fa | 694,059 |
def apply_function(funct, value, iterations):
"""
Example of a function that takes another function as an argument
"""
for index in range(iterations):
value = funct(value)
return value | 65836cb9b76adeb43c6e92bdc72c15d49ebf4b01 | 694,061 |
import errno
def _is_error(self, exception, *errors):
""" Determine if an exception belongs to one of the given named errno module errors. """
errors = [ getattr(errno, error, None) for error in errors ]
return exception.errno in errors | c1aab4862b721f83986b70d96a9906089c44bf5b | 694,068 |
from uuid import uuid4
def create_tmp_name(base=None):
"""Create temporary name using uuid"""
return (base + '_' if base else '') + uuid4().hex[:10] | 041e5d889029be49c50b5597166b94e1234e2c9f | 694,069 |
def _split_dataset_id(dataset_id):
"""splits a dataset id into list of values."""
return dataset_id.split("|")[0].split(".") + [(dataset_id.split("|")[1])] | 9a1c3d23af502fd21db3de9485cfcdb75d84ba6d | 694,076 |
def validate_string(str_argument, str_argument_name):
""" Validates if the given argument is of type string and returns it"""
if not isinstance(str_argument, str):
raise ValueError(f"Illegal str argument: {str_argument_name}")
return str_argument | f1e9dbcbd539aab411c4e2c134259694a8dc597b | 694,084 |
import json
def is_json(string):
"""
Helper function to determine if a string is valid JSON
"""
try:
json_object = json.loads(string)
except ValueError as e:
return False
return True | b3c70037555a38bb1e64452ab42d2e174b3be893 | 694,089 |
def uint32_tag(name, value):
"""Create a DMAP tag with uint32 data."""
return name.encode('utf-8') + \
b'\x00\x00\x00\x04' + \
value.to_bytes(4, byteorder='big') | 2842aee121d1217e2829705135fbff655ea02ab7 | 694,090 |
def get_average_mos(solution, ignore_non_served=False):
"""Returns the average MOS of a solution.
"""
smos = 0
nserved = 0
for u in solution["users"]:
if "mos" in u:
smos += u["mos"]
nserved += 1
if ignore_non_served:
# only take into account users that get some video
return smos/nserved
else:
# calculate avg QoE across all users
return smos/len(solution["users"]) | e75a4e7be7012e4a12dfc127119f7c2b4fc1bbb0 | 694,096 |
def clamp(value, minimum, maximum):
"""
Return clamped value between minimum and maximum.
:param float value:
:param float minimum:
:param float maximum:
"""
if maximum < minimum:
raise ValueError(f"{maximum} is smaller than {minimum}")
return max(minimum, min(value, maximum)) | de32469ad3f7b9c772ccb870a9d16520bc59f481 | 694,098 |
import getpass
def password(what):
"""Prompt the user for a password and verify it.
If password and verify don't match the user is prompted again
Args:
what (string) : What password to enter
Returns:
(string) : Password
"""
while True:
pass_ = getpass.getpass("{} Password: ".format(what))
pass__ = getpass.getpass("Verify {} Password: ".format(what))
if pass_ == pass__:
return pass_
else:
print("Passwords didn't match, try again.") | bf2328d709490333cbc68c2620ee3d0dc087e6e2 | 694,103 |
def checkListAgainstDictKeys(theList, theDict):
"""
Given a list of items, remove any items not in specified dict
:param theList: list, list of items that may not be in theDict
:param theDict: dict, dictionary against which to check (the keys)
:return:
inlist, list, items from list found in dict keys
outlist, list, items from list NOT found in dict keys
"""
# The items to return
inList = list()
outList = list()
# extract the keys as a set
keySet = set(theDict.keys())
# Sift through the sample
for item in theList:
if item in keySet:
inList.append(item)
else:
outList.append(item)
# end if
# end loop
inList.sort()
outList.sort()
return inList, outList | 4274c48cc9e85d4632a3591e4ae1e4ecd7c236c8 | 694,104 |
def title(txt):
""" Provide nice title for parameterized testing."""
return str(txt).split('.')[-1].replace("'", '').replace('>', '') | 06104d59d4ef4770cba4e4951a4be7c1f425890c | 694,106 |
import collections
def convert_defaultdict_to_regular_dict(inputdict: dict):
"""
Recursively convert defaultdict to dict.
"""
if isinstance(inputdict, collections.defaultdict):
inputdict = {
key: convert_defaultdict_to_regular_dict(value)
for key, value in inputdict.items()
}
return inputdict | 17d56b3ae8db0fb91bdb086b953f405a35741b4f | 694,107 |
def get_mung_locs(anc, code, output_bucket):
""" Convenience function to obtain the expected locations for munged scripts.
Parameters
----------
anc : :obj:`str`
Ancestry prefix.
code : :obj:`str`
Phenotype code.
output_bucket : :obj:`str`
The bucket in which the mugning output is stored.
Returns
-------
:obj: `str` with file location, :obj:`str` with log location
"""
file_loc = output_bucket + anc + '/munged_sumstats/' + code + '.sumstats.gz'
log_loc = output_bucket + anc + '/munged_sumstats/' + code + '.log'
return file_loc, log_loc | b5b4d65040229797e37568ae57659aa575887bd4 | 694,110 |
def extend_empty_sets(empty: dict, grammar: dict) -> dict:
"""
Determine which nonterminals of an LL(1) grammar can be empty.
Must be applied repeatedly until converging.
:param empty: nonterminal -> bool
:param grammar: nonterminal -> [productions...]
:returns: Extended copy of ``empty``
"""
return {
symbol: empty.get(symbol) or any(
all(empty.get(p) for p in production)
for production in productions
)
for symbol, productions in grammar.items()
} | a91b18b217d3c8fee7ef86b0eba2d2bd92422ca5 | 694,111 |
import json
def json_read(path):
"""
Reads JSON file from the given path.
"""
with open(path, mode="r", encoding="utf-8") as file:
res = json.load(file)
return res | a3be51d57501a3d7833398b1763b024ba6a2f215 | 694,115 |
def cycle(counter, rule):
"""Returns True when a given forloop.counter is conforming to the
specified `rule`. The rules are given as strings using the syntax
"{step}/{scale}", for example:
* ``forloop.counter|cycle:"1/2"`` returns True for even values
* ``forloop.counter|cycle:"2/2"`` returns True for odd values
What's interesting about this filter is that it works also for more
complex steppings:
* ``forloop.counter|cycle:"1/3"`` returns True every third value
* ``forloop.counter|cycle:"2/3"`` returns True every third value but one
step after 1/3 would
* ``forloop.counter|cycle:"3/3"`` returns True every third value but two
steps after 1/3 would
"""
step, scale = (int(elem) for elem in rule.split("/"))
result = (counter - 1) % scale == step - 1
return result | 0f0da401539bd97c8441f395b2bbd1962facf7cb | 694,116 |
import hashlib
def get_hash(content):
"""Return the hex SHA-1 hash of the given content."""
return hashlib.sha1(content).hexdigest() | 8b202cdffe035d039651c18b780ae0c901a7b8f1 | 694,118 |
def model_auth_fixture() -> dict:
"""Function to generate an auth dictionary with identical keys to those
returned from a get model request.
Returns:
dict: Mock auth dictionary
"""
auth = {
"asset_id": "0a0a0a0a-0a00-0a00-a000-0a0a0000000a",
"reason": "reason for access",
"view": True,
"read": True,
"update": False,
"destroy": False
}
return auth | 56a05a135005b8d551a51f90f3bdef0bff672f72 | 694,121 |
def _get_secondary_status(row):
"""Get package secondary status."""
try:
return row.find('div', {'id': 'coltextR3'}).contents[1]
except (AttributeError, IndexError):
return None | faa2f280e978c574280e610453ceba6116931c41 | 694,126 |
def get_treetagger_triple(string):
"""
Split a single line from TreeTagger's output to obtain a
(word,pos,lemma) triple.
"""
elems = string.split('\t')
# Lines that don't contain exactly 2 tabs are ignored. These are
# usually lines containing a single <repdns> or <repurl> element
# which TreeTagger uses to indicate that it has replaced the token
# in the previous (token, pos, lemma) triple with a special symbol
# (e.g. dns-remplacé). The replaced text is in the "text"
# attribute of the repdns or repurl element.
if len(elems) == 3:
return elems
else:
return None | 292abdae3b7ac1b13ffb68e5bd86ac625b9c3c03 | 694,129 |
def _basename_of_variable(varname):
"""Get the base name of a variable, without the time index.
Given a variable "FooBar_10", the last component is the time index (if present),
so we want to strip the "_10". This does no error checking. You should not be
passing in a variable whose name starts with "Seq_"; this is for user-generated
names, not the internal names for DataTank.
"""
comps = varname.split("_")
# handle variables that aren't time-varying
if len(comps) == 1:
return varname
# this is kind of a heuristic; assume anything that is all digits is a time index
return "_".join(comps[:-1]) if comps[-1].isdigit() else varname | 29e36a160e6885ce4a1e6bbe9d0ebdd038574443 | 694,130 |
import time
def time_str(time_s: float) -> str:
"""Concert a timestamp to a String."""
return time.strftime("%c", time.localtime(time_s)) | f8f82cf32234b1468b4402d1f8c823448229c91a | 694,135 |
def merge_args_to_kwargs(argspec, args, kwargs):
"""
Based on the argspec, converts args to kwargs and merges them into kwargs
Note:
This returns a new dict instead of modifying the kwargs in place
Args:
argspec (FullArgSpec): output from `inspect.getfullargspec`
args (tuple): List of args
kwargs (dict): dict of names args
Returns:
dict: dict of original named are and args that were converted to named agrs
"""
fn_args_to_kwargs = {arg_name: arg_val for arg_name, arg_val in zip(argspec.args, args)}
# We create a copy of the dict to keep the original **kwarg dict pristine
fn_kwargs = kwargs.copy()
fn_args_to_kwargs.update(fn_kwargs)
default_arg_value = zip(reversed(argspec.args), reversed(argspec.defaults or ()))
# Apply defaults if values are missing
for arg_name, arg_val in default_arg_value:
if arg_name not in fn_args_to_kwargs:
fn_args_to_kwargs[arg_name] = arg_val
if argspec.varargs and len(args) > len(argspec.args):
# We were given more args than possible so they much be part of *args
fn_args_to_kwargs['*{}'.format(argspec.varargs)] = args[len(argspec.args)-len(args):]
return fn_args_to_kwargs | 09f82f7af0adbf640f173b65cc0c656638a1ac2b | 694,136 |
def valid_url_string() -> str:
"""Return string of a valid URL."""
return "https://example.com" | c6a50483346b41582d10047cad5f25cdd5e2f986 | 694,139 |
import logging
import functools
import time
def status(status_logger: logging.Logger):
"""
Decorator to issue logging statements and time function execution.
:param status_logger: name of logger to record status output
"""
def status_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
name = func.__name__
status_logger.info(f'Initiated: {name}')
start = time.time()
result = func(*args, **kwargs)
end = time.time()
status_logger.info(f'Completed: {name} -> {end - start:0.3g}s')
return result
return wrapper
return status_decorator | f6e0ce2391ae3450b0ef7fbc827789cd99889d89 | 694,144 |
import zipfile
def get_parts(fname):
"""Returns a list of the parts in an OPC package.
"""
with zipfile.ZipFile(fname) as zip_archive:
parts = [name for name in zip_archive.namelist()]
return sorted(parts) | 458bd85f94df5ab78804eb1df791e6ad54c266c5 | 694,145 |
import pathlib
def _relative_if_subdir(fn):
"""Internal: get a relative or absolute path as appropriate.
Parameters
----------
fn : path-like
A path to convert.
Returns
-------
fn : str
A relative path if the file is underneath the top-level project directory, or an
absolute path otherwise.
"""
fn = pathlib.Path(fn).resolve()
try:
return fn.relative_to(pathlib.Path.cwd())
except ValueError:
return fn | 9efbd0e3b4585315a6c87c0fb3a6cf1082948f11 | 694,146 |
import re
def normalize(string):
"""
This function normalizes a given string according to
the normalization rule
The normalization rule removes "/" indicating filler words,
removes "+" indicating repeated words,
removes all punctuation marks,
removes non-speech symbols,
and extracts orthographic transcriptions.
Arguments
---------
string : str
The string to be normalized
Returns
-------
str
The string normalized according to the rules
"""
# extracts orthographic transcription
string = re.sub(r"\(([^)]*)\)\/\(([^)]*)\)", r"\1", string)
# removes non-speech symbols
string = re.sub(r"n/|b/|o/|l/|u/", "", string)
# removes punctuation marks
string = re.sub(r"[+*/.?!,]", "", string)
# removes extra spaces
string = re.sub(r"\s+", " ", string)
string = string.strip()
return string | 14a62512248979b7ac7ef467b0f74a5201d7e418 | 694,147 |
def user_directory_path(instance, filename):
"""File will be uploaded to MEDIA_ROOT/user_<id>/<filename>"""
return 'user_{0}/{1}'.format(instance.user.id, filename) | 7c12b39184eb358bc7c895ef6c522a6591f7ff4d | 694,148 |
def key_for_value(d, looking):
"""Get the key associated with a value in a dictionary.
Only top-level keys are searched.
Args:
d: The dictionary.
looking: The value to look for.
Returns:
The associated key, or None if no key found.
"""
found = None
for key, value in d.items():
if looking == value:
found = key
break
return found | dd1f04f0232ec5a91556b1858a7481c481e85271 | 694,149 |
import math
def cosine(r_tokens: list, s_tokens: list) -> float:
"""Computes cosine similarity.
COS(r, s) = |r ∩ s| / sqrt(|r| * |s|)
Parameters
----------
r_tokens : list
First token list.
s_tokens : list
Second token list.
Returns
-------
Cosine similarity of r and s.
"""
return len(set(r_tokens).intersection(s_tokens)) / math.sqrt(len(r_tokens) * len(s_tokens)) | 234b7298e8c0c29cbb3d79d420e63518decfe4e9 | 694,152 |
def _dir(m, skip=()):
"""
Get a list of attributes of an object, excluding
the ones starting with underscore
:param m: object, an object to get attributes from
:return: list, a list of attributes as strings
"""
return [a for a in dir(m) if not a.startswith('_') and a not in skip] | 2903d4f91031fa8b7a0fbb81679d879a16af37be | 694,153 |
def networkType(host):
"""Determine if a host is IPv4, IPv6 or an onion address"""
if host.find('.onion') > -1:
return 'onion'
elif host.find(':') == -1:
return 'IPv4'
return 'IPv6' | a0d3e92764cc562c43e643cd596762bce8ccfd58 | 694,156 |
def generate_identifier(order):
"""Return a unique identifier by concatenating a lowercased stripped
version of firstname and lastname of the ninja"""
# get first and last names and convert to lowercase
first_name = order.get('Voornaam').lower()
last_name = order.get('Achternaam').lower()
#return as concatenated string with spaces stripped out
return (first_name + last_name).translate(None, ' ') | 219742da3cd749acd5ccd4fa75a92d673c4e194e | 694,158 |
import logging
def validate_input(key, value):
""" Validate a user input
This function ensures that the user enters a valid input
(could be username or filename). Here, the inputs are valid
if they are non-empty. The function then returns the appropriate
status code and message.
Args:
key (str): name of input to validate (e.g. username, filename)
value (str): value of input to validate (e.g. user1, file.png)
Returns:
status (dict): status message and status code
"""
if len(value) == 0:
status = {"code": 400,
"msg": "Field " + key + " cannot be empty."}
logging.warning("Field " + key + " cannot be empty.")
else:
status = {"code": 200,
"msg": "Request was successful"}
return status | f678018e8cf7de6b6a7f6c17728a2e6b470ed0cb | 694,160 |
def dict_append_to_value_lists(dict_appendee, dict_new):
"""
Appends values from dict_new to list of values with same key in dict_appendee
Args:
dict_appendee: dict with value lists (as created by dict_values_to_lists function
dict_new: dict with new values that need to be appended to dict_appendee
Returns:
dict with appended values
"""
if dict_new is None:
return None
for key in dict_new.keys():
if type(dict_appendee[key]) != list:
raise TypeError("Dict value is not a list")
dict_appendee[key] += [dict_new[key]]
return dict_appendee | 3f39a6bca91c3429a04f0047673f6231d29336eb | 694,168 |
def super_digit(n: int) -> int:
"""Return the result of summing of a number's digits until 1 digit remains."""
ds = n % 9
if ds:
return ds
return 9 | 842e644b2a2916ca75f861e2177b2db52ef313db | 694,170 |
def load_from_lsf(script_file_name):
"""
Loads the provided scritp as a string and strips out all comments.
Parameters
----------
:param script_file_name: string specifying a file name.
"""
with open(script_file_name, 'r') as text_file:
lines = [line.strip().split(sep = '#', maxsplit = 1)[0] for line in text_file.readlines()]
script = ''.join(lines)
if not script:
raise UserWarning('empty script.')
return script | ed91b1a4b21f30e3229b71edaab71a6c7ddc33af | 694,172 |
def has_activity(destination, activity_name):
"""Test if a given activity is available at the passed destination/event/tour."""
return destination.has_activity(activity_name) if destination else False | 01fde72d29bd59deeedc18a3ab1322eb85e58fb3 | 694,173 |
def calculate_coordinates(pth):
"""
Create a set of tuples representing the coordinates that the path
traverses, with a starting point at (0,0)
"""
x = 0
y = 0
coords = set()
for instruction in pth:
direction = instruction[:1]
distance = int(instruction[1:].strip())
if direction.lower() == "d":
for _ in range(distance):
y -= 1
coords.add((x, y))
elif direction.lower() == "u":
for _ in range(distance):
y += 1
coords.add((x, y))
elif direction.lower() == "l":
for _ in range(distance):
x -= 1
coords.add((x, y))
elif direction.lower() == "r":
for _ in range(distance):
x += 1
coords.add((x, y))
else:
raise Exception(f"Unknown direction {direction}")
return coords | 0bba7e13ec8480104f6a96f7caae7f2bd73d3e2d | 694,174 |
def calculate_interval(pi, chrm, pos):
"""
Determines how a position is mapped to an interval number using pi.
Arguments:
pi (dict of lists of ints): the pi map
chrm (int): chromosome number
pos (int): SNP location
Returns:
The interval associated with pos on chrm if the mapping is successful, otherwise None
"""
try:
chrmArray = pi[chrm]
for start, end, ind in chrmArray:
if start <= pos and pos <= end:
return ind
#position was not found in intervals
return None
except KeyError:
#chromosome was not found in pi
return None | 21410b17b8b125a60065b637ea182e92b98d3591 | 694,176 |
def map_to_fasttext_language(lang):
"""
Map 'zh-x-oversimplified' to 'zh' for language identification.
"""
mapping = {
'zh-x-oversimplified': 'zh'
}
return mapping.get(lang, lang) | 48890f698f42c7107b73cae46c0171e7170ff4a8 | 694,181 |
def print_args(args):
"""Convenience function for printing the current value of the input
arguments to the command line.
----------------------------------------------------------------------------
Args:
args: argparse object returned by ArgumentParser.parse_args()
Returns:
None
"""
print("Current input flags...")
for arg in vars(args):
print("\t%s : %s" % (arg, getattr(args, arg)))
return None | 18548ce7ad9f8683cbebf7bbda5198c97ea5dfd9 | 694,184 |
def datetime_pyxll_function_3(x):
"""returns a string description of the datetime"""
return "type=%s, datetime=%s" % (type(x), x) | e9810a137aa1a79d925059a5168d46e0adf0b0ee | 694,193 |
import torch
def get_maxprob_metric(log_probs):
"""
Computes the average max probability
"""
max_lp = log_probs.max(axis = -1).values
return torch.exp(max_lp).mean() | 83eb87ea1b85a25212dc391d2c55a1d4db285a52 | 694,199 |
def make_face_rects(rect):
""" Given a rectangle (covering a face), return two rectangles.
which cover the forehead and the area under the eyes """
x, y, w, h = rect
rect1_x = x + w / 4.0
rect1_w = w / 2.0
rect1_y = y + 0.05 * h
rect1_h = h * 0.9 * 0.2
rect2_x = rect1_x
rect2_w = rect1_w
rect2_y = y + 0.05 * h + (h * 0.9 * 0.55)
rect2_h = h * 0.9 * 0.45
return (
(int(rect1_x), int(rect1_y), int(rect1_w), int(rect1_h)),
(int(rect2_x), int(rect2_y), int(rect2_w), int(rect2_h))
) | 832706e74fd9d008b68687f1cd5f5d6ee9c01cf6 | 694,202 |
import glob
def read_all_file_names(directory, extension):
"""Read all files with specified extension from given path and sorts them
based on a given sorting key.
Parameters
----------
directory: str
parent directory to be searched for files of the specified type
extension: str
file extension, i.e. ".edf" or ".txt"
Returns
-------
file_paths: list(str)
a list to all files found in (sub)directories of path
"""
assert extension.startswith(".")
file_paths = glob.glob(directory + "**/*" + extension, recursive=True)
assert len(file_paths) > 0, (
f"something went wrong. Found no {extension} files in {directory}")
return file_paths | 30217a765768d4d225ae3591037f75ffeeb8c042 | 694,210 |
def inclusion_two_params_from_template(one, two):
"""Expected inclusion_two_params_from_template __doc__"""
return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)} | 4a81da93f96356b1e1eb370755bf7627b0cf434a | 694,211 |
import struct
def parse(data):
"""
SMP code is the first octet of the PDU
0 1 2 3 4 5 6 7
-----------------
| code |
-----------------
References can be found here:
* https://www.bluetooth.org/en-us/specification/adopted-specifications - Core specification 4.1
** [vol 3] Part H (Section 3.3) - Command Format
Return a tuple (code, data)
"""
code = struct.unpack("<B", data[:1])[0]
return (code, data[1:]) | 9d1d97f76213e4cabcc43f13d980cd658fcfae41 | 694,220 |
def wait_for_queue(handle):
"""
Read from ``sbatch`` output whether the queue is full.
:param object handle: sbatch handle
:return: ``True`` if queue is full, else ``False``
:rtype: :py:obj:`bool`
"""
for f in (handle.stdout, handle.stderr):
for line in f:
if ("maximum number of jobs" in line or
# A rare SLURM error, but may cause chaos in the
# information/accounting system
"unable to accept job" in line):
return True
return False | 0a1978354367be99f3fe969df81ae014ab7b2439 | 694,221 |
def object_copy(self, CopySource, ExtraArgs=None, Callback=None,
SourceClient=None, Config=None):
"""Copy an object from one S3 location to this object.
This is a managed transfer which will perform a multipart copy in
multiple threads if necessary.
Usage::
import ibm_boto3
s3 = ibm_boto3.resource('s3')
copy_source = {
'Bucket': 'mybucket',
'Key': 'mykey'
}
bucket = s3.Bucket('otherbucket')
obj = bucket.Object('otherkey')
obj.copy(copy_source)
:type CopySource: dict
:param CopySource: The name of the source bucket, key name of the
source object, and optional version ID of the source object. The
dictionary format is:
``{'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}``. Note
that the ``VersionId`` key is optional and may be omitted.
:type ExtraArgs: dict
:param ExtraArgs: Extra arguments that may be passed to the
client operation
:type Callback: function
:param Callback: A method which takes a number of bytes transferred to
be periodically called during the copy.
:type SourceClient: ibm_botocore or ibm_boto3 Client
:param SourceClient: The client to be used for operation that
may happen at the source object. For example, this client is
used for the head_object that determines the size of the copy.
If no client is provided, the current client is used as the client
for the source object.
:type Config: ibm_boto3.s3.transfer.TransferConfig
:param Config: The transfer configuration to be used when performing the
copy.
"""
return self.meta.client.copy(
CopySource=CopySource, Bucket=self.bucket_name, Key=self.key,
ExtraArgs=ExtraArgs, Callback=Callback, SourceClient=SourceClient,
Config=Config) | 378d7143bf8649e187cba43a07df7b41df9b43c3 | 694,224 |
import re
def getMessageError(response):
"""
Extracts the error message from an ERDDAP error output.
"""
emessageSearch = re.search(r'message="(.*)"', response)
if emessageSearch:
return emessageSearch.group(1)
else:
return "" | 020a597e8b3a93a190536dd83b7dfe12d651ed07 | 694,226 |
def _from_proc_output(output: bytes) -> str:
"""
Convert proc output from bytes to str, and trim heading-
and tailing-spaces
:param output: output in bytes
:return: output in str
"""
return str(output, encoding='utf-8').strip(' \t\n') | 67013919c2f8020f5794766f7bc034e80d09eb20 | 694,227 |
from functools import reduce
def get_deep_dict_value(source: dict, keys: str, default = None):
"""
Get values from deeply nested dicts.
:source (dict): Dictionary to get data from.
:keys (str): Keys split by '|'. E.g. outerkey|middlekey|innerkey.
:default: Default return value.
"""
value = reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("|"), source)
return value | 40de0e150c04589040ebc3b70ae5e8e63b68901d | 694,228 |
def calculate_step_or_functional_element_assignment(child_assignments: list, sufficient_scheme=False):
"""
Assigns a step result or functional element result based of the assignments of its children. In the case of steps,
this would be functional element assignments. In the case of functional elements this would be evidences.
For assignments from child genome properties YES or PARTIAL is considered YES.
See: https://github.com/ebi-pf-team/genome-properties/blob/
a76a5c0284f6c38cb8f43676618cf74f64634d33/code/modules/GenomeProperties.pm#L686
if($evObj->gp){
if(defined($self->get_defs->{ $evObj->gp })){
# For properties a PARTIAL or YES result is considered success
if( $self->get_defs->{ $evObj->gp }->result eq 'YES' or
$self->get_defs->{ $evObj->gp }->result eq 'PARTIAL' ){
$succeed++;
}elsif($self->get_defs->{ $evObj->gp }->result eq 'UNTESTED'){
$step->evaluated(0);
:param sufficient_scheme: If false, any child NOs mean NO. If true, any child YES/PARTIAL means YES
:param child_assignments: A list containing strings of YES, NO or PARTIAL
:return: The assignment as either YES or NO.
"""
no_count = child_assignments.count('NO')
# Given a list of sufficient evidences, any could be PARTIAL or YES and the result would be YES.
if sufficient_scheme:
if no_count < len(child_assignments):
result = 'YES'
else:
result = 'NO'
# Given a list of non-sufficient evidences, all evidences have to be YES or PARTIAL or the result would be NO.
else:
if no_count == 0:
result = 'YES'
else:
result = 'NO'
return result | 9dfa5cbf0c10bd5ed848fd5f1ca6e09dcc64a8c9 | 694,230 |
def _generate_join(collection, local_id, foreign_id):
"""Make join string for query from parameters."""
text = '{{!join from={fid} to={lid} fromIndex={collection}}}'
text = text.format(
collection=collection,
lid=local_id,
fid=foreign_id)
return text | 1e831fadda22866b098b1c0e1673e73d9370dd75 | 694,231 |
def get_tomorrow(utc_now, tz, to_local=False):
"""Return an :class:`~arrow.arrow.Arrow` datetime for *tomorrow 00:00 local
time*.
The calculation is done relative to the UTC datetime *utc_start* converted
to the timezone *tz*.
By default, the result is converted back to UTC. Set *to_local* to
``True`` to get a local date in timezone *tz*.
Since *utc_start* is converted to *tz* first, this function takes care of
local daylight saving time changes.
**Example:** *utc_now* is *2015-01-15 13:37:00+00:00* in UTC. If *tz* is
*Europe/Berlin*, the date corresponds to *2015-01-15 14:37:00+01:00* in
local time. The returned date will be *2015-01-16 00:00:00+01:00* if
*to_local* is ``True`` or *2015-01-15 23:00:00+00:00* else.
"""
today = utc_now.to(tz)
today = today.replace(hour=0, minute=0, second=0, microsecond=0)
tomorrow = today.replace(days=1)
out_tz = tz if to_local else 'utc'
return tomorrow.to(out_tz) | c447f52fa770f81f0da6bcbaa13fbebc8a398d67 | 694,232 |
def extract_pem_cert(tree):
"""
Extract a given X509 certificate inside an XML tree and return the standard
form of a PEM-encoded certificate.
:param tree lxml.etree: The tree that contains the X509 element. This is
usually the KeyInfo element from the XMLDsig Signature
part of the message.
"""
cert = tree.find('.//{http://www.w3.org/2000/09/xmldsig#}X509Certificate').text
return "-----BEGIN CERTIFICATE-----\n" + cert + "-----END CERTIFICATE-----\n" | 6737fd4002f9de25142291be2cd19c265465340a | 694,235 |
import re
def parseVtxIdx(idxList):
"""convert vertex index list from strings to indexes.
idxList : [u'vtx[1]', u'vtx[3]', u'vtx[6]', u'vtx[8]', u'vtx[12:13]']
return : [1,3,6,8,12,13]
"""
parseIdxList = []
for idxName in idxList:
match = re.search(r'\[.+\]', idxName)
if match:
content = match.group()[1:-1]
if ':' in content:
tokens = content.split(':')
startTok = int(tokens[0])
endTok = int(tokens[1])
for rangeIdx in range(startTok, endTok + 1):
parseIdxList.append(rangeIdx)
else:
parseIdxList.append(int(content))
return parseIdxList | 32c3a40ac374865cf61d44e9834a50801c9f236d | 694,239 |
def _transpose(group):
"""
Given a list of 3-tuples from _grouper, return 3 lists.
Also filter out possible None values from _grouper
"""
a, b, c = [], [], []
for g in group:
# g can be None
if g is not None:
x, y, z = g
#if x is not None and y is not None and z is not None:
a.append(x)
b.append(y)
c.append(z)
return a, b, c | 2027c7ee84340d6758fe352058b8b8cd962e4d96 | 694,240 |
def _is_member(s, e):
"""Return true if `e` is in the set `s`.
Args:
s: The set to inspect.
e: The element to search for.
Result:
Bool, true if `e` is in `s`, false otherwise.
"""
return e in s._set_items | 810336bb16babcca3af8bc9c931da3d058b6f14f | 694,242 |
def read(f):
"""Read a file an return its content in utf-8"""
return open(f, 'rb').read().decode('utf-8') | 5d43d64392e8c8ed33cb2dfe3d64d780c6217321 | 694,244 |
def get_file_type(filename):
"""
Return the extension (if any) of the ``filename`` in lower case.
"""
return filename[filename.rfind('.')+1:].lower() | cb0487e0886d60a6d0e5f97fa7d2313293390f5d | 694,245 |
def buildParameters(obj, validList):
"""
>>> class TestClass(object):
... pass
>>> testClass = TestClass()
>>> testClass.a = 1
>>> testClass.b = "2"
>>> testClass.c = 3
>>> testClass.d = True
>>> buildParameters(testClass, ["a", "b"])
['--a', u'1', '--b', u'2']
>>> testClass.b = None
>>> buildParameters(testClass, ["a", "b"])
['--a', u'1']
The following shows support for boolean flags that don't have a value
associated with them:
>>> buildParameters(testClass, ["a", "d"])
['--a', u'1', '--d']
"""
params = []
for param in validList:
attr = getattr(obj, param)
if attr:
param = param.replace("_", "-")
if isinstance(attr, bool):
attr = ""
params.extend(["--%s" % param, str(attr)])
return [x for x in params if x] | 9504d950b3b5827e95543afdf5615a06f3fe3532 | 694,249 |
import socket
import struct
def send_tcp(data,host,port):
"""
Helper function to send/receive DNS TCP request
(in/out packets will have prepended TCP length header)
"""
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((host,port))
sock.sendall(data)
response = sock.recv(8192)
length = struct.unpack("!H",bytes(response[:2]))[0]
while len(response) - 2 < length:
response += sock.recv(8192)
sock.close()
return response | 51d58d7ba31af919466acde7ea19780031c70158 | 694,256 |
def arity(argspec):
""" Determinal positional arity of argspec."""
args = argspec.args if argspec.args else []
defaults = argspec.defaults if argspec.defaults else []
return len(args) - len(defaults) | f19407943f92a2a4faa4735abf678467861153e7 | 694,257 |
def fw(model, input, model_pretrain_method):
"""Call and index forward according to model type."""
output = model(input)
if model_pretrain_method == "torchvision":
return output
elif model_pretrain_method == "Swav":
return output[1]
else:
return output[0] | 6367ab0cdfb4ad1dd2e85fee5e357148ee5f5d71 | 694,259 |
import torch
def postprocess(images):
"""change the range from [-1, 1] to [0., 1.]"""
images = torch.clamp((images + 1.) / 2., 0., 1.)
return images | 37421278b26cd0913905db61379f4b979d1d2a98 | 694,260 |
def dec2sex(rain,decin,as_string=False,decimal_places=2):
"""
Converts decimal coordinates to sexagesimal.
Parameters
----------
rain : float
Input Right Ascension in decimal -- e.g., 12.34567
decin : float
input Declination in decimal -- e.g. -34.56789
as_string : bool
Specifies whether to return output as a string (useful for making tables)
decimal_places : int
Number of decimals places to use when as_string=True
Returns
-------
list
['HH:MM:SS.ss', 'DD:MM:SS.ss']
"""
rmins,rsec=divmod(24./360*rain*3600,60)
rh,rmins=divmod(rmins,60)
#dmins,dsec=divmod(decin*3600,60)
#ddeg,dmins=divmod(dmins,60)
ddeg=int(decin)
dmins=int(abs(decin-ddeg)*60)
dsec=(abs((decin-ddeg)*60)-dmins)*60
if as_string==True: return ['{0}:{1}:{2:0>{4}.{3}f}'.format(int(rh),int(rmins),rsec,decimal_places,decimal_places+3),'{0}:{1}:{2:0>{4}.{3}f}'.format(int(ddeg),int(dmins),dsec,decimal_places,decimal_places+3)]
else: return [int(rh),int(rmins),rsec],[int(ddeg),int(dmins),dsec] | 1404996c46db480183a8cb46a11986bf6c9e7531 | 694,264 |
import base64
def encode_info_basic_http_auth(username, password):
"""
Encodes the username and password to be sent in the `Authenticate`
header in http using basic authentication.
:param username: username
:param password: password
:return: encoded value for the http 'Authenticate' header
"""
user_pass = '{}:{}'.format(username, password)
user_pass = base64.b64encode(user_pass.encode('ascii')).decode('ascii')
return 'Basic {}'.format(user_pass) | 9721f745cd6b38aa9c3b1c98c3eaa19c64949709 | 694,265 |
def is_new_style(cls):
"""
Python 2.7 has both new-style and old-style classes. Old-style classes can
be pesky in some circumstances, such as when using inheritance. Use this
function to test for whether a class is new-style. (Python 3 only has
new-style classes.)
"""
return hasattr(cls, '__class__') and ('__dict__' in dir(cls)
or hasattr(cls, '__slots__')) | a303d87a5ef790d629dff6fcd07c46d029277530 | 694,267 |
def path2FileName(path):
"""Answer the file name part of the path.
>>> path2FileName('../../aFile.pdf')
'aFile.pdf'
>>> path2FileName('../../') is None # No file name
True
"""
return path.split('/')[-1] or None | 7c7d954ae2cf436624fa6e95edac887facf27dd4 | 694,271 |
def file_search(f_name, data_str):
"""Function: file_search
Description: Search for a string in a file and return the line it was
found in a line.
NOTE: Returns only the first instance found in the file.
Arguments:
(input) f_name -> File name searching.
(input) data_str -> Search string.
(output) line - > Full line string was found in or None, if not found.
"""
line = None
with open(f_name, "r") as s_file:
for item in s_file:
if data_str in item:
line = item
break
return line | 0d5b0514165674b390c3225c48f3c3e8810b4006 | 694,275 |
def build_abstract(*args):
"""Combines multiple messages into a single abstract over multiple lines.
>>> build_abstract("test1", "test2")
'test1\\ntest2'
"""
return "\n".join([_arg for _arg in args if _arg]) | 8cc7732e8cfc052e294320f6e96185e53f73b59b | 694,276 |
import plistlib
def load_datafile(filename):
"""Load a data file and return the contents as a dictionary """
with open(filename, 'rb') as f:
data = plistlib.load(f)
return data | f57a4a38afb0d5ae9d21b712ceb28143ba695c27 | 694,277 |
import hashlib
def rgb_from_string(text, min_brightness=0.6):
""" Creates a rgb color from a given string """
ohash = hashlib.md5(text[::-1].encode("ascii")).hexdigest()
r, g, b = int(ohash[0:2], 16), int(ohash[2:4], 16), int(ohash[4:6], 16)
neg_inf = 1.0 - min_brightness
return (min_brightness + r / 255.0 * neg_inf,
min_brightness + g / 255.0 * neg_inf,
min_brightness + b / 255.0 * neg_inf) | feac9c8664dd96610fd9bbada578eb4d10ebfd0b | 694,279 |
def validate_key(key, keyname='Key'):
"""
Check input is valid key (Experiment id, metric name...)
"""
if not isinstance(key, str):
msg = '{} must be str, given: {}{}'
raise ValueError(msg.format(keyname, key, type(key)))
if ':' in key:
msg = '{} cannot contain colon (:): {}'
raise ValueError(msg.format(keyname, key))
return key | bd2bdc070ae0e511cbf3bf1e4cac6e851cdd683e | 694,280 |
def mask_topk(x, topkk):
"""
Returns indices of `topk` entries of `x` in decreasing order
Args:
x: [N, ]
topk (int)
Returns:
array of shape [topk, ]
"""
mask = x.argsort()[-topkk:][::-1]
return mask | 9d8df1efb3152db935368c0155ddd00984030bc4 | 694,283 |
def get_col_info(datadf, colname, colsource = 'source', map='all'):
"""Search a data dictionary dataframe fror a column
return close matches
Parameters
----------
datadf : dataframe,
the dataframe that has dictionary columns.
colname : str
the column name to search for.
colsource : str, optional
the column to search [source, or sourcep_]. The default is 'source'.
map : str, optional
filter on map column ['program', 'all']. The default is 'all'.
Returns
-------
ret : DataFrame
dictionary rows for columns that are close matches to the provided text.
"""
#get info about a column
ret= datadf[datadf[colsource].str.contains(colname, flags=2).fillna(False)]
if map=='program':
ret = ret[ret['map'] == 'program']
return ret | 3b87d1705e627b6f16e129ec3a911027f17c1212 | 694,284 |
def get_consensus(out_fn, trim_margin):
""" Extract consensus sequence from output of spoa.
Parameters
----------
out_fn : str (output from spoa)
trim_margin : int (number of bp to trim on each end of the consensus, as the consensus sequence
is more likely to be erroneous on the ends)
Returns
-------
consensus : str (consensus sequence)
"""
fh = open(out_fn, 'rb')
lines = fh.readlines()
if len(lines) == 0:
return ''
consensus = lines[-1][:-1]
consensus = consensus[trim_margin:len(consensus) - trim_margin]
fh.close()
return consensus | 833289b301d553c5f35a799fd70418d4a63889c6 | 694,285 |
def normalize_string(string):
"""
Standardize input strings by making
non-ascii spaces be ascii, and by converting
treebank-style brackets/parenthesis be characters
once more.
Arguments:
----------
string : str, characters to be standardized.
Returns:
--------
str : standardized
"""
return string.replace("\xa0", " ")\
.replace("\\", "")\
.replace("-LRB-", "(")\
.replace("-RRB-", ")")\
.replace("-LCB-", "{")\
.replace("-RCB-", "}")\
.replace("-LSB-", "[")\
.replace("-RSB-", "]") | 5e0f7850116fe2d7275674f3ff6a938689ac3c3e | 694,287 |
def stairs(N):
"""
Produces stairs array of size N
"""
stairs = []
for i in range(0,N):
# step = ''.join([str(N)]*(i+1)) + ''.join([' ']*(N-i-1))
step = '#'*(i+1) + ' '*(N-i-1)
stairs.append(step)
return stairs | 59b00a6d38d92410e9566846a1f8343f597f2400 | 694,288 |
def clip_box(box, max_width, max_height):
"""clipping a [x,y,w,h] boxes."""
x, y, w, h = box
if x + w > max_width:
w = max_width - x
w = 0.0 if w < 0 else w
if y + h > max_height:
h = max_height - y
h = 0.0 if h < 0 else h
if x > max_width:
x = max_width
if y > max_height:
y = max_height
return [x, y, w, h] | 0468b1827b74c1878d64f8ce0ea921f7bbbd7271 | 694,290 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.