content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _set_default_voltage_ratio(
voltage_ratio: float, subcategory_id: int, type_id: int
) -> float:
"""Set the default voltage ratio for semiconductors.
:param voltage_ratio: the current voltage ratio.
:param subcategory_id: the subcategory ID of the semiconductor with missing
defaults.
:pa... | d084f157c4d105193693af722e72028129e17821 | 3,622,558 |
def PureMultiHeadedAttention(x, params, n_heads=8, dropout=0.0, mode='train',
**kwargs):
"""Pure transformer-style multi-headed attention.
Args:
x: inputs (q, k, v, mask)
params: parameters (none)
n_heads: int: number of attention heads
dropout: float: dropout rate
... | e15a42d748a548a508f50c910f7aa25ca9ccffbc | 3,622,559 |
import functools
def flatten_factory(flatten_children, is_internal):
"""
Adaptor for single_filter_proc to accept multiple elements
"""
return single_to_multiple(functools.partial(single_filter_proc, should_filter))
return single_to_multiple(functools.partial(single_flatten_proc, flatten_children... | 1d90453ecf775f72f8c379d7dfb836e9345e34cc | 3,622,560 |
from typing import Dict
def parse_sentence(obj: Dict) -> BioCSentence:
"""Deserialize a dict obj to a BioCSentence object"""
sentence = BioCSentence()
sentence.offset = obj['offset']
sentence.infons = obj['infons']
sentence.text = obj['text']
for annotation in obj['annotations']:
sente... | 3cf53fb059a367f2200a444735c272883aff8e3e | 3,622,561 |
def _test_for_licensing(esh_machine, identity):
"""
Used to determine whether or not an instance should launch
Returns True OR raise Exception with reason for failure
"""
try:
core_machine = ProviderMachine.objects.get(
instance_source__identifier=esh_machine.id,
inst... | e319ba47a5b9a4ed0f016c1bd995f6e0a5f00fa5 | 3,622,562 |
def numba_find_phys(x, y, bdyx, bdyy):
"""
Computes whether the points x, y are inside of the polygon defined by the
x-coordinates bdyx and the y-coordinates bdyy
The polgon is assumed not to be closed (the last point is not replicated)
"""
inside = np.zeros(x.shape, dtype=bool)
vecPointInPa... | 442ae67606bea4cb6d797e08c2e6382b9eff2579 | 3,622,563 |
from unittest.mock import patch
def _get_session_client_inject_error_and_call_handler(
handler_name: str,
error_name: str = None,
) -> ProgressEvent:
"""Inject a given botocore client error and call a given handler"""
if error_name:
side_effect = botocore.exceptions.ClientError(
... | 7802daf27ab50a9ac99bfe308f02626f381c4eb7 | 3,622,564 |
import inspect
import six
def stream_text(text, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming text.
Returns a buffered generator which encodes a string as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
text : str
The data bytes to stream
c... | 20b62a77b2db501a1d8bb9f0bf6876f0d650b080 | 3,622,565 |
def put_number(image, num):
"""アイコンサイズの画像imageの上に
numの値を表示する。
"""
image = image.convert_alpha()
s = str(num)
if len(s) == 1:
font = cw.cwpy.rsrc.fonts["statusimg1"]
elif len(s) == 2:
font = cw.cwpy.rsrc.fonts["statusimg2"]
else:
font = cw.cwpy.rsrc.fonts["statusim... | e09b49ae5c4d0c71cc6556a64a17a38970dd4493 | 3,622,566 |
import multiprocessing
import requests
def generate_sequences(fuzzing_requests, checkers, fuzzing_jobs=1):
""" Implements core restler algorithm.
@param fuzzing_requests: The collection of requests that will be fuzzed
@type fuzzing_requests: FuzzingRequestCollection
@param checkers: The list of chec... | 041ba055f31556aea11696e63abc5a177270f517 | 3,622,567 |
import json
def linechart():
"""Fake endpoint."""
return json.dumps({
"line1": [1, 4, 3, 10, 12, 14, 18, 10],
"line2": [1, 2, 10, 20, 30, 6, 10, 12, 18, 2],
"line3": rr_list(),
}) | f3de5d176d48f18e987318214ff208f48dafa20c | 3,622,568 |
def server_static(filename):
"""定义/assets/下的静态(css,js,图片)资源路径"""
return static_file(filename, root='./images') | c0e9831200ec73951f1e2aaf45b6f08791ec23be | 3,622,569 |
import tensorflow as tf
import psutil
def build_execution_summary(execution_timestamp, execution_id,
ml_framework_build_label, execution_label,
platform_name, system_name, output_gcs_url,
benchmark_result, env_vars, flags, harness_inf... | 79212ca7e6a7c95123b84af72270476d95a29342 | 3,622,570 |
def retrieve_one(loc_id):
"""
Return one record from the collection matching given ID
:param loc_id: record ID for localization data
:return: matching data object
"""
query = Geolocation.query.filter(Geolocation.visible == 1).filter(
Geolocation.id == loc_id).one_or_none()... | efed22a515de3a271839c9e8fccaa85404a941b4 | 3,622,571 |
def get_seed(seed):
"""Returns the local seeds an operation should use given an op-specific seed.
See @{tf.get_seed} for more details. This wrapper adds support for the case
where `seed` may be a tensor.
Args:
seed: An integer or a @{tf.int64} scalar tensor.
Returns:
A tuple of two @{tf.int64} scal... | cf0405ba0fd6163fdafcf93410e0a306a35eb6c1 | 3,622,572 |
def _SendInsertRequest(client, resources, url_map_ref, url_map):
"""Sends a URL map insert request and waits for the operation to finish.
Args:
client: The API client.
resources: The resource parser.
url_map_ref: The URL map reference.
url_map: The URL map to insert.
Returns:
The operation r... | 9a217297d991fe35b5438e31f100c9d12ee9e2b7 | 3,622,573 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_utilities package"""
reload_params = {"package": u"fn_utilities",
"incident_fields": [],
"action_fields": [u"excel_named_range", u"excel_range", u"extract_file_path", u"parallel_timers", u"utilit... | 2f6a1086183bbc46cd8d310f4afe5887065cd42b | 3,622,575 |
import copy
def random_reset_mutation(random, candidate, args):
"""Return the mutants produced by randomly choosing new values.
This function performs random-reset mutation. It assumes that
candidate solutions are composed of discrete values. This function
makes use of the bounder function as specif... | c357237e22e34b7496f8cc17f4ad0efa2bd4621d | 3,622,576 |
from typing import Dict
def plot_lines_and_violins(
all_version_stats: Dict[str, VersionStats], # {version: version_stats}
all_resource_type_stats: Dict[
str, ResourceTypeStats
], # {resource_type: resource_type_stats}
) -> go.Figure:
"""
Plots 2 subfigures in 1 column
top row: a (ve... | 8b46724dce8a748d018c94734089d671186dea3a | 3,622,577 |
def true_positive_rate(prediction: np.ndarray, ground_truth: np.ndarray) -> float:
"""A.k.a. recall or sensitivity. From the actual positives, how many did I classify as positive?"""
tp = true_positives(prediction, ground_truth)
fn = false_negatives(prediction, ground_truth)
return tp / (tp + fn) | 7fe9ed40b30a104d0b5e628e10e6f105a7d0831a | 3,622,579 |
def is_same_data(data1, data2, precision=10**-5):
"""
Compare two data to be the same.
:param data1: given data1
:type data1: list
:param data2: given data2
:type data2: list
:param precision: comparing precision
:type precision: float
:return: True if they are the same
"""
... | 16e786a552d9190eebb44721ab75ddd45d7086cf | 3,622,581 |
def get_highest_score(league_id):
"""
Gets the highest score of the week
:param league_id: Int league_id
:return: List [score, team_name]
"""
week = get_current_week()
scoreboards = get_league_scoreboards(league_id, week)
max_score = [0, None]
for matchup_id in scoreboards:
... | b2fc905b909169742c960bbc0b8c5c897dc158f6 | 3,622,582 |
import re
def normalise_name(raw_name):
"""
Normalise the name to be used in python package allowable names.
conforms to PEP-423 package naming conventions
:param raw_name: raw string
:return: normalised string
"""
return re.sub(r"[-_. ]+", "_", raw_name).lower() | 2c9aea4a3e83fdb52f952d2308de29d8948f6917 | 3,622,583 |
def webhooks_settings():
"""
Shows the settings page
"""
with get_db() as DB:
c = DB.cursor()
results = c.execute(
"""
SELECT
id,
type,
endpointUrl,
authorizationHeader,
enabled
FROM webhooks
... | 341c26083ea7918db2409604f5a0c137dcd6a66f | 3,622,584 |
def build_parameters(integration_config: dict, instance_config: dict) -> dict:
"""Gets configurations and building the parameters to context
Args:
integration_config: The integration's configuration
instance_config: The instance's config
Returns:
A dictionary of parameters to check... | cb2871f35235df8999e85e46882b944d0595fac3 | 3,622,585 |
def decodeall(b):
"""Decode all CBOR items present in an iterable of bytes.
In addition to regular decode errors, raises CBORDecodeError if the
entirety of the passed buffer does not fully decode to complete CBOR
values. This includes failure to decode any value, incomplete collection
types, incomp... | 15fa36714710350e893faa77f96cc3e515f29aca | 3,622,586 |
def ensemble_architecture(result):
"""Extracts the ensemble architecture from evaluation results."""
architecture = result["architecture/adanet/ensembles"]
# The architecture is a serialized Summary proto for TensorBoard.
summary_proto = tf.summary.Summary.FromString(architecture)
return summary_pr... | 2715f5fdc0b92a80f7af630f3464ec0eb0e9f230 | 3,622,587 |
def average_nifti_list(input_path_list):
"""Averages NIfTIs given as a list of image file paths, into the space of the first. Returns the average NIfTI (does not save).
Images must be the same shape.
"""
return divide(add_nifti_list(input_path_list), np.float(len(input_path_list)))
# ... | 368ae3ee64a4661d8b64425167c614ad0e3ba174 | 3,622,588 |
def transform_inv(T):
"""
Calculates the inverse of the input homogeneous transformation.
This method is more efficient than using C{numpy.linalg.inv}, given
the special properties of the homogeneous transformations.
@type T: array, shape (4,4)
@param T: The input homogeneous transformation
@rtype: array... | 232ef1ba6683856c6d92880f4236b635d10edc6f | 3,622,590 |
def pandas_to_etable(df):
"""
returns a pyet.eTable constructed from given pandas DataFrame
"""
pt = eTable()
pt.Rows = len(df.index)
for cn in df.columns:
dc = df.loc[:, cn].values
pt.AddCol(dc, cn)
return pt | d9632197e79ec1f45c9967167a8ef413efab5eb7 | 3,622,591 |
def db_details_without_password(db_connection_id):
"""
To generate a dictionary for data base details.
Args:
db_connection_id(int):data base connection id.
Returns:
Returns a dictionary containing data base details for a particular
data base connection id.
"""
db_deta... | e3bf353352a768e14849e16b6697a002a99e7c02 | 3,622,592 |
def std_of_displacements(stops, distf=lambda a, b: geodesic(a, b).meters):
"""
Compute standard deviation of displacements feature from stops.
The standard deviation of distances between subsequent stops.
:param stops: dataframe of stops.
:param distf: distance function of the form: ((lat, lon),(l... | acce08afb6d7ec3c0d87ef08e1d822c88cc4b969 | 3,622,593 |
def main(args):
"""The main process of profile-based features.
:param args: an object of the arguments.
"""
file_list = args.inputfiles
label_list = args.labels
output_format = args.f
if len(file_list) == 0:
print 'Input files not found.'
return False
if output_format ==... | 70a3e5eaa0cd688401f5ecc8edfe78d333be8547 | 3,622,594 |
def class_amount(data_amount: int) -> int:
"""Compute class amount (k) of a data size"""
return ceil(1 + 3.3 * log10(data_amount)) | 52a1f4c28d31b9e7f5847728033760f72cce0e1b | 3,622,595 |
def _wrap_coord(tensors):
"""wrap positions to unit cell"""
cell = tf.gather_nd(tensors['cell'], tensors['ind_1'])
coord = tf.expand_dims(tensors['coord'], -1)
frac_coord = tf.linalg.solve(tf.transpose(cell, perm=[0, 2, 1]), coord)
frac_coord %= 1
coord = tf.matmul(tf.transpose(cell, perm=[0, 2,... | 71aa52a518f89688162f846eb18dfa37aad281a8 | 3,622,596 |
def two_linear_model_loss_regularized_dy1dx_lp(w0, w1, x, y, reg_coeff,
norm_type):
"""Penalize by ||dy1/dx||, optimal when first layer is fixed."""
dy1_dx_f = jax.grad(two_linear_model_y1_mean, argnums=2)
dy1_dx = dy1_dx_f(w0, w1, x)
loss = two_linear_model_loss(w... | 75af79d7669e6d2b24a001d973bb463fb6c72ddf | 3,622,597 |
def mask_elon(aia_cumul8, hmi_dat):
"""
Masking for elongation algorithm.
Parameters
----------
aia_cumul8 : list
Cumulative ribbon masks, c=8.
hmi_dat : list
SDO/HMI image data for flare.
Returns
-------
aia8_pos_2 : list
Contains only the positive cumulati... | e37b4bd190f37b5dfd129fadec49466578dbfbf9 | 3,622,598 |
def _validate_pad(padtype, padlen, x, axis, ntaps):
"""Helper to validate padding for filtfilt"""
if padtype not in ['even', 'odd', 'constant', None]:
raise ValueError(("Unknown value '%s' given to padtype. padtype "
"must be 'even', 'odd', 'constant', or None.") %
... | 3daa31203401cf9e67a65768c80c05da4b2d9446 | 3,622,599 |
def get_supported_languages():
"""Return the list of supported language.
"""
if getattr(PARSER, 'filename', None):
return list(sorted(lang for lang in PARSER.sections()))
return list(sorted(DEFAULT.keys())) | 9e270e896da6a60bf3a08013a331d889a46e981a | 3,622,601 |
def createCFileBuilders(env):
"""This is a utility function that creates the CFile/CXXFile
Builders in an Environment if they
are not there already.
If they are there already, we return the existing ones.
This is a separate function because soooo many Tools
use this functionality.
The ret... | 07c6589bc4f49538c4600806a7b80794e418b034 | 3,622,602 |
def get_requirements(integration: Integration, packages: set[str]) -> set[str]:
"""Return all (recursively) requirements for an integration."""
ensure_cache()
all_requirements = set()
to_check = deque(packages)
while to_check:
package = to_check.popleft()
if package in all_requir... | 1a582a63b09748470337a84e350d1788c909e8a9 | 3,622,603 |
def timestr_mod24(timestr):
"""
Given a GTFS HH:MM:SS time string, return a timestring in the same
format but with the hours taken modulo 24.
"""
try:
hours, mins, seconds = [int(x) for x in timestr.split(":")]
hours %= 24
result = "{:02d}:{:02d}:{:02d}".format(hours, mins, s... | ea049f4b31861de56b04dba6f4356ed46930af44 | 3,622,604 |
def set_ext_api(file_path):
"""Smart Function to set Extension."""
ext = file_path.split('.')[-1]
if ext == 'plist':
return 'plist'
elif ext == 'xml':
return 'xml'
elif ext in ['sqlitedb', 'db', 'sqlite']:
return 'db'
elif ext == 'm':
return 'm'
else:
... | 816a7f33c659ff3e0089502530fb916a40982d79 | 3,622,605 |
from pathlib import Path
def gen_ipc_path(base_mac, pipe) -> Path:
"""
Builds a path that should represent some RX pipe
"""
base_path = Path("/tmp/ripple_ipc/rx")
base_path.mkdir(exist_ok=True)
return _gen_ipc_path(base_path, base_mac, pipe) | 93d86a172688f80a49004f62c1f74f8427b3bf3f | 3,622,606 |
def animations():
"""animations() -> tuple
Returns a list of animatable things the user wants to work on.
If this is a command being executed from a menu item in a curve editor, a list of the names of all selected curves is returned. If this list is empty a "No curves selected" error is produced.
If this is a comm... | a30923e499824739c8a0429bdb6a8f10f42928ba | 3,622,608 |
import html
def toggle_language(n_clicks, target_lang):
"""
Toggles the language between English and Chinese.
Args:
n_clicks (int): Number of times the button has been clicked.
target_lang (str): The target language to change to (children attribute of #toggle-language element)
"""
... | a54d31b4eec8d1570c2e7de15e2f87b465c8ef50 | 3,622,610 |
def create_handler(event, context):
"""
Called when CloudFormation custom resource sends the create event
"""
return create_processing_job(event) | 65b129095915e2f4653101e0f83cb15a3731add2 | 3,622,611 |
def finish_multiplier():
"""Starts at 1.5x in the middle of the grid, increases to linearly to 2x for 1st and last place."""
multiplier_floor = 1.15
current_position = ir.car_position()
grid_size = ir.field_size()
mid_positions = grid_size/2
if grid_size % 2 == 1:
mid_positions = [mid_p... | 47878f5d61fe8111a0ae04e929997b86dc424b78 | 3,622,612 |
def combined_roidb(split, task, num_im, num_val_im):
"""
Combine multiple roidbs
"""
imdb = get_vg_imdb(split, task, num_im, num_val_im)
print('Loaded dataset `{:s}` for training'.format(imdb.name))
roidb = get_training_roidb(imdb)
return imdb, roidb | 2ae38d4fd74637862581d68464b68095e1c28756 | 3,622,613 |
from typing import Optional
def gen_payment_op(
dest: xdr_type.AccountID, src: Optional[xdr_type.AccountID] = None,
amount: int = 10
) -> xdr_type.Operation:
"""Generate a payment operation.
"""
body = xdr_pack.nullclass()
body.type = xdr_const.PAYMENT
body.paymentOp = xdr_type.PaymentOp(
... | 369d5071b70af828f2754142cc13926cb0835f5a | 3,622,614 |
def get_affine_transform(center, scale, rot, output_size, shift=np.array([0, 0], dtype=np.float32), inv=False):
"""
adapted from CenterNet: https://github.com/xingyizhou/CenterNet/blob/master/src/lib/utils/image.py
center: ndarray: (cx, cy)
scale: (w, h)
rot: angle in deg
output_size: int or (w,... | 62f74e368b4f3943044e46afae2b41347b13ddf2 | 3,622,616 |
def test_sgf(filename):
"""Parses a sgf file to a game dict.
Args:
filename: str, path of the sgf file
Returns:
None if one of these to Errors occurs:
* sgf contains no moves, affects about 1% of files in KGS dataset
* move in the sgf breaks the minigo ko rule, affects about... | a88e1b9ac3d553b5aa155bd2023c87798c433497 | 3,622,618 |
def dtex_cii_1(tcii, tau_cii, tbg):
"""
"""
return np.power(tex_cii(tcii, tau_cii, tbg), 2.) * 1./(1 + tstar*(1. - np.exp(-tau_cii))/(tcii + J(tbg))) | 67770325bf78dcf42e209b65636aabfe1199e14d | 3,622,619 |
from typing import Optional
import re
def get_pragma_spec(source: str) -> Optional[NpmSpec]:
"""
Extracts pragma information from Vyper source code.
Args:
source: Vyper source code
Returns: NpmSpec object or None, if no valid pragma is found
"""
pragma_match = next(re.finditer(r"(?:\n|... | 8183ae85682db16157d637979ffe5958d4927bf7 | 3,622,620 |
import pytz
from datetime import datetime
def parse_time(input_time):
"""Parse an Atom time stamp."""
parsed = None
try:
parsed = timezone.make_aware(timezone.datetime(*input_time[:-3]),
timezone.utc)
except (pytz.NonExistentTimeError, pytz.AmbiguousTimeErr... | 865c525b4d3811d140bb497929165463d31f25f4 | 3,622,622 |
def add_solution(
respy_obj,
periods_rewards_systematic,
states_number_period,
mapping_state_idx,
periods_emax,
states_all,
*args,
):
"""Add solution to class instance."""
respy_obj.unlock()
respy_obj.set_attr("periods_rewards_systematic", periods_rewards_systematic)
respy_ob... | ea0660fe5956bf5e8f6706a12e766a0cc5e2f2db | 3,622,623 |
def sinusoid(t,A,P,phi,offset):
"""
A simple sinusoid model
"""
return A*np.sin(2.*np.pi*t/P + phi)+offset | 0a4eb494a623dc8f6ab28ad1d5a025ccbb2157af | 3,622,624 |
def sanitize_bucket_and_host(bucket):
# type: (str) -> Tuple[str, str]
"""
if bucket is in following format : 'xxx.amazonaws.com/bucket_name',
Returns a 2-values tuple ('bucket_name', 'xxx.amazonaws.com')
"""
# first case: we got a "<host>/<bucket_name>" input
if "/" in bucket:
host,... | 706bedb456474fe75e4553c793470908702409e5 | 3,622,625 |
from unittest.mock import call
def move_roles_to_base_role_config_group(resource_root, service_name,
role_names, cluster_name="default"):
"""
Moves roles to the base role config group.
The roles can be moved from any role config group belonging to the same
service. The role type of the roles may vary. E... | f2c3951946a9b8d32874532ef8e8e3daab0eddbc | 3,622,626 |
def stamp_allowing_unusual_version_table(
config: Config,
revision: str,
sql: bool = False,
tag: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None:
"""
Stamps the Alembic version table with the given revision; don't run any
migrations.
This ... | c534748b70875dbf9c414fce2f422e82cf0d2405 | 3,622,627 |
def when(*contexts: Context):
"""Returns a function wrapper.
A function decorated with `when` will exit early if any supplied context in `contexts` is active.
The first supplied context to block will be reported as a message.
Consider supplying permanent conditions first.
For example, to block a function when a m... | c232ccb63f41793a0cd68b187f1e41e7feb9532c | 3,622,628 |
import re
from typing import Union
def read(filename: PathLike, **kwargs) -> Union[MuData, AnnData]:
"""
Read MuData object from HDF5 file
or AnnData object (a single modality) inside it
This function is designed to enhance I/O ease of use.
It recognises the following formats:
- FILE.h5mu
... | 0ff959f1f016573fee976b11b1cd74bb752f0f80 | 3,622,629 |
from typing import Iterator
from typing import Tuple
from typing import Sequence
from typing import Dict
from typing import List
def group_nodes(graph: ModuleGraph) -> Iterator[Tuple[str, str, Sequence[BaseNode]]]:
"""
Detect groups of reachable nodes in the graph.
This function groups nodes in two ways:... | f68725648c240b6132a7c8dcf7dfffe2c86b5fa5 | 3,622,630 |
def get_environment(env_name: str) -> Environment:
"""
Get environment for given env name
:return: Environment or None
"""
_check_active_client()
envs = _merlin_client.list_environment() # type: ignore
for env in envs:
if env.name == env_name:
return env
return None | d13c4eb4a15e654da2d6bdfb9a02e28b9f2f41b5 | 3,622,632 |
def cluster_otus(workflow, method, fasta_file, reference_fasta, output_folder):
""" Cluster the otus with usearch
Args:
workflow (anadama2.workflow): an instance of the workflow class.
method (string): tools for sequence analysis - usearhc(default) or vsearch
fasta_file (string): th... | e7ec21806a44bdf7f3c543120482fb4f6de0e41b | 3,622,633 |
def get_mirtarbase():
"""Get generic mirtarbase entry."""
return _get_data(mirtarbase.Mirtarbase) | 03c0df18eebdf9b46525f16b723fa90bc65a50fb | 3,622,634 |
def build_postprocessor():
"""Build the default postprocessors."""
processor = PostProcessor()
# processor.reg.add(function, name, priority)
return processor | 1dc50f7161b8af83cb1cba36edf84605c76b57c1 | 3,622,635 |
def mod(source):
"""Create kernel module shared among multiple tests."""
return source.get_module_for_symbol("snd_request_card") | 484afb203021497614ee18c7ac99200e4cb39a12 | 3,622,636 |
def getAvailableTimesOnDate(client, date):
"""Function that first loads the page for a date and then returns the list of free time slots on that day."""
loadDate(client, date)
return getAvailableTimes(client.html) | bad64a867a87d25c6e6be5e0412703966037d4ca | 3,622,638 |
import six
def make_utf8(x):
"""Encode a string as UTF8
Respect both python2 and python3."""
if isinstance(x, six.text_type):
return x
elif isinstance(x, six.binary_type):
return x.decode('utf8')
else:
raise ValueError('Expected string type, got type %s' % str(type(x))) | f41c7b0933c21f1659cab00df3fa2c50ab4e2bcf | 3,622,639 |
from typing import get_args
import torch
import math
def forward_step(data_iterator, model, input_tensor):
"""Forward step."""
args = get_args()
timers = get_timers()
# Get the batch.
timers('batch-generator').start()
query_tokens, query_mask, \
context_tokens, context_mask, context_indic... | 4538d89a532416eaec8e2268f593beac8a983eb9 | 3,622,640 |
from pathlib import Path
from typing import Union
def _join_subpath(root: Path, source: Union[str, Path],
destination: Path) -> Path:
"""
Appends to destination, source-relative path to root.
Written for use with os.walk() to match subfolders during walk.
For example:
root =... | 493effdf898ba0b07059b092eb6f29ead770a3d4 | 3,622,642 |
import six
def srt_formatter(subtitles, padding_before=0, padding_after=0):
"""
Serialize a list of subtitles according to the SRT format, with optional time padding.
"""
sub_rip_file = pysrt.SubRipFile()
for i, ((start, end), text) in enumerate(subtitles, start=1):
item = pysrt.SubRipItem... | 3aaa355ee4fd578c32fbe8d00c6893b46dbd1b0e | 3,622,644 |
from datetime import datetime
def are_in_same_quarter(first: datetime.date, second: datetime.date) -> bool:
"""Find out if two dates are in the same quarter.
Args:
first (datetime.date): The first date.
second (datetime.date): The second date.
Returns:
bool: True if the dates aar... | f16b16f61805a086d1ae2af36ff2ae3ae2ffdb06 | 3,622,645 |
from typing import Optional
from typing import List
from typing import Tuple
def get_plot_colours(n: int = 10, colourmap: Optional[str] = None) -> List[Tuple[float]]:
"""
Return iterable list of RGB colour values that can be used for custom plotting functions
Returns a list of RGB colours values, potenti... | 8e7107f2453abf01107d2547a0ca65fca87e36e8 | 3,622,646 |
from pathlib import Path
from datetime import datetime
import re
def get_output_file_globbing_template(output_dir: Path, file_prefix: str, file_suffix: str) -> Path:
"""
Returns a canonical path with the given parameters where the start and end times are replaced with a globbing
expression (?).
:para... | e7ab73e55bc9c079f652bc066414b30db61b304b | 3,622,647 |
def evaluate_reaction_rate(results, cell, nuc, rxn):
""" Evaluates a single nuclide reaction rate in a single cell from a results list.
Parameters
----------
results : list of Results
The results to extract data from. Must be sorted and continuous.
cell : str
Cell name to evaluate
... | 88e0b1d90eb3ae600185c0454bd2236b268a68de | 3,622,648 |
def roundFloatsInDict(data, decimals):
"""Recursively rounds all floats in the dictionary to the specified decimal digits.
If a float value is smaller than 10e-decimals it is set to zero.
Args:
data(dict): data dictionary
decimals(int): number of decimals floats should be rounded to
R... | 7a16fad75f378665f5605cbec841e76dc2c91094 | 3,622,649 |
def _get_vuln_info_from_cve(full_cve):
"""Return the vulnerable configurations of operating system and
software for a given CVE.
Args:
full_cve (dict): Full CVE data as a JSON dictionary from API call.
Returns (dict, dict): ({os: [version,]}, {software: [version,])
"""
vulnerable_confi... | 41c6bfefe53fc9dee45edb93787f3d378b76d836 | 3,622,650 |
def toggle_results_visible(session, context, poll):
"""Change the results visible settings of a poll."""
if poll.created:
return i18n.t('callback.poll_already_created', locale=context.user.locale)
poll.results_visible = not poll.results_visible
open_anonymization_settings(context.query.message... | 3056aa5af830439898f4c0dcd51810f3a513d401 | 3,622,651 |
def fnCalculate_DatetimeEpoch(timevec, index, timestamp):
"""
Find the datetime object for the time index.
Created: 24 May 2017 in testepochfunc.py
Edited:
29.08.17: Commented out everything, better to use datetime methods.
As set up originally, results would be imprecise ... | 2e3a76e94178c14161dc40d166df7e7fc3e2cbb1 | 3,622,652 |
from typing import Optional
from typing import Tuple
from typing import Union
from typing import List
def fetchFTPURL(remote_file:URIType, cachedFilename:AbsPath, secContext:Optional[SecurityContextConfig]=None) -> Tuple[Union[URIType, ContentKind], List[URIWithMetadata]]:
"""
Method to fetch contents from ft... | 1a3f10b6427ce43859d9ad0dae6dc1574ea3f84b | 3,622,653 |
from datetime import datetime
import pytz
def compute_stage4(lon, lat, year):
"""Build a daily dataframe for the stage4 data"""
nc = netCDF4.Dataset("/mesonet/data/stage4/%s_stage4_hourly.nc" % (year,))
lons = nc.variables["lon"][:]
lats = nc.variables["lat"][:]
dist = ((lons - lon) ** 2 + (lats -... | 615599e335756df2b82e97b34ccf6a06db0050cd | 3,622,654 |
def celery_place_order(data, staff_id):
"""使用Celery + djcelery实现快递异步下单
使用djcelery可以在任务中方便的直接操作Django数据库,
而且最终的任务可以在Django的后台中查看和修改相关的任务"""
# 创建快递操作对象
express = ProjectExpress()
result = express.place_order(request_data=data)
if result.get('Success'):
ExpressInfo.objects.create(
... | d93cf3d697365b89b0604656117bb15a977f5f72 | 3,622,655 |
def measure_torsion_angles(residues):
"""Calculates the dihedral angles for a list of backbone atoms.
Parameters
----------
residues : [ampal.Residue]
List of `Residue` objects.
Returns
-------
torsion_angles : (float, float, float)
One triple for each residue, containing t... | 4392b09f9c09afd0a75048d590bdfe582d2ae23a | 3,622,656 |
from functools import reduce
def constant_time_compare(x, y):
"""
Compares two byte strings in a way such that execution time is constant
regardless of how much alike the input values are, provided that they
are of the same length.
Comparisons between user input and secret data such as calculated... | fe7fc348d367907eee2c9df3b7d0fbe232072714 | 3,622,657 |
def get_objective_sbml_fbc_ids(model_source):
""" Get the SBML-FBC id of the active objective
Args:
model_source (:obj:`str`): path to model
Returns:
:obj:`tuple`:
* :obj:`str`: SBML-FBC id of the active objective
* :obj:`list` of :obj:`str`: SBML-FBC id of the obj... | 1c6975032879c872e438392ec6be23e8caf9d0e3 | 3,622,658 |
def isNOAAACE(filename):
"""
Checks whether a file is NOAA ACE format.
"""
try:
tempf = open(filename, 'rt')
temp1= tempf.readline()
temp2= tempf.readline()
temp3= tempf.readline()
except:
return False
try:
if not temp1.startswith(':'):
... | f2787ef1e3110aa4105af9bfe7267bfa5d2c0b84 | 3,622,659 |
import ctypes
def uiNewRadioButtons():
"""
Creates a new radio buttons.
:return: uiRadioButtons
"""
clibui.uiNewRadioButtons.restype = ctypes.POINTER(uiRadioButtons)
return clibui.uiNewRadioButtons() | e63179601033359ba2cee0dd2aeae0af35d7e4ce | 3,622,660 |
def gradient_binarizing_scalers(grads_and_vars, clip_factor):
""" Get the scalers."""
gradients, variables = zip(*grads_and_vars)
scalers = []
for gradient in gradients:
if gradient is None:
scalers.append(None)
continue
if (clip_factor > 1.0e-5):
mea... | a95869f41064cb5be2378770f8f969483fd1e2c0 | 3,622,661 |
import time
def cov_spk_ker(spk, object=False, time_format='TDB', support_ker ='',
report=False, unload=True):
"""
Provides time coverage summary for a given object for a given SPK file.
Several options are available. This function is based on the following
SPICE API:
http://naif.... | f757fb35d4f58ae921916c40176868bdbdc635ea | 3,622,662 |
def _str2bool(string):
"""Converts either 'true' or 'false' (not case-sensitively) into a boolean."""
if string is None:
return False
else:
string = string.lower()
if string == 'true':
return True
elif string == 'false':
return False
else:
raise ValueError(
'String should either... | 97755d1901a836bb1e3ce062afdbffc8b5b92de1 | 3,622,663 |
import math
def _get_alpha_bar_from_time(t):
"""
Noise scheduling method proposed by Nichol et. al to avoid too noisy image especially for smaller resolution.
This strategy creates beta as follows:
alpha_bar(t) = f(t) / f(0)
f(t) = cos((t / T + s) / (1 + s) * PI / 2) ** 2
beta(t) ... | ecb79239e2181d6e17db0b30885ec68d48b0a2d3 | 3,622,664 |
def decrementAny(tup):
""" the closest tuples to tup: decrementing by 1 along any dimension.
Never go into negatives though. """
res = []
for i, x in enumerate(tup):
if x > 0:
res.append(tuple(list(tup[:i]) + [x - 1] + list(tup[i + 1:])))
return res | 44d5c968231cfb761c641892883a85c6a168c338 | 3,622,665 |
import unittest
def mock_open(mock=None, read_data=''):
"""
A helper function to create a mock to replace the use of :func:`open()`. It
works for :func:`open()` called directly or used as a context manager.
:param mock: mock object to configure, by default
a :class:`~asynctest.MagicM... | 8379d4da696254e029641cab97d8ff5783265f43 | 3,622,666 |
def ExtractModuleIdIfValidBreakpad(file_path):
"""Extracts breakpad file's module id if the file is valid.
A breakpad file is valid for extracting its module id if it
has a valid MODULE record, formatted like so:
MODULE operatingsystem architecture id name
For example:
MODULE mac x86_64 1240DF90E9AC39038E... | e846cf05976c2c1622160d1a2a639d605e072417 | 3,622,668 |
from datetime import datetime
import pytz
def _timestamp_to_iso_str(timestamp):
"""
Converts the timestamp value into a iso str
Args:
timestamp(float): the timestamp to convert
Returns:
str: converted timestamp
"""
return datetime.fromtimestamp(timestamp).replace(tzinfo=pytz.... | 89257c74a96c5335bc25ef617e41c0eeeb31021e | 3,622,669 |
import pkg_resources
import joblib
def load_classifier(clf_name):
"""
Load classifier.
...
Parameters
----------
clf_name : str
Name of classifier to load.
Returns
-------
clf : scikit-learn classifier
Classifier.
"""
clf_path = pkg_resources.resource_fil... | 6a5278fbce2ba107a76d114859b3eb58d107271a | 3,622,670 |
import calendar
import time
def login():
"""
Try to log a new user in. If a correct username and password have been
provided we return a jwt to the user that can be used to login into any
part of meerkat. Parameters are passed in the POST request data.
Args:
username (str): The users user... | d5744cff57ab0f504d7da3a5c174a1fc8d1935e9 | 3,622,671 |
import random
import operator
def TournamentSelectDBOne(size, prob_selection,db_list):
"""
Function: SelectDBOne
======================
Select one individual from a database using Tournament selection
@param size: number of individual choosen at random from the population
@param prob_select... | 1ca2ddeb8119ce2f8def450d1ca2b51977e5410b | 3,622,672 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.