content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def run_wait(args):
"""
WARNING: DEVELOPER UTILITY, NOT OFFICIALLY SUPPORTED
Wait for the server to become available for workflow submissions.
"""
wait_for_server(args.host, args.port, args.max_tries, args.sleep_time)
return 0 | 955fd5ae083bebcca02d0f576f36bd39af21c21a | 78,901 |
def changed(old,new,delta,relative=True):
""" Tests if a number changed significantly
-) delta is the maximum change allowed
-) relative decides if the delta given indicates relative changes (if True) or absolute change (if False)
"""
delta = abs(delta)
epsilon = 1.0
if old > epsilo... | 50399926dbf3a652b73ab2045e55da6e8f9a14e5 | 78,902 |
def get_waterloo_reviews():
"""
Get all Waterloo reviews.
Returns:
All Waterloo reviews as a single string.
"""
return get_reviews_from_restuaraunts("Waterloo", WATERLOO_REVIEWS_PATH) | b6bcfc8ecd5af9f10004e418d429a78180ac8092 | 78,903 |
def grouper_form_factory(content_model, language=None):
"""Returns a form class used for selecting a grouper to see versions of.
Form has a single field - grouper - which is a model choice field
with available grouper objects for specified content model.
:param content_model: Content model class
""... | 116bd2fd793d846c263eb5e184a90e34d830afba | 78,905 |
from datetime import datetime
def relative_message_time(
sunday: datetime.date,
weekday: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
shift_weeks: int = 0,
) -> datetime.datetime:
"""Creates a test message time for a day of the week relative to the base sunday"""
if weekday ==... | 3f9e6930c12673db4877b954f1cc0c281ad538c9 | 78,906 |
import types
def from_object(obj,getitem_fcn=None,itemlist_name=None,training=True,undetermined_shape=None):
""" Creates a tf.data.Dataset object with configuration parameters for fitting
:param obj: Object instance of the data with 'getitem_fcn' function to access dataset
:param getitem_fcn: getitem_fc... | a991ef2468db1f5ced8eca7f75cb2532b0ca107e | 78,907 |
import gzip
import json
def tp53_pleiotropic_pair_json(infile):
"""Read genotype file"""
with gzip.open(infile, 'r') as fin:
d = json.load(fin)
p = d['pathway']
return (p.index('Cycle'), p.index('Damage')) | 444bdd4fbaa1cf4785e4391f101cd9094e015e38 | 78,908 |
from typing import Any
import torch
import torchvision
def _get_iou_types(model: Any) -> Any:
"""Get the IoU types."""
model_without_ddp = model
if isinstance(model, torch.nn.parallel.DistributedDataParallel):
model_without_ddp = model.module
iou_types = ["bbox"]
if isinstance(model_withou... | 3fafabab60ad7ecc260c9ee4f2f210a5724cf856 | 78,909 |
from pathlib import Path
def is_relative_to(self:Path, *other):
"""Return True if the path is relative to another path or False.
"""
try:
self.relative_to(*other)
return True
except ValueError:
return False | 6715c8e8fa9fcd71f74c40be61e5681c4e95cf73 | 78,910 |
import socket
from contextlib import closing
def check_socket(host: str, port: int) -> bool:
"""Check if given port can be listened to"""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.settimeout(2)
try:
sock.bind((host, port))
sock.liste... | 3683f22bfdb4a548e38c389f8fa21dbd07851745 | 78,911 |
def checkDefaultDesign(func):
"""
Decorator that makes the function use the global oDesign object if
no oDesign win32 COM object is passed as an argument to the function
"""
global oDesignList
def wrapper(*args, **kwargs):
if len(args)==0 or not isinstance(args[0], win32com.client.CDisp... | f70c19ad44a0d38f5a846175f3f1871a18303415 | 78,912 |
def generate_full_sinogram_helical_scan(index, tomo_data, num_proj, pixel_size,
y_start, y_stop, pitch, scan_type="180",
angles=None, flat=None, dark=None,
mask=None, crop=(0, 0, 0, 0)):
"""
G... | e60b8b399423adc0e9bfd36e2f366d72ecaaff7a | 78,913 |
def sampling(args):
"""Reparameterization trick by sampling from an isotropic unit Gaussian.
Instead of sampling from Q(z|X), sample epsilon = N(0,I)
z = z_mean + sqrt(var) * epsilon
:param args:
mean and log of variance of Q(z|X)
:return:
sampled laten... | 1e98e5705b96cfb4fa712674d93301386820a868 | 78,914 |
def force_backprop_mode():
"""Make a context manager which enables back-propagation.
When you want to enable back-propagation in :func:`no_backprop_mode`, call
this method. A :class:`~chainer.Variable` created in this context always
has a computational graph unless overridden by deeper contexts. If you... | a2c63c896a7029c2cfcaf5a6aaeec20434692fbd | 78,916 |
def edit_project(request):
"""
Edit Project Command API
:param request:
:return:
"""
data = request.POST
command = data.get("command")
group = data.get("group")
args = data.get("args")
name = data.get("project")
timeout = data.get("timeout")
status = data.get("status")
... | 271bd593e3454211b8e3622c00885c6d9bcd9d47 | 78,918 |
def parse_bsrn(fbuf, logical_records=('0100',)):
"""
Parse a file-like buffer of a BSRN station-to-archive file.
Parameters
----------
fbuf: file-like buffer
Buffer of a BSRN station-to-archive data file
logical_records: list or tuple, default: ('0100',)
List of the logical reco... | dcff5c79e19584b24cd755638d5c450eda875b48 | 78,919 |
from typing import Optional
def convert_sklearn_tree_to_tfdf_pytree(
sklearn_tree: ScikitLearnTree,
weight: Optional[float] = None,
) -> tfdf.py_tree.tree.Tree:
"""Converts a scikit-learn decision tree into a TFDF pytree.
Args:
sklearn_tree: a scikit-learn decision tree.
weight: an optional weigh... | 78245644940dac013a9201caca9c1be947773614 | 78,920 |
def upsampling_block(lower_input, conv_input, use_upsample=True, filters=16, f_size=(3, 3, 3), activation='elu',
drop=0.3, batch_norm=True, kernel_init='he_normal', pad='same', up_size=(2, 2), bn_first=False,
ndims=2):
"""
Create an upsampling block for the u-net archit... | dfdf8695a5f05237b3d0daa990fcbc55de2dc1b0 | 78,922 |
from pathlib import Path
def extract_all_images(dig_parent_dir, readfile):
"""Return a dictionary of images and their metadata by file path."""
extracted_images = {}
for filepath in (Path(dig_parent_dir) / "dig/html/excavations").iterdir():
if 'slid' in filepath.name and '.mpg' not in filepath.nam... | 195b5ed8aaf3518c7ed613835638856da9222b46 | 78,923 |
def process_wav(wav_rxfilename, process):
"""Return preprocessed wav_rxfilename.
Args:
wav_rxfilename: input
process: command which can be connected via pipe,
use stdin and stdout
Returns:
wav_rxfilename: output piped command
"""
if wav_rxfilename.endswith("|... | bc80531f6e3d09f75fd12953ca1a29270b668ba2 | 78,924 |
def penalize_off_pulse(genotype, weight=20):
"""fitness function handling off pulse notes
Args:
genotype ((int, int)[]): list of tuples (pitch, dur) representing genotype of a chromosome
weight (int, optional): Defaults at 20. Defines penalty/reward rate
Returns:
int: aggr... | 2e137aad7c665772709a4444fa93262089c1d6c6 | 78,925 |
from typing import Optional
def get_job(job_id: Optional[str] = None,
namespace_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetJobResult:
"""
Get information about a job.
"""
__args__ = dict()
__args__['jobId'] = job_id
__args__['n... | 3dd01f76375093b84f544a2102c839ba3438d36c | 78,926 |
def process_value(value, empty=False, type=str, default=None, allowed=None,
true_choices=TRUE_CHOICES, false_choices=FALSE_CHOICES):
"""Process prompted value.
:param str value: The value to process.
:param bool empty: Allow empty value.
:param type type: The expected type.
:param mixed def... | 6ca2b04df0515b305379d32b20e263bc8f44298c | 78,927 |
def dtype_to_ctype(dtype, with_fp_tex_hack=False):
"""
Return the C type that corresponds to `dtype`.
:param dtype: a numpy dtype
"""
if dtype is None:
raise ValueError("dtype may not be None")
dtype = np.dtype(dtype)
if with_fp_tex_hack:
if dtype == np.float32:
... | ca0ab3bc202a9fbc1f260bb159830586235f88f7 | 78,928 |
from typing import Tuple
import email
from datetime import datetime
def decode_ssdp_packet(data: bytes, addr: str) -> Tuple[str, CaseInsensitiveDict]:
"""Decode a message."""
lines = data.split(b'\n')
# request_line
request_line = lines[0].strip().decode()
# parse headers
header_lines = b'\n... | dc91956e2f886ccba8d80105e4815557ef373e04 | 78,929 |
import time
def get_taxonomic_ID(gene_UID_dict):
"""Uses the gene UID to get the taxonomic UID.
Args:
gene_UID_dict: A dictionary where the gene_UID are keys and the taxonomic name from the file is the value.
Returns: taxonomic_UID_dic: A dictionary where the taxonomy UIDs are keys and the ... | e166b8fb8e64bc9b4074791e155bde2172e25b4e | 78,930 |
import re
def replace(yaml_dict, template_dict):
"""Replace matched {{...}} in template_dict with values from yaml_dict
:param yaml_dict: dict representation of a YAML document defining
placeholder values
:type yaml_dict: dict
:param template_dict: dict representation of a YAML document containin... | 3b3799695bdd4c6e59ccf37fd9ebbc89ce2517fb | 78,931 |
import re
def allquery_command_cb(data, buffer, args):
""" Callback for /allquery command """
args = args.strip()
if args == "":
weechat.command("", "/help %s" % SCRIPT_COMMAND)
return weechat.WEECHAT_RC_OK
argv = args.split(" ")
exclude_nick = None
current_server = None
... | e0641e19921d1e5e8695bd53b2336339bd5e0d83 | 78,932 |
def _is_header_line(line):
"""Determines if line represents the headers for the nodetool status
output.
"""
return line.startswith('-- ') | 9cd4d5b3180266f5dc5f9048678b6e9637efa516 | 78,933 |
def get_neighbors(level, address):
"""Compute the addresses of the 4 neighbors of a point
Args:
level: A nonnegative integer representing the level of SG we're
working with.
address: np.array of size (level+1) representing the address
vector of a point in some SG graph... | bb279a0bdf17473964e6552199ca43c9aa93ef28 | 78,934 |
def is_component_connected(graph, index1, index2, vertices_in_component):
"""
Return True if two (co)components are connected else False
INPUT:
- ``graph`` -- Graph whose MD tree needs to be computed
- ``index1`` -- index of the first (co)component
- ``index2`` -- index of the second (co)compo... | 9d527f084d037405911b3bba83bbee4973c04e27 | 78,935 |
from datetime import datetime
def pyc_load(fp):
"""
Load a .pyc file from a file-like object.
Arguments:
fp(file): The file-like object to read.
Returns:
PycFile: The parsed representation of the .pyc file.
"""
magic_1 = U16(fp.read(2), target=MARSHAL_TARGET)
magic_2 = U... | 04edaec689db6ff948a9fabd23eded17cf0baf6a | 78,936 |
import statistics
import pprint
def _computeTimes(resultList, maxTime, resultTypesToGiveMaxTime):
"""
resultList: list of raw results
maxTime: the maximumTime to give result that are of a type in resultTypesToGiveMaxTime
resultTypesToGiveMaxTime: a set of FinalResultTypes to treat as having executed for... | 5de9c7f082f7618f637833a5e8b156475f66f369 | 78,938 |
def new_single_genres(genres, val):
"""Takes the genres list and returns only one genre back if multiple genres are present"""
genres_file = "fma_metadata/genres.csv"
reference_genres = pd.read_csv(genres_file)
reference_tracks = reference_genres.iloc[:, 1]
reference_genres = reference_genres.iloc[:... | e47bda77bea0eaee71ba933d5c41e3990fb383e2 | 78,939 |
def _get_fetch_names(fetches):
"""Get a flattened list of the names in run() call fetches.
Args:
fetches: Fetches of the `Session.run()` call. It maybe a Tensor, an
Operation or a Variable. It may also be nested lists, tuples or
dicts. See doc of `Session.run()` for more details.
Returns:
(l... | c2e8a08ec059cf3e0e7fda89b16a1d4e5aeb7dae | 78,940 |
def tf_local_background(t_inst):
"""
Background = when neighbors are all the same as instruction
"""
# compute local background
max_inst = tf.nn.max_pool(t_inst, [1, 3, 3, 1], [1, 1, 1, 1], 'SAME')
min_inst = -tf.nn.max_pool(-t_inst, [1, 3, 3, 1], [1, 1, 1, 1], 'SAME')
t_local_bg = tf.logica... | 1795c4d33ed43672a47e8172b89240b2073a10b9 | 78,941 |
def is_zip_path(img_or_path):
"""judge if this is a zip path"""
return '.zip@' in img_or_path | 116a718a345163a6e87d911179526b100479fa7b | 78,942 |
import math
def cluster_hot_word_groups(word_groups_result, min_score=common.CLUSTER_MIN_SCORE, improve_ratio=1.075):
"""
热点会重复,需要进行聚合
:param hot_word_groups:
:return:
"""
groups_word_set_list = [set(item[0].split("_")) for item in word_groups_result]
groups_str_list = ["".join(item[0].spl... | 560c2a9b46a5404bb49a53e7c830c1bb3ea51763 | 78,943 |
def extract_from_sql(path, sqlquery):
# type: (str, str) -> Set[TableTargetOperation]
"""
Find every tables in the sqlquery and build a ready to report target with - path, name and operation
@param path: string representing the location of the database
@param sqlquery: string of the sql-query
@... | 073026792b04f6a39f1a4012304f7633fe6a0c2e | 78,944 |
import collections
import random
import copy
def generate_dialog_bfs(scene, cap_templates, ques_templates):
"""Perform approximate breadth-first-search (BFS) to generate dialogs.
Args:
scene: Scene graph for the CLEVR image
cap_templates: List of caption templates
ques_templates: List of question tem... | 3c78abdeb67afe5690923ec3101039b1ebb06f00 | 78,945 |
def wr_def_aftr_zr_dam():
"""
Real Name: b'wr def aftr Zr Dam'
Original Eqn: b'Wr Dem aftr Zr Dam-Wr sup aftr Zr Dam'
Units: b''
Limits: (None, None)
Type: component
b''
"""
return wr_dem_aftr_zr_dam() - wr_sup_aftr_zr_dam() | b49a80e3f91fa441f512d664368080e20b1e2b50 | 78,946 |
import warnings
def PreprocessData(df, train_idx=None, test_idx=None, cat_encoder=None, cat_attr=None, datetime_attr=None, enc_target=None):
"""Preprocess the categorical attributes to ordinal scale.
Args:
df (DataFrame): The data to be preprocessed.
cat_encoder (str, optional): Which encoder... | 1075a6a0bcd7ae3e795f9e0e0a05712746df03f1 | 78,948 |
def scale(x, a, b, c, d):
"""Scales a value from one range to another range, inclusive.
This functions uses globally assigned values, min and max, of N given .nsidat
files
Args:
x (numeric): value to be transformed
a (numeric): minimum of input range
b (numeric): maximum of inp... | e90c528d62d62c28415836497d10b0c61b94ccd8 | 78,949 |
def get_mailer(registry) -> IMailer:
"""Get the active mailer.
:param registry:
:return: IMailer
"""
return registry.getUtility(IMailer) | 8ccfc49e44fafe6b2ac201fb4acb6e06ac2c9f78 | 78,950 |
def label_encoder(data, feature):
"""
标签编码
:param data: 操作数据集
:param feature: 类别特征
:return:
"""
model = LabelEncoder()
model.fit(data[feature])
data[feature] = model.transform(data[feature])
return model, data | 0743f94db98e405ae6e197c25701a808cee2cf10 | 78,951 |
def chunks_from_list(data_ls: list, n: int):
"""Yield successive n-sized chunks from lst."""
split_lst: list = [list(el) for el in mit.divide(n, data_ls)]
return split_lst | 3fc1a8d1df8d08dfee2a3612ae8396d723f40029 | 78,952 |
import math
def distance_two_points(point_a, point_b):
"""
Calculate distance of two points.
"""
distance = math.sqrt(pow((point_a.pos_x - point_b.pos_x), 2) + pow((point_a.pos_y - point_b.pos_y), 2))
return distance | 01b6357315b90bf9d6141547776f33b48294bfa2 | 78,953 |
def find_mask(image: Image, bounding_rect: TalonRect, config: str=None) -> 'src.types.Mask':
"""
Finds a foreground/background mask for use as input to the segmentation
system. Can be given explicit configuration, or pull it from
setting_background_detector.
"""
background_detector_setting = co... | 2467854c8aac36fa050647c202fb65756a8581f1 | 78,955 |
import warnings
def stopping_function(results, args=None, rstate=None, M=None,
return_vals=False):
"""
The default stopping function utilized by :class:`DynamicSampler`.
Zipped parameters are passed to the function via :data:`args`.
Assigns the run a stopping value based on a wei... | 635a4e36b1397a52969c894ed3f2ce347e28daec | 78,956 |
def strip_missing_values(series, missing_val_coding=np.nan):
"""
Helper function. Returns a pd.Series with missing values stripped.
Parameters
----------
series : pandas.Series
missing_val_coding : {np.nan, int, str}, optional
Value that indicates missing entries.
Returns
... | 58f37c7a6177c0848bfe05be4301d6f63180574d | 78,957 |
import requests
def get_module_handbook(module_code, occurence = ''):
"""
Retrieves the module handbook for the supplied module code and occurence (if any)
"""
module_code = module_code.upper()
# Construct the API url
module_handbook_url = '%s/%s/%s/%s' % (BASE_URL, ASPECTS['module'], module... | 03d4b8b0681faaeba241ee4107d5abea228f08d4 | 78,958 |
from typing import List
from typing import Dict
from typing import Any
def parse_foreign(
sf_prints_url: str, card_name: str, card_number: str, set_name: str
) -> List[Dict[str, str]]:
"""
Get the foreign printings information for a specific card
:param card_number: Card's number
:param sf_prints_... | fa4ff5ee62c963409a9279c65aafee669b807952 | 78,959 |
def labeller(landmarkable, group, label_func):
"""
Re-label an existing landmark group on a :map:`Landmarkable` object with a
new label set.
Parameters
----------
landmarkable: :map:`Landmarkable`
:map:`Landmarkable` that will have it's :map:`LandmarkManager`
augmented with a ne... | 07ec5d89337c740e6231b974c44e03cb36639965 | 78,960 |
def is_round_old(logical_array):
"""Decide if the ROI is circular in nature by testing the filled area vs bounding box. Used to find the BB."""
expected_fill_ratio = np.pi / 4
actual_fill_ratio = _vendor_mask.filled_area_ratio(logical_array)
return expected_fill_ratio * 1.2 > actual_fill_ratio > expecte... | 85859bd2ad8efac292d9825b5871e620e5166fce | 78,961 |
def user_recent_tracks(user, count=50):
"""
Gets the user's recent tracks.
* Excludes currently playing tracks
Arguments:
* user (str) -- username
* count (int) -- number of tracks
Returns:
```
[
{
'name' (str) -- track name
'artist' (str) -- artist name
... | 69138126e9e80003b5cfe5497ff5eacdf5cd3149 | 78,962 |
def retrieve_reuters_documents(doc_ids):
""" Retrieves the reuter documents associated with the given list of IDs
Return
------
list of tuple
A list of tuples of docid, title, body and topics
"""
connection = get_connection()
cursor = connection.cursor()
select_command = ... | 29daa54bd67ebed797c3ea76d9a2c7f6119a893c | 78,963 |
def estimate_all(task_id=None, **kwargs): # Put kwargs into a decorator
"""Estimate ETA for all tasks for all users."""
tms_set = TMS.objects.all()
logger.info('starting generating ETAs for the following TMS entries ({}): {}, task_id={}'.format(
len(tms_set), tms_set, task_id))
global_params =... | 26271968c4148195bf85f2b2a365450040b54a00 | 78,964 |
def edit(product_id):
"""
Route for product edit
"""
# request Form data
form = ProductEditForm(request.form)
# Get categories collection from database
categories = mongo.db.categories.find().sort("name", 1)
# Get allergens collection from database
allergens = mongo.db.allergens.find... | d404364c5a4052ebf2e48b5aeafaf22f122d66b6 | 78,965 |
def long_dict_very_big_max():
"""A trie filled with words from the short dictionary, max_compl = 7."""
return Autocomplete(long_dictionary, max_completions=15) | a50d1c0ce94a85f28b055335bbb3e1659f236b06 | 78,966 |
def fxf_domain_map_from_file(input_file):
"""
Read in a tab-delimited file with lens FXFs and domain metadata.
Args:
input_file (str): The path to the tab-delimited metadata file
Returns:
A dictionary mapping lens FXFs to `Domain`
"""
def pad(elems):
return elems + ([No... | 4b5963724f02c2b999e00d180d1fad2cd9a0dcba | 78,967 |
import functools
def ff_coroutine(func_or_coro):
"""
Extended `gen.coroutine` decorator that provides to fire & forget coroutine
without losing parent scope while yielding it:
```
from opentracing import global_tracer
@ff_coroutine
@gen.coroutine
def coro():
... | 02e19fddd64b7de94ac3b2e9b8c7d13d38c9a8d3 | 78,968 |
def command_arg(*args, **kwargs):
"""
Defines a CLI argument for the particular command.
This takes the exact parameteres that `argparse`'s `add_argument`
takes
"""
the_args = args
the_kwargs = kwargs
def decorator(fn):
args = getattr(fn, '_cliargs', [])
args.append((th... | e5f517936e3e7e7be040ceb7f4d2768317f54c9a | 78,969 |
def init(input_mgr, user_data, logger):
"""Initialize the example source tool."""
# Get the selected value from the GUI and save it for later use in the user_data
user_data.server_url = input_mgr.workflow_config["serverURL"] if 'serverURL' in input_mgr.workflow_config else None
user_data.site_name = inp... | edc8ea4492d7b488729755e48529757ece050c7f | 78,970 |
def split_img(image, grid_size):
"""拆图"""
width, height = image.size[0], image.size[1]
m, n = grid_size
w, h = width // n, height // m
return [image.crop((i * w, j * h, (i + 1) * w, (j + 1) * h)) for j in range(m)
for i in range(n)] | da152055afe90ed8ebc9424498f3fd3deed82d5e | 78,971 |
def get_metrics_types():
"""Gets a list of all registered metrics types.
:returns: The metrics type list.
:rtype: list[:class:`metrics.registry.MetricsType`]
"""
return [provider.get_metrics_type() for provider, _serializer in _PROVIDERS.values()] | 3763175dbc05cade9d3f673c8ecc9c6c6e943505 | 78,972 |
def get_inst_program_name(inst_classes, inst, pgm0_is_piano=False):
"""
:param inst_classes:
:param inst:
:param pgm0_is_piano:
:return:
"""
if inst.is_drum:
return u'Drums'
if inst.program == 0:
return inst_classes['0']['name'] if pgm0_is_piano else u'Unknown'
ret... | a12daa5ccffadadb0af43c35fca5330c5a9756e9 | 78,973 |
def hex_to_RGB(hexstr):
"""
Convert hex to rgb.
"""
hexstr = hexstr.strip('#')
r, g, b = int(hexstr[:2], 16), int(hexstr[2:4], 16), int(hexstr[4:], 16)
return (r, g, b) | 7084907ff084229fd2b4656aa301ca72a80d2fab | 78,974 |
def assert_interrupt_signal(library, session, mode, status_id):
"""Asserts the specified interrupt or signal.
Corresponds to viAssertIntrSignal function of the VISA library.
Parameters
----------
library : ctypes.WinDLL or ctypes.CDLL
ctypes wrapped library.
session : VISASession
... | c6035238e75364f591364b49f89bc4204d62200c | 78,976 |
def validate(net, val_data, ctx, eval_metric):
"""Test on test-dataset."""
eval_metric.reset()
# set nms threshold and topk constraint
net.set_nms(nms_thresh=0.45, nms_topk=400)
mx.nd.waitall()
net.hybridize()
for batch in val_data:
data = gluon.utils.split_and_load(batch[0], ctx_li... | 9971a849ad1e2267c06d8c68ff14d5c63e283867 | 78,977 |
import asyncio
async def sleep(msecs: int) -> None:
"""Creates an asynchronous computation that will sleep for the given
time. This is scheduled using a System.Threading.Timer object. The
operation will not block operating system threads for the duration
of the wait."""
return await asyncio.sleep(... | 65fd36f342388309ef996031e3e2bdafa5b8c045 | 78,979 |
def routing(x_hats, n_iters):
"""
Args:
x_hats:
[batch, out_caps, out_caps_dim, in_caps, *]
"""
xp = cuda.get_array_module(x_hats)
n_batch = x_hats.shape[0]
out_caps = x_hats.shape[1]
in_caps = x_hats.shape[3]
if len(x_hats.shape) > 3:
extra_dim = x_hats.shap... | 4f9e4ea737c9086e4b97a12adb84b97a91842869 | 78,980 |
from frappe.model.document import Document
from frappe.utils.nestedset import NestedSet
def get_controller(doctype):
"""Returns the **class** object of the given DocType.
For `custom` type, returns `frappe.model.document.Document`.
:param doctype: DocType name as string."""
def _get_controller():
module_name... | 0cd954b70bcd24192ca17eaa45e41b778fe9ea20 | 78,981 |
def constructConfigPath(library_name, library_version):
"""Generate the name for the JSON config file that will store the library's canonical data.
Args:
library_name (str): name of the library (as extracted by the identifiers)
library_version (str): version of the library (as extracted by the ... | edb24d7f8d0738d152c6dc052e50c917dcaeb7d2 | 78,983 |
def wrap_bytes(value):
"""Returns a bytes_list from a string / byte."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) | 870908ce31394755d4094605fdf8a2f5b988619a | 78,984 |
def makeTrigger(triggerMap, triggerType, params, name):
"""
Takes in a map of names to trigger instance, the type of trigger to make,
and the list of parameters to the constructor, and adds a new trigger
to the trigger map dictionary.
triggerMap: dictionary with names as keys (strings) and triggers... | 0d62f2dfeb962a007c6359e2774a05fcbc2da8a3 | 78,985 |
def _py2java(sc, obj):
""" Convert Python object into Java """
if isinstance(obj, RDD):
obj = _to_java_object_rdd(obj)
elif isinstance(obj, DataFrame):
obj = obj._jdf
elif isinstance(obj, SparkContext):
obj = obj._jsc
elif isinstance(obj, (list, tuple)):
obj = ListCon... | 2318a8b734314eeb792218dde2d0720b58f02e74 | 78,986 |
def eventBridgeEvent():
""" Generates EventBridge Event"""
return {
"version":"0",
"id":"7bf73129-1428-4cd3-a780-95db273d1602",
"detail-type":"Scheduled Event",
"source":"aws.events",
"account":"123456789012",
"time":"2015-11-11T21:29:54Z"... | 1631c3204e8b62b5c06b8a01925b53b5d518e598 | 78,987 |
def generate_inputs_and_targets(trial_number):
"""Get the input and target for the current trial"""
# Cycle through input_list:
inputs = {input_layer:input_list[trial_number%len(input_list)]}
# Get target as rewarded value for selected action
selected_action = action_selection.output_port.value
... | f9ea0dd4d3820bac0dce3bf55dfbd215e73941f6 | 78,988 |
def _guess_concat(data):
"""
Guess concat function from given data
"""
return {
type(u''): u''.join,
type(b''): bytes,
}.get(type(data), list) | 193130eea686e5b91db39f5db7a9977b6b91dd32 | 78,989 |
def get_network_name() -> str:
"""
Get the currently connected network name.
Returns:
str: The name of the network.
"""
return networks.active_provider.network.name | 13dea550e629aa06d0d60c1ee0583200e1b1b5d0 | 78,990 |
def list_notifications_by_clothe(self, id):
"""function that is responsible for bringing the list of notifications for clothing"""
try:
clothes_filter = Clothes.objects.get(id=id)
like_filter = notification.objects.filter(
like_id__clothe_id = clothes_filter).order_by('-date')
... | ffc25e836fe6f39f1f7bcba3c324400a138d558b | 78,991 |
async def delete_backup(backup_name: str):
""" Returns this weeks meal plan """
try:
BACKUP_DIR.joinpath(backup_name).unlink()
except:
HTTPException(
status_code=400,
detail=SnackResponse.error("Unable to Delete Backup. See Log File"),
)
return SnackResp... | 401a302c64f845bd71b94844f16dab57a9bc0f90 | 78,993 |
def refine_subsentence(vg):
"""
transform some subsentence to relative
Input=verbal structure Output=verbal structure
"""
#init
i = 0
while i < len(vg.vrb_sub_sentence):
if vg.vrb_sub_sentence[i].aim == 'what':
#We have to make some chan... | b808aa7ee33ea817b9f394e746951e1f0a7c3245 | 78,994 |
from typing import Optional
def parse_github_org_name(org_url: str) -> Optional[str]:
"""
Get org name from a github url
"https://github.com/os3224" -> "os3224"
"""
r = parse("https://github.com/{}", org_url)
if r is None:
return ''
return r[1].strip().rstrip('/') | d8cac434b310b60c7ccc98b50c077cb50c55e064 | 78,995 |
def resample_train(df):
"""
Resample training data (stage 2 only)
"""
# Separate classes
df_agree = df[df.label == "agree"]
df_disagree = df[df.label == "disagree"]
df_discuss = df[df.label == "discuss"]
# df_unrelated = df[df.label == "unrelated"]
# Upsample "disagree"
n = len(... | c6c53d2bcc2ad4860f9b24cd415f0768c90c1c4d | 78,996 |
def dwconv3x3_block(in_channels,
out_channels,
stride=1,
pad=1,
dilate=1,
use_bias=False,
bn_eps=1e-5,
activation=(lambda: F.relu)):
"""
3x3 depthwise version of the standa... | 8e24d81f92ad1635033a9d363017ab09eab81467 | 78,997 |
def rstrip_last_line(text):
"""rstrip only the last line of text"""
if not text:
return text
if endswith_whitespace(text):
text += " "
lines = text.splitlines()
lines[-1] = lines[-1].rstrip()
return "\n".join(lines) | c002ae7d3f357735e18df6a71891a7ba0ff28670 | 78,999 |
def load_health_data(df,project_id, bucket_id):
"""
Pushes workout data to GCS from local
---
df : pandas dataframe returned from transform_workout_data()
project_id : GCP project id
bucket_id : GCS bucket name
---
Returns : GCSUpload.run() returns the name of the blob created during the... | 8e66db047be9b2da7fb0d734427bd4e62426a82e | 79,000 |
def wind_stress_curl(Tx, Ty, x, y):
"""Calculate the curl of wind stress (Tx, Ty).
Args:
Tx, Ty: Wind stress components (N/m^2), 3d
x, y: Coordinates in lon, lat (degrees), 1d.
Notes:
Curl(Tx,Ty) = dTy/dx - dTx/dy
The different constants come from oblateness of the ellip... | 243f0154623ac98e6d5b7df29c7db187cda45892 | 79,001 |
import csv
def get_ability_names(csv_dir, pkm_abilities, languages):
"""Get the name of each pokémon ability in different languages.
Args:
csv_dir (pathlib.Path): Path to csv directory.
pkm_abilities (dict): Dict of dict containing ability infos.
languages (dict): Dictionary of suppor... | fed5413f8905f17ac02cd7b3df0745538f3595a6 | 79,002 |
import random
def synonym_replacement(words, n, key_words):
"""
同义词替换,替换一个语句中的n个单词为其同义词
:param words: list, inupt sentence
:param n: int, replace words
:return: list, new_words
"""
new_words = words.copy()
random_word_list = list(set([word for word in words if word not in stop_words]... | 346ffcce9116fa95b3f02b03a533637ffcee8259 | 79,003 |
def get_loaders(config):
"""
Get Dataloaders for train/test
Args:
config: Dict, configuration dictionary for the dataset
Returns:
Dict[Dataloader] containing the train and test dataloaders
"""
print(config)
train_dset = wds.WebDataset(config["sources"]["train"])
val_dset... | 25026db40c918cc80a141d755c82a0cf023c863b | 79,004 |
from bs4 import BeautifulSoup
def extract_text(html):
"""Extracts text from raw HTML."""
text = fulltext(html, 'ko')
# NOTE: Is this an appropriate condition to check?
if float(len(text)) / len(html) > TEXT_HTML_RATIO_THRESHOLD:
return text
soup = BeautifulSoup(html, 'html.parser')
a... | 442af74dd4c892938d0ac9c5ccdb7902578defaf | 79,005 |
def Serialize(d):
"""
递归抽取所有的MsgEntry。
"""
ret = []
if isinstance(d, dict):
d=d.values()
for i in d:
if (isinstance(i, dict)) or (isinstance(i, list)):
ret += Serialize(i)
elif isinstance(i, TMsgEntry):
if i.enable:
ret.append(i)
... | 8759f2a4099e92e01f24ffb65aae5fa1758e8764 | 79,006 |
def img_find_particles(img, min_sigma=0.5, max_sigma=5, num_sigma=20, threshold=0.1, overlap=0.85):
"""
This uses Laplacian of Gaussians method to determine the number and size of particles in the image.
:return:
"""
# particles
particles = blob_log(img, min_sigma=min_sigma, max_sigma=max_sigma... | 3a10f6c1172f38adf600eaff3bcef45b6f6020fe | 79,007 |
def score(x_value, y_value):
"""
Calculate the score
"""
distance = sqrt(x_value ** 2 + y_value ** 2)
if distance <= 1:
return 10
if distance <= 5:
return 5
if distance <= 10:
return 1
return 0 | 62dc7fefdd96a659c10b5e34ea1655faabe070d3 | 79,008 |
from typing import List
import json
def predict_loads(
trace: str,
loads: List[List[int]],
) -> List[List[List[List[int]]]]:
"""
Predict loads for a trace with the training data up to some time.
Returns: Arrival Time > Prediction Time > Job Type > List of Samples
"""
path = f"out/loads/{tr... | e93232bed52e16438a15dee2bf377dae29cc97b5 | 79,010 |
def get_method_attr(method, cls, attr_name, default = False):
"""Look up an attribute on a method/ function.
If the attribute isn't found there, looking it up in the
method's class, if any.
"""
Missing = object()
value = getattr(method, attr_name, Missing)
if value is Missing and cls is not... | 4c5bb4383e22f6b63d78f4b0b5266225b0e7c1d2 | 79,011 |
import torch
def focal_loss(labels, logits, alpha, no_of_classes):
"""Compute the focal loss between `logits` and the ground truth `labels`.
Focal loss = -alpha_t * (1-pt)^gamma * log(pt)
where pt is the probability of being classified to the true class.
pt = p (if true class), otherwise pt = 1 - p. p... | fb87746d52efaa52cc3d14c362345ecb528bd9ca | 79,012 |
import test
def dekanta_item_response():
"""dekanta search result from file"""
return test.fake_response_from_file('dekanta_item.html', url=DEKANTA_ITEM_URL) | b794bb8cd07528c8551409cd1bb0a0f6bfec0548 | 79,013 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.