content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def delete_data(data, object_name, **kwargs):
"""
Delete data
"""
data.delete()
is_queryset = isinstance(data, QuerySet)
return {
"is_queryset": is_queryset,
"data": data,
"object_name": object_name,
} | 28405ae426e53fc3637a4b281775cba99e112a0a | 3,659,100 |
def get_g(source):
""" Read the Graph from a textfile """
G = {}
Grev = {}
for i in range(1, N+1):
G[i] = []
Grev[i] = []
fin = open(source)
for line in fin:
v1 = int(line.split()[0])
v2 = int(line.split()[1])
G[v1].append(v2)
Grev[v2].append(v1)
... | f2771c28d6c86a0af035cc38cd5cdad2774b0dba | 3,659,101 |
def _mercator(lat_long):
"""
Calculate the 2D X and Y coordinates from a set of coordinates based on radius, latitude and longitude using the
Mercator projection.
:param lat_long: The coordinates of the points to be projected expressed as radius, latitude and longitude.
:type lat_long: list[tuple]
... | cc1f4eb97f4c5a1505b88ab5aa8fa6992744dccf | 3,659,102 |
def subjectForm(request, experiment_id):
"""
Generates the fourth page, the demographic/participant data form of an experiment.
"""
experiment = get_object_or_404(Experiment, pk=experiment_id)
form = SubjectDataForm(experiment=experiment)
t = Template(experiment.demographic_data_page_tpl)
... | 48273e891c87b30157c13c726376a9d3052eebe6 | 3,659,103 |
def sigma_0(x):
"""First rotational + shifting mixing function
σ_256_0(x) = ROTR_7(x) ⊕ ROTR_18(x) ⊕ SHR_3(x)
"""
return ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3) | 9090dc6652944189765657ad9b3650f54b10e70a | 3,659,104 |
from datetime import datetime
def edit_entry(edit_result):
"""Edit entry"""
new_entry = edit_result.copy()
edit_key = None
edit_value = None
date_keys = ["Date"]
int_keys = ["Time Spent"]
while edit_key not in edit_result:
reset_screen("key", "Please type the key you want to edit."... | e63b9d94f192fdc2175457ebc1ce7f9562e1cf41 | 3,659,105 |
import sys
import os
def build_input_files(filename, base_path = 'input_files', out = sys.stdout):
"""
build_input_files(filename, base_path = 'input_files')
takes a 'well-formated' input fileand outputs a
directory structure with the properly formated input files
created in them.
"""
... | a40def5dfc8d52f905e8a82ddafb5f756771a3e7 | 3,659,106 |
def srpd(mvec, k, ra, Nmax, w, V):
"""
Calculate the Steered Response Power Density (SRPD)
:param mvec: SHD coefficients for the TF bin to be analysed
:param k: Wave number (2*pi*f/c)
:param ra: Radius of the microphone array
:param Nmax: Maximum SHD order to be used
:param w: Diagonal eig... | 0506c76812bfdff447f09e4dae8380635e894040 | 3,659,107 |
import torch
def batch_inverse(tensor):
"""
Compute the matrix inverse of a batch of square matrices. This routine is used for removing rotational motion
during the molecular dynamics simulation. Taken from https://stackoverflow.com/questions/46595157
Args:
tensor (torch.Tensor): Tensor of s... | b8defb26561e38d5e16e2483f27287a334b2cd61 | 3,659,108 |
def create(**kwds):
"""
Add data.
"""
status_code = 200
message = "Successfully added data."
articles = []
for a in kwds.get("articles", []):
a = Article.query.filter_by(id=a).first()
if a:
articles.append(a)
cols = {"user_id": current_user.id, "name": kwds[... | a8add828427b285700f23a041bd2c592346775f2 | 3,659,109 |
def _center_size_bbox_to_corners_bbox(centers, sizes):
"""Converts bbox center-size representation to corners representation.
Args:
centers: a tensor with shape [N, 2] representing bounding box centers
sizes: a tensor with shape [N, 2] representing bounding boxes
Returns:
corners: tensor with shap... | 885bbbe2760a464c6fd3bad0811e91a70610eb8c | 3,659,110 |
from datetime import datetime
def get_starting_month(number_of_months_to_get,
include_actual_month=True,
actual_date=datetime.datetime.now()):
"""
Get starting month based on parameters
:param number_of_months_to_get: Numbers of months to get - e.g: 2
:par... | c075ef074b644749ca72955598c098cf76845608 | 3,659,111 |
import token
def cvt_raise_stmt(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base:
"""raise_stmt: 'raise' [test ['from' test | ',' test [',' test]]]"""
# 0 1 2 3 2 3 4 5
#-# Raise(expr? exc, expr? cause)
assert ctx.is_REF, [node]
if len(node.children) == 1:
... | 8e7809ff9317a285838f0c0a1a25a0b40634b88f | 3,659,112 |
def user_in_user_groups(user_id, **options):
"""
Get all user groups a user belongs to
:param user_id: The id of user
:param user_id: str
:param options: Generic advanced options dict, see online documentation
:type options: dict, optional
:re... | 70b83b81ee4d03e7ab5fff68be710c02c01aaa0d | 3,659,113 |
def read_book(title_path):
"""Read a book and return it as a string"""
with open(title_path, "r", encoding = "utf8") as current_file: #encoding = "utf8" causes a problem when running the code in Python 2.7. However, it runs normally when using Python 3.5.
text = current_file.read()
text = text.r... | e5273c6b0b71638b47ce5ee5beb33c715c914a1b | 3,659,114 |
from datetime import datetime
def eval_whole_scene_one_epoch(sess, ops, test_writer):
""" ops: dict mapping from string to tf ops """
global EPOCH_CNT
is_training = False
test_idxs = np.arange(0, len(TEST_DATASET_WHOLE_SCENE))
num_batches = len(TEST_DATASET_WHOLE_SCENE)
total_correct = 0
... | 0c5fd39c8cb464a0b4883be15aa687882a20f94a | 3,659,115 |
def _create_save_name(save_path: str, case_date: date, field_names: list, fix: str = "") -> str:
"""Creates file name for saved images."""
date_string = case_date.strftime("%Y%m%d")
return f"{save_path}{date_string}_{'_'.join(field_names)}{fix}.png" | a731effa50ae291df31fcd4b282a924a057561dd | 3,659,116 |
def list_favorite_queries():
"""List of all favorite queries.
Returns (title, rows, headers, status)"""
headers = ["Name", "Query"]
rows = [(r, favoritequeries.get(r)) for r in favoritequeries.list()]
if not rows:
status = '\nNo favorite queries found.' + favoritequeries.usage
else:
... | e3b20d3d06a76d7f621fa830e2d22f0d3e6614ad | 3,659,117 |
def random_portfolio_weights(weights_count) -> np.array:
""" Random portfolio weights, of length weights_count. """
weights = np.random.random((weights_count, 1))
weights /= np.sum(weights)
return weights.reshape(-1, 1) | 47ba5ea84b24ede66fe4d1071fb82f721a550995 | 3,659,118 |
def matrix2list(mat):
"""Create list of lists from blender Matrix type."""
return list(map(list, list(mat))) | 9b4b598eb33e4d709e15fd826f23d06653659318 | 3,659,119 |
def convert_handle(handle):
"""
Takes string handle such as 1: or 10:1 and creates a binary number accepted
by the kernel Traffic Control.
"""
if isinstance(handle, str):
major, minor = handle.split(':') # "major:minor"
minor = minor if minor else '0'
return int(major, 16)... | ed4ef5107178bd809a421e0b66c621d9bdaceef1 | 3,659,120 |
def index(request):
"""Display start page"""
return HttpResponseRedirect(reverse('admin:index')) | c237e46affb7217bbcfc1146d98f84fb1cc20cc6 | 3,659,121 |
import traceback
from datetime import datetime
async def check_data(user_input, hass, own_id=None):
"""Check validity of the provided date."""
ret = {}
if(CONF_ICS_URL in user_input):
try:
cal_string = await async_load_data(hass, user_input[CONF_ICS_URL])
try:
Calendar.from_ical(cal_string)
except E... | a0b9302cb1f69c98585edb0bae918675ceab32cf | 3,659,122 |
import os
import json
import warnings
def run(
uri,
entry_point="main",
version=None,
parameters=None,
docker_args=None,
experiment_name=None,
experiment_id=None,
backend="local",
backend_config=None,
use_conda=None,
storage_dir=None,
synchronous=True,
run_id=None,
... | 56c0c9f333e0b4861533c59db14793e5b3d9af1e | 3,659,123 |
def general_search_v2(params, sed_mod, lnprior, Alambda,
sed_obs, sed_obs_err=0.1,
vpi_obs=None, vpi_obs_err=None,
Lvpi=1.0, Lprior=1.0,
cost_order=2, av_llim=-0.001, debug=False):
"""
when p = [teff, logg, [M/H], Av, DM], t... | 9629d0ecdec38f4e55bf3becb219c5c348300988 | 3,659,124 |
import re
def demangle_backtrace(backtrace):
"""
Returns a demangled backtrace.
Args:
* backtrace, a backtrace to demangle
"""
new_bt = []
frame_regex = re.compile(FRAME_PATTERN)
lines = backtrace.splitlines()
for line in lines:
frame = frame_regex.match(line)
i... | 676b90c16223b24f539520306a7725434eb28363 | 3,659,125 |
import sys
import os
def resource_path(base_path, rel_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
# PyInstaller creates a temp folder and stores path in _MEIPASS
return os.path.join(getattr(sys, '_MEIPASS', base_path), rel_path) | aae3961d92f433aef4b8b3b4a1a946e89282548c | 3,659,126 |
def legendre(N, x):
"""
Returns the value of Legendre Polynomial P_N(x) at position x[-1, 1].
"""
P = np.zeros(2 * N)
if N == 0:
P[0] = 1
elif N == 1:
P[1] = x
else:
P[0] = 1
P[1] = x
for i in range(2, N + 1):
P[i] = (1.0 / float(i)) * ((2 * i - 1... | 0e02e19ef0a251aa4b30823d1598fc5fb8933288 | 3,659,127 |
def skip_any_whitespace(doc, idx):
"""Iterate through characters in ``doc`` starting from index ``idx`` until
a non-whitespace character is reached. This iteration will also attempt to
ignore comments.
Args:
doc (str): The JSPEC document.
idx (int): The starting index for the iterator.
... | 18038bce945fb35222254a0fedf5d3936bb83308 | 3,659,128 |
def normalized_cross_correlation(f, g):
""" Normalized cross-correlation of f and g.
Normalize the subimage of f and the template g at each step
before computing the weighted sum of the two.
Hint: you should look up useful numpy functions online for calculating
the mean and standard deviati... | fb6057d882b655a43a7d4a7d3c7ced00d32eeabf | 3,659,129 |
import numpy
def sphere_coordinates(sphere, inversion=False):
"""
Compute spherical coordinates (longitude, latitude) on a sphere.
Parameters
----------
sphere: (AimsTimeSurface_3_VOID)
a sphere mesh: vertices must be on a sphere with center 0.
inversion: bool
if True, the lon... | 82f9e9c0e969904414761ed2ebe70d30194277e5 | 3,659,130 |
from typing import Dict
def example_parameter_sets() -> Dict[str, ExampleParameterSet]:
"""Lists the available example parameter sets.
They can be downloaded with :py:func:`~download_example_parameter_sets`."""
# TODO how to add a new model docs should be updated with this part
examples = chain(
... | cd60157809ca2abae77bc4616c7c46db55580818 | 3,659,131 |
def get_height(img):
"""
Returns the number of rows in the image
"""
return len(img) | 765babc9fbc1468ef5045fa925843934462a3d32 | 3,659,132 |
def wpt_ask_for_name_and_coords():
"""asks for name and coordinates of waypoint that should be created"""
name = input("Gib den Namen des Wegpunkts ein: ")
print("Gib die Koordinaten ein (Format: X XX°XX.XXX, X XXX°XX.XXX)")
coordstr = input(">> ")
return name, coordstr | d38a728c5a6ecd1fde9500175ea5895ade8c6880 | 3,659,133 |
def car_following_with_adp(distance_2_tan, radian_at_tan, distance_integral, K, estimated_dis, rec):
""" Control with `distance_2_tan`, `radian_at_tan` and `distance_integral`
with `K` trained from the ADP algorithm.
While following the car in front of it with a simple P controller and `distance_2_c... | 7a49b257e7361451deae10d37a8d8ec811f4890d | 3,659,134 |
def construct_full_available(cards, suits):
"""
Construct suit availability grid - a list of available suits for each
rank slot in each player's deck. Returns grid and array giving the the
total number of available suits for each slot.
"""
num_players, num_in_deck = cards.shape
num_availabl... | 0f4b2712a1346372d0782edfbc7c7b69a8e9e8e6 | 3,659,135 |
import yaml
def get_commands_blacklist() -> list:
"""
Get commands from `features.yml` to blacklist,
preventing them from being added to the bot
:returns: list
"""
log.info("Getting commands blacklist...")
cmds = []
if osp.isfile(features_path):
with open(features_path, 'r'... | 6f76dbf354efff7b845a50ca8180a904b6d3a6d2 | 3,659,136 |
import io
def fit_gaussians(estimated_hapcov,
chromosomes=None, output_dir=None, cov_max=None, cov_min=None, level=0, cov_sample=None):
"""
Fits a 7-component Gaussian mixture model to the coverage distribution of the sample, using the appropriate attributes of the PloidyEstimation
obje... | 660952140f6ea8685488a108e11ea1ca6f4e7fc5 | 3,659,137 |
from natsort import natsorted
from sklearn.cluster import DBSCAN
def remove_outliers(cords, eps: int = 1, min_samples: int = 2):
"""
Remove outlying cells based on UMAP embeddings with DBScan (density based clustering)
Call as: sub.obs["d_cluster"] = remove_outliers(sub.obsm["X_umap"], min_samples = 10)
... | 0b4c581158bc3c074b60ad5d29b333418a4f52ce | 3,659,138 |
def sum_squares(n):
"""
Returns: sum of squares from 1 to n-1
Example: sum_squares(5) is 1+4+9+16 = 30
Parameter n: The number of steps
Precondition: n is an int > 0
"""
# Accumulator
total = 0
for x in range(n):
total = total + x*x
return total | 669a5aa03a9d9a9ffe74e48571250ffa38a7d319 | 3,659,139 |
def resolve_attribute(thing, name):
"""
A replacement resolver function for looking up symbols as members of
*thing*. This is effectively the same as ``thing.name``. The *thing* object
can be a :py:func:`~collections.namedtuple`, a custom Python class or any
other object. Each of the members of *thing* must be of ... | 76f7b4548a177168d98bb5cdf4c022bfe8e0d36e | 3,659,140 |
def moment_fluxes(indices, wts_left, wts_right, xi_left, xi_right):
"""
Computes moment fluxes
inputs:
-------
num_nodes: number of quadrature nodes, depends on inversion algorithm
indices: moment indices, size [ num_moments, num_internal_coords ]
wts_left: weights on the left side, ... | 24ed54b56afe127963e6cc7f9d74448e8415edb0 | 3,659,141 |
import argparse
import sys
def get_args():
"""Get the command-line arguments"""
parser = argparse.ArgumentParser(
description='Emulate wc (word count)',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file',
help='Input ... | 8a891c5b3dac1f62db31455d596d7744335d8530 | 3,659,142 |
def froc_curve_per_side(df_gt, df_pred, thresholds, verbose, cases="all"):
"""
Compute FROC curve per side/breast. All lesions in a breast are considered TP if
any lesion in that breast is detected.
"""
assert cases in ["all", "cancer", "benign"]
if not cases == "all":
df_exclude = df_g... | 6a113856a920f775be3ce652fa09d9d79fb9be00 | 3,659,143 |
import itertools
def make_lists(*args, **kwargs):
"""
The make_lists function attaches auxiliary things to an input key_list
of (normally) AD objects. Each key gets exactly one auxiliary thing from
each other list -- these lists can be as long as the key_list, or have
only one item in (in which ca... | 5bdfd32ad317238e21f631655d01bf629722c959 | 3,659,144 |
def get_free_comment_url_ajax(content_object, parent=None, ajax_type='json'):
"""
Given an object and an optional parent, this tag gets the URL to POST to for the
creation of new ``FreeThreadedComment`` objects. It returns the latest created object
in the AJAX form of the user's choosing (json or xml).... | 7d22d2f2b0e012d462d0244d8154cd9ae00ee608 | 3,659,145 |
import gc
def getDefensivePacts(playerOrID, askingPlayerOrID):
"""
Returns a list of CyPlayers who have a Defensive Pact with playerOrID.
The askingPlayerOrID is used to limit the list to players they have met.
"""
pacts = []
askedPlayer, askedTeam = getPlayerAndTeam(playerOrID)
askingPlayer, askingTeam = ge... | 246c67fa315f41ca2f417a880a970e52d68775c5 | 3,659,146 |
def cosine_score(vector1, vector2):
"""Calculate cosine cosine score between two spectral vectors."""
return np.dot(vector1, vector2)/np.sqrt(np.dot(np.dot(vector1, vector1), np.dot(vector2, vector2))) | 5b206abb179f1635eeda6267e8019901c480afad | 3,659,147 |
def fixture_times() -> Problem[int]:
"""Generate a problem which tests a times function."""
@test_case(4, 6)
@test_case(-2, 16)
@test_case(2, -3, aga_hidden=True, aga_output=-6)
@problem()
def times(x: int, y: int) -> int:
"""Compute x * y."""
return x * y
return times | a00286a5827ec0c4fe7cb390d0d420d11823eb15 | 3,659,148 |
def get_axis_bounds(ax=None):
"""Obtain bounds of axis in format compatible with ipyleaflet
Returns:
bounds np.array with lat and lon bounds.
bounds.tolist() gives [[s, w],[n, e]]
"""
if ax is None:
ax = plt.gca()
return np.array([ax.get_ylim(), ax.get_xlim()]).T | 32bc97cf6596775dbfdffea655f5346a1fd21764 | 3,659,149 |
def get_pymatgen_structure(cell:tuple) -> Structure:
"""
Get pymatgen structure from cell.
Args:
cell: Cell (lattice, scaled_positions, symbols).
"""
return Structure(lattice=cell[0],
coords=cell[1],
species=cell[2]) | c76e0e71da83737f079d36e56b4867e551affeff | 3,659,150 |
def get_next_event(event_id: int):
"""Returns the next event from the selected one.
This route may fail if the event is not repeated, or if the event is
too far ahead in time (to avoid over-generation of events).
"""
# TODO(funkysayu): Implement the user visibility limit.
# Check if we already... | 7a9865352dda9dd44c82a92f7f807a64a5ed993d | 3,659,151 |
def conditional_samples(x_3, x_prime_3, MC_method, M):
"""Generate mixed sample sets of interest distributed accroding to a conditional PDF.
Parameters
----------
x_3 : np.ndarray
Array with shape (n_draws, 3).
x_prime : np.ndarray
Array with shape (n_draws, 3).
MC_method : stri... | e80d238f27a65271115fd3de2f574bfc3bbdb432 | 3,659,152 |
def recombine(geno_matrix, chr_index, no_loci): #, no_samples):
"""
Recombine at randomly generated breakpoints.
"""
recomb = {0: 0, 1: 2, 2: 1, 3: 3} # '0|1' <-> '1|0'
no_samples = geno_matrix.shape[0]
#print(no_samples)
masked, bp_list = designate_breakpoints(chr_index, no_loci, no_sample... | 455ee154763b31e4d5baa9653caa9f9a118f248e | 3,659,153 |
def update_record_files_async(object_version):
"""Get the bucket id and spawn a task to update record metadata."""
# convert to string to be able to serialize it when sending to the task
str_uuid = str(object_version.bucket_id)
return update_record_files_by_bucket.delay(bucket_id=str_uuid) | ba0ed0af4e6a604801344aa459b6279c5a79dfae | 3,659,154 |
import platform
def check_platform():
"""
str returned
"""
return platform.system() | 73e813c55807e7d84517cb7ce51ce9db34e42c23 | 3,659,155 |
def get_field_keys(table):
""" Field keys for a selected table
:param table:
:return: list op dictionaries
"""
cql = 'SHOW FIELD KEYS FROM \"{}\"'.format(table)
response = db_man.influx_qry(cql).get_points()
return [x for x in response] | ca7be2b79c1641d407fa52ea805e5d99bb2b5c42 | 3,659,156 |
def extract_text_from_spans(spans, join_with_space=True, remove_integer_superscripts=True):
"""
Convert a collection of page tokens/words/spans into a single text string.
"""
if join_with_space:
join_char = " "
else:
join_char = ""
spans_copy = spans[:]
if remove_intege... | ccb45164f695bdbbc53eac9c4cf6596e67c24fd0 | 3,659,157 |
def cf_resource_pool(cli_ctx, *_):
"""
Client factory for resourcepools.
"""
return cf_connectedvmware(cli_ctx).resource_pools | 6cc838a7ad23786b5d86f945da98410506f7e758 | 3,659,158 |
import os
import logging
import sys
import re
def init_log():
""" Initialise the logging. """
level = script_args.log_level
log_dir = os.path.abspath(script_args.log_dir)
logger = logging.getLogger(__name__)
log_format = (
'[%(asctime)s] [%(levelname)s] '
'[%(name)s] [%(funcName)s(... | ac3a172486980271878914481eaf7fbec3c80ecc | 3,659,159 |
from typing import OrderedDict
def get_bcolz_col_names(cols):
"""整理适应于bcolz表中列名称规范,返回OrderedDict对象"""
trantab = str.maketrans(IN_TABLE, OUT_TABLE) # 制作翻译表
# col_names = OrderedDict(
# {col: get_acronym(col.translate(trantab)) for col in cols})
col_names = OrderedDict()
for col in cols:
... | 9f52cd5adba9ef5d45ff74ef9b35825b80e2c621 | 3,659,160 |
def classify_loss(logits, target, eps):
"""
"""
if eps > 0:
loss = cross_entropy_with_smoothing(logits, target, eps, None)
else:
loss = F.cross_entropy(logits, target.view(-1))
return loss | 549d2c1cbd3275153960ffde6f029c231b9e5703 | 3,659,161 |
def flip(position, adjacent):
"""finds the furthest position on grid up to which the player has captured enemy pieces"""
interval = (adjacent[0] - position[0], adjacent[1] - position[1])
if adjacent[0] < 0 or adjacent[0] > (8*tile_size):
return False
elif adjacent[1] < 0 or adjacent[1] > (8*til... | f6691ae4fe078668220c68c1df4706a0f5825faf | 3,659,162 |
def is_android_raw(raw):
"""
Returns a string that describes the type of file, for common Android
specific formats
"""
val = None
# We do not check for META-INF/MANIFEST.MF,
# as you also want to analyze unsigned APKs...
# AndroidManifest.xml should be in every APK.
# classes.dex an... | 6bdf574b3c8c36ead45f6f9b84c19705c1597b08 | 3,659,163 |
def zeros_from_spec(nested_spec, batch_size):
"""Create nested zero Tensors or Distributions.
A zero tensor with shape[0]=`batch_size is created for each TensorSpec and
A distribution with all the parameters as zero Tensors is created for each
DistributionSpec.
Args:
nested_spec (nested Te... | 8c89a930a6fd81d793c95166b90f4621312e69a9 | 3,659,164 |
def type_to_str(t):
"""Return str of variable type."""
if not hasattr(t, "broadcastable"):
return str(t)
s = broadcastable_to_str(t.broadcastable)
if s == "":
s = str(t.dtype)
else:
s = dtype_to_char(t.dtype) + s
return s | a07982cbc6c8922c43620d23a3dcced24bafbef4 | 3,659,165 |
def save(self, fname="", ext="", slab="", **kwargs):
"""Saves all current database information.
APDL Command: SAVE
Parameters
----------
fname
File name and directory path (248 characters maximum,
including the characters needed for the directory path).
An unspecified direc... | ddc79dc0f54e32d6cd96e115ad9842c1689c17b1 | 3,659,166 |
def rollout(
env,
agent,
max_path_length=np.inf,
render=False,
render_kwargs=None,
fast_rgb=True
):
"""
The following value for the following keys will be a 2D array, with the
first dimension corresponding to the time dimension.
- observations
- acti... | a90c712155648773e72d5226b0f2be4c7fe72b2a | 3,659,167 |
import os
import scipy
def _get_colors(data, verbose=False):
"""
Get how often each color is used in data.
Parameters
----------
data : dict
with key 'path' pointing to an image
verbose : bool, optional
Returns
-------
color_count : dict
Maps a grayscale value (0.... | 7c515f3559a00410d6cc382778bc49efdfa387c9 | 3,659,168 |
def data_dir():
"""The data directory."""
return DATA | f7696b434ebdab7ec1619f42bed124ba562de64d | 3,659,169 |
def create_single_test(j):
"""Walk through the json cases and recursively write the test cases"""
si = []
for tnum, c in enumerate(j['cases']):
if 'cases' in c:
si.extend(create_single_test(c))
else:
si.extend(write_testcase(c, tnum))
return si | 4a37a95f59e90b5314ea225f58144fa112b9722e | 3,659,170 |
def _token_text(token):
"""Helper to get the text of a antlr token w/o the <EOF>"""
istream = token.getInputStream()
if istream is None:
return token.text
n = istream.size
if token.start >= n or token.stop >= n:
return []
return token.text | 0821c44eea9dfc229034bebc45211f8e6336c552 | 3,659,171 |
def show_interface(enode, dev, shell=None):
"""
Show the configured parameters and stats of an interface.
:param enode: Engine node to communicate with.
:type enode: topology.platforms.base.BaseNode
:param str dev: Unix network device name. Ex 1, 2, 3..
:rtype: dict
:return: A combined dict... | 54ae542cf5df747ad45e016b8296a7ae5408635e | 3,659,172 |
def get_params_for_category_api(category):
"""Method to get `GET` parameters for querying MediaWiki for category details.
:param category: category name to be passed in params.
:return: GET parameters `params`
"""
params = CATEGORY_API_PARAMS.copy()
params['cmtitle'] = 'Category:' + category
... | c97be0a2aae9b1d92e5a02d4376e0a186f669735 | 3,659,173 |
def get_dict_or_generate(dictionary, key, generator):
"""Get value from dict or generate one using a function on the key"""
if key in dictionary:
return dictionary[key]
value = generator(key)
dictionary[key] = value
return value | e31cd2b6661cf45e5345ce57d1e628174e6fd732 | 3,659,174 |
def createNotInConfSubGraph(graphSet, possibleSet):
"""
Return a subgraph by removing all incoming
edges to nodes in the possible set.
"""
subGraph = {}
for i in graphSet:
subGraph[i] = graphSet[i] - possibleSet
return subGraph | d3cbee9049416d7ff865306713e9a12f26717fae | 3,659,175 |
def _backprop_gradient_pure(dL, L):
"""
Given the derivative of an objective fn with respect to the cholesky L,
compute the derivate with respect to the original matrix K, defined as
K = LL^T
where L was obtained by Cholesky decomposition
"""
dL_dK = np.tril(dL).copy()
N = L.shape[... | 28ab304a375e20f952da341024a09477221d54c5 | 3,659,176 |
import random
def get_random_instance() -> random.Random:
"""
Returns the Random instance in the random module level.
"""
return random._inst | ee66055275153ce8c3eae67eade6e32e50fe1d79 | 3,659,177 |
import types
def to(cond, inclusive = True):
"""
Stream elements until the one that fits some condition.
Arguments:
cond -- Either a function or some other object. In the first case, the
function will be applied to each element; in the second case, the object
will be co... | bc7b4fec4b868e12f4e075256ada80c05dfd2c4d | 3,659,178 |
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, ... | 073f474ada5d43811564180026cb9d4b2b052cf4 | 3,659,179 |
def mixlogistic_invcdf(y, *, logits, means, logscales, mix_dim,
tol=1e-8, max_bisection_iters=60, init_bounds_scale=100.):
"""
inverse cumulative distribution function of a mixture of logistics, via bisection
"""
if _FORCE_ACCURATE_INV_CDF:
tol = min(tol, 1e-14)
ma... | ef25170fbaaa5eae55b22b09d2d2fb66d20d03fe | 3,659,180 |
import cgitb
def FormatException(exc_info):
"""Gets information from exception info tuple.
Args:
exc_info: exception info tuple (type, value, traceback)
Returns:
exception description in a list - wsgi application response format.
"""
return [cgitb.handler(exc_info)] | 733c2170a08f9880f8c191c1c6a52ee1ab455b7f | 3,659,181 |
def trackers_init(box, vid_path, image):
"""Initialize a single tracker"""
tracker = cv2.TrackerCSRT_create()
tracker.init(image, box)
return tracker, cv2.VideoCapture(vid_path) | 9b32501ad68dcc698fad2b734ff140be7a137903 | 3,659,182 |
from typing import Optional
def get_image(id: Optional[int] = None,
name: Optional[str] = None,
slug: Optional[str] = None,
source: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetImageResult:
"""
Get information on an i... | 180e133173ddb6e99d1743326ec5dcacbc7d5901 | 3,659,183 |
def _infer_added_params(kw_params):
"""
Infer values for proplot's "added" parameters from stylesheets.
"""
kw_proplot = {}
mpl_to_proplot = {
'font.size': ('tick.labelsize',),
'axes.titlesize': (
'abc.size', 'suptitle.size', 'title.size',
'leftlabel.size', 'r... | fec171caef3562344ee86684edc944b0d08af3f3 | 3,659,184 |
def create_table_description(config: ConfigLoader):
""" creates the description for the pytables table used for dataloading """
n_sample_values = int(config.SAMPLING_RATE * config.SAMPLE_DURATION)
table_description = {
COLUMN_MOUSE_ID: tables.Int16Col(),
COLUMN_LABEL: tables.StringCol(10)
... | bd26332586a87e66e14427adb3b0c1ddfd809ce9 | 3,659,185 |
def get_target_rank_list(daos_object):
"""Get a list of target ranks from a DAOS object.
Note:
The DaosObj function called is not part of the public API
Args:
daos_object (DaosObj): the object from which to get the list of targets
Raises:
DaosTestError: if there is an error ob... | 9ce003a4e21ed0fbbf58b57989273939613fff95 | 3,659,186 |
import copy
def find_global_best(particle_best=[]):
"""
Searches for the best particle best to make it the global best.
:param particle_best:
:return:
"""
best_found = None
for particle in particles_best:
if best_found is None:
best_found = copy(particle)
... | 15a6b0f970e385fdc83fcffe19808c61d2a14d7f | 3,659,187 |
def rename_to_monet_latlon(ds):
"""Short summary.
Parameters
----------
ds : type
Description of parameter `ds`.
Returns
-------
type
Description of returned object.
"""
if "lat" in ds.coords:
return ds.rename({"lat": "latitude", "lon": "longitude"})
el... | 18647e3bbf82bae9d02db3e965c0ddfd51ddd6dd | 3,659,188 |
def payments_reset():
""" Removes all payments from the database """
Payment.remove_all()
return make_response('', status.HTTP_204_NO_CONTENT) | c5132e8a1809a2b04ba4282d3f05aafbcf996209 | 3,659,189 |
def get_smallerI(x, i):
"""Return true if string x is smaller or equal to i. """
if len(x) <= i:
return True
else:
return False | 1588ef998f4914aa943a063546112766060a9cbf | 3,659,190 |
import re
def _ParseSourceContext(remote_url, source_revision):
"""Parses the URL into a source context blob, if the URL is a git or GCP repo.
Args:
remote_url: The remote URL to parse.
source_revision: The current revision of the source directory.
Returns:
An ExtendedSourceContext suitable for JSO... | 3bb14066280e616f103d3aa55710706c967df432 | 3,659,191 |
def decrypt_and_verify(message, sender_key, private_key):
"""
Decrypts and verifies a message using a sender's public key name
Looks for the sender's public key in the public_keys/ directory.
Looks for your private key as private_key/private.asc
The ASN.1 specification for a FinCrypt message reside... | 9c3d43cc2ee01abd68416eaad4ea21fe066916a7 | 3,659,192 |
def find_best_margin(args):
""" return `best_margin / 0.1` """
set_global_seeds(args['seed'])
dataset = DataLoader(args['dataset'], args)
X_train, X_test, X_val, y_train, y_test, y_val = dataset.prepare_train_test_val(args)
results = []
for margin in MARGINS:
model = Perceptron(feature_... | 40f3a80c56546e0fc9ae42c70cfc633dc83ba111 | 3,659,193 |
import os
import json
def get_user_balances(userAddress):
"""
:param userAddress:
:return:
"""
try:
data = get_request_data(request) or {}
from_block = data.get("fromBlock", int(os.getenv("BFACTORY_BLOCK", 0)))
ocean = Ocean(ConfigProvider.get_config())
result = oc... | acb2b6cf91723b0d9d15969d32a7ba58032b607f | 3,659,194 |
def unfold(raw_log_line):
"""Take a raw syslog line and unfold all the multiple levels of
newline-escaping that have been inflicted on it by various things.
Things that got python-repr()-ized, have '\n' sequences in them.
Syslog itself looks like it uses #012.
"""
lines = raw_log_line \
... | 9e23bdd82ac15086468a383a1ef98989aceee25e | 3,659,195 |
import subprocess
def metis(hdf5_file_name, N_clusters_max):
"""METIS algorithm by Karypis and Kumar. Partitions the induced similarity graph
passed by CSPA.
Parameters
----------
hdf5_file_name : string or file handle
N_clusters_max : int
Returns
-------
labels : a... | 43b991921ccf62f958fc094dd5bafe9d969cad9c | 3,659,196 |
def _mcs_single(mol, mols, n_atms):
"""Get per-molecule MCS distance vector."""
dists_k = []
n_atm = float(mol.GetNumAtoms())
n_incomp = 0 # Number of searches terminated before timeout
for l in range(0, len(mols)):
# Set timeout to halt exhaustive search, which could take minutes
r... | fd2adf4ee9e3811acd4acb144f3b7861ac4b64ff | 3,659,197 |
def new_transaction():
"""
新的交易
:return:
"""
values = request.get_json()
# 检查 POST 请求中的字段
required = ['sender', 'recipient', 'amount']
if not all(k in values for k in required):
return 'Missing values', 400
# 创建新的交易
index = blockchain.new_transaction(values['sender'], v... | 06af06839e6afcaf4188cca724cebc7878455534 | 3,659,198 |
async def get_favicon():
"""Return favicon"""
return FileResponse(path="assets/kentik_favicon.ico", media_type="image/x-icon") | 8597f21ad240cd43f59703624d380e3b879a1a8a | 3,659,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.