content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def do(ARGV):
"""Allow to check whether the exception handlers are all in place.
"""
if len(ARGV) != 3: return False
elif ARGV[1] != "<<TEST:Exceptions/function>>" \
and ARGV[1] != "<<TEST:Exceptions/on-import>>": return False
if len(ARGV) < 3: return False
exception = A... | 56b83d119f74a00f1b557c370d75fb9ff633d691 | 1,255 |
def get_available_language_packs():
"""Get list of registered language packs.
:return list:
"""
ensure_autodiscover()
return [val for (key, val) in registry.registry.items()] | faf3c95ff808c1e970e49c56feb5ad1f61623053 | 1,256 |
import ctypes
def topo_star(jd_tt, delta_t, star, position, accuracy=0):
"""
Computes the topocentric place of a star at 'date', given its
catalog mean place, proper motion, parallax, and radial velocity.
Parameters
----------
jd_tt : float
TT Julian date for topocentric place.
de... | fba937116b5f63b450fb028cc68a26e0e10305ae | 1,257 |
def py_multiplicative_inverse(a, n):
"""Multiplicative inverse of a modulo n (in Python).
Implements extended Euclidean algorithm.
Args:
a: int-like np.ndarray.
n: int.
Returns:
Multiplicative inverse as an int32 np.ndarray with same shape as a.
"""
batched_a = np.asarray... | 87f4e21f9f8b5a9f10dbf4ec80128a37c1fa912c | 1,258 |
def resample_nearest_neighbour(input_tif, extents, new_res, output_file):
"""
Nearest neighbor resampling and cropping of an image.
:param str input_tif: input geotiff file path
:param list extents: new extents for cropping
:param float new_res: new resolution for resampling
:param str output_f... | 107bcb72aff9060d024ff00d86b164cf41078630 | 1,260 |
def harvester_api_info(request, name):
"""
This function returns the pretty rendered
api help text of an harvester.
"""
harvester = get_object_or_404(Harvester, name=name)
api = InitHarvester(harvester).get_harvester_api()
response = api.api_infotext()
content = response.data[harvester.n... | 6b02168d7c77414c57ca74104ff93dae1e698e30 | 1,261 |
import sqlite3
def init_db():
"""Open SQLite database, create facebook table, return connection."""
db = sqlite3.connect('facebook.sql')
cur = db.cursor()
cur.execute(SQL_CREATE)
db.commit()
cur.execute(SQL_CHECK)
parse = list(cur.fetchall())[0][0] == 0
return db, cur, parse | 61d8cc968c66aaddfc55ef27ee02dec13c4b28f2 | 1,262 |
def aggregate_gradients_using_copy_with_variable_colocation(
tower_grads, use_mean, check_inf_nan):
"""Aggregate gradients, colocating computation with the gradient's variable.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over towers. The inner list is over indiv... | bf6bc2f7b0a7bb9eaa23a0c28686bfe16a8e3ced | 1,264 |
def module_for_category( category ):
"""Return the OpenGL.GL.x module for the given category name"""
if category.startswith( 'VERSION_' ):
name = 'OpenGL.GL'
else:
owner,name = category.split( '_',1)
if owner.startswith( '3' ):
owner = owner[1:]
name = 'OpenGL.GL.... | 0e88467a1dd7f5b132d46a9bdc99765c274f69f3 | 1,265 |
def timestamp() -> str:
"""generate formatted timestamp for the invocation moment"""
return dt.now().strftime("%d-%m-%Y %H:%M:%S") | 4f5e3de7f8d0027a210055850c4fa2b4764a39b2 | 1,267 |
def sde(trains, events=None, start=0 * pq.ms, stop=None,
kernel_size=100 * pq.ms, optimize_steps=0,
minimum_kernel=10 * pq.ms, maximum_kernel=500 * pq.ms,
kernel=None, time_unit=pq.ms, progress=None):
""" Create a spike density estimation plot.
The spike density estimations give an esti... | 0b045ec676a9c31f4e0f89361d5ff8c13a238624 | 1,268 |
def content(obj):
"""Strip HTML tags for list display."""
return strip_tags(obj.content.replace('</', ' </')) | 413eed5f6b9ede0f31ede6a029e111a2910cc805 | 1,269 |
def flux(Q, N, ne, Ap, Am):
"""
calculates the flux between two boundary sides of
connected elements for element i
"""
# for every element we have 2 faces to other elements (left and right)
out = np.zeros((ne, N + 1, 2))
# Calculate Fluxes inside domain
for i in range(1, ne - 1):
... | decc1b84cd0f23ac7f437d2c47e76cf6ed961a28 | 1,270 |
import shutil
def cp_dir(src_dir, dest_dir):
"""Function: cp_dir
Description: Copies a directory from source to destination.
Arguments:
(input) src_dir -> Source directory.
(input) dest_dir -> Destination directory.
(output) status -> True|False - True if copy was successful.
... | 13f82a485fb46e102780c2462f0ab092f0d62df1 | 1,271 |
import torch
def listnet_loss(y_i, z_i):
"""
y_i: (n_i, 1)
z_i: (n_i, 1)
"""
P_y_i = F.softmax(y_i, dim=0)
P_z_i = F.softmax(z_i, dim=0)
return - torch.sum(y_i * torch.log(P_z_i)) | c2b7dd9800ed591af392b17993c70b443f99524c | 1,272 |
def normalize(data, **kw):
"""Calculates the normalization of the given array. The normalizated
array is returned as a different array.
Args:
data The data to be normalized
Kwargs:
upper_bound The upper bound of the normalization. It has the value
of 1 by default.
lower... | 2f6f1a28a5bac4eee221923465a022c79ec185af | 1,274 |
def cc_across_time(tfx, tfy, cc_func, cc_args=()):
"""Cross correlations across time.
Args:
tfx : time-frequency domain signal 1
tfy : time-frequency domain signal 2
cc_func : cross correlation function.
cc_args : list of extra arguments of cc_func.
Returns:
... | c22670b2f722884b048758dbc20df3bc58cd9b0f | 1,276 |
import chardet
def predict_encoding(file_path, n_lines=20):
"""Predict a file's encoding using chardet"""
# Open the file as binary data
with open(file_path, "rb") as f:
# Join binary lines for specified number of lines
rawdata = b"".join([f.readline() for _ in range(n_lines)])
retur... | 1ccef9982846fe0c88124b9e583cf68be070e63a | 1,277 |
def redirect_handler(url, client_id, client_secret, redirect_uri, scope):
"""
Convenience redirect handler.
Provide the redirect url (containing auth code)
along with client credentials.
Returns a spotify access token.
"""
auth = ExtendedOAuth(
client_id, client_secret, redirect_uri,... | c682af3d7da51afdcba9a46aa4b44dd983d3fe40 | 1,278 |
def convert_coordinate(coordinate):
"""
:param coordinate: str - a string map coordinate
:return: tuple - the string coordinate seperated into its individual components.
"""
coord = (coordinate[0], coordinate[1])
return coord | a3852f5b4e4faac066c8f71e945ed7f46fbf2509 | 1,279 |
from typing import List
def get_noun_phrases(doc: Doc) -> List[Span]:
"""Compile a list of noun phrases in sense2vec's format (without
determiners). Separated out to make it easier to customize, e.g. for
languages that don't implement a noun_chunks iterator out-of-the-box, or
use different label schem... | 38d78164147b012437f7c8b8d4c7fe13eb574515 | 1,282 |
import json
def load_file_from_url(url):
"""Load the data from url."""
url_path = get_absolute_url_path(url, PATH)
response = urlopen(url_path)
contents = json.loads(response.read())
return parse_file_contents(contents, url_path.endswith(".mrsys")) | 7eaa3d666c9e1fbdd9bad57047dd1b98712bd22b | 1,283 |
def speedPunisherMin(v, vmin):
"""
:param v:
:param vmin:
:return:
"""
x = fmin(v - vmin, 0)
return x ** 2 | 9e6e929226ea20d70d26f6748f938981885914c7 | 1,284 |
def hexagonal_packing_cross_section(nseeds, Areq, insu, out_insu):
""" Make a hexagonal packing and scale the result to be Areq cross section
Parameter insu must be a percentage of the strand radius.
out_insu is the insulation thickness around the wire as meters
Returns:
(wire diameter... | 759cc26a9606ac327851d9b1e691052123029d66 | 1,286 |
def bk():
"""
Returns an RGB object representing a black pixel.
This function is created to make smile() more legible.
"""
return introcs.RGB(0,0,0) | 0343367302c601fce9057a8191b666a098eaec81 | 1,287 |
def autoEpochToTime(epoch):
"""
Converts a long offset from Epoch value to a DBDateTime. This method uses expected date ranges to
infer whether the passed value is in milliseconds, microseconds, or nanoseconds. Thresholds used are
TimeConstants.MICROTIME_THRESHOLD divided by 1000 for milliseconds, as-... | 1f2ae0397044c19413544a359a1d966a4f223128 | 1,288 |
def compile_recursive_descent(file_lines, *args, **kwargs):
"""Given a file and its lines, recursively compile until no ksx statements remain"""
visited_files = kwargs.get('visited_files', set())
# calculate a hash of the file_lines and check if we have already compiled
# this one
file_hash = hash_... | 9e5306c2d2cc6696883ac3ec37114c13340fe1f5 | 1,289 |
def majority_voting(masks, voting='hard', weights=None, threshold=0.5):
"""Soft Voting/Majority Rule mask merging; Signature based upon the Scikit-learn VotingClassifier (https://github.com/scikit-learn/scikit-learn/blob/2beed55847ee70d363bdbfe14ee4401438fba057/sklearn/ensemble/_voting.py#L141)
Parameters
... | 882e98bc3a0c817c225f740042eb43b3bc4734fa | 1,290 |
def animate(zdata,
xdata,
ydata,
conversionFactorArray,
timedata,
BoxSize,
timeSteps=100,
filename="particle"):
"""
Animates the particle's motion given the z, x and y signal (in Volts)
and the conversion factor (to convert ... | aa0f08481f7efc39dae725a0c5f7fbc377586261 | 1,291 |
import re
def name_of_decompressed(filename):
""" Given a filename check if it is in compressed type (any of
['.Z', '.gz', '.tar.gz', '.zip']; if indeed it is compressed return the
name of the uncompressed file, else return the input filename.
"""
dct = {
'.Z': re.compile('.Z$'),
... | ee0c49edca853fbf1da8caccbba68c9cde391f6b | 1,292 |
import random
def sample_distribution(distribution):
"""Sample one element from a distribution assumed to be an array of normalized
probabilities.
"""
r = random.uniform(0, 1)
s = 0
for i in range(len(distribution)):
s += distribution[i]
if s >= r:
return i
return len(distribution) - 1 | 2e8a5e2d3c8fd6770e78a6ad30afc52f63c43073 | 1,293 |
def benchmark(func):
"""Decorator to mark a benchmark."""
BENCHMARKS[func.__name__] = func
return func | 0edadb46c446ed5603434d14ab7a40cdf76651b5 | 1,294 |
def do_positive_DFT(data_in, tmax):
"""
Do Discrete Fourier transformation and take POSITIVE frequency component part.
Args:
data_in (array): input data.
tmax (float): sample frequency.
Returns:
data_s (array): output array with POSITIVE frequency component part.
data_w (... | c3bab6b9595cf77869f65eacf6acf6d7f990ca10 | 1,295 |
def service(base_app, location):
"""Service fixture."""
return base_app.extensions["invenio-records-lom"].records_service | 52ad7f4624e7d0af153f0fcaaccfb56effddb86d | 1,296 |
def check_file_content(path, expected_content):
"""Check file has expected content.
:param str path: Path to file.
:param str expected_content: Expected file content.
"""
with open(path) as input:
return expected_content == input.read() | 77bdfae956ce86f2422ed242c4afcaab19cab384 | 1,297 |
from datetime import datetime
import select
def verify_apikey(payload,
raiseonfail=False,
override_authdb_path=None,
override_permissions_json=None,
config=None):
"""Checks if an API key is valid.
This version does not require a session.... | f1f5d9f65b2c9b8b9175ea4729042d9bb040a0e7 | 1,299 |
def case_mc2us(x):
""" mixed case to underscore notation """
return case_cw2us(x) | 13cd638311bea75699789a2f13b7a7d854f856bd | 1,301 |
def detail_url(reteta_id):
""""Return reteta detail URL"""
return reverse('reteta:reteta-detail', args=[reteta_id]) | 4b7219b5e0d7ae32656766a08c34f54a02d1634e | 1,303 |
def load_metadata_txt(file_path):
"""
Load distortion coefficients from a text file.
Parameters
----------
file_path : str
Path to a file.
Returns
-------
tuple of floats and list
Tuple of (xcenter, ycenter, list_fact).
"""
if ("\\" in file_path):
raise ... | 44e6319aec6d77910e15e8890bcd78ffcdca3aa4 | 1,304 |
import torch
def _output_gradient(f, loss_function, dataset, labels, out0, batch_indices, chunk):
"""
internal function
"""
x = _getitems(dataset, batch_indices)
y = _getitems(labels, batch_indices)
if out0 is not None:
out0 = out0[batch_indices]
out = []
grad = 0
loss_va... | 252f79065ce953eb99df17842d62786cebadee67 | 1,305 |
def __material_desc_dict(m, d):
""" Unpack positions 18-34 into material specific dict. """
return dict(zip(MD_FIELDS[m],
{"BK": __material_bk, "CF": __material_cf,
"MP": __material_mp, "MU": __material_mu,
"CR": __material_cr, "VM": __material_vm,
... | 9f87ce915bd5d226fa1d1ffd5991779c9a4fbdba | 1,306 |
def toint(x):
"""Try to convert x to an integer number without raising an exception."""
try: return int(x)
except: return x | bd1a675cb3f8f5c48e36f8f405a89dc637f3f558 | 1,307 |
def obtain_time_image(x, y, centroid_x, centroid_y, psi, time_gradient, time_intercept):
"""Create a pulse time image for a toymodel shower. Assumes the time development
occurs only along the longitudinal (major) axis of the shower, and scales
linearly with distance along the axis.
Parameters
-----... | 4a57399e041c0fd487fe039e5091986438d4b8b8 | 1,308 |
import re
def remove_comment(to_remove, infile):
"""Removes trailing block comments from the end of a string.
Parameters:
to_remove: The string to remove the comment from.
infile: The file being read from.
Returns:
The paramter string with the block comment removed (if comment wa... | 0172b295c9a023eb96fbad7a6c3a388874e106bc | 1,309 |
def generate_notification_header(obj):
"""
Generates notification header information based upon the object -- this is
used to preface the notification's context.
Could possibly be used for "Favorites" descriptions as well.
:param obj: The top-level object instantiated class.
:type obj: class w... | e02c2bdd9827077a49236ed7aa813458659f453c | 1,310 |
def promptyn(msg, default=None):
""" Display a blocking prompt until the user confirms """
while True:
yes = "Y" if default else "y"
if default or default is None:
no = "n"
else:
no = "N"
confirm = raw_input("%s [%s/%s]" % (msg, yes, no))
confirm =... | 1bec535462b8e859bac32c424e8500c432eb7751 | 1,311 |
def plan_launch_spec(state):
""" Read current job params, and prescribe the next training job to launch
"""
last_run_spec = state['run_spec']
last_warmup_rate = last_run_spec['warmup_learning_rate']
add_batch_norm = last_run_spec['add_batch_norm']
learning_rate = last_run_spec['learning_rate']... | 5fee797f24db05eccb49a5b10a9d88917987f905 | 1,312 |
def ssgenTxOut0():
"""
ssgenTxOut0 is the 0th position output in a valid SSGen tx used to test out the
IsSSGen function
"""
# fmt: off
return msgtx.TxOut(
value=0x00000000, # 0
version=0x0000,
pkScript=ByteArray(
[
0x6a, # OP... | 3bee03ef9bc3a326fff381b6d2594c3ea4c909e7 | 1,313 |
def sexag_to_dec(sexag_unit):
""" Converts Latitude and Longitude Coordinates from the Sexagesimal Notation
to the Decimal/Degree Notation"""
add_to_degree = (sexag_unit[1] + (sexag_unit[2]/60))/60
return sexag_unit[0]+add_to_degree | c9c4394920d2b483332eb4a81c0f0d9010179339 | 1,314 |
import apysc as ap
from typing import Any
from typing import Tuple
def is_immutable_type(value: Any) -> bool:
"""
Get a boolean value whether specified value is immutable
type or not.
Notes
-----
apysc's value types, such as the `Int`, are checked
as immutable since these js types are imm... | 79538477528df2e13eaf806231e2f43c756abacd | 1,315 |
def add_column_node_type(df: pd.DataFrame) -> pd.DataFrame:
"""Add column `node_type` indicating whether a post is a parent or a leaf node
Args:
df: The posts DataFrame with the columns `id_post` and `id_parent_post`.
Returns:
df: A copy of df, extended by `node_type`.
"""
if "node... | 3ad8a12f1a872d36a14257bdaa38229768714fa5 | 1,316 |
import random
def read_motifs(fmotif):
"""
create a random pool of motifs to choose from for the monte-carlo simulations
"""
motif_pool = []
for line in open(fmotif):
if not line.strip(): continue
if line[0] == "#": continue
motif, count = line.rstrip().split()
moti... | 168a7f82727917aa5ca1a30b9aa9df1699261585 | 1,317 |
from App import Proxys
import math
def createCone( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a cone with the specified attributes (axis is 0:x, 1:y, 2:z). Other rigid body parameters can be specified with keyword argume... | 43a7e0134627ed8069359c29bc53f354d70498d9 | 1,318 |
from typing import Union
def ef(candles: np.ndarray, lp_per: int = 10, hp_per: int = 30, f_type: str = "Ehlers", normalize: bool = False, source_type: str = "close", sequential: bool = False) -> Union[
float, np.ndarray]:
# added to definition : use_comp: bool = False, comp_intensity: float = 90.0,
"""
... | 6dd19e9a1cb5a8f293f4ec3eebef625e2b05bcfe | 1,319 |
from typing import Dict
def parse_displays(config: Dict) -> Dict[str, QueryDisplay]:
"""Parse display options from configuration."""
display_configs = config.get("displays")
if not display_configs:
return {}
displays = {}
for name, display_config in display_configs.items():
displa... | a7f3c32d3ceaf6c39ea16ee7e2f7ec843036487e | 1,320 |
async def update_result(user: dict, form: dict) -> str:
"""Extract form data and update one result and corresponding start event."""
informasjon = await create_finish_time_events(user, "finish_bib", form) # type: ignore
return informasjon | b9b97f3b08f08dc35a0744f38323d76ecb0c3fba | 1,321 |
from typing import List
import torch
import copy
def rasterize_polygons_within_box(
polygons: List[np.ndarray], box: np.ndarray, mask_size: int
) -> torch.Tensor:
"""
Rasterize the polygons into a mask image and
crop the mask content in the given box.
The cropped mask is resized to (mask_size, mas... | 98a35b477338f0f472d34b49f4be9f9cd0303654 | 1,322 |
def has_ao_num(trexio_file) -> bool:
"""Check that ao_num variable exists in the TREXIO file.
Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function.
Returns:
True if the variable exists, False otherwise
Raises:
- Exception from trexio.Error class if ... | 6a10204cc5d64a71e991fed1e43fd9ff81a250b9 | 1,323 |
def teapot(size=1.0):
"""
Z-axis aligned Utah teapot
Parameters
----------
size : float
Relative size of the teapot.
"""
vertices, indices = data.get("teapot.obj")
xmin = vertices["position"][:,0].min()
xmax = vertices["position"][:,0].max()
ymin = vertices["position"]... | 94cef5111384599f74bfe59fb97ba417c738ca50 | 1,324 |
def f30(x, rotations=None, shifts=None, shuffles=None):
"""
Composition Function 10 (N=3)
Args:
x (array): Input vector of dimension 2, 10, 20, 30, 50 or 100.
rotations (matrix): Optional rotation matrices (NxDxD). If None
(default), the official matrices from the benchmark suit... | d2bfe7a0bba501e1d7d5bcf29475ecc36f73913b | 1,325 |
def loadNode( collada, node, localscope ):
"""Generic scene node loading from a xml `node` and a `collada` object.
Knowing the supported nodes, create the appropiate class for the given node
and return it.
"""
if node.tag == tag('node'): return Node.load(collada, node, localscope)
elif node.ta... | 68083c4490e44e71f33d1221776837f2c1d59b69 | 1,326 |
def create_xla_tff_computation(xla_computation, type_spec):
"""Creates an XLA TFF computation.
Args:
xla_computation: An instance of `xla_client.XlaComputation`.
type_spec: The TFF type of the computation to be constructed.
Returns:
An instance of `pb.Computation`.
"""
py_typecheck.check_type(xl... | 5a02051913026029cab95d12199eb321fa511654 | 1,327 |
def render_contact_form(context):
"""
Renders the contact form which must be in the template context.
The most common use case for this template tag is to call it in the
template rendered by :class:`~envelope.views.ContactView`. The template
tag will then render a sub-template ``envelope/contact_fo... | e243502fadbf094ed7277ec5db770a3b209174e2 | 1,328 |
from typing import List
from typing import Dict
def get_basic_project(reviews: int = 0) -> List[Dict]:
"""Get basic project config with reviews."""
reviews = max(reviews, MIN_REVIEW)
reviews = min(reviews, MAX_REVIEW)
middle_stages, entry_point = _get_middle_stages(reviews, OUTPUT_NAME)
input_st... | 14c2252dec69ebbcec04fbd00de0fa5ac6d1cdf7 | 1,329 |
import re
def choose_quality(link, name=None, selected_link=None):
"""
choose quality for scraping
Keyword Arguments:
link -- Jenitem link with sublinks
name -- Name to display in dialog (default None)
"""
if name is None:
name = xbmc.getInfoLabel('listitem.label')
if link.sta... | a75214cd0acd1c0e3ede34241baeb07342aadb1b | 1,330 |
def picp_loss(target, predictions, total = True):
"""
Calculate 1 - PICP (see eval_metrics.picp for more details)
Parameters
----------
target : torch.Tensor
The true values of the target variable
predictions : list
- predictions[0] = y_pred_upper, predicted upper limit of the t... | a6d8d150241b1a2f8dda00c9c182ba7196c65585 | 1,331 |
def index_wrap(data, index):
"""
Description: Select an index from an array data
:param data: array data
:param index: index (e.g. 1,2,3, account_data,..)
:return: Data inside the position index
"""
return data[index] | 42b53f1d9edf237b904f822c15ad1f1b930aa69c | 1,333 |
def mzml_to_pandas_df(filename):
"""
Reads mzML file and returns a pandas.DataFrame.
"""
cols = ["retentionTime", "m/z array", "intensity array"]
slices = []
file = mzml.MzML(filename)
while True:
try:
data = file.next()
data["retentionTime"] = data["scanList"... | 2c6f1956d7c499c9f22bc85665bd6b5ce9ed51c3 | 1,335 |
def metadata_volumes(response: Response,
request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST),
sourcetype: str=Query(None, title=opasConfig.TITLE_SOURCETYPE, description=opasConfig.DESCRIPTION_PARAM_SOURCETYPE),
... | e8e4a686eaac21b20f2d758b8bc7de74d38571ab | 1,336 |
def do_step_right(pos: int, step: int, width: int) -> int:
"""Takes current position and do 3 steps to the
right. Be aware of overflow as the board limit
on the right is reached."""
new_pos = (pos + step) % width
return new_pos | 530f3760bab00a7b943314ca735c3a11343b87f5 | 1,337 |
def log_agm(x, prec):
"""
Fixed-point computation of -log(x) = log(1/x), suitable
for large precision. It is required that 0 < x < 1. The
algorithm used is the Sasaki-Kanada formula
-log(x) = pi/agm(theta2(x)^2,theta3(x)^2). [1]
For faster convergence in the theta functions, x should
b... | e873db3a45270eb077d9dc17f2951e2e791ad601 | 1,338 |
import unicodedata
def simplify_name(name):
"""Converts the `name` to lower-case ASCII for fuzzy comparisons."""
return unicodedata.normalize('NFKD',
name.lower()).encode('ascii', 'ignore') | a7c01471245e738fce8ab441e3a23cc0a67c71be | 1,339 |
async def parse_regex(opsdroid, skills, message):
"""Parse a message against all regex skills."""
matched_skills = []
for skill in skills:
for matcher in skill.matchers:
if "regex" in matcher:
opts = matcher["regex"]
matched_regex = await match_regex(messa... | aa3ad8ff48854b974ba90135b510074644e10028 | 1,340 |
def interpolate_minusones(y):
"""
Replace -1 in the array by the interpolation between their neighbor non zeros points
y is a [t] x [n] array
"""
x = np.arange(y.shape[0])
ynew = np.zeros(y.shape)
for ni in range(y.shape[1]):
idx = np.where(y[:,ni] != -1)[0]
if len(idx)>1:
... | db3e347ba75a39f40cd3ee90481efe8392ce08ed | 1,341 |
def precision(y, yhat, positive=True):
"""Returns the precision (higher is better).
:param y: true function values
:param yhat: predicted function values
:param positive: the positive label
:returns: number of true positive predictions / number of positive predictions
"""
table = continge... | f643631781565ddb049c1c4d22c6e5ea64ce4a22 | 1,342 |
def add_posibility_for_red_cross(svg):
"""add a symbol which represents a red cross in a white circle
Arguments:
svg {Svg} -- root element
"""
symbol = Svg(etree.SubElement(svg.root,
'symbol',
{'id': 'red_cross',
... | df621fb907187a36cb3f7387047a8cda6cb42992 | 1,343 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 529cb8d6312eaa129a52f1679294d85c1d9bfbd0 | 1,345 |
import ctypes
def dasopw(fname):
"""
Open a DAS file for writing.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopw_c.html
:param fname: Name of a DAS file to be opened.
:type fname: str
:return: Handle assigned to the opened DAS file.
"""
fname = stypes.stringToCha... | 63f164ba82e6e135763969c8823d7eb46dd52c0e | 1,346 |
import re
def is_ncname(value):
"""
BNode identifiers must be valid NCNames.
From the `W3C RDF Syntax doc <http://www.w3.org/TR/REC-rdf-syntax/#section-blank-nodeid-event>`_
"The value is a function of the value of the ``identifier`` accessor.
The string value begins with "_:" and the entire val... | 78cbfe9209b9f39cd6bc90c0ed5c8e5291bc1562 | 1,347 |
from typing import Dict
def health_func() -> Dict[str, str]:
"""Give the user the API health."""
return "ok" | 5c14795d9d0560ddb34b193575917ac184dbe8a3 | 1,348 |
def queue_worker(decoy: Decoy) -> QueueWorker:
"""Get a mock QueueWorker."""
return decoy.mock(cls=QueueWorker) | aec88b037e393b195abd0c2704e8f2784e9a9f8d | 1,349 |
def astra_fp_3d(volume, proj_geom):
"""
:param proj_geom:
:param volume:
:return:3D sinogram
"""
detector_size = volume.shape[1]
slices_number = volume.shape[0]
rec_size = detector_size
vol_geom = build_volume_geometry_3d(rec_size, slices_number)
sinogram_id = astra.data3d.crea... | 7066bb61dc29fac331ffb13c6fe1432349eac185 | 1,350 |
def get_wf_neb_from_images(
parent,
images,
user_incar_settings,
additional_spec=None,
user_kpoints_settings=None,
additional_cust_args=None,
):
"""
Get a CI-NEB workflow from given images.
Workflow: NEB_1 -- NEB_2 - ... - NEB_n
Args:
parent (Structure): parent structure... | 15ed110d3685c9d8de216733e8d87f6c07580529 | 1,351 |
def categorize_folder_items(folder_items):
"""
Categorize submission items into three lists: CDM, PII, UNKNOWN
:param folder_items: list of filenames in a submission folder (name of folder excluded)
:return: a tuple with three separate lists - (cdm files, pii files, unknown files)
"""
found_cdm... | 14e840817cce4cc91ed50d6d9dcfa1c19a2bcbeb | 1,352 |
def _broadcast_all(indexArrays, cshape):
"""returns a list of views of 'indexArrays' broadcast to shape 'cshape'"""
result = []
for i in indexArrays:
if isinstance(i, NDArray) and i._strides is not None:
result.append(_broadcast(i, cshape))
else:
result.append(i)
... | b7b98245bc534074e408d5c9592bf68ae53f580e | 1,353 |
def _none_tozero_array(inarray, refarray):
"""Repair an array which is None with one which is not
by just buiding zeros
Attributes
inarray: numpy array
refarray: numpy array
"""
if inarray is None:
if _check_ifarrays([refarray]):
inarray = np.zeros_like(refarray)... | 9b0852655a13b572106acc809d842ca38d24e707 | 1,354 |
def dpuGetExceptionMode():
"""
Get the exception handling mode for runtime N2Cube
Returns: Current exception handing mode for N2Cube APIs.
Available values include:
- N2CUBE_EXCEPTION_MODE_PRINT_AND_EXIT
- N2CUBE_EXCEPTION_MODE_RET_ERR_CODE
"""
return pyc_l... | fd33aba868a05f3cc196c89e3c2d428b0cce108a | 1,355 |
import re
def clean_links(links, category):
"""
clean up query fields for display as category buttons to browse by
:param links: list of query outputs
:param category: category of search from route
:return: list of cleansed links
"""
cleansedlinks = []
for item in links:
# remo... | f43af81a8ef8e5520726e886dd74d991c999a32d | 1,356 |
from typing import Any
from typing import Optional
def as_bool(value: Any, schema: Optional[BooleanType] = None) -> bool:
"""Parses value as boolean"""
schema = schema or BooleanType()
value = value.decode() if isinstance(value, bytes) else value
if value:
value = str(value).lower()
v... | 7085b7bc7eccb2db95f5645b358e4940914f68f9 | 1,357 |
from typing import Dict
from typing import List
from typing import Tuple
def get_raw_feature(
column: Text, value: slicer_lib.FeatureValueType,
boundaries: Dict[Text, List[float]]
) -> Tuple[Text, slicer_lib.FeatureValueType]:
"""Get raw feature name and value.
Args:
column: Raw or transformed column... | 29323b8e1a7ef32f19ff94f31efca20567780aa4 | 1,358 |
from typing import Union
def ndmi(nir: Union[xr.DataArray, np.ndarray, float, int],
swir1: Union[xr.DataArray, np.ndarray, float, int]) -> \
Union[xr.DataArray, np.ndarray, float, int]:
"""
Normalized difference moisture index.
Sentinel-2: B8A, B11
Parameters
----------
nir ... | f66a68cd75d9c030c0257e1d543c2caf9efcf652 | 1,359 |
def _collect_data_and_enum_definitions(parsed_models: dict) -> dict[str, dict]:
"""
Collect all data and enum definitions that are referenced as interface messages or as a nested type within an interface message.
Args:
parsed_models: A dict containing models parsed from an AaC yaml file.
Retur... | 0d561003c8cdbe7d2eb7df2f03d5939f70d81467 | 1,360 |
def _list_goals(context, message):
"""Show all installed goals."""
context.log.error(message)
# Execute as if the user had run "./pants goals".
return Phase.execute(context, 'goals') | 5e823770528e97b4254e426a2d99113d119368b0 | 1,361 |
def values(df, varname):
"""Values and counts in index order.
df: DataFrame
varname: strign column name
returns: Series that maps from value to frequency
"""
return df[varname].value_counts().sort_index() | ea548afc8e0b030e441baa54abad32318c9c007f | 1,362 |
def get_or_none(l, n):
"""Get value or return 'None'"""
try:
return l[n]
except (TypeError, IndexError):
return 'None' | c46a0f4c8edc9286b0122f1643e24a04113a5bfc | 1,363 |
def pfam_clan_to_pdb(clan):
"""get a list of associated PDB ids for given pfam clan access key.
:param clan: pfam accession key of clan
:type clan: str
:return: List of associated PDB ids
:rettype:list"""
url='http://pfam.xfam.org/clan/'+clan+'/structures'
pattern='/structure/[A-Z, 0-9]... | 820e8a058edfeee256ab01281020c6e38e2d7c6d | 1,364 |
def fib(n):
"""Compute the nth Fibonacci number.
>>> fib(8)
21
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-2) + fib(n-1) | 0db631be60754376e1a9287a4486ceb5ad7e392f | 1,365 |
from typing import List
from typing import Union
def score_tours_absolute(problems: List[N_TSP], tours: List[Union[int, NDArray]]) -> NDArray:
"""Calculate tour lengths for a batch of tours.
Args:
problems (List[N_TSP]): list of TSPs
tours (List[Union[int, NDArray]]): list of tours (in either... | b13ad2df2bfaf58f2b6989f2f2e67d917475b5bb | 1,367 |
def has(pred: Pred, seq: Seq) -> bool:
"""
Return True if sequence has at least one item that satisfy the predicate.
"""
for x in seq:
if pred(x):
return True
return False | bc41ceb21804cd273d0c2a71327f63f2269763d9 | 1,368 |
from typing import Optional
from typing import Union
from typing import List
from typing import Dict
from typing import Any
import re
from datetime import datetime
def _get_dataset_domain(
dataset_folder: str,
is_periodic: bool,
spotlight_id: Optional[Union[str, List]] = None,
time_unit: Optional[str]... | bc230145eee3f60491b4c42453fcbf5145ac7761 | 1,369 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.