content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def default_role(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""Set the default interpreted text role."""
if not arguments:
if roles._roles.has_key(''):
# restore the "default" default role
del roles._roles['']
... | f1f6ed82da74cd898d4df0753cd1044a6666d216 | 3,641,200 |
from typing import Dict
import os
import json
def get_zind_json(server_token, output_folder) -> Dict:
"""
Returns the dict for the ZInD json.
Sends a request to the BridgeAPI to get details about the ZInD Dataset
Stores the respose json file in output folder
:param server_token: token for access t... | 85134d6dcec3a0ad1cdc0d206c2879e99ad22963 | 3,641,201 |
def input_fn(evaluate=False) -> tf.data.Dataset:
"""
Returns the text as char array
Args:
n_repetitions: Number of times to repeat the inputs
"""
# The dataset
g = ( evaluate_generator if evaluate else train_generator )
ds = tf.data.Dataset.from_generator( generator=g,
out... | 2954eb4b4f657fff3e029096a562516842c615e8 | 3,641,202 |
import os
def make_model_path(model_base_path: Text, model_name: Text,
version: int) -> Text:
"""Make a TFS-flavored model path.
Args:
model_base_path: A base path containing the directory of model_name.
model_name: A name of the model.
version: An integer version of the model.
... | 0c170550d53100f4ac916d26da9afc3be3330691 | 3,641,203 |
async def validate_input(data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
harmony = await get_harmony_client_if_available(data[CONF_HOST])
if not harmony:
raise CannotConnect
return {
CONF_NAME: fin... | fc174ed28bd80fd8e118094ea21358b9c8f41fa3 | 3,641,204 |
import numpy
def window_tukey(M, alpha=0.5):
"""Return a Tukey window, also known as a tapered cosine window.
The function returns a Hann window for `alpha=0` and a boxcar window for `alpha=1`
"""
if alpha == 0:
return numpy.hann(M)
elif alpha == 1:
return window_boxcar(M)
n =... | f62d216de29e2271270a4fc3c03b0f93930f1275 | 3,641,205 |
def workshopsDF(symbol="", **kwargs):
"""This is a meeting or series of meetings at which a group of people engage in discussion and activity on a particular subject, product or service to gain hands-on experience.
https://iexcloud.io/docs/api/#workshops
Args:
symbol (str): symbol to use
"""
... | 7f6417acecdd7a2bd7279e5d0367894458589241 | 3,641,206 |
def free_path(temp, diff, m_mol):
"""
Calculates the free path for a molecule
Based on free_path.m by Joni Kalliokoski 2014-08-13
:param temp: temperature (K)
:param diff: diffusion coefficient (m^2/s)
:param m_mol: molar mass (kg/mol)
:return: free path (m)
"""
return 3*diff*np.sqrt... | 053a2af667e1e9ecc85f1ea6ca898c80e14ec81f | 3,641,207 |
def comp_periodicity_spatial(self):
"""Compute the (anti)-periodicities of the machine in space domain
Parameters
----------
self : Machine
A Machine object
Returns
-------
pera : int
Number of spatial periodicities of the machine over 2*pi
is_apera : bool
True ... | b34a50f0df0bc1bfd3ffaddb5e8a57780e50a6b8 | 3,641,208 |
import torch
def shuffle_tensor(input):
"""
Returns a new tensor whose elements correspond to a randomly shuffled version of the the elements of the input.
Args:
input (`torch.Tensor`): input tensor.
Returns:
(`torch.Tensor`): output tensor.
"""
return input[torch.randperm(in... | e7c3ff4180123de1fe6322296ba08863de9766a4 | 3,641,209 |
def relaunch_failed_jobs(tasks, spec_file, verbose=False):
""" Relaunch jobs that are failed from the given list """
job_cnts = 0 # number of newly launched jobs
for i, task in enumerate(tasks):
job_id = str(task[-1]) # the last entry
# Try to launch until succeed
while True:
... | d78c250e1c6f10c60bb81aea077063f6f5b15b12 | 3,641,210 |
def intensityTriWave(coeff,L,ang):
"""Simulate the intensity observed a distance L from
the grating. Standard Zernike coefficients, L, and
the diffraction angle ang are used as input.
"""
k = 2*np.pi/405.e-6 #blue wavevector
x,y = np.meshgrid(np.linspace(-1.1,1.1,1000),np.linspace(-1.1,1.1,1000)... | 3b85a0d437fce65d8f164b31a3fc2e85fca33006 | 3,641,211 |
import requests
import time
import ast
def do_auth_code_grant(fqdn, force_login=False, identity=None):
"""Perform an Oauth2 authorization grant consent flow."""
code_verifier, code_challenge = _gen_code()
scope = (SCOPE_FORMAT.format(fqdn=fqdn))
host = GLOBUS_AUTH_HOST
creds = _lookup_credentia... | 0e5583d1d6a273e165f0d8d9bed82e3c9af491cd | 3,641,212 |
import json
def decode(serialized: str) -> Node:
"""Decode JSON as a `Node`"""
node = json.loads(serialized)
return dict_decode(node) if isinstance(node, dict) else node | b608b6c18c09d7061e09d722445ca1f50fd78b3f | 3,641,213 |
def validate_duration_unit(recv_duration_unit):
"""Decapitalize and check in units_list"""
units_list = DaysAndUnitsList.units_list
recv_duration_unit = recv_duration_unit.lower()
if recv_duration_unit in units_list:
return True
else:
return False | 784693ea8106c601b884a729ad2afd2a75b94ba2 | 3,641,214 |
def make_word_list1():
"""Reads lines from a file and builds a list using append."""
t = []
fin = open('words.txt')
for line in fin:
word = line.strip()
t.append(word)
return t | 7af7b0697557e8bba891d73bd8217860350b810e | 3,641,215 |
import logging
import json
import os
def create_app(environment: str = None):
"""Create the Flask application.
Returns:
obj: The configured Flask application context.
"""
app = Flask(__name__)
if environment is None:
app.config.from_object(ConfigurationFactory.from_env())
el... | 07b6e899f6992008f072040d445abfb339f1c9a4 | 3,641,216 |
def metropolis(data, likelihood, priors, samples=1000, par_init=None,
width_prop=.5):
"""
Returns the posterior function of the parameters given the likelihood and
the prior functions. Returns also the number of the accepted jumps in the
Metropolis-Hastings algorithm.
Notes:
- <w... | 3857e237390a8373eecbc575209e96d42b6ff614 | 3,641,217 |
def _get_single_spec_df(reference_dict, mapping_dict, spectrum):
"""Primary method for reading and storing information from a single spectrum.
Args:
reference_dict (dict): dict with reference columns to be filled in
mapping_dict (dict): mapping of engine level column names to ursgal unified col... | 3d286e9bc206c0b59364cf9ef6d861b5cde9e9d4 | 3,641,218 |
import re
def in2func(inp):
"""Function converts input expression to a mathematical expression."""
# Validate Function
if inp == "":
raise ValueError( f"Enter a function to plot!")
for char in re.findall("[a-zA-Z_]+", inp):
if char not in allowed_inputs:
# Error will commun... | d3bf2faaed00f7b57c5bcd5b2681c94846671793 | 3,641,219 |
from datetime import datetime
def filter_posts(posts: list, parsing_date: datetime) -> list:
"""Отфильтровывает лишние посты, которые не входят в месяц парсинга"""
res = []
for post in posts:
post_date = datetime.fromtimestamp(post['date'])
if post_date.month == parsing_date.month:
... | 381d5cb37e4ae3439c335a7962352431ad3ca17c | 3,641,220 |
import requests
import re
def parse_bing():
"""
解析bing网页的壁纸链接,采用正则表达式匹配
:return: IMG_info,IMG_url
"""
base_url = 'https://cn.bing.com/'
language_parameter = '?mtk=zh-CN'
# base_url = 'https://www.bing.com/?mkt=zh-CN'
try:
resp = requests.get(base_url+language_parameter, headers... | 4a963514f385a931882a75f45be774cbab4428ff | 3,641,221 |
def quadsum(*args, **kwargs):
"""Sum of array elements in quadrature.
This function is identical to numpy.sum except that array elements are
squared before summing and then the sqrt of the resulting sums is returned.
The docstring from numpy.sum is reproduced below for convenience (copied
2014-12-... | ef842dab6258dc46b84098098115151a240f767b | 3,641,222 |
import codecs
def open_file(path):
"""open_file."""
return codecs.open(path, encoding='utf8').read() | f7fd375ea76e8e7872e465e89eea5c02f3396115 | 3,641,223 |
def get_api_status():
"""Get API status"""
return "<h4>API Is Up</h4>" | 5c88fc39bc5a970c4d223d8fe87c4fa3ad473b50 | 3,641,224 |
import os
import shutil
def kmeans_anchors(train_path='../datasets/ego-hand/train.txt', k_clusters=9, img_size=416, save_path=None):
"""Generate anchors for the dataset.
Normalised labels: cls id, center x, center y, width, height
"""
# Get paths of training images and labels
ann_paths = []
t... | 7fa736435b4ee444de976ff969e29e4684d735fc | 3,641,225 |
def fgt_set_pressureUnit(pressure_index, unit):
"""Override the default pressure unit for a single pressure channel"""
unit_array = (c_char * (len(unit)+1))(*([c_char_converter(c) for c in unit]))
c_error = c_ubyte(lib.fgt_set_pressureUnit(c_uint(pressure_index), unit_array))
return c_error.value, | 8b7b75ffc598f70e7bbf3e1742a7837bf71f474f | 3,641,226 |
import os
import pkgutil
def get_standard_dev_pkgs() -> set[str]:
"""Check the standard dev package locations for hutch-python"""
pythonpath = os.environ.get('PYTHONPATH', '')
if not pythonpath:
return set()
paths = pythonpath.split(os.pathsep)
valid_paths = filter(not_ignored, paths)
... | b4f6c37b6a12bc36d5d9a6230d8d2c3a67f96b80 | 3,641,227 |
def create_alert_from_slack_message(payload, time):
"""
Create a new raw alert (json) from the new alert form in Slack
"""
alert_json = {}
values = payload['view']['state']['values']
for value in values:
for key in values[value]:
if key == 'severity':
alert_js... | 1ae8b93a6b9f8bd7532ac193cb6dfde58bf8d409 | 3,641,228 |
def psd(buf_in, buf_out):
"""
Perform discrete fourier transforms using the FFTW library and use it to
get the power spectral density. FFTW optimizes
the fft algorithm based on the size of the arrays, with SIMD parallelized
commands. This optimization requires initialization, so this is a factory
... | 9573935fd0e80e3e1a53237334a46f21d94984ab | 3,641,229 |
def get_cell_ids(num_celltypes=39):
"""get valid cell ids by removing cell types with missing data.
Return:
A cell id list.
"""
missing_ids = [8,23,25,30,32,33,34,35,38,39,17]
return [item for item in list(range(1,num_celltypes+1)) if item not in missing_ids] | a7c8f881ad62af9c4287cd50b9b01118f724c4f8 | 3,641,230 |
def limit_data():
"""Slice data by dolphot values and recovered stars in two filters"""
fmt = '{:s}_{:s}'
filter1, filter2 = filters.value.split(',')
selected = data[
(np.abs(data[fmt.format(filter1, 'VEGA')]) <= 60) &
(np.abs(data[fmt.format(filter2, 'VEGA')]) <= 60) &
(data[fmt... | 785d027c13a05b97f2b98526dd0762e95e4e0fd6 | 3,641,231 |
import os
import re
import glob
def purge_versions(path, suffix, num_keep, reverse=False):
"""
Purge file versions created by get_versioned_path.
Purge specified quantity in normal or reverse sequence.
"""
(base, ext) = os.path.splitext(path)
re_strip_version = re.compile('(.*)-%s(-[0-9]*)?' ... | bf3c99b4a4dae596fec795f435387269bdfa9261 | 3,641,232 |
from typing import Dict
from typing import Optional
from typing import Callable
def make_valance_getter(
lexicon: Dict[str, float],
lemmatize: bool = True,
lowercase: bool = True,
cap_differential: Optional[float] = C_INCR,
) -> Callable[[Token], float]:
"""Creates a token getter which return the ... | 825e8bf624240e3628537dbcfc6a09af2d54cd83 | 3,641,233 |
import re
def proper_units(text: str) -> str:
"""
Function for changing units to a better form.
Args:
text (str): text to check.
Returns:
str: reformatted text with better units.
"""
conv = {
r"degK": r"K",
r"degC": r"$^{\circ}$C",
r"degrees\_celsius":... | 5113d227db1a75ec8fa407c5f9edd5a897960d82 | 3,641,234 |
import re
from datetime import datetime
def coerce_number(value, convert = float):
""" 将数据库字段类型转为数值类型 """
pattern = re.compile(r'^\d{4}(-\d\d){2}')
format = '%Y-%m-%d %H:%M:%S'
if isinstance(value, basestring) and pattern.match(value):
#将字符串的日期时间先转为对象
try:
mask = format[:le... | a36b3b8e814d722d6814a3306c692a8c7cbe28a5 | 3,641,235 |
def create_credential_resolver():
"""Create a credentials resolver for Localstack."""
env_provider = botocore.credentials.EnvProvider()
default = DefaultCredentialProvider()
resolver = botocore.credentials.CredentialResolver(
providers=[env_provider, default]
)
return resolver | 36426521d5928aec1cb7c01308afe3d60c3f9959 | 3,641,236 |
def does_algorithm_implementation_have_capabilities_to_execute_parameter(parameter_kisao_id, algorithm_specs):
""" Determine if an implementation of an algorithm has the capabilities to execute a model langugae
Args:
parameter_kisao_id (:obj:`str`): KiSAO id for an algorithm parameter
algorithm... | 653712ae621bd014547e04009243cefe4c9eb8e1 | 3,641,237 |
def main():
"""
This method allows the script to be run in stand alone mode.
@return Exit code from running the script
"""
record = Record()
result = record.Run()
return result | 5460a32b9202c133da9ca109f5f2784fe21d7ee2 | 3,641,238 |
def stamp_pixcov_from_theory(N,cmb2d_TEB,n2d_IQU=0.,beam2d=1.,iau=False,return_pow=False):
"""Return the pixel covariance for a stamp N pixels across given the 2D IQU CMB power spectrum,
2D beam template and 2D IQU noise power spectrum.
"""
n2d = n2d_IQU
cmb2d = cmb2d_TEB
assert cmb2d.ndim==4
... | 1ad8d5c2925f5e7ab5636348cbedbed1383c2963 | 3,641,239 |
def make_data_parallel(module, expose_methods=None):
"""Wraps `nn.Module object` into `nn.DataParallel` and links methods whose name is listed in `expose_methods`
"""
dp_module = nn.DataParallel(module)
if expose_methods is None:
if hasattr(module, 'expose_methods'):
expose_methods ... | 9992b8980f2cdec22e13f6805b4d02d3694c4b4a | 3,641,240 |
def model_creator(model_dict, X_train, y_train, rd=None, rev=None):
"""Returns a SVM classifier"""
# Load model based on model_dict
clf = model_loader(model_dict, rd, rev)
# If model does not exist, train a new SVM
if clf is None:
clf = model_trainer(model_dict, X_train, y_train, rd, rev)
... | 6f962c898167d1466b80a074aa7289ff26b0c3e2 | 3,641,241 |
import torch
def bert_predict(model, loader):
"""Perform a forward pass on the trained BERT model to predict probabilities
on the test set.
"""
# Put the model into the evaluation mode. The dropout layers are disabled during
# the test time.
model.eval()
all_logits = []
# For each ba... | 602e219ce3fbed8afb86d11daf06ab09efe9c1b3 | 3,641,242 |
def eval_input_fn(training_dir, params):
"""Returns input function that feeds the model during evaluation"""
return _input_fn('eval') | 0bb40833dee0e7564d166b7aabb27a54d61cdf2d | 3,641,243 |
def GNIs(features, labels, mode, params, config):
"""Builds the model function for use in an estimator.
Arguments:
features: The input features for the estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionary.... | 724b32981a3b79c6725e4a7c6add9ab0f5046647 | 3,641,244 |
def b58decode(v, length):
""" decode v into a string of len bytes
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += __b58chars.find(c) * (__b58base**i)
result = ''
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + result
... | 3a9d1d5da02c2174bcf0220de705a92a91cd0b18 | 3,641,245 |
import os
import sys
import json
def create_sample_meta_info(args):
"""
Load and parse samples json for templating
"""
if not os.path.exists(args.samples_json):
print('could not find file: {}!'.format(args.samples_json))
sys.exit(1)
sample_info = json.load(open(args.samples_json))... | ed12624f608125d70897954357804f6c6cc099e8 | 3,641,246 |
def has_remove_arg(args):
"""
Checks if remove argument exists
:param args: Argument list
:return: True if remove argument is found, False otherwise
"""
if "remove" in args:
return True
return False | 9b07fe70cecfbdf6e6e2274e5b3e715f903331c7 | 3,641,247 |
def supported_locales(prefix, parsed_args, **kwargs):
"""
Returns all supported locales.
:param prefix: The prefix text of the last word before the cursor on the command line.
:param parsed_args: The result of argument parsing so far.
:param kwargs: keyword arguments.
:returns list: list of all... | db6f73699120dc4b784b1f46ed7c9fbe4a3cc9a9 | 3,641,248 |
def generate_tool_panel_dict_for_tool_config( guid, tool_config, tool_sections=None ):
"""
Create a dictionary of the following type for a single tool config file name. The intent is to call this method for every tool config
in a repository and append each of these as entries to a tool panel dictionary for... | 8e976cf4d54212d0477ef4ae7d4fb1dd532363fa | 3,641,249 |
def get_tmp_dir():
"""get or create the tmp dir corresponding to each process"""
tmp_dir = result_dir / "tmp"
tmp_dir.mkdir(exist_ok=True)
return tmp_dir | 406962c5783dff1d23523bd5bd258b7bb18ed149 | 3,641,250 |
def get_logs(job_id, user, index):
"""get logs"""
return instance().get_logs(job_id=job_id,
user=user,
log_index=int(index)) | f2d959835c34ffec475d5e9da18e74feef13b5d9 | 3,641,251 |
def repeat_as_list(x: TensorType, n: int):
"""
:param x: Array/Tensor to be repeated
:param n: Integer with the number of repetitions
:return: List of n repetitions of Tensor x
"""
return [x for _ in range(n)] | cb4924909d93899a555c11bd70950c6cbb77cf85 | 3,641,252 |
def transition(x, concat_axis, nb_filter, dropout_rate=None, weight_decay=1E-4):
"""Apply BatchNorm, Relu 1x1Conv2D, optional dropout and Maxpooling2D
:parameter x: keras model
:parameter concat_axis: int -- index of contatenate axis
:parameter nb_filter: int -- number of filters
:parameter dropout... | 30d89aca3a330dc6b04b4c9ee21a8620c8ba69f1 | 3,641,253 |
def _bug_data_diff_plot(
project_name: str, project_repo: pygit2.Repository,
bugs_left: tp.FrozenSet[PygitBug], bugs_right: tp.FrozenSet[PygitBug]
) -> gob.Figure:
"""Creates a chord diagram representing the diff between two sets of bugs as
relation between introducing/fixing commits."""
commits_to_... | c41684a622e3ff5dc0a43ba49a2e4186073a40e3 | 3,641,254 |
import torch
def scale_params(cfg):
"""
Scale:
* learning rate,
* weight decay,
* box_loss_gain,
* cls_loss_gain,
* obj_loss_gain
according to:
* effective batch size
* DDP world size
* image size
* num YOLO output layers
* nu... | a74472a5c5ce2a6b83eab0467c66b468226c222d | 3,641,255 |
def get_model(args):
"""
Load model and move tensors to a given devices.
"""
if args.model == "lstm":
model = LSTM(args)
if args.model == "lstmattn":
model = LSTMATTN(args)
if args.model == "bert":
model = Bert(args)
if args.model == "lqt":
model = LastQuery(a... | 131a4e3d8832d9b0aa099c55f7a8851d3a8907ef | 3,641,256 |
def convert_to_boolean(value):
"""Turn strings to bools if they look like them
Truthy things should be True
>>> for truthy in ['true', 'on', 'yes', '1']:
... assert convert_to_boolean(truthy) == True
Falsey things should be False
>>> for falsey in ['false', 'off', 'no', '0']:
... asser... | 7cbf7a8fd601904c7aa8b685f6a3b3f5eaaa5c51 | 3,641,257 |
def getSampleBandPoints(image, region, **kwargs):
"""
Function to perform sampling of an image over a given region, using ee.Image.samp;e(image, region, **kwargs)
Args:
image (ee.Image): an image to sample
region (ee.Geometry): the geometry over which to sample
Returns:
An ee.F... | 4cfbc3c180b805abe52c718f81cc16c409693922 | 3,641,258 |
def updateRIPCount(idx,RIPtracker,addRev=0,addFwd=0,addNonRIP=0):
"""Add observed RIP events to tracker by row."""
TallyRev = RIPtracker[idx].revRIPcount + addRev
TallyFwd = RIPtracker[idx].RIPcount + addFwd
TallyNonRIP = RIPtracker[idx].nonRIPcount + addNonRIP
RIPtracker[idx] = RIPtracker[idx]._replace(revRIPcoun... | 7f83c547d9acd6c697174fffa1ccb3aec6e91a24 | 3,641,259 |
def serialize(obj):
""" Return a JSON-serializable representation of an object """
cls = obj.__class__
cls_name = cls.__name__
module_name = cls.__module__
serializer = None
if hasattr(obj, "to_serializable"):
# The object implements its own serialization
s = obj.to_serializable(... | 3fd5449922808a1e1772b3937bca6736c63df9a2 | 3,641,260 |
def download_file(url, offset=0, filename='tmp', verbosity=True):
"""
Intended for simulating the wget linux command
:param url: The URL for the resource to be downloaded
:param offset: Number of bytes to be skipped
:param filename: Name of file where the content downloaded will be stored
:param... | dd9a3a3c0b0e1b96d39d5929adce53f8f0c8e5c2 | 3,641,261 |
async def async_unload_entry(hass, config_entry):
"""Unload a config entry."""
controller_id = CONTROLLER_ID.format(
host=config_entry.data[CONF_CONTROLLER][CONF_HOST],
site=config_entry.data[CONF_CONTROLLER][CONF_SITE_ID]
)
controller = hass.data[DOMAIN].pop(controller_id)
return aw... | 2341f49794ecd9f9824330594cf3955bca117455 | 3,641,262 |
from collections import OrderedDict
import astropy.io.fits as pyfits
from .. import utils
import os
def convert_1D_to_lists(file='j234420m4245_00615.1D.fits'):
"""
Convert 1D spectral data to lists suitable for putting into dataframes
and sending to the databases.
"""
if not os.path.exists(file):... | b507da9251e59e024c6f631aa412778f278afc4f | 3,641,263 |
import operator
def get_farthest_three_shots(gps_shots):
"""get three shots with gps that are most far apart"""
areas = {}
for (i, j, k) in combinations(gps_shots, 3):
areas[(i, j, k)] = area(np.array(i.metadata.gps_position), np.array(j.metadata.gps_position), np.array(k.metadata.gps_position))
... | 697d87549bee0a8ff3adee30ceb7b41a24f3d66b | 3,641,264 |
from operator import sub
def __parse_entry(entry_line):
"""Parse the SOFT file entry name line that starts with '^', '!' or '#'.
:param entry_line: str -- line from SOFT file
:returns: tuple -- type, value
"""
if entry_line.startswith("!"):
entry_line = sub(r"!\w*?_", '', entry_line)
... | 1a645cb4dcaafaa4de1db7011d3ff54931b8123f | 3,641,265 |
def _mut_insert_is_applied(original, mutated):
""" Checks if mutation was caused by `mut_insert`.
:param original: the pre-mutation individual
:param mutated: the post-mutation individual
:return: (bool, str). If mutation was caused by function, True. False otherwise.
str is a message explaini... | f19bb092e1eefc14435f5bb90a030558980fed4c | 3,641,266 |
from typing import Dict
from typing import Any
def remap_ids(
mapping_table: Dict[Any, int] = {}, default: int = 0, dtype: DTypes = "i"
) -> Model[InT, OutT]:
"""Remap string or integer inputs using a mapping table, usually as a
preprocess before embeddings. The mapping table can be passed in on input,
... | 4380b9377930d6affac6703a0a1e656a916b45db | 3,641,267 |
def get_text(cell):
""" get stripped text from a BeautifulSoup td object"""
return ''.join([x.strip() + ' ' for x in cell.findAll(text=True)]).strip() | 08037cbe5d2058206de029417f03d211d350820f | 3,641,268 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--dataset', dest='dataset',
help='training dataset',
default='pascal_voc', type=str)
parser.add_argument('--net', dest='net',
... | 03ae21f2150fb309bcf49587588dbfa7496e91a8 | 3,641,269 |
import torch
def test_augmentation(text, text_lengths, augmentation_class):
"""
test_augmentation method is written for augment input text in evaluation
:param text: input text
:param text_lengths: text length
:param augmentation_class: augmentation class
:return:
"""
augmentation_tex... | 2f83ec9fa0afa110d05f05f52e85cae65a28c6f9 | 3,641,270 |
def selfintersection(linear_ring: Points):
"""
not support warp polygon.
"""
validate.linear_ring(linear_ring)
if len(linear_ring) == 4:
return (
abs(
linear_ring[0][1] * (linear_ring[1][0] - linear_ring[2][0])
+ linear_ring[1][1] * (linear_ring[2]... | d0b92d7796a3281a4481071f0b0666fdf79c6952 | 3,641,271 |
import math
def ToMercPosition(lat_deg, num_tiles):
"""Calculate position of a given latitude on qt grid.
LOD is log2(num_tiles)
Args:
lat_deg: (float) Latitude in degrees.
num_tiles: (integer) Number of tiles in the qt grid.
Returns:
Floating point position of latitude in tiles relative to equat... | 1ae7e7b2da9ec3ee20756ef7ffa13d99485aaea7 | 3,641,272 |
def conv3x3(in_planes, out_planes, stride=1, dilation=1, groups=1, bias=False):
"""2D 3x3 convolution.
Args:
in_planes (int): number of input channels.
out_planes (int): number of output channels.
stride (int): stride of the operation.
dilation (int): dilation rate of the operation.
... | d5658d81f5fbc5d196418e4e4b005dbf7d3f20ae | 3,641,273 |
import re
def extract_current_alarm(strValue):
"""抽取show alarm current命令的信息
Args:
strValue (str): show alarm current显示的信息
Returns:
list: 包含信息的字典
"""
# TODO: FIXME: 抽取告警信息没有实现
titleExpr = re.compile('\s*(Item Description)\s+(Code vOLT)\s+(Object)\s+(Begintime)\s+(Endtime)\s*'... | 656acd8e25af509594ae28b89110508bc7a17fcd | 3,641,274 |
def parse_hostnames(filename, hostnames):
"""Parses host names from a comma-separated list or a filename.
Fails if neither filename nor hostnames provided.
:param filename: filename with host names (one per line)
:type filename: string
:param hostnames: comma-separated list of host names
:type hostnames: ... | b3fce0f3af7f59217fd18bfce53baec87784759f | 3,641,275 |
def ssh(host, command, stdin=None):
"""Run 'command' (list) on 'host' via ssh.
stdin is an string to send."""
return run([*SSH_COMMAND, ssh_user_host(host), *command], stdin=stdin) | 9719aef39530e285d27a2e9dd5a7ceab09f3793e | 3,641,276 |
import six
import os
def _bgzip_file(finput, config, work_dir, needs_bgzip, needs_gunzip, needs_convert, data):
"""Handle bgzip of input file, potentially gunzipping an existing file.
Handles cases where finput might be multiple files and need to be concatenated.
"""
if isinstance(finput, six.string_... | 7a5b30a1352c570fb4c7fedaafc916c1e185f5ae | 3,641,277 |
def cart_step1_choose_type_of_order(request):
"""
This view is not login required because we want to display some summary of
ticket prices here as well.
"""
special_fares = get_available_fares_for_type(TicketType.other)
context = {"show_special": bool(special_fares)}
return TemplateResponse(... | 869941df96c750c0049f6ab5e50e5fad17679af2 | 3,641,278 |
def buildAndTrainModel(model, learningRate, batchSize, epochs, trainingData, validationData, testingData, trainingLabels, validationLabels, testingLabels, MODEL_NAME, isPrintModel=True):
"""Take the model and model parameters, build and train the model"""
# Build and compile model
# To use other optimi... | 9e9170ccb817be6ec3908c16390d1afe4f96b2e7 | 3,641,279 |
def vflip():
"""Toggle vertical flipping of camera image."""
# Catch ajax request with form data
vflip_val = 'error'
if request.method == 'POST':
vflip_val = request.form.get('vflip')
if vflip_val is not None:
app.logger.info('Form brightness submitted: %s', vflip_val)
... | 064280aadbdc53783d983caa66a52d294732be9e | 3,641,280 |
def getGoalHistogramData(responses):
"""
Goal Completion histogram chart on project detail page.
Return: {obj} Counts and % of each Goal Completion rating across given responses.
"""
try:
snapshotResponses = responses.exclude(Q(primary_goal__isnull=True) | Q(primary_goal__name=''))
respsnapshotResponsesCount =... | 782c911f1a751ccf4c441874520f0cbc66b4a89c | 3,641,281 |
def hookes_law(receiver_nodes, sender_nodes, k, x_rest):
"""Applies Hooke's law to springs connecting some nodes.
Args:
receiver_nodes: Ex5 tf.Tensor of [x, y, v_x, v_y, is_fixed] features for the
receiver node of each edge.
sender_nodes: Ex5 tf.Tensor of [x, y, v_x, v_y, is_fixed] features... | 30182ed5e91e07affa4db117c9e24a9cf76e3646 | 3,641,282 |
def check_output_filepath(filepath):
"""
Check and return an appropriate output_filepath parameter.
Ensures the file is a csv file. Ensures a value is set. If
a value is not set or is not a csv, it will return a
default value.
:param filepath: string filepath name
:returns: a string re... | 63fcf697dbde9a62cc39311b4d234955520f6394 | 3,641,283 |
import re
def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None):
"""Open local files instead of URLs.
If it's a local file path, leave it alone; otherwise,
open as a file under ./files/
This is meant as a side effect for unittest.mock.Mock
"""
if re.match... | 28705c7d1785853f99d544967e745a12a58321f0 | 3,641,284 |
def concat_chunked_data(jsons, f_src='c', *args, **kwargs):
"""
Takes chunks of data and combines them into a numpy array
of shape trial x cells x time, concatendated over trials, and
clips the trials at shortest frame number and fewest cells. Args and
kwargs are passed to process_data.
Args:
... | cfd978a1ac74d35d857e152e6051e88b05ccf495 | 3,641,285 |
def hmc_update(context, hmc_uuid, values, session=None):
"""Updates an existing HMC instance in the Database"""
return IMPL.hmc_update(context, hmc_uuid, values, session) | 943dd2359b2458429d60bb8c68ee20c40651b8fe | 3,641,286 |
def _dense_difference(fun, x0, f0, h, one_sided, method):
"""
Calculates an approximation of the Jacobian of `fun`at the point `x0` in dense matrix form.
NOTE: Inspired from: https://github.com/scipy/scipy/blob/master/scipy/optimize/_numdiff.py
Parameters
----------
fun : callable
Func... | 47d840a70fe2b8d22bf9fec4fdbb0e5190dec2f2 | 3,641,287 |
def alternate( name, *functions ):
"""Construct a callable that functions as the first implementation found of given set of alternatives
if name is a function then its name will be used....
"""
if not isinstance( name, (bytes,unicode)):
functions = (name,)+functions
name = name.__name__... | 5e751a5332c3e8e9e37f5544e9461c772bc525ac | 3,641,288 |
from typing import Optional
from typing import Callable
def check_messenger(messenger: Optional[Callable]):
"""
Check that `messenger` is a `utipy.Messenger` object or `None`.
In the latter case a `utipy.Messenger` with `verbose=False` is returned.
Parameters
----------
messenger : `utipy.M... | b50bc38d5034e3d4d4d35d4532a504024008361f | 3,641,289 |
import re
def convert(s):
"""Take an input string s, find all things that look like SGML character
entities, and replace them with the Unicode equivalent.
Function is from:
http://stackoverflow.com/questions/1197981/convert-html-entities-to-ascii-in-python/1582036#1582036
"""
matches = re.findal... | 0a25ee189ff107e5cd725bba1d1d20d6cb1c0f0c | 3,641,290 |
def check_data_selection(race_id=None, category_index=None, racer_id=None):
"""Makes sure that we are trying to show data that is in the database."""
errors = []
if not race_id in Races.get_column('race_id'):
race_id = Races.get_random_id()
errors.append('race')
categories = Races.get_c... | 6d5b4eeaf1149fdac76e83bb94a6b6d482d0d280 | 3,641,291 |
from typing import List
def request_access_ticket(pat: str, permission_endpoint: str,
resources: List[dict],
secure: bool = False) -> str:
"""
As a Resource Server, request permission to the AS to access a resource,
generating a ticket as a result.
- CA... | ae032fc67c1aed0bd52b808e4d922992aed39ba6 | 3,641,292 |
def index(request):
"""
Root page view. Just shows a list of liveblogs.
"""
# Get a list of liveblogs, ordered by the date of their most recent
# post, descending (so ones with stuff happening are at the top)
liveblogs = Liveblog.objects.annotate(
max_created=Max("posts__created")
).... | 518c64db21bd843dc34513c4d5677a18e5eac319 | 3,641,293 |
def model_fn_builder(
bert_config,
num_labels,
init_checkpoint,
learning_rate,
num_train_steps,
num_warmup_steps,
use_tpu,
use_one_hot_embeddings
):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
... | 088e636bf21caa316995dbd69b680dedd42ca21a | 3,641,294 |
def strarray(*args):
"""strarray(strarray_t array, size_t array_size, int code) -> char"""
return _idaapi.strarray(*args) | 9dfb42d81d307a32f201f1b55a1ef81cbede7c27 | 3,641,295 |
def _single_value_set(target_list, value):
"""
Return true if this constraint has only one value and it is
this one.
"""
return len(target_list) == 1 and target_list[0] == value | 472ebe1aa9726c70642423d05fa55723496e9bc5 | 3,641,296 |
def get_positive_input(message, float_parse=False, allow_zero=False):
""" Obtains and returns a positive int from the user.
Preconditions:
message: non-empty string
float_parse: bool defaulted to False
allow_zero: bool defaulted to False
Parameters:
message: The message that is printed whe... | 17982ff069907464c70df7b6efb1f42d3811962e | 3,641,297 |
def hellinger(p, q):
"""Compute Hellinger distance between 2 distributions."""
return np.linalg.norm(np.sqrt(p) - np.sqrt(q)) / np.sqrt(2) | f976a96af2e4acaf81961b93f2cfe7a868d912e3 | 3,641,298 |
def usd_currency(currency_df: pd.DataFrame, value: int, date: str) -> float:
"""
Compute VALUE/(USD/SYMBOL)
Parameters
----------
currency_df : pd.DataFrame
USD/SYMBOL df
value : int
Value of product
date : str
Currency quote day
Returns
---------
float
... | 15ce0d8f9db3b5dc1e1a684dc27daa63d163853b | 3,641,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.