content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def byte_builtin():
"""byte: Immutable bytes array."""
return bytes("\xd0\xd2NUT", "utf-8").decode() | 62e0d556d20ece651adb0a13b11d07670e0ea4f6 | 35,960 |
import torch
def predict_interaction(model, n0, n1, tensors, use_cuda):
"""
Predict whether a list of protein pairs will interact.
:param model: Model to be trained
:type model: dscript.models.interaction.ModelInteraction
:param n0: First protein names
:type n0: list[str]
:param n1: Secon... | 2c7ffecbd4435c7a5df620f895e9f3c299684494 | 35,961 |
def hessian(f, varlist, constraints=[]):
"""Compute Hessian matrix for a function f wrt parameters in varlist
which may be given as a sequence or a row/column vector. A list of
constraints may optionally be given.
Examples
========
>>> from sympy import Function, hessian, pprint
>>> from s... | 7033abc3342d3de4efb91a3a461b8c09632bc395 | 35,962 |
def extract_column_names(row_list):
"""
Extract names of columns from row list obtained from table csv. The first row contains all row names
:param row_list: List of all rows in csv used for table creation
:return: List of names present in table csv
"""
return row_list[0] | 2adef82a7f583c262922ad28aa0de47b8b9b5e51 | 35,963 |
def index_to_point(index, origin, spacing):
"""Transform voxel indices to image data point coordinates."""
x = origin[0] + index[0] * spacing[0]
y = origin[1] + index[1] * spacing[1]
z = origin[2] + index[2] * spacing[2]
return (x, y, z) | 072f1ad5d1adc1e81d4771725475f6a07f32f3ce | 35,964 |
def MakeEmptyTable(in_table=[[]], row_count=0, column_count=0):
"""
1 Read in *in_table*
2 Create an empty table
of '' values,
which has with the same number of rows and columns as the table,
(where columns based on the first row).
3 If the user has specified *row_count* and/or ... | 55b32c2914cb8e2194999e1b8ba2211373ef1bcb | 35,965 |
import torch
def choose_pseudo_gt(boxes, cls_prob, im_labels):
"""Get proposals with highest score.
inputs are all variables"""
num_images, num_classes = im_labels.size()
boxes = boxes[:,1:]
assert num_images == 1, 'batch size shoud be equal to 1'
im_labels_tmp = im_labels[0, :]
gt_b... | 7565a9a72052c839cad5cf12033fdf144bfcb4b0 | 35,966 |
def transform_covariance_matrix(transformation, histogram):
"""
Compute the covariance matrix of a new histogram given by:
new_histogram = transformation * histogram
"""
A = transformation
V = compute_numpy_covariance_matrix(histogram)
return A * V * A.T | f75918f83fdc8b06ab6c4a2b973a02549cb286d5 | 35,968 |
import math, random
def split_list(data, splits={'train': 8, 'test': 2}, shuffle=True, seed=0):
"""
Split the list according to a given ratio
Args:
data (list): a list of data to split
splits (dict): a dictionary specifying the ratio of splits
shuffle (bool): shuffle the list befo... | d9b25512e666a03ec2b589850c47a45231b279a0 | 35,969 |
def decoder_gen(
original_input: tuple,
decoder_config: dict
):
"""
Create the architecture for the VAE decoder
"""
decoder_inputs = keras.layers.Input(shape=[decoder_config["latent_dim"]])
print("decoder_inputs", decoder_inputs._keras_shape)
# Reshape input to be an image
#for ori... | fdcc683d48c795fba7e25c4ce47bf71a9459b6e4 | 35,970 |
def root():
"""
root - returns 200 OK
"""
return Response("It's alive!", status=200) | 5fa735a9cc2242928165d4e7c58e7ac576973044 | 35,972 |
def testplugin(module):
"""returns True if module has nessesary parameters"""
logger.write( module.title )
return True | c2e66b38735e43e16f351fde5d59a43d71a0b734 | 35,973 |
import requests
def put(*args, **kwargs):
"""Sends an HTTP PUT Request.
:param args: URL argument on the first index(args[1]).
:param kwargs: Optional arguments that ``requests.put`` takes.
:returns: :class:`Response` object or `None` if an error occurred.
:rtype: :class:`requests.Response` or `... | dc2e01aa6f6c293264b0435eeca9adf17a95820d | 35,974 |
async def save_transform(data):
"""
Calculate the transormation matrix that calibrates the gantry to the deck
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current sessio... | 696b92dbba0c220988129d64d14f5d1f9e2ab828 | 35,975 |
import unittest
def test_with_html():
"""Runs the unit tests with html."""
tests = unittest.TestLoader().discover('./app/test', pattern='test*.py')
outfile = open("./Report.html", "wb")
runner = HTMLTestRunner(
stream=outfile,
title='Unit Test Backend Report',
... | 2067907861625118e4cec54d1d02638b6b41cac2 | 35,978 |
def cpm_what_channels(folder):
"""Helper functions to print available channels given a folder with
polysomnography files"""
pg = PSGcompumedics(folder)
return pg.available_channel | d8b494ff93917769272036d2eac570838f8aca5d | 35,979 |
def all_close(goal, actual, tolerance):
"""
Convenience method for testing if a list of values are within a tolerance of
their counterparts in another list
@param: goal A list of floats, a Pose or a PoseStamped
@param: actual A list of floats, a Pose or a PoseStamped
@param: tolerance ... | a6aa910798e8ad6516274cee49bc2c2445afc5d3 | 35,980 |
def cloud_to_clusters(cloud: np.array) -> np.array:
"""Converts provided cloud into a set of clusters."""
clusters = defaultdict(lambda: [])
for vertex in cloud:
center = tuple(vertex[6:9])
if center != (0, 0, 0):
clusters[center].append(vertex)
print(' * [INFO]', len(list(c... | 1a7d5396e238b622e2dd3339990c6d876e689503 | 35,981 |
def split_remote_url(url):
"""check if the user provided a local file path or a
remote. If remote, try to strip off protocol info.
"""
remote_url = is_remote_url(url)
if not remote_url:
return url
for prefix in REMOTE_PREFIXES:
url = url.replace(prefix, '')
if '@' in ur... | e672d79a7b00f1a0c6928869efe5ca811673edaa | 35,982 |
import json
def load_json(filename, user_limit=0, badge_limit=0):
"""
Loads data form JSON
"""
with open(filename) as f:
data = json.loads(f.read())
if user_limit:
data['transactions'] = data['transactions'][:user_limit]
if badge_limit:
data['badges'] = data['badges'][:... | 79890f86dcc0090f89b7c401959e3e2dfc86828c | 35,983 |
def lon2decimal(input):
"""
Convert a Longitude into decimal angle.
"""
lng_degrees = int(input[0:3])
lng_minutes = int(input[3:5])
lng_seconds = float(input[5:-2])
lng_negative = ('W' == input[-1])
return dms2decimal(lng_degrees, lng_minutes, lng_seconds, lng_negative) | 557af79e9ef4fcd773ab28fea4efa99fbeb1ed38 | 35,984 |
def get_coordinate_color(color_image, coordinate, colors: list):
"""
Takes a color_image, coordinate (tuple), and list of color thresholds in HSV.
If the pixel is within a color threshold, return the index of the color in the list.
Coordinate should be in y, x format.
"""
try:
if coordinate == None:
return... | 3dade67def84f6fde70df3a7241e410c306a3806 | 35,985 |
def constraint_wrapper(fun, constraint):
"""
Wrap a function such that it's first argument is constrained
"""
def inner(x, *args, **kwargs):
"""the wrapped function"""
return fun(constraint(x), *args, **kwargs)
return inner | f9055fe2cd269e4586c545bfa951bdf2ba0677c1 | 35,986 |
import collections
def parse():
"""Parse input. Return the polymer template, its pairs, and the rules."""
with open('../data/day14.txt') as f:
polymer = f.readline().strip()
pairs = collections.defaultdict(int)
for i in range(len(polymer) - 1):
pairs[polymer[i:i+2]] += 1
... | b1e00b1176a6e60362af47e0fda9113104ed8083 | 35,988 |
def tourney_key(proto_obj):
"""Build a key from a scores_messages.Tournament protobuf object."""
return tourney_key_full(proto_obj.id_str) | 768a1e84b7ce95ec65450cb6775355b48704b335 | 35,989 |
import re
def timedelta_from_duration_string(s):
"""Convert time duration string to number of seconds."""
if re.match(r'^\d+$', s):
return timedelta(seconds=int(s))
td_args = {}
for part in s.split(','):
part = part.strip()
m = re.match(r'(\d+)\s+(year|month|day|hour|minute|se... | b3c7bd937a40057518cfb19eb2af2ff3bb070602 | 35,990 |
import functools
def wrapped(wrapped_function, additional_result_wrapper=None, self_index=0):
"""
Using these decorators will take care of unwrapping and rewrapping the target object.
Thus all following code is written as if the methods live on the wrapped object
Also perfect to adapt free functi... | 0f5c024109ecab4103d70feb5c04a84323180d30 | 35,991 |
def format_y_ticks_as_percents(plot):
"""Formats y ticks as nice-looking percents.
Args:
plot: matplotlib.AxesSubplot object.
"""
y_ticks = plot.get_yticks()
plot.set_yticklabels(get_percent_strings(y_ticks))
return plot | 5d45ede7fa51fbe9d18fd9cd2130714035b3e6a1 | 35,993 |
def can_cast(value, class_type):
"""
Check if the value can be cast to the class_type, used in the parse tcl string function for tcl expressions like
[Ada inputs 0] or [Ada alias robotblur]
Args:
value (object): The object we're attempting to cast.
class_type (class): The class we're at... | 85c415d2eaadb16a532e209110c1fd0f778cb681 | 35,994 |
def conv(
value,
filter_size,
output_dim,
dropout=0.0,
activation="linear",
padding="valid",
weight_source=None):
"""
Perform a single scale of convolution and optionally add spatial dropout.
"""
if weight_source is None:
conv_layer = Conv1... | 19b002b5059ff28da5cdf255fde8547e3597852c | 35,995 |
def insert_row(dataset_name, position, validate=False):
"""Create instance of insert row command.
Parameters
----------
dataset_name: string
Name of the dataset
position: int
Index position where row is inserted
validate: bool, optional
Validate the created command speci... | bc2fed6ce8a6a50a21bb1e8c60d067518722a628 | 35,996 |
def build(argmap, data):
"""Builds an array of arguments from the provided map and data.
The argmap must consist of a mapping of keys to argbuilder functions.
keys in the argmap are indexed into data, and if they are present, the
corresponding values are passed to the corresponding argmap function. Th... | d9c6c9eede6d6a9ae36fea77dceb3c70cbfbdbbd | 35,997 |
def get_prox_dist_points_cll(ppCll1, key=[]):
""" get prox and dist ends of the centerline assuming that origin is cranial,
right, anterior
"""
# Get prox and dist point for ppCll1
pends1 = np.array([ppCll1[0], ppCll1[-1]]) # pp centerline is in order of centerline points
if 'vLRA' in key:
... | 418f7aea0d7fba1fa3201deed02f61c0e7c4a804 | 35,998 |
def proxy_a_distance(source_X, target_X, verbose=False):
"""
Compute the Proxy-A-Distance of a source/target representation
"""
nb_source = np.shape(source_X)[0]
nb_target = np.shape(target_X)[0]
if verbose:
print('PAD on', (nb_source, nb_target), 'examples')
multiple_search = Fals... | 1bdb183717d16daad4377436376ee2d0118fc7e4 | 35,999 |
def pubkey_to_bech32_address(data: bytes, witver: int) -> BTCAddress:
"""
Bitcoin pubkey to bech32 address
Source:
https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program
https://github.com/mcdallas/cryptotools/blob/master/btctools/address.py
May raise:
- EncodingErr... | 348c68db3feaa994ea55161456f5559613f86a2f | 36,000 |
def get_gender(id):
"""
:param id: feature id
:return: feature dictionary
"""
for gender in __gender_dict:
if __gender_dict[gender] == id:
return gender
raise ValueError("Id does not correspond to a Universal Dependency gender") | 26d399507159a6992d67000c2e03164b3de6c82b | 36,001 |
import torch
def create_supervised_evaluator(
model, prepare_batch, metrics=None, device=None, non_blocking=False, output_transform=val_transform,
):
"""Factory function for creating an evaluator for supervised segmentation models.
Args:
model (`torch.nn.Module`): the model to train.
prepar... | 7c5cd0f778ed7785af9fe7460c5c0d452201fbe1 | 36,002 |
def fit_datapack(datapack,template_datapack,ant_idx = -1, time_idx=-1, dir_idx=-1, freq_idx=-1):
"""Fit a datapack to a template datapack using Bayesian optimization
of given kernel. Conjugation occurs at 350km."""
antennas,antenna_labels = datapack.get_antennas(ant_idx)
directions, patch_names = datap... | 804b2b5e7b8bf31d9301e16636e7a14202e23b76 | 36,004 |
def get_similar_pkg_installed_by_conda(ggd_recipe):
"""Method to get a list of similarly installed package names, referring to package installed by conda
get_similar_pkg_installed_by_conda
==================================
Method to identify if there are similar packages to the one provided installed ... | 1d8083626fe1dd71eb6d706b3f2440e803d930a6 | 36,005 |
from re import T
import numpy
def pinv(mat: T.Tensor) -> T.Tensor:
"""
Compute matrix pseudoinverse.
Args:
mat: A square matrix.
Returns:
tensor: The matrix pseudoinverse.
"""
return numpy.linalg.pinv(mat) | 028c0376dcab3838e31d8b247e4ccf630905d54f | 36,006 |
def devices_date_stamper(devices):
"""
Return a function that given a date time will return the dates when devices
will make their requests.
:param devices:
:return:
"""
def mapper(date):
def stamper(x):
return date + timedelta(seconds=x)
return map(stamper, next... | 3ce0d377f1bdb3938a38e5fc60e6e3098ecc66e5 | 36,007 |
from typing import List
def getTestFragments() -> List[str]:
"""
Returns a small list of testing fragments.
>>> len(getTestFragments())
5
"""
return ['tttttt', 'ttttgg', 'tggaga', 'agacgc', 'cgcggg'] | 4bd66b0a0c90df0d20f3d66d9b789a31419e63f6 | 36,008 |
def json_response(data, code=200, mimetype='application/json'):
"""
For ajax(json) response, wrapper json data to convert HttpResponse.
"""
resp = HttpResponse(data, mimetype)
resp.code = code
return resp | ebcbcc94026892d7de9d4be629a8be29c660dfd1 | 36,009 |
def get_funds_list(country=None):
"""
This function retrieves all the available funds and returns a list of each one of them.
All the available funds can be found at: https://www.investing.com/funds/
Args:
country (:obj:`str`, optional): name of the country to retrieve all its available funds f... | d9eed610752d87a797e922fa90dd300ebc5c4526 | 36,010 |
def powerlaw_dl(p, x):
"""
p are parameters of the model
"""
return p[0]*(x/80.)**(p[1]+2) | d2d0a331b260514a3e5a6dd0d78d2a55e6d1eedd | 36,011 |
import math
def poisson_trunc(expectation, top):
"""
Returns a random variable following a Poisson distribution with expected
value `expectation`, truncated so that values greater than `n` are not
possible.
The probability that the value exceeds `n` is added onto the probability
for `n`.
... | 6dd786220afbf655ecc509c514c0f432a15bbc48 | 36,012 |
def get_forecast_metadata_variables(ds):
"""
Returns a list of variables that represent forecast reference time
metadata.
:param netCDF4.Dataset ds: An open netCDF4 Dataset.
:rtype: list
"""
forecast_metadata_standard_names = {
"forecast_period",
"forecast_reference_time",
... | 83b8fe0eb785c1a3129ec19df680ce135cd3fa82 | 36,014 |
def feet(i):
"""
feet(i)
Return i (in inches) converted to feet.
"""
return i / 12 | bff46c1399aabee1f589dea98c9c43ced30d0756 | 36,015 |
def confirm_action(msg):
"""Ultra-lightweight confirmation dialog"""
return ConfirmAction(app.window, _("Are you sure?"), msg).run() | 119d8cdbb8ad1ef65d4bba67a4026f4335c451b8 | 36,016 |
def create_dataset(path, column_name, label_name, defaults, batch_size, shuffle):
""" Create tf.dataset from csv file.
Args:
path (str): Path to the csv file.
column_names (list:str): List of string to specify which columns to use in dataset (including label).
label_name (str): Colu... | 91428eef76aed05e8b5c79cdc9227e6cf759d81c | 36,017 |
def canonical_letter_permute_form(F, word):
"""
Apply a permutation of the letters of F so
that the different letters appearing in the
word appear in order (1,2,3,...).
"""
assert is_FreeGroup(F), "F must be a free group"
r = F.rank()
assert word in F, "word must be in F"
word_rep =... | f12897c981137a672b1e64391aee2763a670b547 | 36,018 |
def get_16bytes_from_seed(n):
"""TI pseudo-random number generator"""
mod1 = 2147483563
mod2 = 2147483399
mult1 = 40014
mult2 = 40692
if n:
seed1 = (mult1 * n) % mod1
seed2 = n % mod2
else:
seed1 = 12345
seed2 = 67890
result_arr = bytearray(16)
for i... | 4e1d3aad238d0d6a13921052b12d18a474ad9b08 | 36,019 |
def remove_first_space(x):
"""
remove_first_space from word x
:param x: word
:type x: str
:return: word withou space in front
:rtype: str
"""
try:
if x[0] == " ":
return x[1:]
else:
return x
except IndexError:
return x | f84819fe7d486851749945e932590900c125abe7 | 36,020 |
def sum_merge_tables(df1, df2, policy_id_column_name, df1_group_by, df2_group_by, df1_kpis, df2_kpis, df_no_dupl=None):
"""
Sums separately two dataframes and merge them
Arguments --> the two 2 dataframes to sum and merge, the policy id column name
the variables to aggregate on in ... | 955505efc0535f198c4ac557d62f05350e315b31 | 36,021 |
def thcf_partial1(x):
""" Partial derivative of the Three-Hump Camel Function with respect to x1.
"""
partial = x[1] + 4 * x[0] - 4.2 * (x[0] ** 3) + (x[0] ** 5)
return partial # Gradient 1 | cccc2505978cc49fffa0a445157ba5fdaf0abc30 | 36,022 |
def props(prop_name: str, *prop_names: str) -> "PropertyFilter":
"""
Factory to create filter using list of props
"""
def prop_filter(*, prop: "PropertyName", path: "PropertyPath") -> bool:
return any(str(prop) == p for p in (prop_name, *prop_names))
return prop_filter | b3bf389ebe63b11ad4c79fab244491e25b39bca0 | 36,023 |
def add_coords(filtered_lst):
""" Find coordinates for list of films """
for line in filtered_lst:
try:
location = line[2]
location = location.split(", ")
geolocator = geopy.Nominatim(user_agent="main.py")
geocode = RateLimiter(geolocator.geocode, min_del... | 31ee2bd4c856afef2d51f72ad130e2be37556594 | 36,024 |
def rphiz_to_xyz(values):
"""Converts axis values from cylindrical coordinates into cartesian coordinates
Parameters
----------
values: array
Values of the axis to convert (Nx3)
Returns
-------
ndarray of the axis (Nx3)
"""
r = values[:, 0]
phi = values[:, 1]
z = va... | 523631b90957819826e244614258dbb6be77bfd0 | 36,025 |
def build_load_statement(tablename, retry=True, options=""):
"""build a command line statement to upload data.
Upload is performed via the :doc:`csv2db` script.
The returned statement is suitable to use in pipe expression.
This method is aware of the configuration values for database
access and th... | 8917396c7d5650bf1777f3b2e31c495a2b28baf2 | 36,026 |
def recentlist():
""" Return a list of recently completed games for the indicated user """
rq = RequestData(request)
user_id = rq.get("user")
versus = rq.get("versus")
count = rq.get_int("count", 14) # Default number of recent games to return
# Limit count to 50 games
if count > 50:
... | 8d85da92a452d279db94e225d625688d5956b799 | 36,027 |
def nice_std(ls):
"""
Method to return standard deviation of a list or equivalent array with NaN values
Args:
ls: (list), list of values
Returns:
(numpy array), array containing standard deviation of list of values or NaN if list has no values
"""
if len(ls) > 0:
ret... | e812d351e67f38cbdf062ebd3a54e972501bc9f3 | 36,028 |
def check_pano_submission(path):
"""Checks if all files required for the submission exist and are in the right format."""
ready_for_submission = True
# check if path contains a predictions.json
json_path = path / 'predictions.json'
print('Checking for "predictions.json" ... ', end='', flush=True)
if json_path... | f9f03b581d4af5d603694b7c29b2ab6fd42e81b0 | 36,029 |
def leftmostNonzeroEntries(M):
"""Returns the leftmost nonzero entries of M."""
return [ abs(M[l][M.nonzero_positions_in_row(l)[0]])
for l in range(0,M.dimensions()[0])
if M.nonzero_positions_in_row(l) != [] ] | 9e42297dc3000a41dcdceebff10c4fc53e1709ac | 36,030 |
def tophat_binary(image, kernel=None, n=None):
"""
It is the difference between input image and
opening of the image
"""
tophat = cv2.morphologyEx(image,cv2.MORPH_TOPHAT, kernel)
return tophat | 6903257998cc78cd1d86fa8af318fbde3e6ed725 | 36,031 |
def kl_div(input, label, reduction='mean', name=None):
"""
This operator calculates the Kullback-Leibler divergence loss
between Input(X) and Input(Target). Notes that Input(X) is the
log-probability and Input(Target) is the probability.
KL divergence loss is calculated as follows:
$$l(x, y) =... | ef7629de18522ffd310e490fe171c1c0de5dcbfd | 36,032 |
def _json_target_decode(dct):
"""Target json object decoder"""
if "itf" in dct:
dct["itf"] = CanedgeInterface[dct["itf"].upper()]
if "chn" in dct:
dct["chn"] = CanedgeChannel[dct["chn"].upper()]
if "db" in dct:
dct["db"] = dct["db"].lower()
if "method" in dct:
dct["me... | 8a252e097c71bd9cdf967c9242aa76d157e01f8c | 36,033 |
def init_ax(fontsize=24, nrows=1, ncols=1):
"""
:param fontsize:
:return:
"""
font = {'family': 'Times New Roman'}
mpl.rc('font', **font)
mpl.rcParams['legend.fontsize'] = fontsize
mpl.rcParams['axes.labelsize'] = fontsize
mpl.rcParams['xtick.labelsize'] = fontsize
mpl.rcParams[... | b163c6ae2bfc99d06941088fc202bd6650dab038 | 36,034 |
def is_sequence(arg):
"""Returns True is passed arg is a list or a tuple"""
return isinstance(arg, list) or isinstance(arg, tuple) | 12a0a0186695f8b79a48905a22c0c1c69cde219f | 36,035 |
def _Levy(x):
"""
Global Minimum at `z_1 = (1, 1, ..., 1)` with `f(z_1) = 0`.
"""
w = 1 + (x - 1) / 4
w_mid = w[:, :-1]
f = np.sum(np.multiply((w_mid - 1)**2, 1 + 10 * np.sin(np.pi * w_mid + 1)**2), axis = 1)
f += np.sin(np.pi * w[:, 0])**2 + (w[:, -1] - 1)**2 * (1 + np.sin(2 * np.pi * w[:, -1])**2)
... | f648e2b417ed8c7c025d5e8d09f6e8b44cd4ab11 | 36,037 |
def generateWorld2():
"""
Generates world with collidable walls and grass paths\n
Types:\n
Grass -> 0\n
Wall -> 1
"""
walls = 0
grass = 0
#possibility = [None, 0, 1, None, None]
for i in range(0, worldSize):
for j in range(0, worldSize):
worldmap[i][j]["TYPE"... | bfc13e2345049aadcb3d6216759cd8787ac4b89b | 36,038 |
import torch
def pad_shift(x, shift, padv=0.0):
"""Shift 3D tensor forwards in time with padding."""
if shift > 0:
padding = torch.ones(x.size(0), shift, x.size(2)).to(x.device) * padv
return torch.cat((padding, x[:, :-shift, :]), dim=1)
elif shift < 0:
padding = torch.ones(x.size(... | 95f883714222787eb5fd92f7a0c6f1777c989399 | 36,039 |
import asyncio
async def async_million_state_changed_helper(hass):
"""Run a million events through state changed helper."""
count = 0
entity_id = 'light.kitchen'
event = asyncio.Event(loop=hass.loop)
@core.callback
def listener(*args):
"""Handle event."""
nonlocal count
... | c8cb579e277fc889da4e2732164e95c70ae4b7ac | 36,040 |
def add_dim(*, opt=False, shapes=None, typ=None, use_var=False):
"""Construct a new dimension type based on the list of 'shapes' that
are present in a dimension.
"""
if use_var:
offsets = [0] + list(accumulate(shapes))
return "%svar(offsets=%s) * %s" % ('?' if opt else '', offsets, ty... | a8cd553c736ff8f20d043c873e9c71589d807698 | 36,041 |
def _allocate_returned_states(model, inputs, return_states=None):
"""Create empty placeholders for model outputs."""
seq_len = inputs[list(inputs.keys())[0]].shape[0]
vulgar_names = {"reservoir": model.reservoir, "readout": model.readout}
# pre-allocate states
if return_states == "all":
sta... | 722259f07fbd1b0f5ced0883112ecfb5fea4f81a | 36,042 |
from typing import Dict
from typing import Mapping
import logging
def from_obographs(
jsondoc: Dict, curie_map: Dict[str, str], meta: Dict[str, str] = None
) -> MappingSetDataFrame:
"""
Converts a obographs json object to an SSSOM data frame
Args:
jsondoc: The JSON object representing the... | 3b91af2fceb49ea1ff1c43edb6273c54309f105a | 36,043 |
from typing import List
import torch
from typing import Optional
def nll_loss_multimodes(pred: List[torch.Tensor], data: torch.Tensor, mask: torch.Tensor, modes_pred: torch.Tensor, noise: Optional[float]=0.0 ) -> float:
"""NLL loss multimodes for training.
Args:
pred is a list (with N modes) of predictions
... | 4d0b342b936111a65fdea4a880d122c6d4837b2e | 36,044 |
def pmps_to_mpo(pmps):
"""Convert a local purification MPS to a mixed state MPO.
A mixed state on n sites is represented in local purification MPS
form by a MPA with n sites and two physical legs per site. The
first physical leg is a 'system' site, while the second physical
leg is an 'ancilla' site... | 53ec35adbe5943f08ebf5370e1329f252f8422be | 36,045 |
def pynautobot_api():
"""Factory to create pynautobot api instance."""
return Api(url="https://mocknautobot.example.com", token="1234567890abcdefg") | bb8f4094e6700140473d03b76168ab31269fd7cb | 36,046 |
def actionAngle_physical_input(method):
"""Decorator to convert inputs to actionAngle functions from physical
to internal coordinates"""
@wraps(method)
def wrapper(*args,**kwargs):
if len(args) < 3: # orbit input
return method(*args,**kwargs)
ro= kwargs.get('ro',None)
... | 754aae2faf086036853be029b56452edd5567400 | 36,047 |
def super_reduced_string(s):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/reduced-string/problem
Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest
length by doing a series of operations. In each operation he selects a pair of ... | 09c48f38a877ff9ae92b985bd793224bd81247c8 | 36,049 |
from IPython import get_ipython
def is_in_notebook():
"""Determines if current code is executed from an ipython notebook.
If is_in_notebook() is True, then is_in_ipython() must also be True.
"""
is_in_notebook = False
if is_in_ipython():
# The import and usage must be valid under the execution path.
... | 7e1a49e74e116798dbb6bbcd72a80405fe3228a9 | 36,051 |
def xor_hex_strings(str1, str2):
"""
Return xor of two hex strings.
An XOR of two pieces of data will be as random as the input with the most randomness.
We can thus combine two entropy sources in this way as a safeguard against one source being
compromised in some way.
For details, see http://c... | 2a992bd8cc2542e1bffd5d3ab29f7f96b66acfdc | 36,052 |
def CreateIonDataFromInput(ionInputList):
"""
input: ionInputList <list>(string, string, string, string): list of ions to specify and their properties
summary: takes values in each entry of the ionInputList and makes a IonDataDict
output: dictionary<string, Ionic>: dict of Ionic class wich contains info... | 8bcdc503a4a82c959f69134c375e26971942677a | 36,053 |
import torch
def batch_img(data, vocab):
"""Pad and batch a sequence of images."""
c = data[0].size(0)
h = max([t.size(1) for t in data])
w = max([t.size(2) for t in data])
imgs = torch.zeros(len(data), c, h, w).fill_(1)
for i, img in enumerate(data):
imgs[i, :, 0:img.size(1), 0:img.si... | e123813b14e7e35bea4786a7fc1772bdfb0673a1 | 36,054 |
def _build_neural_network_formulation(block, network_structure, layer_constraints, activation_constraints):
"""
Adds the neural network formulation to the given Pyomo block.
Parameters
----------
block : Block
the Pyomo block
network_structure : NetworkDefinition
the neural netw... | 5df1cb370d3d6aec19102e966fd9468b7fcc129d | 36,055 |
def Add(path, value, ttl_seconds=DEFAULT_TTL_SECONDS):
"""Atomically adds an entry to memcache only if it does not already exist.
Args:
path: A list of items (see ToCacheKey).
value: The value to store in the cache.
ttl_seconds: An integer number of seconds to keep the value in the cache.
Returns:
... | c105aaad0fd6e053c245431a85ea0148dda19c8b | 36,056 |
def node(helper):
"""
Report any storage capacity and useage inconsistencies between the
storage node and the API
"""
# Get a list of active LVM Volumes
lvs = [lv for lv in helper.volumes._scan_volumes()
if lv['origin'] == '']
# Get our node id
node_id = request(helper, 'node... | 9a5ceaa695c9ab0394826ae1046c0c66436f0284 | 36,057 |
def rotate_tour(tour, start=0):
"""
Rotate a tour so that it starts at the given ``start`` index. This is
equivalent to rotate the input list to the left.
Parameters
----------
tour: list
The input tour
start: int, optional (default=0)
New start index for the tour
Returns
-------
rotated: ... | b2356aaecb00dc993e88b5f7105c0b4aed495521 | 36,058 |
def get_mesh(X, h=0.02, padding=0.5):
"""Build a regular meshgrid using the range of the features in X
"""
x_min, x_max = X[:, 0].min() - padding, X[:, 0].max() + padding
y_min, y_max = X[:, 1].min() - padding, X[:, 1].max() + padding
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min,... | e67756a6dacd62db1d77bfd4a75c6d55e512a8b4 | 36,059 |
def setting(key, default=None, domain=None):
"""
Settings helper based on saltstack's query
Allows a simple way to query settings from YAML
using the style `path:to:key` to represent
path:
to:
key: value
"""
rtn = settings.PROMGEN
lookup = key.split(":")
if domain:
... | d7afd5be423e8934490d99d9090fec9ac53809dc | 36,060 |
def literal_schema(literal, theories, default_theory=None,
theory_assertion=None):
"""Return the schema that applies to LITERAL or None.
:param: LITERAL is a Literal for which we want the schema
:param: THEORIES is a dictionary mapping the name of the theory
to the theory obje... | d9848dc3311732201745000b3ecc514652192a89 | 36,061 |
def green(inputs, value=255, **kwargs):
"""Generate pure green channel"""
x = np.zeros_like(inputs)
x[..., 1] = value
return x | f1258447501737b13540fe1e83656a082eef88a8 | 36,062 |
import torch
def solve_kernel(data: torch.Tensor, kernel: Kernel, koopman: bool = True):
"""Pseudoinverse solution for Koopman & Perron-Frobenius operators over RKHS
Args:
data: simulation data (see `prep_snapshots`)
kernel: positive-definite kernel.
koopman: if True, Koopman operator, else Perron-Frobenius... | 87e2e0ccb9f05bf8807b2adb84e14ad9c1248a1f | 36,063 |
def cadindateDetailsofEvent(request):
"""
Returns candidate details
:param request:
:return: boolean
"""
try:
if request.method=='GET':
id=request.GET.copy()
if 'id' in id :
eventRegistrationId = id['id']
if EventRegistration.object... | dcdca50d76d8a4caae0033849eb1326dc08a9363 | 36,064 |
def no_space(original_str, keyslist, replace_str):
"""
:param original_str: A string found in the keyslist
:param keyslist: A list of keys found in the each of the two knowledge
graph dictionaries (nodes and edges)
:param replace_str: A string to replace the original_str in the keysl... | 1184effc9dc301b234e01c469839783f2c16e25b | 36,065 |
from typing import Callable
from typing import Optional
from typing import Union
from typing import Tuple
from typing import List
def scipy_expm_solver(
generator: Callable,
t_span: Array,
y0: Array,
max_dt: float,
t_eval: Optional[Union[Tuple, List, Array]] = None,
):
"""Fixed-step size matri... | fc1c9c1a40ee1b272b520ac33c1f52d198999d7c | 36,067 |
from datetime import datetime
def time_to_hhmmss(tm: datetime.time) -> str:
"""Convert a datetime.time to HHMMSS string."""
if tm is not None:
return "%.2d%.2d%.2d" % (tm.hour, tm.minute, tm.second)
else:
return "" | 936cc1784d1f3cd5d3ec2809e3aaedc98a2fb7ef | 36,068 |
def parse_devices(header, lines):
"""Parses output of lsblk"""
cols = parse_header(header)
mappings = {}
flat = {}
parents = []
indent = 0
last = None
for line in lines:
index = 0
name = None
mapping = {'children': [], 'parent': None}
for col in cols:
... | 1757dfb4901d78c4f543d440e3580a9a51919252 | 36,069 |
from typing import List
from typing import Dict
def _calc_j5_dependants(conf: List[BaseJoint], flag_sum: int, theta123: List[float], j5_solutions: Dict[bool, float],
tf14: np.ndarray, xdir: np.ndarray, zdir: np.ndarray) -> JointSolution:
"""
Calculate the dependant last joint for given... | 6501c82b90c2874eb36afde2f78328b68b695407 | 36,070 |
def format_data(value):
"""
返回百分数据的值
"""
return round(value*100, 1) | add5b16641f3cd0fef69f2cb54ce9448a2e1ad1b | 36,071 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.