content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def canonicalize_path(cwd, path, debug):
"""Given a path composed by concatenating two or more parts,
clean up and canonicalize the path."""
# // => /
# foo/bar/../whatever => foo/whatever [done]
# foo/bar/./whatever => foo/whatever [done]
# /foo/bar => /foo/bar [done]
# foo/bar... | f8714f93106dcb3330c2f0df635aae5975f68abf | 3,646,500 |
import click
import functools
import sys
def context_command(func):
"""
Base options for jobs that can override context variables on the command
line.
The command receives a *context_overrides* argument, a dict ready to be
deep merged in templates contexts.
"""
@click.option('--context',... | b140411121b814a732f6988be77c607811a148c6 | 3,646,501 |
def checksum(number):
"""Calculate the checksum. A valid number should have a checksum of 1."""
check = 0
for n in number:
check = (2 * check + int(10 if n == 'X' else n)) % 11
return check | 8ada40ca46bc62bbe8f96d69528f2cd88021ad6a | 3,646,502 |
def instanceof(value, type_):
"""Check if `value` is an instance of `type_`.
:param value: an object
:param type_: a type
"""
return isinstance(value, type_) | 3de366c64cd2b4fe065f15de10b1e6ac9132468e | 3,646,503 |
def step(y, t, dt):
""" RK2 method integration"""
n = y.shape[0]
buf_f0 = np.zeros((n, ndim+1))
buf_f1 = np.zeros((n, ndim+1))
buf_y1 = np.zeros((n, ndim+1))
buf_f0 = tendencies(y)
buf_y1 = y + dt * buf_f0
buf_f1 = tendencies(buf_y1)
Y = y + 0.5 * (buf_f0 + buf_f1) * dt
retu... | e3c946b37d96ad0083fc5cc7a8d84b2f03ca897b | 3,646,504 |
import torch
import gc
def sample_deletes(graph_, rgb_img_features, xyz,
delete_scores, num_deletes, threshold,
gc_neighbor_dist, padding_config,
**kwargs):
"""Sample Deletes.
Args:
graph_: a torch_geometric.data.Batch instance with attributes... | 3a24d3806e3e7aebf5ae6d2c7141149358d21607 | 3,646,505 |
def make_char(hex_val):
"""
Create a unicode character from a hex value
:param hex_val: Hex value of the character.
:return: Unicode character corresponding to the value.
"""
try:
return unichr(hex_val)
except NameError:
return chr(hex_val) | edbbad92c56ec74ff28295c46dca4f2976768d0a | 3,646,506 |
def normalize(features):
"""
Normalizes data using means and stddevs
"""
means, stddevs = compute_moments(features)
normalized = (np.divide(features, 255) - means) / stddevs
return normalized | 3b4c07bf80e68ec3d6c807a9293aa5b4f4203401 | 3,646,507 |
def get_args_from_str(input: str) -> list:
"""
Get arguments from an input string.
Args:
input (`str`): The string to process.
Returns:
A list of arguments.
"""
return ARG_PARSE_REGEX.findall(input) | 50de69e4ee60da31a219842ce09833a92218ea14 | 3,646,508 |
import os
def get_all_files(repo_root):
"""Get all files from in this repo."""
output = []
for root, _, files in os.walk(repo_root):
for f in files:
if f.lower().endswith(tuple(CPP_SUFFIXES + ['.py'])):
full_name = os.path.join(root, f)[len(repo_root) + 1:]
... | 3a7cfcba087df93be74dd064d92f679cc987b714 | 3,646,509 |
from typing import List
def simulate(school: List[int], days: int) -> int:
"""Simulates a school of fish for ``days`` and returns the number of fish."""
school = flatten_school(school)
for day in range(1, days + 1):
school = simulate_day(school)
return sum(school) | efcfbfdde9c3fc941a40028459ddc35db0653296 | 3,646,510 |
import torch
def SPTU(input_a, input_b, n_channels: int):
"""Softplus Tanh Unit (SPTU)"""
in_act = input_a+input_b
t_act = torch.tanh(in_act[:, :n_channels, :])
s_act = torch.nn.functional.softplus(in_act[:, n_channels:, :])
acts = t_act * s_act
return acts | a03cc114cf960af750b13cd61db8f4d2e6c064ad | 3,646,511 |
def is_fouling_team_in_penalty(event):
"""Returns True if fouling team over the limit, else False"""
fouls_to_give_prior_to_foul = event.previous_event.fouls_to_give[event.team_id]
return fouls_to_give_prior_to_foul == 0 | ac1578af1092586a30b8fc9cdb3e5814da1f1544 | 3,646,512 |
import re
def is_img_id_valid(img_id):
"""
Checks if img_id is valid.
"""
t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE)
t = re.sub(r'\.+', '.', t)
if img_id != t or img_id.count(':') != 1:
return False
profile, base_name = img_id.split(':', 1)
if not profile or not ... | 749a8830d1a932465ca0c9c8c3a18032e2dc357e | 3,646,513 |
import warnings
def lmc(wave, tau_v=1, **kwargs):
""" Pei 1992 LMC extinction curve.
:param wave:
The wavelengths at which optical depth estimates are desired.
:param tau_v: (default: 1)
The optical depth at 5500\AA, used to normalize the
attenuation curve.
:returns tau:
... | 04c89605e8ad4188c62b631e173a9c8fe714958a | 3,646,514 |
def minMax(xs):
"""Calcule le minimum et le maximum d'un tableau de valeur xs (non-vide !)"""
min, max = xs[0], xs[0]
for x in xs[1:]:
if x < min:
min = x
elif x > max:
max = x
return min,max | 8453b71e5b62592f38f4be84f4366fb02bd0171b | 3,646,515 |
def events(request):
"""Events"""
# Get profile
profile = request.user.profile
# Get a QuerySet of events for this user
events = Event.objects.filter(user=request.user)
# Create a new paginator
paginator = Paginator(events, profile.entries_per_page)
# Make sure page request is an int,... | 3561856af65d2e54eb4f00a13ca85ece4c939b7a | 3,646,516 |
from typing import Tuple
from typing import Callable
def latent_posterior_factory(x: np.ndarray, y: np.ndarray) -> Tuple[Callable]:
"""Factory function that yields further functions to compute the log-posterior
of the stochastic volatility model given parameters `x`. The factory also
constructs functions ... | 0fe2ec7a7fab480fbe19a374e71ac3ab5232d8e0 | 3,646,517 |
def update_build_configuration_set(id, **kwargs):
"""
Update a BuildConfigurationSet
"""
data = update_build_configuration_set_raw(id, **kwargs)
if data:
return utils.format_json(data) | ee02faf0d683e271747d6e30a3ef8ffd9c271e6c | 3,646,518 |
from typing import Optional
def create_app(settings_override: Optional[dict]=None) -> Flask:
"""
Create a Flask app
:param settings_override: any settings to override
:return: flask app
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config.settings')
... | 2a4ee3b8f4f67db1966a678b6059b53aa21ac73f | 3,646,519 |
def compute_prefix_function(pattern):
"""
Computes the prefix array for KMP.
:param pattern:
:type pattern: str
:return:
"""
m = len(pattern)
prefixes = [0]*(m+1)
i = 0
for q in range(2, m + 1):
while i > 0 and pattern[i] != pattern[q - 1]:
i = prefixes[... | 7933cc33eba53247e858ae40b9691d101c7030e6 | 3,646,520 |
def binary_indicator(states,
actions,
rewards,
next_states,
contexts,
termination_epsilon=1e-4,
offset=0,
epsilon=1e-10,
state_indices=None,
... | 68531010c695e4bb8d49d05f5b0ba8799e1e3cf5 | 3,646,521 |
import math
def sigmoid(num):
"""
Find the sigmoid of a number.
:type number: number
:param number: The number to find the sigmoid of
:return: The result of the sigmoid
:rtype: number
>>> sigmoid(1)
0.7310585786300049
"""
# Return the calculated value
return... | 73730a39627317011d5625ab85c146b6bd7793d8 | 3,646,522 |
def list_lattices(device_name: str = None, num_qubits: int = None,
connection: ForestConnection = None):
"""
Query the Forest 2.0 server for its knowledge of lattices. Optionally filters by underlying
device name and lattice qubit count.
:return: A dictionary keyed on lattice names a... | a6fb4754f3f76135ed2083441782924f03160994 | 3,646,523 |
def inflate_tilegrid(
bmp_path=None,
target_size=(3, 3),
tile_size=None,
transparent_index=None,
bmp_obj=None,
bmp_palette=None,
):
"""
inflate a TileGrid of ``target_size`` in tiles from a 3x3 spritesheet by duplicating
the center rows and columns.
:param Optional[str] bmp_path... | b3c67c9aaa38cc77208f6fc7cafe91814a0fdbb4 | 3,646,524 |
def get_name_and_version(requirements_line: str) -> tuple[str, ...]:
"""Get the name a version of a package from a line in the requirement file."""
full_name, version = requirements_line.split(" ", 1)[0].split("==")
name_without_extras = full_name.split("[", 1)[0]
return name_without_extras, version | 424b3c3138ba223610fdfa1cfa6d415b8e31aff3 | 3,646,525 |
def _compute_eval_stats(params, batch,
model,
pad_id):
"""Computes pre-training task predictions and stats.
Args:
params: Model state (parameters).
batch: Current batch of examples.
model: The model itself. Flax separates model state and architecture.
... | cc7e9b48d6255c8f82ae2bff978c54631d246bda | 3,646,526 |
import locale
import itertools
def validateTextFile(fileWithPath):
"""
Test if a file is a plain text file and can be read
:param fileWithPath(str): File Path
:return:
"""
try:
file = open(fileWithPath, "r", encoding=locale.getpreferredencoding(), errors="strict")
# Read only a... | 22167a4501ca584061f1bddcc7738f00d4390085 | 3,646,527 |
from bs4 import BeautifulSoup
def get_title(filename="test.html"):
"""Read the specified file and load it into BeautifulSoup. Return the title tag
"""
with open(filename, "r") as my_file:
file_string = my_file.read()
file_soup = BeautifulSoup(file_string, 'html.parser')
#find all ... | 31c35588bb10132509a0d35b49a9b7eeed902018 | 3,646,528 |
import re
def is_valid_dump_key(dump_key):
"""
True if the `dump_key` is in the valid format of
"database_name/timestamp.dump"
"""
regexmatch = re.match(
r'^[\w-]+/\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}_\d+\.\w+\.dump$',
dump_key,
)
return regexmatch | 66fd7d465f641a96bd8b22e95918a6dcbefef658 | 3,646,529 |
import math
def GetProfileAtAngle( imdata, xc,yc, angle, radius, width=1 ):
"""
Returns a 1D profile cut through an image at specified angle, extending to
specified radius.
Note: this is designed to imitate pvect, so angles are measured CCW from +x axis!
This function uses IRAF coordinates (1... | 5c20ae064989251a807690e8f90f7156a6dbe642 | 3,646,530 |
import os
def create_out_dir_name(params):
"""
Create output directory name for the experiment based on the current date
and time.
Args:
params (dict): The parameters of the experiment.
Returns:
str: The path to the output directory.
"""
current_timestamp = timestamp()
... | 29700a90c780e9ed7e9f23b10f0fc66d1df03864 | 3,646,531 |
def extract_axon_and_myelin_masks_from_image_data(image_data):
"""
Returns the binary axon and myelin masks from the image data.
:param image_data: the image data that contains the 8-bit greyscale data, with over 200 (usually 255 if following
the ADS convention) being axons, 100 to 200 (usually 127 if f... | 087f80d4c55b7bbba7e60720be26ff3e3ca1648a | 3,646,532 |
def create_mne_array(recording, ch_names=None):
"""
Populate a full mne raw array object with information.
Parameters
----------
lfp_odict : bvmpc.lfp_odict.LfpODict
The lfp_odict object to convert to numpy data.
ch_names : List of str, Default None
Optional. What to name the mn... | f39a3e38174e0b915c55c4cf3ad4692fa38bca64 | 3,646,533 |
def expand_advanced(var, vars_, nounset, indirect, environ, var_symbol):
"""Expand substitution."""
if len(vars_) == 0:
raise MissingClosingBrace(var)
if vars_[0] == "-":
return expand_default(
var,
vars_[1:],
set_=False,
nounset=nounset,
... | 1be5d66c18775bca8669d97ccf8ccd439f154ff2 | 3,646,534 |
def overlap(n2, lamda_g, gama):
""" Calculates the 1/Aeff (M) from the gamma given.
The gamma is supposed to be measured at lamda_g
(in many cases we assume that is the same as where
the dispersion is measured at).
"""
M = gama / (n2*(2*pi/lamda_g))
return M | 00e1d59a6a8e5b908acfa3097cfb9818edaf608f | 3,646,535 |
def fill_none(pre_made_replays_list):
"""Fill none and reformat some fields in a pre-made replays list.
:param pre_made_replays_list: pre-made replays list from ballchasing.com.
:return: formatted list.
"""
for replay in pre_made_replays_list:
if replay["region"] is None:
replay... | ee900227a8afcba71e6a00ef475892da4fdc3e3b | 3,646,536 |
def parse_args_from_str(arg_str, arg_defs): # , context=None):
"""
Args:
args_str (str): argument string, optionally comma-separated
arg_defs (tuple): list of argument definitions
context (dict, optional):
When passed, the arguments are parsed for ``$(var_name)`` macros,
... | 1c21cf170c360c7b429b1303bd19e1a23ea5cd3c | 3,646,537 |
import torch
def model_evaluation(
data_loader,
ml_model_name,
ml_model,
smiles_dictionary,
max_length_smiles,
device_to_use,
):
"""
Evaluation per batch of a pytorch machine learning model.
Parameters
----------
data_loader : torch.utils.data
The training data as ... | 8c381eee394e989f8920cc52ad4b94ca4b502741 | 3,646,538 |
def reverse_dict2(d):
"""Reverses direction of dependence dict
>>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}
>>> reverse_dict(d) # doctest: +SKIP
{1: ('a',), 2: ('a', 'b'), 3: ('b',)}
:note: dict order are not deterministic. As we iterate on the
input dict, it make the output of this functio... | 2419538a13699015f8fefa156e89cf9b1960e358 | 3,646,539 |
import random
def Flip(p, y='Y', n='N'):
"""Returns y with probability p; otherwise n."""
return y if random.random() <= p else n | 072e170e3f37508a04f8bdbed22470b178f05ab9 | 3,646,540 |
import pylearn2.datasets.avicenna
def resolve_avicenna(d):
"""
.. todo::
WRITEME
"""
return pylearn2.config.checked_call(pylearn2.datasets.avicenna.Avicenna,d) | b15ef76cee9d71da26b84025d191aab43c95b297 | 3,646,541 |
def sub_to_db(sub,
add_area=True,
area_srid=3005,
wkt=True,
wkb=False,
as_multi=True,
to_disk=False,
procs=1,
engine=None):
"""
Convert the object to a SQLite database. Returns the |db| module exposin... | 6f3d3763a129a4235c0e5c0e884f7ab62bdfc391 | 3,646,542 |
def T_autoignition_methods(CASRN):
"""Return all methods available to obtain T_autoignition for the desired
chemical.
Parameters
----------
CASRN : str
CASRN, [-]
Returns
-------
methods : list[str]
Methods which can be used to obtain T_autoignition with the given input... | ab194547a1cc7b5eeb2032b1decad366bc4b43c2 | 3,646,543 |
import configparser
import os
def parse_config2(filename=None):
"""
https://docs.python.org/3.5/library/configparser.html
:param filename: filename to parse config
:return: config_parse result
"""
_config = configparser.ConfigParser(allow_no_value=True)
if filename:
# ConfigParse... | cf260f09e4c293915ab226b915aebed6cb98113f | 3,646,544 |
def masa(jd, place):
"""Returns lunar month and if it is adhika or not.
1 = Chaitra, 2 = Vaisakha, ..., 12 = Phalguna"""
ti = tithi(jd, place)[0]
critical = sunrise(jd, place)[0] # - tz/24 ?
last_new_moon = new_moon(critical, ti, -1)
next_new_moon = new_moon(critical, ti, +1)
this_solar_month = raasi(... | b8b7572f4b5dc597d844683e30c92be618e32c43 | 3,646,545 |
from scipy.special import erf
def sigma(s):
"""The probablity a normal variate will be `<s` sigma from the mean.
Parameters
----------
s : float
The number of sigma from the mean.
Returns
-------
p : float
The probability that a value within +/-s would occur.
"""
ret... | 88727617b1cca678613818be8fdb90e114b25438 | 3,646,546 |
def addneq_parse_residualline(line: str) -> dict:
"""
Parse en linje med dagsløsningsresidualer fra en ADDNEQ-fil.
Udtræk stationsnavn, samt retning (N/E/U), spredning og derefter et vilkårligt
antal døgnresidualer.
En serie linjer kan se således ud:
GESR N 0.07 0.02 -0.... | 6d1556cbd01f3fe4cd66dcad231e41fa6b1b9470 | 3,646,547 |
import os
def extract_header(file_path):
"""
Loads the header from a PSG-type file at path 'file_path'.
Returns:
dictionary of header information
"""
fname = os.path.split(os.path.abspath(file_path))[-1]
_, ext = os.path.splitext(fname)
load_func = _EXT_TO_LOADER[ext[1:]]
head... | 8eaccdd9b8252ea0a9651278895be517d0acc023 | 3,646,548 |
def get_xsd_schema(url):
"""Request the XSD schema from DOV webservices and return it.
Parameters
----------
url : str
URL of the XSD schema to download.
Returns
-------
xml : bytes
The raw XML data of this XSD schema as bytes.
"""
response = HookRunner.execute_inj... | 12f5088fea1b9268d75ee90d60b729c8a9577dd0 | 3,646,549 |
def get_char_pmi(data):
"""
获取 pmi
:param data:
:return:
"""
print('get_char_pmi')
model = kenlm.LanguageModel('../software/kenlm/test.bin')
res = []
for line in data:
words = line.strip().split()
length = len(words)
words.append('\n')
i = 0
pm... | 2cb28e7671561a52efbbf98431e3c938700f691a | 3,646,550 |
def fahrenheit_to_celsius(fahrenheit):
"""Convert a Fahrenheit temperature to Celsius."""
return (fahrenheit - 32.0) / 1.8 | 4aee3dd0b54450fabf7a3a01d340b45a89caeaa3 | 3,646,551 |
import random
import itertools
def sample_blocks(num_layers, num_approx):
"""Generate approx block permutations by sampling w/o replacement. Leave the
first and last blocks as ReLU"""
perms = []
for _ in range(1000):
perms.append(sorted(random.sample(list(range(0,num_layers)), num_approx)))
... | b4b75e77b3749bc7766c709d86bf1f694898fc0d | 3,646,552 |
def adjacent_values(vals, q1, q3):
"""Helper function for violinplot visualisation (courtesy of
https://matplotlib.org/gallery/statistics/customized_violin.html#sphx-glr-gallery-statistics-customized-violin-py)
"""
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adja... | a596ed82a1d66213dbdd3f19b29d58b36979c60d | 3,646,553 |
def l2_first_moment(freq, n_trials, weights):
"""Return the first raw moment of the squared l2-norm of a vector (f-p), where `f` is an MLE
estimate
of the `p` parameter of the multinomial distribution with `n_trials`."""
return (np.einsum("aiai,ai->", weights, freq) - np.einsum("aiaj,ai,aj->", weights, ... | bf597aaa57759dc6d4f0ee1f5ed4f99f49ea271b | 3,646,554 |
def sigmoid(x: float, a: float = 1, b: float = 1, shift: float = 0) -> float:
"""
Sigmoid function represented by b * \frac{1}{1 + e^{-a * (x - shift)}}}
Args:
x (float): Input x
a (float, optional): Rate of inflection. Defaults to 1.
b (float, optional): Difference of lowest to hig... | 761497db712619008c1261d2388cea997ae3fff8 | 3,646,555 |
def db_credentials():
"""Load creds and returns dict of postgres keyword arguments."""
creds = load_json('creds.json')
return {
'host': creds['db_host'],
'user': creds['db_username'],
'password': creds['db_password'],
'database': creds['db_database']
} | 4248452ffb5a9c05b14449972c1db7a18d906b73 | 3,646,556 |
import logging
def generate_corpus_output( cfg, docL, tfidfL ):
""" Generate a list of OutputRecords where the number of key words
is limited to the cfg.corpusKeywordCount highest scoring terms.
(i.e. cfg.usePerDocWordCount == False)
"""
outL = []
# for the cfg.corpusKeyWordCount highest... | 2296d319fd00022df73da9e7d8484adfd5ab16ad | 3,646,557 |
import os
def expand(directory: str) -> str:
"""Apply expanduser and expandvars to directory to expand '~' and env vars."""
temp1 = os.path.expanduser(directory)
return os.path.expandvars(temp1) | ffad07715d5425211304e340c084c8f134bbcb22 | 3,646,558 |
import sys
def gather_ensemble_info(nmme_model):
"""Gathers ensemble information based on NMME model."""
# Number of ensembles in the forecast (ens_num)
# Ensemble start index (ens_start)
# Ensemble end index (ens_end)
if nmme_model == "CFSv2":
ens_num=24
ens_start=1
ens_e... | 56516751dc87415b6a08541eadb02b67a5bc6629 | 3,646,559 |
import tqdm
def harmonic_fitter(progressions, J_thres=0.01):
"""
Function that will sequentially fit every progression
with a simple harmonic model defined by B and D. The
"B" value here actually corresponds to B+C for a near-prolate,
or 2B for a prolate top.
There... | 55a2c4080938c947501ed830f4236ca8f87608e8 | 3,646,560 |
def print_KruskalWallisH(div_calc):
"""
Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that
each group must have at least 5 measurements.
"""
calc = defaultdict(list)
try:
for k1, v1 in div_calc.iteritems():
for k2, v2 in v1.iteritems():
... | 74579ad2f9ee4336ab33f099982a9419d723774e | 3,646,561 |
import random
import string
def _random_exptname():
"""Generate randome expt name NNNNNNNN_NNNNNN, where N is any number 0..9"""
r = ''.join(random.choice(string.digits) for _ in range(8))
r = r + '_' + ''.join(random.choice(string.digits) for _ in range(6))
return r | d9c72ed4bf742adf50e1fdad4f6acb1cc0046167 | 3,646,562 |
def remove_store(store_name):
""" Deletes the named data store.
:param store_name:
:return:
"""
return get_data_engine().remove_store(store_name) | ea8ada276095c2ceb85b339b2a925fa53fd93a1e | 3,646,563 |
from typing import Union
from pathlib import Path
import subprocess
def is_tracked_upstream(folder: Union[str, Path]) -> bool:
"""
Check if the current checked-out branch is tracked upstream.
"""
try:
command = "git rev-parse --symbolic-full-name --abbrev-ref @{u}"
subprocess.run(
... | 8c58efe0d0619aaa6517d656ba88f1e29653197a | 3,646,564 |
import random
def limit_checkins_per_user(checkins: list, num_checkins_per_user: int, random_seed=1):
"""
Limit for each user a maximum number of check-ins by randomly select check-ins.
Parameters
----------
checkins: list
list of check-ins
num_checkins_per_user: int
max numbe... | 286760c3630162b78c314f9f8be0943350f47859 | 3,646,565 |
import warnings
import warnings
def getCharacterFilmography(characterID, charIF, charDF, movieIF, movieKF,
personIF, personKF, limit=None):
"""Build a filmography list for the specified characterID."""
try:
ifptr = open(charIF, 'rb')
except IOError, e:
warnings.... | ddf7f1da3e95441a2da9d3fe2f16065e0a13f634 | 3,646,566 |
def sqrt_fixed_full(x, config, is_training=True, causal=True):
"""Full attention matrix with sqrt decomposition."""
bsize = x.shape[0]
query, key, value = attention.get_qkv(x, x, x, hidden_size=config.model_size,
num_heads=config.num_heads,
... | 3ee88f2adf767c6fb6e0f1c006ff301c45ffc322 | 3,646,567 |
def mcf_from_row(row, gene_to_dcid_list):
"""Generate data mcf from each row of the dataframe"""
gene = row['Gene name']
tissue = get_class_name(row['Tissue'])
cell = get_class_name(row['Cell type'])
expression = EXPRESSION_MAP[row['Level']]
reliability = RELIABILITY_MAP[row['Reliability']]
... | ee78c68bb89a100fa4e0b972d0907e14dcb6d289 | 3,646,568 |
def loads(json_str, target=None):
"""
Shortcut for instantiating a new :class:`JSONDecoder` and calling the :func:`from_json_str` function.
.. seealso::
For more information you can look at the doc of :func:`JSONDecoder.from_json_str`.
"""
return _decoder.from_json_str(json_str, target) | 76eab90dd544d695f55967969d81ef9cccb1c2fd | 3,646,569 |
def discover(discover_system: bool = True) -> Discovery:
"""
Discover capabilities offered by this extension.
"""
logger.info("Discovering capabilities from aws-az-failure-chaostoolkit")
discovery = initialize_discovery_result(
"aws-az-failure-chaostoolkit", __version__, "aws"
)
dis... | ad9b7674f8f8f7cc06ce21dacba2138231b7e69c | 3,646,570 |
def getter_nofancy(a, b, asarray=True, lock=None):
""" A simple wrapper around ``getter``.
Used to indicate to the optimization passes that the backend doesn't
support fancy indexing.
"""
return getter(a, b, asarray=asarray, lock=lock) | 63e355eb3245c8f394c345fb2ebd4e469fcd7500 | 3,646,571 |
def xy_to_array_origin(image):
"""Return view of image transformed from Cartesian to array origin."""
return rgb_transpose(image[:, ::-1]) | e2e47f95093e1808cfbe7c2ba28af8c3e5b40307 | 3,646,572 |
import csv
def read_csv(infile, delimiter=',', encoding='utf-8', named=False):
"""Reads a csv as a list of lists (unnamed) or a list of named tuples (named)
Args:
string infile: the file to read in
OPTIONAL:
string delimiter: the delimiter used (default ',')
encoding en... | 7318293d884fa80a7d93d8046f66b3801d809f42 | 3,646,573 |
def is_ivy_enabled(ctx):
"""Determine if the ivy compiler should be used to by the ng_module.
Args:
ctx: skylark rule execution context
Returns:
Boolean, Whether the ivy compiler should be used.
"""
# Check the renderer flag to see if Ivy is enabled.
# This is intended to support ... | 57018cd180e3cfb580874249a31731f6762f4900 | 3,646,574 |
def get_directions_id(destination):
"""Get place ID for directions, which is place ID for associated destination, if an event"""
if hasattr(destination, 'destination'):
# event with a related destination; use it for directions
if destination.destination:
return destination.destinatio... | f7cd182cb5ea344c341bf9bfaa7a4389335ae353 | 3,646,575 |
def decode_token(params, token_field=None):
"""
This function is used to decode the jwt token into the data that was used
to generate it
Args:
session_obj: sqlalchemy obj used to interact with the db
params: json data received with request
token_field: name of the field that tok... | 8adac31df7d5659c06f5c4d66fc86ae556531aae | 3,646,576 |
from matplotlib import pyplot
import numpy
def gas_arrow(ods, r, z, direction=None, snap_to=numpy.pi / 4.0, ax=None, color=None, pad=1.0, **kw):
"""
Draws an arrow pointing in from the gas valve
:param ods: ODS instance
:param r: float
R position of gas injector (m)
:param z: float
... | 04ef7568cf6b6f7e9357fa05ae3996ecf74ab3c1 | 3,646,577 |
import sys
def get_word_vector(text, model, num):
"""
:param text: list of words
:param model: word2vec model in Gensim format
:param num: number of the word to exclude
:return: average vector of words in text
"""
# Creating list of all words in the document which are p... | 586ea6fdd7845ed21322d824b0bc7155345899ed | 3,646,578 |
def find_storage_pool_type(apiclient, storagetype='NetworkFileSystem'):
"""
@name : find_storage_pool_type
@Desc : Returns true if the given storage pool type exists
@Input : type : type of the storage pool[NFS, RBD, etc.,]
@Output : True : if the type of storage is found
False : if th... | 1d3e64185e0361f02a8cc7e2e4316895e22e517e | 3,646,579 |
from typing import Any
from typing import cast
def parse_year(candidate: Any) -> int:
"""Parses the given candidate as a year literal. Raises a ValueError
when the candidate is not a valid year."""
if candidate is not None and not isinstance(candidate, int):
raise TypeError("Argument year is expec... | 337cc3be16e1e1246d1d1f02b55665c655fe131f | 3,646,580 |
def dropout2d(tensor: Tensor, p: float = 0.2) -> Tensor:
"""
Method performs 2D channel-wise dropout with a autograd tensor.
:param tensor: (Tensor) Input tensor
:param p: (float) Probability that a activation element is set to zero
:return: (Tensor) Output tensor
"""
# Check argument
as... | 6719fa5a3e55665770faf1034677642d78561f83 | 3,646,581 |
def svn_repos_finish_report(*args):
"""svn_repos_finish_report(void * report_baton, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_finish_report(*args) | 19b42660beb7fa5995a8c5e6e0cb5df39116ddb5 | 3,646,582 |
import array
import itertools
def problem451():
"""
Consider the number 15.
There are eight positive numbers less than 15 which are coprime to 15: 1,
2, 4, 7, 8, 11, 13, 14.
The modular inverses of these numbers modulo 15 are: 1, 8, 4, 13, 2, 11,
7, 14
because
1*1 m... | efb000a8f367cf13e7aec2117efed092e3d5a5f3 | 3,646,583 |
import torch
def collate_molgraphs(data):
"""Batching a list of datapoints for dataloader.
Parameters
----------
data : list of 3-tuples or 4-tuples.
Each tuple is for a single datapoint, consisting of
a SMILES, a DGLGraph, all-task labels and optionally
a binary mask indicati... | 3ff726fca71ab64ec1e2e665babd8f46b027e819 | 3,646,584 |
def reshape_practice(x):
"""
Given an input tensor of shape (24,), return a reshaped tensor y of shape
(3, 8) such that
y = [
[x[0], x[1], x[2], x[3], x[12], x[13], x[14], x[15]],
[x[4], x[5], x[6], x[7], x[16], x[17], x[18], x[19]],
[x[8], x[9], x[10], x[11], x[20], x[21], x[22], x[23]],
]
... | b7d71df428ca13729d908771b6e5ce14aa5662e2 | 3,646,585 |
def recouvrement_view(request, id):
"""
Fonction Detail
"""
user = request.user
recouvrement = Recouvrement.objects.filter(user=user).get(id=id)
context = {
'recouvrement': recouvrement,
}
template_name = 'pages/recouvrement/recouvrement_view.html'
return render(reque... | f0e26257a39ef385b9dfaa51bff68b0fec51a263 | 3,646,586 |
def getFileServicesNames(fileServices=None, verbose=True):
"""
Returns the names and description of the fileServices available to the user.
:param fileServices: a list of FileService objects (dictionaries), as returned by Files.getFileServices(). If not set, then an extra internal call to Jobs.getFileServi... | ef476f2c661dadebee8e8a16863ff2f4c286d99e | 3,646,587 |
def username_in_path(username, path_):
"""Checks if a username is contained in URL"""
if username in path_:
return True
return False | 131a8fa102fd0a0f036da81030b005f92ea9aab0 | 3,646,588 |
def str_parse_as_utf8(content) -> str:
"""Returns the provided content decoded as utf-8."""
return content.decode('utf-8') | 75b8d5f1f8867c50b08146cc3edc1d0ab630280a | 3,646,589 |
def TypeProviderClient(version):
"""Return a Type Provider client specially suited for listing types.
Listing types requires many API calls, some of which may fail due to bad
user configurations which show up as errors that are retryable. We can
alleviate some of the latency and usability issues this causes by... | 2e735b37d01b9a9a0b44d5cf04acd89d2a8d9b90 | 3,646,590 |
from typing import Optional
from datetime import datetime
from typing import List
from typing import Dict
from typing import Any
def create_indicator(
pattern: str,
pattern_type: str,
created_by: Optional[Identity] = None,
name: Optional[str] = None,
description: Optional[str] = None,
valid_fr... | 421e9d1d060709facb9a8b8d6831b6a45ef479c9 | 3,646,591 |
def import_data(
path_to_csv: str,
response_colname: str,
standards_colname: str,
header: int = 0,
nrows: int = None,
skip_rows: int = None,
) -> pd.DataFrame:
"""Import standard curve data from a csv file.
Args:
path_to_csv: Refer to pd.read_csv docs.
response_colname: ... | fffc650ac7b672e0585b0dc307977c4adf9a0a69 | 3,646,592 |
def plus(x: np.ndarray, y: np.ndarray) -> np.ndarray:
""" 矩阵相加"""
if x.shape == y.shape:
return x + y | 9d042d90c8d3ca9588c02ddd9ed53ec725785d13 | 3,646,593 |
def add_noise(wave, noise, fs, snr, start_time, duration, wave_power):
"""Add a noise to wave.
"""
noise_power = np.dot(noise, noise) / noise.shape[0]
scale_factor = np.sqrt(10**(-snr/10.0) * wave_power / noise_power)
noise = noise * scale_factor
offset = int(start_time * fs)
add_length = mi... | 3f8df3098751b081f93b61da16682bdac2bf6a02 | 3,646,594 |
def _sort_factors(factors, **args):
"""Sort low-level factors in increasing 'complexity' order."""
def order_if_multiple_key(factor):
f, n = factor
return len(f), n, default_sort_key(f)
def order_no_multiple_key(f):
return len(f), default_sort_key(f)
if args.get('multiple', Tru... | 60be823e0f12b0e33d6a9567458cc98d95d1f900 | 3,646,595 |
def get_affix(text):
"""
This method gets the affix information
:param str text: Input text.
"""
return " ".join(
[word[-4:] if len(word) >= 4 else word for word in text.split()]) | eb0aa68e803ce6c0ae218f4e0e2fd1855936b50f | 3,646,596 |
async def async_setup_entry(hass, config_entry):
"""Konfigurowanie integracji na podstawie wpisu konfiguracyjnego."""
_LOGGER.info("async_setup_entry " + str(config_entry))
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, "sensor")
)
return True | 0bbef08a544cccede0efd18fbbf9a0b7dddfbec9 | 3,646,597 |
def analyse_branching(geom,ordering_system,conversionFactor,voxelSize):
""" Does a branching analysis on the tree defined by 'geom'
Inputs:
- geom: A geometry structure consisting of element list, node location and radii/lengths
- ordering_system: the ordering system to be used in analysis (e.... | 25c72b51094c59317e167cca6662c5ccfa8805b0 | 3,646,598 |
def remove_start(s: str) -> str:
"""
Clear string from start '-' symbol
:param s:
:return:
"""
return s[1:] if s.startswith('-') else s | 03504a3094798f6582bcae40233f7215e8d4d780 | 3,646,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.