content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _get_docker_client():
"""Returns the docker client"""
try:
return docker.from_env(version='auto')
except docker_errors.DockerException as e:
err_msg = 'Could not create docker client: {}. Have you started the docker daemon?'.format(e)
future_utils.raise_from(ValueError(err_msg), ... | b653844c88a7b04751cc7cf76cfc786af8990b1e | 59,700 |
def generate_ensemble(num_layers, *activations):
"""Given a set of string names and a number of target layers, generate
a list of ensemble architectures with those activations
Args:
num_layers: int
the number of hidden layers in the neural network, and also
the number of activation fun... | 42bce2fc861122938d2e5da54e4538b0e6a285bc | 59,701 |
import torch
def load_data(training_file_path: str, dev_file_path: str, batch_size: int, max_length: int, device,
is_bert_model=True):
"""
loads training data from csv files
:param batch_size:
:param max_length:
:param device:
:param is_bert_model:
:param training_file_path:
... | 6b668cb8e792444ee7997c255b9e24e08b0453bc | 59,702 |
def run_cso_classifier_batch_model_single_worker(papers, modules="both", enhancement="first"):
"""Run the CSO Classifier in *BATCH MODE*.
It takes as input a set of papers, which include abstract, title, and keywords and for each one of them returns a
list of relevant concepts from CSO. This function requi... | ec11a82c4dcbd6d711ec3add837280b3f291141a | 59,703 |
def pdt2num(pdt, time_units, calendar, start_of_period=True):
"""
Convert an Iris PartialDateTime object into a Python datetime object. If
the day of the month is not specified in `pdt` then it is set as 1 in the
output unless `start_of_period` isn't True, when 30 is used as the day of
the month (be... | a06a70368db16f83d8d2c0a8fa79a395b6599546 | 59,704 |
import time
def get_log_file(name):
"""
Returns a new recomputation log file name, with a timestamp
"""
return "{dir}/{name}/{time}.txt".format(dir=logs_dir, name=name, time=time.strftime("%Y%m%d-%H%M%S")) | 02d7f6c39a064f77e58428b0422e327c8553ff0c | 59,705 |
def fib2(n):
"""Zwraca liste liczb Fibonacciego mniejszych niz n
"""
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result | 246f5bf991d6f5af08cb312d83c9b755f0f269c3 | 59,706 |
def int_to_string(msg):
"""Convert the integer 'msg' to a string.
This function is the inverse of string_to_int().
"""
# convert to binary first
binmsg = bin(msg)[2:]
# pad the message so length is divisible by 8
binmsg = "0"*(8-(len(binmsg)%8)) + binmsg
msg = bytearray()
# convert b... | 780a5b8e7f087eee4ca3f01e12d2b9b52b183f22 | 59,707 |
def regular_graphing_method():
"""
This function was created to determine whether the user wants to graph the data on top of each other or on separate graphs.
:return boolean regular_ontop: regular_ontop is returned to determine how the data will graph
Note: if regular_ontop is true, the non-derivativ... | 75cb8de45df76cb6facf91ac0ae6e0ca9f37cf31 | 59,708 |
def div_to_int(int_numerator, int_denominator, round_away=False):
"""Integer division with truncation or rounding away.
If round_away evaluates as True, the quotient is rounded away from
zero, otherwise the quotient is truncated.
"""
is_numerator_negative = False
if int_numerator < 0:
int_numerator =... | 3fc3b307cf691a9bea2a33a0bf468398c77db645 | 59,709 |
def get_users(recipe):
"""Get all users and times for comments"""
all_comments = recipe.comments
users = []
times = []
for comment in all_comments:
user = User.query.get(comment.user_id)
users.append(user)
times.append(comment.created_at)
return users,times | 24da2525af4c844336b4a6b2f17f439a43fbf0b3 | 59,710 |
import os
def dict_to_dir(data, path=str()):
"""dict_to_dir expects data to be a dictionary with one top-level key."""
dest = os.path.join(os.getcwd(), path)
if isinstance(data, dict):
for k, v in data.items():
os.makedirs(os.path.join(dest, k))
dict_to_dir(v, os.path.joi... | afb173d4963691033fe95fa7e5711a56ca90e139 | 59,711 |
def correct_angle(x, verbose=False, only_angles=True):
"""correct_angle
This function converts the angles obtained with normal2angle to angles that we can use on the scanner. The scanner doesn't like angles >45 degrees. If inserted, it will flip all kinds of parameters such as slice orientation and foldover.
... | b131c0304701f31f44421296936c85b94812c656 | 59,712 |
import re
def get_pids(linesl):
"""
Required layout lines.
Returns dictionary of pid:meaning
"""
pids = {}
foundstartpids = False
for line in linesl:
# After table
if "These PIDs are superseded by PIDs 194, 195, and 196." in line:
break
# Before table
if not foundstartpids and " ... | 1216b337283851ceb0e6721abd124b2a83a0157c | 59,713 |
def frontpage(request):
"""Renders OCELoT frontpage."""
if request.method == 'POST':
form = LeaderboardForm(request.POST)
submissions = Submission.objects.all().order_by('-score')
if form.data['testset']:
submissions = submissions.filter(test_set=form.data['testset'])
... | dd021b9776760f9fc7dc448781ec9d877520a07a | 59,714 |
def publish_XdFloat(self):
"""
Publish XdFloat
"""
# fix double quotes in label
self.label.replace('"', '"')
self.save()
# it is a modelling error to use multiple reference ranges with the same
# Xdinterval in a Xdquantity
used_ctid_list = []
# default return message
... | bbab0db59b4c8ebc8606fd329452db57010857d5 | 59,715 |
def __improve_tasks_info(cluster_name, tasks):
"""Get more information for a list of tasks."""
containers_instances = get_containers_instances(cluster_name)
for task in tasks:
for inst in containers_instances:
if inst["containerInstanceArn"] == task["containerInstanceArn"]:
... | a83a8e0b3ea27de7cd4d585b0d4e6efae54672fd | 59,716 |
def rf_inverse_mask(src_tile_col: Column_type, mask_tile_col: Column_type) -> Column:
"""Where the rf_mask (second) tile DOES NOT contain NODATA, replace values in the source
(first) tile with NODATA."""
return _apply_column_function('rf_inverse_mask', src_tile_col, mask_tile_col) | 556eab93f674cae611f26d6b55752f95d863f0bb | 59,717 |
from typing import OrderedDict
def register_models(database_state, models, register_indexes=False,
new_app_label='tests', db_name='default', app=evo_test):
"""Register models for testing purposes.
Args:
database_state (django_evolution.db.state.DatabaseState):
The data... | 2fa833fcda7c6e2933b3ffb0d2e0d93de5f7589f | 59,718 |
def nearest_feature(geometry, geometry_collection, r_tree=None):
""" Return nearest feature from geometry collection to given geometry
If some of the geometries intersect, the nearest feature is the one whose centroid is the closest to the centroid
of the given geometry (but distance remains 0)
:param ... | 51d43d23788661bbd8a87737276b153b9cea41eb | 59,719 |
def get_contract(contract_name):
"""
This function will grab the contract address from the config if defined; otherwise deploy mock contract and return address
Args:
contract_name (string)
Returns:
brownie.network.contract.ProjectContract: the most recently deployed ver... | 961c9206d5571f1cf3a009d5c3295542ec7dcc9a | 59,720 |
def get_profile_url(self):
"""Returns the URL for this User's profile."""
return '%s%s/' % (reverse('user', args=[self.id]), self.username) | bffce22685b8b4fe429e2c8614d4905d5bbc2e04 | 59,721 |
def tryShiftBits(rs, bits, bitsBefore, bitsAfter, tryFirst, \
f6b = False, block0FixedBits = False):
"""
Given 3 packets of data (sample, before sample, and
after sample), error correct the sample using various shifts.
The bits represent a single block of a FIS-B message,
or the entire ADS-B message.
... | 7eeb64ed50bc0699ee2bd6922eb579c5bfc03881 | 59,722 |
def non_max_suppression(boxes, scores, max_output_size, iou_threshold=None, name=None):
"""Greedily selects a subset of bounding boxes in descending order of score,
pruning away boxes that have high intersection-over-union (IOU) overlap
with previously selected boxes. Bounding boxes are supplied as
[y1... | 608075ea7aef718e6a4aa79c3d6992e1ea2a6733 | 59,723 |
def match_server_args_factory(tick_rate: int, realtime: bool, observations_only: bool, env_config_string: str):
""" Helper factory to make a argument dictionary for servers with varying ports """
def match_server_args(port):
arg_dict = {
"tick_rate": tick_rate,
"port": port,
... | 5059d0a4224067f485455a54f4e6d1f83ba68531 | 59,724 |
from typing import Iterable
from typing import Any
def parametrize(arg_names: Iterable[str], arg_values: Iterable[Iterable[Any]]):
"""
Decorator to create parameterized tests.
# Parameters
arg_names : `Iterable[str]`, required.
Argument names to pass to the test function.
arg_values : `I... | e385d2449a2572d89a055d7cbdcc2475b00b2942 | 59,725 |
def objective(hyperparameters, iteration):
"""Objective function for random search. Returns
the cross validation score from a set of hyperparameters."""
# Number of estimators will be found using early stopping
if 'n_estimators' in hyperparameters.keys():
del hyperparameters['n_estimators']
... | 605fc55866a6e42651e2faca4a0e16d0a4877ddc | 59,726 |
def get_dataset_length(audio_files):
"""Get the size of the dataset given the file paths"""
length = 0
for file in audio_files:
info = torchaudio.info(file)
samples = info.num_frames * cargan.SAMPLE_RATE / info.sample_rate
if samples < cargan.MAX_LENGTH:
length += 1
... | 1c06436b86fe8c658a652ff581598bd5f97a1e9c | 59,727 |
from bs4 import BeautifulSoup
def _req_widiget():
"""
初始化环境
:return:
"""
url = 'https://captcha.luosimao.com/api/widget?k=e7b4d20489b69bab25771f9236e2c4be&l=zh-cn&s=normal&i=_2ymuhhcry'
resp = session.get(url)
bsobj = BeautifulSoup(resp.text, 'lxml')
data_token = bsobj.select('#l_captc... | a1a45338ea01b4bd9cf5778944d300ba06d7cc48 | 59,728 |
def rotation_matrix_arbitrary_axis(angle, axis):
"""
Returns a rotation matrix of `angle` radians about `axis`.
Parameters
----------
angle : :class:`float`
The size of the rotation in radians.
axis : :class:`numpy.ndarray`
A 3 element aray which represents a vector. The vector... | 7194576e97f4d65b54021bbabe43fba8b57a8d12 | 59,729 |
import torch
def generate_metrics_table(benchmarks, dataloader, metrics, device=None, dtype=None):
"""Generate metrics table for all benchmarks.
Parameters
----------
benchmarks : dict
Dictionary where keys are benchmark names and values are instances of `Benchmark` (possible
also `to... | 8fabd19bf809416127674ecfff86fae8b89a94cb | 59,730 |
import io
def rose(factory=None):
"""Return rose image.
Resulting image is 70 x 48, RGB, truecolor.
"""
return io.read('rose:', factory=factory) | 072d8ec8afbfe250219468d3eb67061659f7bd6b | 59,731 |
def default_colors_to_resets(s):
"""Hack to make sphinxcontrib.ansi recognized sequences"""
return s.replace(b"[39m", b"[0m").replace(b"[49m", b"[0m") | 0f025233ac63416fef47e85ebb258bb543a4c115 | 59,732 |
def delete(isamAppliance, replica, session, check_mode=False, force=False):
"""
Terminating a session
"""
check_value, warnings = _check(isamAppliance)
if check_value is True:
if force is True or search(isamAppliance=isamAppliance, replica=replica, session=session) is True:
if c... | 2e9bb77d82734a541a7b0135012577b7821d3839 | 59,733 |
def plot_mean_with_runs(data, type_, ind, smooth_over, names, colours=None,
figsize=(12, 6), xlim=None, ylim=None, alpha=0.2,
plot_avg=True, env_type="continuing",
keep_shape=False, fig=None, ax=None, detrend=None):
"""
Plots the mean retur... | 47391fced6709c41cdd94c4f2cc8653a2651d86d | 59,734 |
def _load_multipage_tiff(path):
"""Load tiff images containing many images in the channel dimension"""
return np.array([np.array(p) for p in ImageSequence.Iterator(Image.open(path))]) | b61dfe371818e4a132db5d99d1b9a295473eba92 | 59,735 |
def processImage(frap_image, subtract_bg = False, prebleach_ss=True):
"""
Function which processes frap image
:param frap_image: FRAP Image
"""
# background subtraction
frap_image.reset_image_data()
frame_data = frap_image.get_image_data()
if subtract_bg:
print('Subtracting backg... | 20907395d1e034b0c04b78c77e372d0bce922ec2 | 59,736 |
def clean_input():
"""
Make sure we're not getting bad data from the front end,
format data to be machine readable
"""
if not 'password' in request.form:
abort(400)
if not 'ttl' in request.form:
abort(400)
time_period = request.form['ttl'].lower()
if not time_period in ... | 8e367250053328df80745c745b716c65f8b96412 | 59,737 |
def nchw2nhwc_func_register(func_name):
"""Register func in NCHW2NHWC_FUNCS"""
def decorator(func):
NCHW2NHWC_FUNCS[func_name] = func.__name__
def wrapper(self, call, op_args):
attrs = nchw2nhwc_attrs_changer(call.attrs)
return func(self, op_args, attrs)
return... | 450dc9c119233e5a94343b53b68d4111ea9937c3 | 59,738 |
def draw_path(data, path, draw_options=None, simplify=None):
"""Adds code for drawing an ordinary path in PGFPlots (TikZ).
"""
# For some reasons, matplotlib sometimes adds void paths which consist of
# only one point and have 0 fill opacity. To not let those clutter the
# output TeX file, bail out ... | 6d4721a5c54247c91600384330e14e05686e4709 | 59,739 |
def trailFilter(elem, osmdata):
"""
Currently filters in all trails with "highway" in the accepted highways list.
"""
return OSMData.get_tag(elem, OSMData.KEY_HIGHWAY) in OSMData.ACCEPTED_HIGHWAYS | 1120bddb4ef60c0ce415aa8405d17a072553c1b2 | 59,740 |
from typing import List
import argparse
def get_input() -> List[int]:
"""
Parse arguments passed to script.
Return:
Path
path to gziped file for this problem.
"""
parser = argparse.ArgumentParser()
msg = "comma separated numbers, i.e '0,3,6'"
parser.add_argument("sequence", he... | dba07be45f6b111cd89f7791769461864185ca9d | 59,741 |
from geopy.geocoders import IGNFrance
def geotag_Compte(df, prefix='', IGN_API=''):
"""
This function corrects Phenix original geo coordinates (longitude and latitude).
This function uses IGN geocoding API to convert adresses into Longitude and Latitude coordinates.
Args:
df (DataFrame): 'Com... | 60eafe996faefebfb12465dbe177a050c4c5451e | 59,742 |
def mask_maxipix(mydata, mymask):
"""Mask the Maxipix frames."""
mydata[:, 255:261] = 0
mydata[255:261, :] = 0
mymask[:, 255:261] = 1
mymask[255:261, :] = 1
return mydata, mymask | 0c508c6740569e99cdb745b75b399dac8021e9bf | 59,743 |
import os
def fetch_ranks_from_azureml_preprocess():
"""Look up distributed arguments from Azure ML environment variables.
Assumes OpenMPI image.
Note:
Sets up NCCL environment variables used by Azure ML:
- NCCL_SOCKET_IFNAME
- NCCL_IB_DISABLE
"""
ranks = DistributedPrep... | a808dce37100fae2cdc3e630c55c54324de6af87 | 59,744 |
import os
def is_arch_s390x() -> bool:
"""
if it is a travis s390x cpu architecture
Parameter
---------
TRAVIS_CPU_ARCH
from environment
Examples:
>>> # Setup
>>> save_cpu_arch = os.getenv('TRAVIS_CPU_ARCH')
>>> # Test
>>> os.environ['TRAVIS_CPU_ARCH'] = 's390x'
... | f587f89f26d0c4b842deeb38995a01667cbbc567 | 59,745 |
import math
def get_distance(lat_1, lng_1, lat_2, lng_2):
"""calculates the distance between two coordinates
Args:
lat_1 (float): start latitude
lng_1 (float): start longitude
lat_2 (float): end latitude
lng_2 (float): end longitude
Returns:
float: distance in me... | 3e09826a4b556e897f2c39d792ed2f1d8da6109c | 59,746 |
import math
def spherical_to_cartesian(r, theta, phi):
"""
:param r: Radius.
:param theta: in radians.
:param phi: azimuth angle in radians
:return: x=[x1, x2, x3] coordinates.
"""
return [r*math.sin(phi)*math.cos(theta), r*math.sin(phi)*math.sin(theta), r*math.cos(phi)] | 08d0748d5acd9dab4e74a19879b2f8ac7858bb31 | 59,747 |
def forget_password(request):
"""
后台卖家忘记密码功能
:param request:
:return:
"""
return render(request, "shop/forgot-password.html") | d446d393a77c982a465f777783aba0c063ae5f79 | 59,748 |
def load_wavesolution(filenames):
""" Load the wavesolution from saved data """
wsol = WaveSolution()
wsol.load(filenames)
return wsol | e0dab57a11b16695c374fd9e43e8649ca745dbe4 | 59,749 |
def show_current(name):
"""
Display the current highest-priority alternative for a given alternatives
link
CLI Example:
.. code-block:: bash
salt '*' alternatives.show_current editor
"""
try:
return _read_link(name)
except OSError:
log.error("alternative: %s do... | dea167ff753a0f4a1570e752047c12045e374428 | 59,750 |
import copy
def flat_ingredients_list_DFS(product):
"""
Recursive function to search the ingredients graph by doing a Depth First Search and return it as a flat list of
all nodes.
Sub ingredients are placed right after their parents.
Args:
product (dict): Dict corresponding to a product o... | d2b3ada88963d3967fa8fffc4aa294bed4b1fe31 | 59,751 |
def add_dist_along_vector(p0, p1, dist):
"""Add distance along vector"""
p0 = np.array(p0)
p1 = np.array(p1)
u = (p1 - p0) / np.linalg.norm((p1 - p0))
return p0 + dist * u | b96c6f44990fe88288a63dd7998f4c73fa8e508a | 59,752 |
import json
def hash_block(block):
"""Hashes a block and returns a string representation of it.
Arguments:
:block: The block that should be hashed.
"""
return hash_string_256(json.dumps(block, sort_keys=True).encode()) | 3e7b48307debb199c59c3116e7a0eff66879581c | 59,753 |
import os
import imp
def load_all():
"""Loads 3rd party plugin modules (note that this does not yet run startup processors, etc)
"""
def load_module(module_path):
logger.info('Loading Plugin Module %s' % module_path)
module_path_only = os.path.join(*module_path.split('/')[:-1])
mo... | ce4fcb59e221a5a5f2652f9102e750e188ccc14a | 59,754 |
def _prep_torque_resources(resources):
"""Prepare resources passed to torque from input parameters.
"""
out = []
has_walltime = False
for r in resources.split(";"):
if "=" in r:
k, v = r.split("=")
k.strip()
v.strip()
else:
k = ""
... | 0832bb393d25e51be9156f814e4da4a76ce4a845 | 59,755 |
import os
def get_load_dotenv(default: bool = True) -> bool:
"""Get whether the user has disabled loading dotenv files by setting
:envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the
files.
:param default: What to return if the env var isn't set.
"""
val = os.environ.get("FLASK_SKIP... | 8540c9ee0a73592f4365a1f17a2479f1ef5db5f8 | 59,756 |
def divide_by(y):
"""divide_by(y)(x) = x / y
Note I'm using the future division here - the answer on two ints will
be a float.
Be careful with this because division is not commutative.
You may be interested in func.flip(divide_by) to reverse the arguments.
>>> divide_by(2)(4)
2.0
>>>... | c98de33a14840cdd421737bda44605142572a4f3 | 59,757 |
from typing import Union
async def filter_users(
email: str = None,
banned: bool = False,
normal: bool = True,
order_by: str = "register_date",
order: str = "desc",
page: int = 1,
limit: int = 10,
db: Session = Depends(deps.get_db),
user: Union[m... | ae169f68219bb3c9c4c2b8e99f881cd8d394845c | 59,758 |
from .model_store import download_model
import os
def get_prnet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PRNet model with specific parameters.
Parameters:
----------
model_name : str or None, def... | e6c0e6d4302f6610c4f171e81963b422274dda2c | 59,759 |
import scipy
def pca_transform(pca, mean, arr):
"""
Apply a PCA transformation to argument
Parameters
----------
pca : sklearn.decomposition.PCA
A PCA projector. See wot.ot.get_pca
arr : numpy ndarray or scipy.sparse matrix
The array to project.
Returns
-------
re... | d0d4ea83f40b4655aadc23df5a35a4cd94a6145c | 59,760 |
async def webfonts(filename) -> Response:
"""Web font static endpoint."""
return await send_from_directory(webfonts_dir, filename) | d51d96067de2232ab3fb63a19107fab0e2546fc2 | 59,761 |
import operator
def operator_index(idx):
"""
Convert `idx` into an integer index using `__index__()` or raise
`TypeError`.
This is the same as `operator.index()` except it disallows boolean types.
This is a slight break in NumPy compatibility, as NumPy allows bools in
some contexts where `__... | da31876fc3e1f41115d57d7a60ca42fc88eea262 | 59,762 |
def calc_events(N: pd.Series, S: pd.Series) -> pd.Series:
"""
The Kaplan-Meier estimator of survival function is given by
S(t) = product_{i:t_i<=t}(1 - D_i / N_i)
Where S is event-free probability, D is number of events, and N is number of observations
Assume S(t+10) = S(t) * ((N(t+10) - D(t+10)) / ... | a21f4e64cb38c9c51a80975bf8b68afe110c4419 | 59,763 |
def cashflow_data(terminal, element): #(Terminal, element):
"""Place cashflow data in element dataframe
Elements that take two years to build are assign 60% to year one and 40% to year two."""
# years
years = terminal.modelframe
#years = list(range(Terminal.startyear, Terminal.startyear + Terminal... | 27e4b5488d1b726e7c77bc51d85733f2703877ae | 59,764 |
def rainbow_network(num_actions, num_atoms, support, network_type, state):
"""The convolutional network used to compute agent's Q-value distributions.
Args:
num_actions: int, number of actions.
num_atoms: int, the number of buckets of the value function distribution.
support: tf.linspace, the support o... | 4b881ce064412e9b358b6cd21e526263984b30b7 | 59,765 |
from scipy.spatial import ConvexHull
def constructOutlines(x,y,clusterlabels): # compute convex hull, one per cluster label
"""Construct the convex hull (outline) of points in (x,y) feature space,
Parameters
----------
x, y : seq (e.g. tuple,list,1-d array)
Location of points in (x,y) featu... | 2b1c0810210229fa0cd156fdf3fb6cc873409a6c | 59,766 |
import collections
def list_sims(product=None, yyyymmdd=None):
"""List available simulation results.
Each simulation is represented as a dictionary describing product
type, simulation date, and whether all expected files are present,
and it also includes a list of filenames, e.g.
{'product': 'lon... | 6f9372c770eada26a8c3917634a552628bb5b79c | 59,767 |
import torch
def masked_log_softmax(vector, mask=None, dim=-1):
"""
This performs a log-softmax on just the non-masked portions of `vector`
(see https://github.com/allenai/allennlp/blob/main/allennlp/nn/util.py#L286-L314)
"""
if mask is not None:
mask = mask.float()
while mask.dim(... | 9fd966cd381355c6117c72348f5bcab845ef1f00 | 59,768 |
def bprop_bool_and(x, y, out, dout):
"""Backpropagator for primitive `bool_and`."""
return C.zeros_like(x), C.zeros_like(y) | 47a3ee91573807d50d6f9f04cd6540aedd60eadb | 59,769 |
def prop_has_qualifiers(ents_dict, qid, pid, i):
"""
Checks if the property has qualifiers
"""
return "qualifiers" in get_prop(ents_dict=ents_dict, qid=qid, pid=pid)[i].keys() | 52364577b26ec6b90546da557563247cc2cc3d9a | 59,770 |
import csv
def read_txt_detV2(textpath):
"""
read det.txt to a dict
:param textpath: text path, String
:return: a dict with key = frameid and value is a list of lists [x1, y1, x2, y2] in the frame, dict
"""
# line format : [frameid, personid, x, y, w, h ...]
with open(textpath) as f:
... | e3a11ea640cbbd9074155eab5bb5af77f2f4877e | 59,771 |
def proof_of_work(last_proof):
"""
Simple Proof of Work Algorithm:
- Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p'
- p is the previous proof, and p' is the new proof
"""
proof = 0
while valid_proof(last_proof, proof) is False:
proof += ... | d9eade72b1ca2f58adda5966119a5fd3d1499bea | 59,772 |
import sys
def strip_output(nb, keep_output, keep_count, extra_keys=''):
"""
Strip the outputs, execution count/prompt number and miscellaneous
metadata from a notebook object, unless specified to keep either the outputs
or counts.
`extra_keys` could be 'metadata.foo cell.metadata.bar metadata.ba... | 81fa28843fe503e8f98bd323802cde5a15af4d95 | 59,773 |
def bincount(map_bins, map_weights=None, length=None) :
"""Wrapper for numpy.bincount with protection of weights and alattening numpy arrays
"""
weights = None if map_weights is None else map_weights.flatten()
return np.bincount(map_bins.flatten(), weights, length) | aff130a625b786fff4fb7a1d3ed0ebab8fbbe7d6 | 59,774 |
def lazy_method(fn):
"""Decorator that makes a method lazy-evaluated."""
attr_name = '_lazy_' + fn.__name__
def _lazy_method(self,*args, **kw):
if not hasattr(self, attr_name) or kw.get("new_process",False):
setattr(self, attr_name, fn(self,*args, **kw))
return getattr(self, att... | cad299288b5b02a061605f661e806f92d269f333 | 59,775 |
import argparse
def main( argv ):
"""
Script execution entry point
@param argv List of arguments passed to the script
@return Shell exit code (0 = success)
"""
# imports when using this as a script
# create and configure an argument parser
parser = argparse.ArgumentParser(
... | bb0b3995b9bd1b1d57d3d5e84c432f304fd8045a | 59,776 |
def dist_node(n1, n2, nelx, nely, nelz, dof):
"""
Returns the distance between two nodes. Used to define which active
elements are associated to which loads.
"""
p1 = node2point(n1, nelx, nely, nelz, dof)
p2 = node2point(n2, nelx, nely, nelz, dof)
return np.linalg.norm(np.asarray(p1) - np.a... | e983f3661db2e7ef6dce718b33ab57b0fe1e1989 | 59,777 |
def check_vehicle_accident_suppression(check_df, project_id, post_deid_dataset, pre_deid_dataset=None, mapping_dataset=None):
"""Run motor vehicle accident suppression check
Parameters
----------
check_df: pd.DataFrame
Dataframe containing the checks that need to be done
project_id: str... | 67fb47115820ee66c78be4aa32c635ae697d4424 | 59,778 |
def player_died_bullet(playerx, playery, rect_enemy):
"""this function cheks if player died by enemies bullet"""
pos_player = playerx, playery
if rect_enemy.collidepoint(pos_player):
return True
else:
return False | 073482e3da88e0aa448d30f2c0dd71e6cd7fe6e3 | 59,779 |
import torch
def topk(vec, k):
""" Return the largest k elements (by magnitude) of vec"""
# on a gpu, sorting is faster than pytorch's topk method
# topkIndices = torch.sort(vec**2)[1][-k:]
# however, torch.topk is more space efficient
# topk on cuda returns what looks like uninitialized memory i... | d0b0830aca482758c833769c661ee7d19ae63438 | 59,780 |
def create_member_account_discovery_role(servicenow_url, parent_account,
member_account_discovery_role,
assume_role_external_id):
"""
Creates entry in the cloud service account assume role table for master account to
setup r... | 1e4d1c198f104bfb28ed2238a361f05b79486b5e | 59,781 |
def setup_js_tag_helper(app, pagename, templatexname, context, doctree):
# type: (Sphinx, unicode, unicode, Dict, nodes.Node) -> None
"""Set up js_tag() template helper.
.. note:: This set up function is added to keep compatibility with webhelper.
"""
pathto = context.get('pathto')
def js_tag(... | 2458fc514a1bc6e6ff1ad95df6fe7a4c0bd41ae2 | 59,782 |
def text2number(text: str) -> str:
"""
Convert an English short-scale **text** to it's numerical value.
The function attempts to parse **text** and return a numeric string
containing the corresponding value. The number(s) in the string will
be in scientific notation.
The function returns a pse... | 1e46fe17bb852c65d90fd3fe402669f9e1a03dea | 59,783 |
from typing import Optional
def build_matrixstore(
application: FastAPI,
config: Config,
user_service: LoginService,
service: Optional[MatrixService] = None,
) -> MatrixService:
"""
Matrix module linking dependency
Args:
application: flask application
config: server config... | 5ed18ef98fdb3b080326c658b4558c96a92bee62 | 59,784 |
def rev(repo, subset, x):
"""Revision with the given numeric identifier.
"""
# i18n: "rev" is a keyword
l = getargs(x, 1, 1, _("rev requires one argument"))
try:
# i18n: "rev" is a keyword
l = int(getstring(l[0], _("rev requires a number")))
except (TypeError, ValueError):
... | 00cafa7df962e4b93dcac5df558b2da7c18fcc64 | 59,785 |
import requests
def request_insee(url: str):
"""
Call an INSEE api with token regeneration if needed.
"""
connector = INSEEConnector()
response = requests.get(url, headers=connector.header())
if response.status_code == 401:
connector.generate_token()
response = requests.get(ur... | 427ba86051e8cfb2a45244f10ff30c6549cce5a2 | 59,786 |
def suffstats(func):
"""decorate func with ff.suffstats if you have several ffs that share some underlying computation
func will be run once for each hypothesis before any actual scorer is called"""
_SUFFSTATS_.append(func)
return func | 707d8d2bf3f704b7bc27a6a23227e910c3f6803e | 59,787 |
import re
def parse_metadata(e, patterns):
"""Parse heading metadata
Arguments:
e (HtmlElement): html element containing header text
patterns (dict): dictionary with as keys the 'class'
attribute value the patterns apply to, and as values
tuples, containing a ... | d16e6ef20eb9e344da645ba4acdd47d8a2471e7a | 59,788 |
import glob
import os
def parse_path(f1, f2):
"""Parse two input arguments and return two lists of file names"""
# if second argument is missing or is a wild card, point it
# to the current directory
f2 = f2.strip()
if f2 == '' or f2 == '*':
f2 = './'
# if the first argument is a d... | 48dd4cd70e7e45c73cd4a41ad13fe0bd79d7270b | 59,789 |
import importlib
import inspect
def get_module_docs(module_string):
"""
Returns docs dictionary that contains docs data form module-level variables, functions and classes
for given module string (e.g. "package1.package2....packageN.module").
"""
if not module_string:
return None
module... | 51bc5af9821058c07490b2e92cc2c9ccb2842590 | 59,790 |
def create_some_config_by_shop_id(shop_id: int):
"""
为店铺创建一些奇奇怪怪的设置
:param shop_id:
:return:
"""
config_info = {"id": shop_id}
some_config = SomeConfig(**config_info)
some_config.save()
return some_config | afa1300e89adf5a2864112d8366e5f203a16ce30 | 59,791 |
def delete_baselines_by_ids(baseline_ids):
"""
delete a list of baselines given their ID
"""
_validate_uuids(baseline_ids)
account_number = view_helpers.get_account_number(request)
query = SystemBaseline.query.filter(
SystemBaseline.account == account_number, SystemBaseline.id.in_(baseli... | 267a836336fd9a12e0cdbee89249c7306ed41191 | 59,792 |
def _char_array(size: int, doc: str) -> Field:
"""
Character string, zero padded to next multiple of 4 bytes.
Args:
doc: DocString for this parameter
Returns:
Field for the dataclass parameter.
"""
return _param(bytes, f"{size}s{-size % 4}x", doc) | 98f934af62249328f30df1593174b05941ef9ec7 | 59,793 |
def helm_env_vars(env_vars):
"""Convert environmental variables to a "--set" string for Helm deployments.
Args:
env_vars (Iterable): Environmental variables we wish to store in Helm.
Returns:
str: String containing variables to be set with Helm release.
"""
env_vars = list(env_vars... | 081619191f22f6ef74f415519befecd706198847 | 59,794 |
def op(params,ops):
"""
Operator for sites in center of lattice
"""
# Collect needed operators
X = ops.X
I = ops.I
Z = ops.Z
# Interaction with field
op = -0.25*params[0]*quick_op(X,I)
op += -0.25*params[0]*quick_op(I,X)
# Interaction between spins
op += -params[1]*quick_... | c68a9a787b2f82e110f83a3305e441863aa79ff4 | 59,795 |
import math
def jump_search(arr, search):
"""Takes in a sorted array arr and a value to search for"""
interval = int(math.sqrt(len(arr)))
for i in range(0, len(arr), interval):
if arr[i] < search:
low = i
elif arr[i] == search:
return i
else:
bre... | d1aac70dca9d3f92c05f9e9da37de3786ae75460 | 59,796 |
import json
def _loadCredentials():
"""Loads stmp credentials from a json file.
File format:
{
"hostname": "smtp.gmail.com",
"port": 587,
"user": "gmail address",
"password": "gmail password"
}
"""
with open(_CREDENTIALS_PATH, 'r') as f:
return json.loads(f.read()) | 58524e0b9d5d3139dbc95a948b8f5a923ef18e82 | 59,797 |
def deep_merge(source: dict, destination) -> dict:
"""Deep merge for dictionaries
Args:
source (dict): Dict to merge
destination (Any): hm...
Returns:
dict: hm...
"""
for key, value in source.items():
if isinstance(value, dict):
node = destination.setdef... | a429dbfe9860384cd9ace95ed70cf7bd0ab32b14 | 59,798 |
from typing import Optional
def multilabel_confusion_matrix(y_true: np.ndarray, y_pred: np.ndarray, *,
sample_weight: Optional[np.ndarray] = None,
labels: Optional[np.ndarray] = None,
samplewise: bool = False)\
... | 90cb96bf387a3e78d2783517ecc621283b4125cb | 59,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.