content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def actor_path(data, actor_id_1, goal_test_function):
"""
Creates the shortest possible path from the given actor ID to
any actor that satisfies the goal test function.
Returns a a list containing actor IDs.
If no actors satisfy the goal condition, returns None.
"""
agenda = {actor... | 8e41d7075b3ade8f75481959f9aa376a096aaa1c | 3,651,700 |
from typing import Optional
from pathlib import Path
from typing import List
import sys
def create_script_run(snapshot_root_directory: Optional[Path] = None,
entry_script: Optional[PathOrString] = None,
script_params: Optional[List[str]] = None) -> ScriptRunConfig:
"""
... | 1c2aaaae087dfd8eb583d2c4a641c585ffda3be4 | 3,651,701 |
def M_to_E(M, ecc):
"""Eccentric anomaly from mean anomaly.
.. versionadded:: 0.4.0
Parameters
----------
M : float
Mean anomaly (rad).
ecc : float
Eccentricity.
Returns
-------
E : float
Eccentric anomaly.
"""
with u.set_enabled_equivalencies(u.di... | 071f33a294edf6627ad77caa256de48e94afad76 | 3,651,702 |
import os
def load_beijing():
"""Load and return the Beijing air quality dataset."""
module_path = os.path.dirname(__file__)
data = pd.read_csv(
os.path.join(module_path, 'data', 'beijing_air_quality.csv'))
return data | cd33c1a7034e5b0a7f397ff644631c8d1aaa7a0c | 3,651,703 |
def encrypt(plaintext, a, b):
"""
加密函数:E(x) = (ax + b)(mod m) m为编码系统中的字母数,一般为26
:param plaintext:
:param a:
:param b:
:return:
"""
cipher = ""
for i in plaintext:
if not i.isalpha():
cipher += i
else:
n = "A" if i.isupper() else "a"
... | 0cbb57250d8d7a18740e19875f79127b8057ab06 | 3,651,704 |
import pathlib
import shlex
import os
def construct_gn_command(output_path, gn_flags, python2_command=None, shell=False):
"""
Constructs and returns the GN command
If shell is True, then a single string with shell-escaped arguments is returned
If shell is False, then a list containing the command and ... | 2177ea4436305733268a427e0c4b006785e41b2d | 3,651,705 |
import subprocess
def reads_in_file(file_path):
""" Find the number of reads in a file.
Count number of lines with bash wc -l and divide by 4 if fastq, otherwise by 2 (fasta) """
return round(int(subprocess.check_output(["wc", "-l", file_path]).split()[0]) /
(4 if bin_classify.for... | 2a1bbee200564fb8e439b9af5910d75ee1a275ab | 3,651,706 |
def _url_as_filename(url: str) -> str:
"""Return a version of the url optimized for local development.
If the url is a `file://` url, it will return the remaining part
of the url so it can be used as a local file path. For example,
'file:///logs/example.txt' will be converted to
'/logs/example.txt'... | d1aef7a08221c7788f8a7f77351ccb6e6af9416b | 3,651,707 |
from typing import Dict
def hard_max(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]):
""" ONNX Hardmax to XLayer AnyOp conversion function
Input tensor shape: N dims
Output tensor shape: 2D
"""
logger.info("ONNX Hardmax -> XLayer AnyOp")
... | 5f412e98836cd377d40a759ab0487aa81cc4f3dc | 3,651,708 |
from typing import AnyStr
from typing import List
def sol_files_by_directory(target_path: AnyStr) -> List:
"""Gathers all the .sol files inside the target path
including sub-directories and returns them as a List.
Non .sol files are ignored.
:param target_path: The directory to look for .sol files
... | e41ad3da26ffa1d3c528f34362ac1aeeadeb2b3c | 3,651,709 |
def _call(sig, *inputs, **kwargs):
"""Adds a node calling a function.
This adds a `call` op to the default graph that calls the function
of signature `sig`, passing the tensors in `inputs` as arguments.
It returns the outputs of the call, which are one or more tensors.
`sig` is OpDefArg.a `_DefinedFunction`... | 6fd65281118e33bbcd9d567a7c528d85976e75e7 | 3,651,710 |
def api_url_for(view_name, _absolute=False, _xml=False, *args, **kwargs):
"""Reverse URL lookup for API routes (that use the JSONRenderer or XMLRenderer).
Takes the same arguments as Flask's url_for, with the addition of
`_absolute`, which will make an absolute URL with the correct HTTP scheme
based on ... | 6efcfbe15003652fd95294e941426ece07b37e9d | 3,651,711 |
import torch
def cov(x, rowvar=False, bias=False, ddof=None, aweights=None):
"""Estimates covariance matrix like numpy.cov"""
# ensure at least 2D
if x.dim() == 1:
x = x.view(-1, 1)
# treat each column as a data point, each row as a variable
if rowvar and x.shape[0] != 1:
x = x.t(... | 6b5666a3e7fa6fe0c0e115286e10d2e756ba8ee9 | 3,651,712 |
def threadsafe_generator(f):
"""A decorator that takes a generator function and makes it thread-safe.
Args:
f(function): Generator function
Returns:
None
"""
def g(*args, **kwargs):
"""
Args:
*args(list): List of non-key worded,variable length arguments.
... | 6a3e53984c85c951e5ffefa2ed238af86d8fc3e3 | 3,651,713 |
def load_many_problems(file, collection):
"""Given a ZIP file containing several ZIP files (each one a problem),
insert the problems into collection"""
problems = list()
try:
with ZipFile(file) as zfile:
for filename in zfile.infolist():
with zfile.open(filename) a... | 08d60f5c7905397254715f80e74019f3496d84e5 | 3,651,714 |
def CheckStructuralModelsValid(rootGroup, xyzGridSize=None, verbose=False):
"""
**CheckStricturalModelsValid** - Checks for valid structural model group data
given a netCDF root node
Parameters
----------
rootGroup: netCDF4.Group
The root group node of a Loop Project File
xyzGri... | d11ce42b041b8be7516f827883a37b40f6f98477 | 3,651,715 |
def get_load_balancers():
"""
Return all load balancers.
:return: List of load balancers.
:rtype: list
"""
return elbv2_client.describe_load_balancers()["LoadBalancers"] | b535f47ce94106a4c7ebe3d84ccfba7c57f22ba9 | 3,651,716 |
import glob
import os
def get_datasets(folder):
"""
Returns a dictionary of dataset-ID: dataset directory paths
"""
paths = glob(f"{folder}/*")
return {os.path.split(p)[-1]: p for p in paths if os.path.isdir(p)} | 1d26bddaa82624c5edb7f0e2fe0b11d5287f6f61 | 3,651,717 |
def file_preview(request):
"""
Live preview of restructuredtext payload - currently not wired up
"""
f = File(
heading=request.POST['heading'],
content=request.POST['content'],
)
rendered_base = render_to_string('projects/doc_file.rst.html', {'file': f})
rendered = restructur... | e83570b7b31b4a2d526f1699f8b65c5623d6f7ee | 3,651,718 |
def makeMask(n):
"""
return a mask of n bits as a long integer
"""
return (long(2) << n - 1) - 1 | c0fe084ec9d6be1519115563cce3c0d3649947c6 | 3,651,719 |
def link_name_to_index(model):
""" Generate a dictionary for link names and their indicies in the
model. """
return {
link.name : index for index, link in enumerate(model.links)
} | ba0e768b1160218908b6ecf3b186a73c75a69894 | 3,651,720 |
import tqdm
import os
def create_audio_dataset(
dataset_path: str, dataset_len=100, **kwargs
) -> pd.DataFrame:
""" Creates audio dataset from file structure.
Args:
playlist_dir: Playlist directory path.
# TODO dataset_len (optional): Number of audio files to include.
Returns:
... | 054b2ee756beeeade248ce75f9369e9224e093f4 | 3,651,721 |
import json
def photos_page():
"""
Example view demonstrating rendering a simple HTML page.
"""
context = make_context()
with open('data/featured.json') as f:
context['featured'] = json.load(f)
return make_response(render_template('photos.html', **context)) | dfb172e01f659be163c7dffdb13cc5cbaa28ab10 | 3,651,722 |
import json
def get_user_by_id(current_user, uid):
""" Получение одного пользователя по id в json"""
try:
user_schema = CmsUsersSchema(exclude=['password'])
user = CmsUsers.query.get(uid)
udata = user_schema.dump(user)
response = Response(
response=json.dumps(udat... | 9f91319020fb0b386d506b4365c2912af3ed5874 | 3,651,723 |
def update_bond_lists_mpi(bond_matrix, comm, size, rank):
"""
update_bond_lists(bond_matrix)
Return atom indicies of angular terms
"""
N = bond_matrix.shape[0]
"Get indicies of bonded beads"
bond_index_full = np.argwhere(bond_matrix)
"Create index lists for referring to in 2D arrays"
indices_full = create_... | 60fd4e5ee7418d182f0c29b0d69e0f148a5a40ee | 3,651,724 |
from sys import flags
def RepoRegion(args, cluster_location=None):
"""Returns the region for the Artifact Registry repo.
The intended behavior is platform-specific:
* managed: Same region as the service (run/region or --region)
* gke: Appropriate region based on cluster zone (cluster_location arg)
* ku... | 8a0e16ebbdedd82490a2ca8cc358c74386c963d2 | 3,651,725 |
from ibis.omniscidb.compiler import to_sql
def compile(expr: ibis.Expr, params=None):
"""Compile a given expression.
Note you can also call expr.compile().
Parameters
----------
expr : ibis.Expr
params : dict
Returns
-------
compiled : string
"""
return to_sql(expr, dia... | 01bfe1be13b9a78adba04ca37a08aadbf551c827 | 3,651,726 |
def get_border(border, size):
"""
Get border
"""
i = 1
while size - border // i <= border // i: # size > 2 * (border // i)
i *= 2
return border // i | 45233f53cdf6f0edb5b4a9262b61f2a70ac42661 | 3,651,727 |
def load_normalized_data(file_path, log1p=True):
"""load normalized data
1. Load filtered data for both FACS and droplet
2. Size factor normalization to counts per 10 thousand
3. log(x+1) transform
4. Combine the data
Args:
file_path (str): file path.
Returns:
adata_combin... | 3c180c1f2ba1e118678331795eb42b7132686ed6 | 3,651,728 |
def from_copy_number(
model: cobra.Model,
index: pd.Series,
cell_copies: pd.Series,
stdev: pd.Series,
vol: float,
dens: float,
water: float,
) -> cobra.Model:
"""Convert `cell_copies` to mmol/gDW and apply them to `model`.
Parameters
----------
model: cobra.Model
cob... | 858d563ad0f4ae16e83b36db3908895671809431 | 3,651,729 |
def getstatusoutput(cmd):
"""Return (exitcode, output) of executing cmd in a shell.
Execute the string 'cmd' in a shell with 'check_output' and
return a 2-tuple (status, output). The locale encoding is used
to decode the output and process newlines.
A trailing newline is stripped from the output.
... | 9a243e5e138731fe6d2c6525fea3c5c36a1d1119 | 3,651,730 |
import re
def _get_values(attribute, text):
"""Match attribute in text and return all matches.
:returns: List of matches.
"""
regex = '{}\s+=\s+"(.*)";'.format(attribute)
regex = re.compile(regex)
values = regex.findall(text)
return values | 59a0fdb7a39221e5f728f512ba0aa814506bbc37 | 3,651,731 |
def time_axis(tpp=20e-9, length=20_000) -> np.ndarray:
"""Return the time axis used in experiments.
"""
ts = tpp * np.arange(length)
ten_percent_point = np.floor(length / 10) * tpp
ts -= ten_percent_point
ts *= 1e6 # convert from seconds to microseconds
return ts | 6cd18bcbfa6949fe98e720312b07cfa20fde940a | 3,651,732 |
from cyder.core.ctnr.models import CtnrUser
def _has_perm(user, ctnr, action, obj=None, obj_class=None):
"""
Checks whether a user (``request.user``) has permission to act on a
given object (``obj``) within the current session CTNR. Permissions will
depend on whether the object is within the user's cu... | 998119c3aa9b50fcdd9fdec1f734374f04fe51c6 | 3,651,733 |
def read_chunk(file: File, size: int=400) -> bytes:
""" Reads first [size] chunks from file, size defaults to 400 """
file = _path.join(file.root, file.name) # get full path of file
with open(file, 'rb') as file:
# read chunk size
chunk = file.read(size)
return chunk | dfa1fd576fe14c5551470fb76a674dccd136e200 | 3,651,734 |
def parse_input(file_path):
"""
Turn an input file of newline-separate bitrate samples into
input and label arrays. An input file line should look like this:
4983 1008073 1591538 704983 1008073 1008073 704983
Adjacent duplicate entries will be removed and lines with less than
two samples will ... | 1e1aada5b8da01d362f7deb0b2145209bb55bcc0 | 3,651,735 |
import os
def read(rel_path):
""" Docstring """
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, rel_path), 'r') as fp:
return fp.read() | ec84c8ccf878e7f9ad8ccfb0239e7d82c7ba7f99 | 3,651,736 |
import sys
def main(argv=None):
"""Main command line interface."""
if argv is None:
argv = sys.argv[1:]
cli = CommandLineTool()
try:
return cli.run(argv)
except KeyboardInterrupt:
print('Canceled')
return 3 | a4a5dec5c09c6f7ee7a354aea34b98899841ed0f | 3,651,737 |
from typing import Dict
from typing import Any
import torch
def extract_attrs_for_lowering(mod: nn.Module) -> Dict[str, Any]:
"""If `mod` is in `module_fetch_book`, fetch the mod's attributes that in the `module_fetch_book`
after checking module's version is compatible with the `module_fetch_book`.
"""
... | ec2ff68f2164eabdc0aae9acdcc7ff51b83a77dd | 3,651,738 |
from typing import Set
import requests
def get_filter_fields(target: str, data_registry_url: str, token: str) -> Set[str]:
"""
Returns a list of filterable fields from a target end point by calling OPTIONS
:param target: target end point of the data registry
:param data_registry_url: the url of the d... | 34b6cccc2f8529391357ab70b212f1fddbd9e37d | 3,651,739 |
def azimuthalAverage(image, center=None):
"""
Calculate the azimuthally averaged radial profile.
image - The 2D image
center - The [x,y] pixel coordinates used as the center. The default is
None, which then uses the center of the image (including
fracitonal pixels).
http... | f086d0868bd56b01de976f346e2a66f5e0d7a10b | 3,651,740 |
def train_transforms_fisheye(sample, image_shape, jittering):
"""
Training data augmentation transformations
Parameters
----------
sample : dict
Sample to be augmented
image_shape : tuple (height, width)
Image dimension to reshape
jittering : tuple (brightness, contrast, sat... | c815d28a5e9e62234544adc4f2ba816e9f1c366a | 3,651,741 |
from typing import Any
def build_json_output_request(**kwargs: Any) -> HttpRequest:
"""A Swagger with XML that has one operation that returns JSON. ID number 42.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :... | b920f0955378f0db1fdddadefc4037a33bedecad | 3,651,742 |
def merge_extended(args_container: args._ArgumentContainer, hold: bool, identificator: str) -> int:
"""
Merge the args_container into the internal, like merge_named, but hold specifies if the internal container should not be cleared.
:param args_container: The argument container with the data to merge
... | 111765aa0a62a1050387670472d3718aca8a015f | 3,651,743 |
def video_path_file_name(instance, filename):
""" Callback for video node field to get path file name
:param instance: the image field
:param filename: the file name
:return: the path file name
"""
return path_file_name(instance, 'video', filename) | b34b96961ad5f9275cd89809828b8dd0aed3dafb | 3,651,744 |
def radiative_processes_mono(flux_euv, flux_fuv,
average_euv_photon_wavelength=242.0,
average_fuv_photon_wavelength=2348.0):
"""
Calculate the photoionization rate of helium at null optical depth based
on the EUV spectrum arriving at the planet.
... | b555fe1af2bdcdab4ac8f78ed2e64bef35a2cdab | 3,651,745 |
import typing
from datetime import datetime
def date_yyyymmdd(now: typing.Union[datetime.datetime, None] = None, day_delta: int = 0, month_delta: int = 0) -> str:
"""
:param day_delta:
:param month_delta:
:return: today + day_delta + month_delta -> str YYYY-MM-DD
"""
return date_delta(now, day... | 8a3ff535964aba6e3eeaa30dc6b98bfcab1b5794 | 3,651,746 |
from .geocoder import description_for_number as real_fn
def description_for_number(*args, **kwargs):
"""Return a text description of a PhoneNumber object for the given language.
The description might consist of the name of the country where the phone
number is from and/or the name of the geographical are... | c60423fb26d892a43db6017a08cce3d589481cb6 | 3,651,747 |
def get_pathway_nodes(pathway):
"""Return single nodes in pathway.
:param pathme_viewer.models.Pathway pathway: pathway entry
:return: BaseAbundance nodes
:rtype: list[pybel.dsl.BaseAbundance]
"""
# Loads the BELGraph
graph = from_bytes(pathway.blob)
collapse_to_genes(graph)
# Ret... | 5ec451d9e9192b7d07230b05b2e3493df7ab3b4d | 3,651,748 |
def check_currrent_user_privilege():
"""
Check if our user has interesting tokens
"""
# Interesting Windows Privileges
# - SeDebug
# - SeRestore
# - SeBackup
# - SeTakeOwnership
# - SeTcb
# - SeCreateToken
# - SeLoadDriver
# - SeImpersonate
# - SeAssignPrimaryToken
... | 7780717dfbf887f80ff90151ba2f00e49b810e2e | 3,651,749 |
import copy
def handle_domain_addition_commands(client: Client, demisto_args: dict) -> CommandResults:
"""
Adds the domains to the inbound blacklisted list.
:type client: ``Client``
:param client: Client to use.
:type demisto_args: ``dict``
:param demisto_args: The demis... | b5b281e3254a433c9431e77631001cb2be4e37e3 | 3,651,750 |
import torch
def _tc4(dom: AbsDom):
""" Validate that my AcasNet module can be optimized at the inputs. """
mse = nn.MSELoss()
max_retries = 100
max_iters = 30 # at each retry, train at most 100 iterations
def _loss(outputs_lb):
lows = outputs_lb[..., 0]
distances = 0 - lows
... | f008fd4bff6e1986f2354ef9338a3990e947656c | 3,651,751 |
def skip_url(url):
"""
Skip naked username mentions and subreddit links.
"""
return REDDIT_PATTERN.match(url) and SUBREDDIT_OR_USER.search(url) | 60c54b69916ad0bce971df06c5915cfbde10018c | 3,651,752 |
def registry():
"""
Return a dictionary of problems of the form:
```{
"problem name": {
"params": ...
},
...
}```
where `flexs.landscapes.AdditiveAAVPackaging(**problem["params"])` instantiates the
additive AAV packaging landscape for the given set of paramet... | 5dd2e4e17640e0831daf02d0a2a9b9f90305a1c4 | 3,651,753 |
import time
import random
def ecm(n, rounds, b1, b2, wheel=2310, output=True):
"""Elliptic Curve Factorization Method. In each round, the following steps are performed:
0. Generate random point and curve.
1. Repeatedly multiply the current point by small primes raised to some power, determined
... | 9490e6ac4308aed9835e85b3093a1c2b18877fd1 | 3,651,754 |
from typing import Optional
import re
from datetime import datetime
import logging
def dc_mode_option(update: Update, contex: CallbackContext) -> Optional[int]:
"""Get don't care response mode option"""
ndc = contex.user_data[0]
if ndc.response_mode == DoesntCare.ResponseMode.TIME:
if not re.matc... | accf998e660898d9de2d17d45e18b6d49ba90f4c | 3,651,755 |
def is_in_period(datetime_, start, end):
"""指定した日時がstartからendまでの期間に含まれるか判定する"""
return start <= datetime_ < end | 3b830cb8d9e74934a09430c9cd6c0940cf36cf2e | 3,651,756 |
def create_experiment_summary():
"""Returns a summary proto buffer holding this experiment"""
# Convert TEMPERATURE_LIST to google.protobuf.ListValue
temperature_list = struct_pb2.ListValue().extend(TEMPERATURE_LIST)
return summary.experiment_pb(
hparam_infos=[
api_pb2.HParamInfo(name="initial_t... | 678a9f1b004f4c5a60784ccf814082731eace826 | 3,651,757 |
import requests
def get_session(token, custom_session=None):
"""Get requests session with authorization headers
Args:
token (str): Top secret GitHub access token
custom_session: e.g. betamax's session
Returns:
:class:`requests.sessions.Session`: Session
"""
sessi... | 88bf566144a55cf36daa46d3f9a9886d3257d767 | 3,651,758 |
def mass_to_tbint_to_energy_map(dpath, filterfn=lambda x: True,
fpath_list=None):
"""Given a directory, creates a mapping
mass number -> ( a, b, c, d, j -> energy )
using the files in the directory
:param fpath_list:
:param dpath: the directory which is a direct p... | a13caba5ff41e2958d7f4e6104eb809de1cda1c1 | 3,651,759 |
import unicodedata
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
text = unicodedata.normalize('NFD', text)
text = text.encode('ascii', 'ignore')
text = text.... | 4a6e11e0a72438a7e604e90e44a7220b1426df69 | 3,651,760 |
import json
def json_formatter(result, _verbose):
"""Format result as json."""
if isinstance(result, list) and "data" in result[0]:
res = [json.dumps(record) for record in result[0]["data"]]
output = "\n".join(res)
else:
output = json.dumps(result, indent=4, sort_keys=True)
re... | 68aae87577370d3acf584014651af21c7cbfa309 | 3,651,761 |
def show_all_companies():
"""Show all companies a user has interest in."""
# redirect if user is not logged in
if not session:
return redirect('/')
else:
# get user_id from session
user_id = session['user_id']
user = User.query.filter(User.user_id == user_id).one()
... | 7f2d7215627747ff44caff4f58324dce2e3aa749 | 3,651,762 |
def ll_combined_grad(x, item_ids, judge_ids, pairwise=[], individual=[]):
"""
This function computes the _negative_ gradient of the loglikelihood for
each parameter in x, for both the individual and pairwise data.
Keyword arguments:
x -- the current parameter estimates.
item_ids -- the ids... | 54936fe9b0e9b7a17acb7455c606bf754532a8b8 | 3,651,763 |
def relu(inp): # ReLu function as activation function
"""
ReLu neural network activation function
:param inp: Node value before activation
:return: Node value after activation
"""
return np.max(inp, 0) | fbe6caf2246684a62d00956e38579fab3dff3418 | 3,651,764 |
from typing import List
from typing import Tuple
import logging
def augment_sentence(tokens: List[str], augmentations: List[Tuple[List[tuple], int, int]], begin_entity_token: str,
sep_token: str, relation_sep_token: str, end_entity_token: str) -> str:
"""
Augment a sentence by adding tags... | 916745727dd6ce19e67a28bdadb2bd74b54075a3 | 3,651,765 |
import multiprocessing
def evaluate_model_recall_precision(mat, num_items, testRatings, K_recall, K_precision, num_thread):
"""
Evaluate the performance (Hit_Ratio, NDCG) of top-K recommendation
Return: score of each test rating.
"""
global _mat
global _testRatings
global _K_recall
glo... | bb504053937faf6e3017f8d79fee6a4a4e864b15 | 3,651,766 |
def pipe_hoop_stress(P, D, t):
"""Calculate the hoop (circumferential) stress in a pipe
using Barlow's formula.
Refs: https://en.wikipedia.org/wiki/Barlow%27s_formula
https://en.wikipedia.org/wiki/Cylinder_stress
:param P: the internal pressure in the pipe.
:type P: float
:param D: the ou... | 9985d35c2c55e697ce21a880bb2234c160178f33 | 3,651,767 |
def node_constraints(node):
"""
Returns all constraints a node is linked to
:param node: str
:return: list(str)
"""
return maya.cmds.listRelatives(node, type='constraint') | 85c619f4c1b6ec24feb8c3dac3e73b92f8fdf7fc | 3,651,768 |
import os
def save_data_file(sourceFile, destination = None, subdirectory = None, user = None, verbose = True):
""" Function used to save (i.e copy) a data file into a directory of choice after an experimental session
Parameters: sourceFile - the path of the file that was generated by the experimental s... | 1950fd776ccee91d0b2500297b2b3f94cb734415 | 3,651,769 |
import os
def parse_file_name(filename):
"""
Parse the file name of a DUD mol2 file to get the target name and the y label
:param filename: the filename string
:return: protein target name, y_label string (ligand or decoy)
"""
bname = os.path.basename(filename)
splitted_bname = bname.split... | 8f9de132e622feffc513453be36b80f386b36c9c | 3,651,770 |
def load_opencv_stereo_calibration(path):
"""
Load stereo calibration information from xml file
@type path: str
@param path: video_path to xml file
@return stereo calibration: loaded from the given xml file
@rtype calib.data.StereoRig
"""
tree = etree.parse(path)
stereo_calib_elem = ... | 07ace05e8d377ba1fdcef632e5afa1d9ea309185 | 3,651,771 |
def _IsSingleElementTuple(token):
"""Check if it's a single-element tuple."""
close = token.matching_bracket
token = token.next_token
num_commas = 0
while token != close:
if token.value == ',':
num_commas += 1
if token.OpensScope():
token = token.matching_bracket
else:
token = to... | 8d675bcee737ddb106817db79e2b989509d2efaa | 3,651,772 |
def exportBufferView(gltf: GLTF2, primaryBufferIndex: int, byteOffset: int, byteLength: int) -> GLTFIndex:
"""Creates a glTF bufferView with the specified offset and length, referencing the default glB buffer.
Args:
gltf: Gltf object to append new buffer onto.
primaryBufferIndex: Index of the p... | 6905f3544470860a125b0d28f5f422a39bc7b91f | 3,651,773 |
import numpy
def ReadCan(filename):
"""Reads the candump in filename and returns the 4 fields."""
trigger = []
trigger_velocity = []
trigger_torque = []
trigger_current = []
wheel = []
wheel_velocity = []
wheel_torque = []
wheel_current = []
trigger_request_time = [0.0]
tr... | 773657474462aa3a129ea7459c72ea0b0dc0cefa | 3,651,774 |
def retrieve(func):
"""
Decorator for Zotero read API methods; calls _retrieve_data() and passes
the result to the correct processor, based on a lookup
"""
def wrapped_f(self, *args, **kwargs):
"""
Returns result of _retrieve_data()
func's return value is part of a URI, and ... | 442f18f4c00a13b5eb68285202088b009f9f351b | 3,651,775 |
from typing import Dict
async def health() -> Dict[str, str]:
"""Health check function
:return: Health check dict
:rtype: Dict[str, str]
"""
health_response = schemas.Health(name=settings.PROJECT_NAME,
api_version=__version__)
return health_response.dict() | 8c2841cea1fb9118cbc063d9352d375188025614 | 3,651,776 |
def detail(video_id):
""" return value is
[
{
'video_path' : s
},
{
'person_id': n,
'person_info_list' : [
{
'frame' : n
'millisec' : n
... | 7447f5ea45ab6fa1c6d10f97ac7d57add68fdf40 | 3,651,777 |
import os
def list_terminologies():
""" Get the list of available Amazon Translate Terminologies for this region
Returns:
This is a proxy for boto3 get_terminology and returns the output from that SDK method.
See `the boto3 documentation for details <https://boto3.amazonaws.com/v1/documentati... | 7eeaa65fa5d20d508d12d010fcf0d4410cc8b45d | 3,651,778 |
import logging
def RunLinters(prefix, name, data, settings=None):
"""Run linters starting with |prefix| against |data|."""
ret = []
if settings is None:
settings = ParseOptions([])
ret += settings.errors
linters = [x for x in FindLinters(prefix) if x not in settings.skip]
for linter in linters:
... | 9b8c780fe3684405d17e59897bee11118dff5590 | 3,651,779 |
def element_norm_spatial_exoao(processes,
comp_sol,
test_time,
test_var_list,
exact_solution,
subel_ints = 1,
zfill=None,
... | 323fe13213a5ae8ad980d760943bc5cf1fc46074 | 3,651,780 |
from typing import Iterator
def generate_close_coordinates(
draw: st.DrawFn, prev_coord: Coordinates[str, np.float64]
) -> Coordinates[str, np.float64]:
"""Create coordinates using Hypothesis."""
diff = [
draw(hynp.from_dtype(np.dtype(np.float64), min_value=0.1, max_value=1.0)),
draw(hynp.... | 8b207d5989f59a30e0c99eebd4654b609a03be93 | 3,651,781 |
from typing import Union
def redistribute_vertices(
geom: Union[LineString, MultiLineString],
distance: float
) -> Union[LineString, MultiLineString]:
"""Redistribute the vertices of input line strings
Parameters
----------
geom : LineString or MultiLineString
Input li... | 1a5f0c3f409d5f3de46831bfa8456a734985d2b8 | 3,651,782 |
def get_boolean_value(value):
"""Get the boolean value of the ParameterValue."""
if value.type == ParameterType.PARAMETER_BOOL:
return value.bool_value
else:
raise ValueError('Expected boolean value.') | fc5452a45983d16f30433ffe54b8883c24c1eb94 | 3,651,783 |
import torch
def eval_bayesian_optimization(net: torch.nn.Module, input_picture: DATA,\
label_picture: DATA, ) -> float:
""" Compute classification accuracy on provided dataset to find the optimzed hyperparamter
settings.
Args:
net: trained neural network
Input: The image
... | 4833627f5239f7c713f11a1ab9f97e6898a303b1 | 3,651,784 |
import urllib
def parse(url):
"""
URL-parsing function that checks that
- port is an integer 0-65535
- host is a valid IDNA-encoded hostname with no null-bytes
- path is valid ASCII
Args:
A URL (as bytes or as unicode)
Returns:
... | d1af42d9ee5b9c786cae9a6a16da89a545d27e33 | 3,651,785 |
def is_amicable(num: int) -> bool:
""" Returns whether the number is part of an amicable number pair """
friend = sum(divisors(num)) - num
# Only those in pairs are amicable numbers. If the sum is the number itself, it's a perfect number
return friend != num and sum(divisors(friend)) - friend == num | e5fc62d4f390a95f6d54d57979c4e39b9d4e4316 | 3,651,786 |
import html
def no_data_info():
"""Returns information about not having enough information yet to display"""
return html.Div(children=[dcc.Markdown('''
# Please wait a little bit...
The MongoDB database was probably just initialized and is currently empty. You will need to wait a bit (~30 min)... | 59ce4a2a0e2b18298006746be31f30b8c2cb4a6a | 3,651,787 |
def delta_t(soil_type):
""" Displacement at Tu
"""
delta_ts = {
"dense sand": 0.003,
"loose sand": 0.005,
"stiff clay": 0.008,
"soft clay": 0.01,
}
return delta_ts.get(soil_type, ValueError("Unknown soil type.")) | c542adb7c302bc1f50eb4c49bf9da70932758814 | 3,651,788 |
def extractPlate(imgOriginal, listOfMatchingChars, PlateWidthPaddingFactor, PlateHeightPaddingFactor):
""" Extract license-plate in the provided image, based on given contours group that corresponds for matching characters """
# Sort characters from left to right based on x position:
listOfMatchingChars.so... | f6d726727762b752003ae16c3cf9d286a0ebe990 | 3,651,789 |
def create_stratified_name(stem, stratification_name, stratum_name):
"""
generate a standardised stratified compartment name
:param stem: str
the previous stem to the compartment or parameter name that needs to be extended
:param stratification_name: str
the "stratification" or rational... | 2677dec386dfd235e7fb5d088c5481987acf4beb | 3,651,790 |
import inspect
import typing
def bind_args_kwargs(sig: inspect.Signature, *args: typing.Any, **kwargs: typing.Any) -> typing.List[BoundParameter]:
"""Bind *args and **kwargs to signature and get Bound Parameters.
:param sig: source signature
:type sig: inspect.Signature
:param args: not keyworded arg... | 3fc8b16449981e920998ff84839a71cbbfc26d28 | 3,651,791 |
def user(user_type):
"""
:return: instance of a User
"""
return user_type() | a8c8cd4ef57915c555864f6fc09dce63c2a1c6fb | 3,651,792 |
def true_or_false(item):
"""This function is used to assist in getting appropriate
values set with the PythonOption directive
"""
try:
item = item.lower()
except:
pass
if item in ['yes','true', '1', 1, True]:
return True
elif item in ['no', 'false', '0', 0, None, Fal... | 3e7c0cee07f6796c6134b182572a7d5ff95cf42d | 3,651,793 |
import copy
def validate_task(task, variables, config=None):
""" Validate that a simulation can be executed with OpenCOR
Args:
task (:obj:`Task`): request simulation task
variables (:obj:`list` of :obj:`Variable`): variables that should be recorded
config (:obj:`Config`, optional): Bi... | d1b65ead34f3fa1c83bc451ac297411d02c33978 | 3,651,794 |
import time
def time_ms():
"""currently pypy only has Python 3.5.3, so we are missing Python 3.7's time.time_ns() with better precision
see https://www.python.org/dev/peps/pep-0564/
the function here is a convenience; you shall use `time.time_ns() // 1e6` if using >=Python 3.7
"""
return int(time... | 1bff241db79007314d7a876ddd007af137ba7306 | 3,651,795 |
def _calculate_mk(tp, fp, tn, fn):
"""Calculate mk."""
ppv = np.where((tp + fp) > 0, tp / (tp + fp), np.array(float("nan")))
npv = np.where((tn + fn) > 0, tn / (tn + fn), np.array(float("nan")))
npv = tn / (tn + fn)
numerator = ppv + npv - 1.0
denominator = 1.0
return numerator, denominator | d777db3abd9296b2a67e038396d29e8ef8529a74 | 3,651,796 |
def geometric_progression_for_stepsize(
x, update, dist, decision_function, current_iteration
):
"""Geometric progression to search for stepsize.
Keep decreasing stepsize by half until reaching
the desired side of the boundary.
"""
epsilon = dist / np.sqrt(current_iteration)
while True:
... | d5a043f434efa68e827ff89f6f469eab37a79383 | 3,651,797 |
def absorption_two_linear_known(freq_list, interaction_strength, decay_rate):
""" The absorption is half the imaginary part of the susecptibility. """
return susceptibility_two_linear_known(freq_list, interaction_strength,
decay_rate).imag/2.0 | 9d4819715150ce63753f4e356c406685852fc761 | 3,651,798 |
def mad(x, mask, base_size=(11, 3), mad_size=(21, 21), debug=False, sigma=True):
"""Calculate the MAD of freq-time data.
Parameters
----------
x : np.ndarray
Data to filter.
mask : np.ndarray
Initial mask.
base_size : tuple
Size of the window to use in (freq, time) when
... | 7c62ed0af54bcab2e32a12d98580c989cdfd42ef | 3,651,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.