content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main(argv):
""" Runs evaluation on trained network
"""
# Set parameters for evaluation
threshold = 0.4
batch_size = 10
eval_itr = 1
output_dir = argv[0]# directory where the model is saved
data_path = argv[1]
gpu_device_name = argv[-1]
# Load generator
with o... | 38,800 |
def parse_args(input_args):
"""
Parse the supplied command-line arguments and return the input file glob
and metric spec strings.
:param input_args: Command line arguments.
:return: A triplet, the first element of which is the input file glob,
the second element is the output file name... | 38,801 |
def create_api_group(**kwargs):
"""Create user group required for processing of security in API"""
Group.objects.get_or_create(name=API_GROUP_NAME) | 38,802 |
def _diffuse(field: jnp.ndarray, diffusion_coeff: float, delta_t: float) -> jnp.ndarray:
"""
Average each value in a vector field closer to its neighbors to simulate
diffusion and viscosity.
Parameters
----------
field
The vector field to diffuse. *Shape: [y, x, any].*
diffusion_coe... | 38,803 |
def test_difference_in_time():
"""Test that the differnce in time to our cutrrent time in an integre, and that
the difference between now and the current time is 0"""
now = difference_in_time(current_time())
assert isinstance(now, int)
assert now == 0 | 38,804 |
def dAdzmm_ron_s0(u0, M, n2, lamda, tsh, dt, hf, w_tiled):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
print(u0.real.flags)
print(u0.imag.flags)
M3 = uabs(np.ascontiguousarray(u0.real), np.ascontiguousarray(u0.imag))
temp = fftshift(ifft(f... | 38,805 |
def create_support_bag_of_embeddings_reader(reference_data, **options):
"""
A reader that creates sequence representations of the input reading instance, and then
models each question and candidate as the sum of the embeddings of their tokens.
:param reference_data: the reference training set that deter... | 38,806 |
def test_unique_keplerids():
"""Ensure we don't include the same file twice."""
total_count = query_one("SELECT COUNT(*) FROM tpf;")
filename_count = query_one("SELECT COUNT(DISTINCT filename) FROM tpf;")
assert total_count == filename_count | 38,807 |
def get_hosts_cpu_frequency(ceilo, hosts):
"""Get cpu frequency for each host in hosts.
:param ceilo: A Ceilometer client.
:type ceilo: *
:param hosts: A set of hosts
:type hosts: list(str)
:return: A dictionary of (host, cpu_frequency)
:rtype: dict(str: *)
"""
hosts_cpu_total ... | 38,808 |
def set_int(api, key, value):
"""Set an integer global value on a `btn.API`."""
if value is None:
api.delete_global(key)
else:
api.set_global(key, str(value)) | 38,809 |
def test_otsu_thresholding_3():
"""
Test Otsu thresholding with invalid int
"""
manager = ThresholdingManager("otsu")
with pytest.raises(TypeError):
manager.otsuThresholding(100) | 38,810 |
def _cloture(exc):
"""
Return a function which will accept any arguments
but raise the exception when called.
Parameters
------------
exc : Exception
Will be raised later
Returns
-------------
failed : function
When called will raise `exc`
"""
# scoping will sav... | 38,811 |
def _with_environment_variables(cmd: str, environment_variables: Dict[str, object]):
"""Prepend environment variables to a shell command.
Args:
cmd (str): The base command.
environment_variables (Dict[str, object]): The set of environment
variables. If an environment variable value ... | 38,812 |
def update_spam_assets(db: 'DBHandler') -> int:
"""
Update the list of ignored assets using query_token_spam_list and avoiding
the addition of duplicates. It returns the amount of assets that were added
to the ignore list
"""
spam_tokens = query_token_spam_list(db)
# order maters here. Make ... | 38,813 |
def _load_idx(filename):
"""Loads a single IDX file."""
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, "data", filename)
with gzip.open(filename, "rb") as f:
return idx.read_array(f) | 38,814 |
def png_info(path):
"""Returns a dict with info about the png"""
import png
r = png.Reader(filename=path)
x, y, frames, info = r.read()
return info | 38,815 |
def setup_config(config_file=None, custom_config_file=None, **kwargs):
"""Helper function to setup config at startup"""
if config_file:
config = get_config()
config.add_config_path(config_file)
backend.__global_config__ = update(backend.__global_config__, vars(config)["_sections"])
i... | 38,816 |
def _(data: ndarray, outliers: ndarray, show_report: bool = True) -> ndarray:
"""Process ndarrays"""
if type(data) != type(outliers):
raise TypeError("`data` and `outliers` must be same type")
# convert to DataFrame or Series
data = DataFrame(data).squeeze()
outliers = DataFrame(outliers).sq... | 38,817 |
def tag_whiteout_codebase_resources(project):
"""
Mark overlayfs/AUFS whiteout special files CodebaseResource as "ignored-whiteout".
See https://github.com/opencontainers/image-spec/blob/master/layer.md#whiteouts
for details.
"""
whiteout_prefix = ".wh."
qs = project.codebaseresources.no_sta... | 38,818 |
def bool_from_string(subject, strict=False, default=False):
"""
将字符串转换为bool值
:param subject: 待转换对象
:type subject: str
:param strict: 是否只转换指定列表中的值
:type strict: bool
:param default: 转换失败时的默认返回值
:type default: bool
:returns: 转换结果
:rtype: bool
"""
TRUE_STRINGS = ('1', 't', ... | 38,819 |
def prot_to_vector(seq: str) -> np.ndarray:
"""Concatenate the amino acid features for each position of the sequence.
Args:
seq: A string representing an amino acid sequence.
Returns:
A numpy array of features, shape (len(seq), features)"""
# convert to uppercase
seq = seq.upper()
... | 38,820 |
def project_root(project):
"""Return the path the root dir of the vendored project.
If "project" is an empty string then the path prefix for vendored
projects (e.g. "ptvsd/_vendored/") will be returned.
"""
if not project:
project = ''
return os.path.join(VENDORED_ROOT, project) | 38,821 |
def test_Normal():
"""Tests Normal distribution"""
# Create the distribution
dist = pfd.Normal()
# Check default params
assert dist.loc == 0
assert dist.scale == 1
# Call should return backend obj
assert isinstance(dist(), tfd.Normal)
# Test methods
npdf = lambda x, m, s: (1.... | 38,822 |
def set_partition(num, par):
"""
A function returns question for partitions of a generated set.
:param num: number of questions.
:param par: type of items in the set based on documentation.
:return: questions in JSON format.
"""
output = question_list_maker(num, par, 'set-par... | 38,823 |
def meanS_heteroscedastic_metric(nout):
"""This function computes the mean log of the variance (log S) for the heteroscedastic model. The mean log is computed over the standard deviation prediction and the mean prediction is not taken into account.
Parameters
----------
nout : int
Number of out... | 38,824 |
def ec2_connect(module):
""" Return an ec2 connection"""
region, ec2_url, boto_params = get_aws_connection_info(module)
# If we have a region specified, connect to its endpoint.
if region:
try:
ec2 = connect_to_aws(boto.ec2, region, **boto_params)
except (boto.exception.No... | 38,825 |
def read_lris(raw_file, det=None, TRIM=False):
"""
Read a raw LRIS data frame (one or more detectors)
Packed in a multi-extension HDU
Based on readmhdufits.pro
Parameters
----------
raw_file : str
Filename
det : int, optional
Detector number; Default = both
TRIM : bool, ... | 38,826 |
def add_index_col(data):
"""Adds index column
Args:
data (dataframe): WMT dataset with BLANC score
Returns:
data (dataframe): WMT dataset with index column
""" | 38,827 |
def test_list_unsigned_int_max_length_nistxml_sv_iv_list_unsigned_int_max_length_1_3(mode, save_output, output_format):
"""
Type list/unsignedInt is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/unsignedInt/Schema+Instance/NISTSchema-SV-IV-list-unsignedIn... | 38,828 |
def mu(n: int) -> int:
"""Return the value of the Moebius function on n.
Examples:
>>> mu(3*5*2)
-1
>>> mu(3*5*2*17)
1
>>> mu(3*3*5*2)
0
>>> mu(1)
1
>>> mu(5)
-1
>>> mu(2**10-1)
-1
"""
if n == 1:
re... | 38,829 |
async def test_form_auth_exception(hass):
"""Test we handle auth exception."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.rituals_perfume_genie.config_flow.Account.authenticate",
... | 38,830 |
def test_cartesian_dc_dd(sample_data, colv, args):
"""create a dask cartesian df. If gpus,
output should be a dask_cudf df, else dask df"""
if bool(args.gpus) and not args.has_gpu:
with pytest.raises(ImportError):
import cudf
return
dc_ddf = dq.transform.scatter_and_gpu(sampl... | 38,831 |
def find_last(arr, val, mask=None, compare="eq"):
"""
Returns the index of the last occurrence of *val* in *arr*.
Or the last occurrence of *arr* *compare* *val*, if *compare* is not eq
Otherwise, returns -1.
Parameters
----------
arr : device array
val : scalar
mask : mask of the a... | 38,832 |
def find_orphans(input_fits, header_ihdus_keys):
"""Return a dictionary with keys=(ihdu, key) and values='label' for missing cards in 'header_ihdus_keys'
Parameters:
-----------
input_fits: astropy.io.fits.HDUList instance
FITS file where to find orphan header cards
header_ihdus_keys: l... | 38,833 |
def solve(n_vec, m_vec, p_vec, repeat, dns_level, seed, solver='gurobi'):
"""
Solve random optimization problems
"""
print("Solving random problems with solver %s\n" % solver)
# Define statistics to record
std_solve_time = np.zeros(len(n_vec))
avg_solve_time = np.zeros(len(n_vec))
min_... | 38,834 |
def Rotation_multiplyByBodyXYZ_NInv_P(cosxy, sinxy, qdot):
"""
Rotation_multiplyByBodyXYZ_NInv_P(Vec2 cosxy, Vec2 sinxy, Vec3 qdot) -> Vec3
Parameters
----------
cosxy: SimTK::Vec2 const &
sinxy: SimTK::Vec2 const &
qdot: SimTK::Vec3 const &
"""
return _simbody.Rotation_multiplyByB... | 38,835 |
def sqrt(x: float):
"""
Take the square root of a positive number
Arguments:
x (int):
Returns:
(float): √x
Raises:
(ValueError): If the number is negative
"""
if x < 0:
raise ValueError('Cannot square-root a negative number with this '
... | 38,836 |
def get_tree_type(tree):
"""Return the (sub)tree type: 'root', 'nucleus', 'satellite', 'text' or 'leaf'
Parameters
----------
tree : nltk.tree.ParentedTree
a tree representing a rhetorical structure (or a part of it)
"""
if is_leaf_node(tree):
return SubtreeType.leaf
tree_t... | 38,837 |
def intersection(ls1, ls2):
"""
This function returns the intersection of two lists without
repetition. This function uses built in Python function set()
to get rid of repeated values so inputs must be cast to list
first.
Parameters:
-----------
ls1 : Python list
The first list. Cannot be array.
ls2 : Pyt... | 38,838 |
def run_tutorial(options):
"""Run a selection dlapp console CLI tutorial.
Parameters
----------
options (argparse.Namespace): a argparse.Namespace instance.
Returns
-------
None: will call ``sys.exit(0)`` if end user requests a tutorial
"""
is_tutorial_needed = options.tutorial
... | 38,839 |
def params_count(model):
"""
Computes the number of parameters.
Args:
model (model): model to count the number of parameters.
"""
return np.sum([p.numel() for p in model.parameters()]).item() | 38,840 |
def open_cmd_in_path(file_path: Path) -> int:
""" Open a terminal in the selected folder. """
if platform.system() == "Linux":
return execute_cmd(["x-terminal-emulator", "-e", "cd", f"{str(file_path)}", "bash"], True)
elif platform.system() == "Windows":
cmd_path = shutil.which("cmd")
... | 38,841 |
def get_f(user_id, ftype):
"""Get one's follower/following
:param str user_id: target's user id
:param str ftype: follower or following
:return: a mapping from follower/following id to screen name
:rtype: Dict
"""
p = dict(user_id=user_id, count=200, stringify_ids=True,
include... | 38,842 |
def walk_extension(
state: State,
trie_prefix: Bytes,
node_key: Bytes,
extension_node: ExtensionNode,
dirty_list: List[Tuple[Bytes, Node]],
cursor: Any,
) -> Optional[InternalNode]:
"""
Consume the last element of `dirty_list` and update the `ExtensionNode` at
`node_key`, potentially... | 38,843 |
def gffintRead():
"""
Read the integrated free-free gaunt factors of [1]_.
"""
xuvtop = os.environ['XUVTOP']
fileName = os.path.join(xuvtop, 'continuum','gffint.dat' )
input = open(fileName)
lines = input.readlines()
input.close()
#
ngamma = 41
g2 = np.zeros(ngamma, np.float... | 38,844 |
def test_interface(transform_constructor, constructor_kwargs, outliers_solid_tsds: TSDataset, in_column):
"""Checks outliers transforms doesn't change structure of dataframe."""
transform = transform_constructor(in_column=in_column, **constructor_kwargs)
start_columns = outliers_solid_tsds.columns
outli... | 38,845 |
def bottleneck_block_v2(inputs, filters, strides, training, projection_shortcut, data_format):
"""
3-layer bottleneck residual block with batch normalization and relu before convolution layer.
:param inputs: Input images
:param filters: number of filters
:param strides: strides of convolutions
:... | 38,846 |
def update_index(homework):
"""Check if the index of the given dataset is up to date with server version, and update it if needed.
Parameters:
homework (str): The name of the dataset to check the index of.
Returns:
bool: Indicates if we were able to check the index and upda... | 38,847 |
def load_network_interface_load_balancer_relations(neo4j_session: neo4j.Session, update_tag: int) -> None:
"""
Creates (:LoadBalancer)-[:PART_OF_SUBNET]->(:EC2Subnet) if
(:LoadBalancer)--(:NetworkInterface)--(:EC2Subnet).
"""
ingest_network_interface_loadbalancer_relations = """
MATCH (i:LoadBal... | 38,848 |
def preprocess_lines(lines, otherAutorizedSymbols, sentencesSeparator=None):
""" complete my dataset"""
if sentencesSeparator :
result = []
for line in lines :
e = line.split(sentencesSeparator)
if e[0] != "__Error__" and e[1]!= "__Error__" :
lignes_i = sent_tokenize(e[0])
lignes... | 38,849 |
def is_slashable_validator(validator: Validator, epoch: Epoch) -> bool:
"""
Check if ``validator`` is slashable.
"""
return (not validator.slashed) and (validator.activation_epoch <= epoch < validator.withdrawable_epoch) | 38,850 |
def check_rate_limit() -> None:
"""
Check whether or not a user has exceeded the rate limits specified in the
config. Rate limits per API key or session and per user are recorded.
The redis database is used to keep track of caching, by incrementing
"rate limit" cache keys on each request and setting... | 38,851 |
def connect_and_update(_id, padding, host, port, dbname, collname,
updates_per_process, process_number, replica_set):
"""
Updates document with _id <updates_per_process> times.
"""
client = MongoClient(host=[get_hostport_string(host=host, port=port)],
repl... | 38,852 |
def prepare_squeezing(q):
"""This operation prepares modes 0 to 4
as squeezed states with r = -1.
Args:
q (register): the qumode register.
"""
S = Sgate(-1)
S | q[0]
S | q[1]
S | q[2]
S | q[3] | 38,853 |
def test_validate_kwargs():
"""It should raise an error if at least one kwarg is not in one of the methods"""
assert validate_kwargs({'encoding': 'utf8'}, 'csv')
with pytest.raises(ValueError) as e:
validate_kwargs({'sheet_name': 0}, 'csv')
assert str(e.value) == "Unsupported kwargs: 'sheet_name... | 38,854 |
def update_db(mode):
"""Mode can be 'add', 'move', 'delete'"""
def decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
# did and rse are the first 2 args
did, rse = args[0], args[1]
update_db = kwargs.get('update_db', False)
if not update_... | 38,855 |
def right_size2(a1, a2):
"""
Check that a1 and a2 have equal shapes.
a1 and a2 are NumPy arrays.
"""
if hasattr(a1, 'shape') and hasattr(a2, 'shape'):
pass # ok, a1 and a2 are NumPy arrays
else:
raise TypeError('%s is %s and %s is %s - both must be NumPy arrays' \
... | 38,856 |
def arguments_parser() -> argparse.Namespace:
""" Parses arguments. """
parser = argparse.ArgumentParser(description="Input File containing list of repositories url's")
parser.add_argument("-u", "--username", default='Luzkan',
help="GitHub Username. \
(default... | 38,857 |
def spherDist(stla, stlo, evla, evlo):
"""spherical distance in degrees"""
return SphericalCoords.distance(stla, stlo, evla, evlo) | 38,858 |
def main_func(argv: List[str]):
"""
Main function that should handle all the top-level processing for this program
(other than argument parsing, which takes place beforehand)
:param argv: List of arguments passed to the program (meant to be sys.argv)
"""
# Parse the input flags using argparse
... | 38,859 |
def test_edge_redundancy_COPYx1():
"""Test Edge Redundancy - COPYx1"""
n = COPYx1()
r_ji, true_r_ji = n.edge_redundancy(bound='upper'), [0., 1.]
assert (r_ji == true_r_ji), ('Edge Redundancy (upper) for COPYx1 node does not match. %s != %s' % (r_ji, true_r_ji))
r_ji, true_r_ji = n.edge_redundancy(bo... | 38,860 |
def get_example(matrix, start_row, input_timesteps=INPUT_TIMESTEPS, output_timesteps=OUTPUT_TIMESTEPS):
"""Returns a pair of input, output ndarrays. Input starts at start_row and has the given input length.
Output starts at next timestep and has the given output length."""
# Make sure there are enough time ... | 38,861 |
def full_mul_modifier(optree):
""" extend the precision of arguments of a multiplication to get the full result of the multiplication """
op0 = optree.get_input(0)
op1 = optree.get_input(1)
optree_type = optree.get_precision()
assert(is_std_integer_format(op0.get_precision()) and is_std_integer_form... | 38,862 |
def test_config_reader_decrypt(mock_decrypt, boto_fs):
"""
Should decrypt all the secrets and parameters
"""
mock_decrypt.return_value = b'PlainTextData'
config_file = 'config.yaml'
secrets_file = 'config.secrets.yaml'
session.aws_profile = None
session.aws_region = 'us-east-1'
... | 38,863 |
def should_see_details(company: Company, response: Response, table_of_details: Table):
"""Supplier should see all expected Company details of Profile page."""
visible_details = [row["detail"] for row in table_of_details]
content = response.content.decode("utf-8")
title = DETAILS["NAME"] in visible_deta... | 38,864 |
def find_used_modules(modules, text):
"""
Given a list of modules, return the set of all those imported in text
"""
used = set()
for line in text.splitlines():
for mod in modules:
if 'import' in line and mod in line:
used.add(mod)
return used | 38,865 |
def string2mol2(filename, string):
"""
Writes molecule to filename.mol2 file, input is a string of Mol2 blocks
"""
block = string
if filename[-4:] != '.mol2':
filename += '.mol2'
with open(filename, 'w') as file:
file.write(block)
return None | 38,866 |
def getTimeFormat():
"""
def getTimeFormat(): This functions returns the time format used in the bot.
"""
return timeFormat | 38,867 |
def parse_dir(directory):
"""Iterative view of the catalog tree
Args:
directory (path): Path to the catalog
"""
for dir in os.listdir(directory):
if dir in ['.git', '.github']:
continue
next_dir = os.path.join(directory, dir)
if os.path.isdir(next_dir):
... | 38,868 |
def _writeAll():
"""
Write ODS files for a single, hardwired month. For testing.
"""
l2_path = '/nobackup/1/GEO/ABI_Testing/Level2/'
odsdir = '/nobackup/1/GEO/ABI_Testing/ODS/Y2018/M08'
nc4dir = '/nobackup/1/GEO/ABI_Testing/Level3/Y2018/M08'
for day in range(1,32):
for hour in (0,3,... | 38,869 |
def publish(build_entry: dict):
"""Publishes the specified build entry to docker hub"""
for tag in build_entry['tags']:
print('[PUSHING]:', tag)
os.system('docker push {}'.format(tag)) | 38,870 |
def concatenate(
arrays: Sequence[PolyLike],
axis: int = 0,
out: Optional[ndpoly] = None,
) -> ndpoly:
"""
Join a sequence of arrays along an existing axis.
Args:
arrays:
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the fi... | 38,871 |
def get_cik_map(key="ticker"):
"""Get dictionary of tickers to CIK numbers.
Args:
key (str): Should be either "ticker" or "title". Choosing "ticker"
will give dict with tickers as keys. Choosing "title" will use
company name as keys.
Returns:
Dictionary with either ... | 38,872 |
def _pg_tv2(x, w, y, info):
"""Projected Gradient method for TV2 proximity"""
_call(lib.PG_TV2, x, w, y, info, np.size(x)) | 38,873 |
def _data_layers():
"""Index all configured data layers by their "shorthand". This doesn't
have any error checking -- it'll explode if configured improperly"""
layers = {}
for class_path in settings.DATA_LAYERS:
module, class_name = class_path.rsplit('.', 1)
klass = getattr(import_module... | 38,874 |
def sha1base64(file_name):
"""Calculate SHA1 checksum in Base64 for a file"""
return _compute_base64_file_hash(file_name, hashlib.sha1) | 38,875 |
def readfsa(fh):
"""Reads a file and returns an fsa object"""
raw = list()
seqs = list()
for line in fh:
if line.startswith(">") and len(raw) > 0:
seqs.append(Fsa("".join(raw)))
raw.clear()
raw.append(line)
if len(raw) > 0:
seqs.append(Fsa("".join(raw)... | 38,876 |
def test_tex_hilbert_operations():
"""Test the tex representation of Hilbert space algebra operations"""
H1 = LocalSpace(1)
H2 = LocalSpace(2)
assert latex(H1 * H2) == r'\mathcal{H}_{1} \otimes \mathcal{H}_{2}' | 38,877 |
def with_timeout(name):
"""
Method decorator, wraps method with :py:func:`asyncio.wait_for`. `timeout`
argument takes from `name` decorator argument or "timeout".
:param name: name of timeout attribute
:type name: :py:class:`str`
:raises asyncio.TimeoutError: if coroutine does not finished in ... | 38,878 |
def test_all_steps_fit_transform():
"""
All steps must implement fit and transform. Otherwise, raise TypeError.
"""
with pytest.raises(TypeError):
TransformerPipeline([('svc', NoTransformT())])
with pytest.raises(TypeError):
TransformerPipeline([('svc', NoFitT())]) | 38,879 |
def results():
"""
function for predicting a test dataset input as a body of the HTTP request
:return: prediction labels array
"""
data = request.get_json(force=True)
data = pd.DataFrame(json.loads(data))
prediction = model.predict(data)
output = list(map(int, prediction))
r... | 38,880 |
def check_table_updates() -> bool:
"""Check whether the table needs to be updated.
Returns:
* A `boolean` indicating whether the tables need updating
* A `string` indicating the online version.
Raises:
SSLError:HTTPSConnectionPool: Max retries exceeded with url
"""
... | 38,881 |
def tradedate_2_dtime(td):
""" convert trade date as formatted by yfinance to a datetime object """
td_str = str(int(td))
y, m, d = int(td_str[:4]), int(td_str[4:6]), int(td_str[6:])
return datetime(y, m, d) | 38,882 |
def frmchg(frame1, frame2, et):
"""frmchg(SpiceInt frame1, SpiceInt frame2, SpiceDouble et)"""
return _cspyce0.frmchg(frame1, frame2, et) | 38,883 |
def map_popularity_score_keys(popularity):
"""
Maps popularity score keys to be more meaningful
:param popularity: popularity scores of the analysis
:return: Mapped dictionary of the scores
"""
return dict((config.popularity_terms[key], value) for (key, value) in popularity.items()) | 38,884 |
def update_bit_width_for_mlir(op_graph: OPGraph):
"""Prepare bit_width of all nodes to be the same, set to the maximum value in the graph.
Args:
op_graph: graph to update bit_width for
"""
max_bit_width, offending_nodes = get_op_graph_max_bit_width_and_nodes_over_bit_width_limit(
op_gra... | 38,885 |
def _get_utf16_setting() -> Callable[[Optional[bool]], bool]:
"""Closure for holding utf16 decoding setting."""
_utf16 = False
def _utf16_enabled(utf16: Optional[bool] = None) -> bool:
nonlocal _utf16
if utf16 is not None:
_utf16 = utf16
return _utf16
return _utf16_... | 38,886 |
def uproot_ntuples_to_ntuple_dict(uproot_ntuples, properties_by_track_type,
keep_invalid_vals=False):
"""Takes in a collection of uproot ntuples and a dictionary from
track types to desired properties to be included, returns an ntuple
dictionary formed by selecting properties from the ntuples and th... | 38,887 |
def get_container_sas_token(block_blob_client,
container_name, blob_permissions):
"""
Obtains a shared access signature granting the specified permissions to the
container.
:param block_blob_client: A blob service client.
:type block_blob_client: `azure.storage.blob.Bloc... | 38,888 |
def pssm(sequences, db, evalue, n_iter, outdir, num_threads):
"""
Obtain all .pssm files for query protein sequences
@param sequences,: query protein sequences
@param db: database used for PSI-BLAST
@param evalue: BLAST evalue
@param n_iter: num. of PSI-BLAST iterations
@param outdir: direct... | 38,889 |
def create_mesh(
pdb_file: Optional[str] = None,
pdb_code: Optional[str] = None,
out_dir: Optional[str] = None,
config: Optional[ProteinMeshConfig] = None,
) -> Tuple[torch.FloatTensor, NamedTuple, NamedTuple]:
"""
Creates a ``PyTorch3D`` mesh from a ``pdb_file`` or ``pdb_code``.
:param pdb... | 38,890 |
def init_logger(logger_name="pfp_log", log_file_name="pfp.log", to_file=True, to_console=True):
"""
Purpose:
Returns a logger object.
Usage:
logger = pfp_log.init_logger()
Author: PRI with acknowledgement to James Cleverly
Date: September 2016
"""
# create the logfiles directory if... | 38,891 |
def to_one_hot(y):
"""Transform multi-class labels to binary labels
The output of to_one_hot is sometimes referred to by some authors as the
1-of-K coding scheme.
Parameters
----------
y : numpy array or sparse matrix of shape (n_samples,) or
(n_samples, n_classes... | 38,892 |
def test__withdraw(test_teardown):
"""
Basic test for removing applications
"""
user_id = "someid456"
# We create an application in the DB
applications = apply_internal(user_id, job_id, resume, comment)
applications_by_user = get_applications_internal(user_id, 'user')
assert len(applica... | 38,893 |
def test_igw_filter_by_tags_boto3():
""" internet gateway filter by vpc id """
ec2 = boto3.resource("ec2", "us-west-1")
client = boto3.client("ec2", "us-west-1")
igw1 = ec2.create_internet_gateway()
igw2 = ec2.create_internet_gateway()
tag_value = str(uuid4())
igw1.create_tags(Tags=[{"Key":... | 38,894 |
def empty_cache(cond, delete=True, verbose=True):
"""Delete global variables specified by cond and call torch.cuda.empty_cache()
"""
for k in [k for k, v in globals().items() if cond(k, v)]:
if verbose:
print(k)
if delete:
del globals()[k]
torch.cuda.empty_cache() | 38,895 |
def random():
"""
getting a random number from 0 to 1
"""
return randrange(10000) / 10000 | 38,896 |
def parameter_string_to_value(
parameter_string: str,
passthrough_estimate: bool = False,
) -> Union[float, int, str]:
"""Cast a parameter value from string to numeric.
Args:
parameter_string:
The parameter value, as a string.
passthrough_estimate:
Whether to ret... | 38,897 |
def getNLCDRasterDataForBoundingBox(config, outputDir, bbox,
coverage=DEFAULT_COVERAGE,
filename='NLCD',
srs='EPSG:4326',
resx=0.000277777777778,
... | 38,898 |
def rfsize(spatial_filter, dx, dy=None, sigma=2.):
"""
Computes the lengths of the major and minor axes of an ellipse fit
to an STA or linear filter.
Parameters
----------
spatial_filter : array_like
The spatial receptive field to which the ellipse should be fit.
dx : float
... | 38,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.