content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import dask.dataframe as dd
def read_json(
url_path,
orient="records",
lines=None,
storage_options=None,
blocksize=None,
sample=2 ** 20,
encoding="utf-8",
errors="strict",
compression="infer",
meta=None,
engine=pd.read_json,
**kwargs
):
"""Create a dataframe from a ... | ec5b47fc10b58548c27728136989829df1ca81d8 | 3,605,700 |
import torch
def nograd_param(x):
"""
Naively make tensor from x, then wrap with nn.Parameter without gradient.
"""
return nn.Parameter(torch.tensor(x), requires_grad=False) | c483c0fc2b1db5b1d9ff4b16106784bc5de8e7d4 | 3,605,701 |
def process_files(args, changed_files, todo_files, license_info):
"""
Processes all license files
:param args: arguments of the hook
:param changed_files: list of changed files
:param todo_files: list of files where t.o.d.o. is detected
:param license_info: license info named tuple
:return: ... | 84d0c118a7d66969b15297a3bc964547761d5ddc | 3,605,702 |
def node_attach(db, storage, registry, user):
"""
Attach to a node
"""
node_id = request.form.get('node_id')
registry.attach(node_id, request.form.get('address'), user.user_id)
broadcast('attach', {
'node_id': node_id,
'owner': user.dict()
})
return '' | 8e88acfecf5468fb2d6700d332a45853b93c47c6 | 3,605,703 |
import subprocess
def check_output(*args, **kwargs):
"""allow string or multiple args to be specified instead of list"""
if isinstance(args[0], list):
new_args = args
else:
if len(args) == 1 and isinstance(args[0], basestring):
args = args[0].split()
new_args = [args]
... | 23cca6bd1c612206433b76c88243f855a436616e | 3,605,704 |
def hingeval(x: ArrayLike, mn: float, mx: float) -> ArrayLike:
"""Computes hinge transformation values.
Args:
x: Array-like of covariate values
mn: Minimum covariate value to fit hinges to
mx: Maximum covariate value to fit hinges to
Returns:
Array of hinge features
"""... | b72c6c8aa1425bb3fabf4452ce7ba78793d87792 | 3,605,705 |
def next_token_inside_string(s, inside_string):
"""Given a code string s and an initial state inside_string, return
whether the next token will be inside a string or not."""
for token, value in PythonLexer().get_tokens(s):
if token is Token.String:
value = value.lstrip('bBrRuU')
... | 65e9e9f0fbcf49e899f45a7259b53f54ee120925 | 3,605,706 |
def summerE(n: int) -> int:
"""
Uses the arithmetic series formula.
Avoids generating the multiples, thanks to math.
"""
def sum_multiples(divisor: int, terms: int) -> int:
return divisor * (terms * (terms + 1)) // 2
fizzsum = sum_multiples( 3, (n-1) // 3)
buzzsum = sum_mu... | 6b4ee36075a5b46bd51c58c3bd44c103061c7cd1 | 3,605,707 |
import requests
def post_data(url, file):
"""
:param url: 接口url
:param file: 上传文件的路径
:return:
"""
files = {"file": open(file, "rb")}
s = requests.session()
r = s.post(url, files=files, verify=False)
r_json = r.json()
print('r', r_json)
if r_json.get('success... | 24e53797698e61789c3233cc1bf150fdbf0485fd | 3,605,708 |
from typing import Optional
from typing import Dict
from typing import Any
from pathlib import Path
import torch
import transformers
def train(
dataset: DatasetDict,
model_name: str = "trained-speakerbox",
model_base: str = DEFAULT_BASE_MODEL,
max_duration: float = 2.0,
seed: Optional[int] = None,... | 2ba74f36381eb9a7cd25b39d1036c7a0ab8a09c0 | 3,605,709 |
from datetime import datetime
def centerline_to_polygon(
centerline: NDArrayFloat, width_scaling_factor: float = 1.0, visualize: bool = False
) -> NDArrayFloat:
"""Convert a lane centerline polyline into a rough polygon of the lane's area.
The input polyline may be 2d or 3d. Centerline height will be pro... | 3e663370cf7ff0720b464b7e8b475e3158917d99 | 3,605,710 |
import csv
def parse_blastn_output(tsv, step_id, parse_descriptions=True):
"""
Parse output from a search step (in BLAST tabular format).
Expects a tsv file with the following format fields:
qseqid sseqid stitle evalue \
bitscore score length pident \
nident mismatch positive gap... | f4e9770f89b3286d2a906ff20bf3165916cc7ad9 | 3,605,711 |
def evidence_type_number_to_name(num: int) -> str:
"""
Transforms evidence type number to it's corresponding name
:param num: The evidence type number
:return: The string name of the evidence type
"""
name: str = str()
supported_types = ['Network', 'Process', 'File', 'Registry', 'Security', ... | 1f6a8e57334e08e997a3f86e629df04cb9602594 | 3,605,712 |
def energy(_x, _params):
"""Kinetic and Potential Energy of rigid body.
_x is an array/list in the following order:
q1: Yaw q2: Lean |-(Euler 3-1-2 angles used to orient A
q3: Pitch /
q4: N[1] displacement of mass center.
q5: N[2] displacement of mass center.
... | f83a9c292cd370614c04b14d8ba3c96bf0f6143e | 3,605,713 |
def loglike_new(X, p, theta):
"""(Incomplete) Loglikelihood of Bernoulli mixture model"""
N, K = X.shape[0], len(p)
theta = theta.T # Transpose for easier comparability with derivations
S, LL = np.empty((N,K)), np.empty((N,1))
log_S = np.repeat(log(p), [N], axis=0).reshape(K,N).T + ... | 20d0fd3bc25f0fe7cce1c32ddedc36acdc70f5d9 | 3,605,714 |
def solution(n):
"""Returns the largest palindrome made from the product of two 3-digit
numbers which is less than n.
>>> solution(20000)
19591
>>> solution(30000)
29992
>>> solution(40000)
39893
"""
# fetchs the next number
for number in range(n - 1, 10000, -1):
# ... | 67e91eb9bbd778dd67bac7a2287f1d333ff49961 | 3,605,715 |
import requests
def get_epoch():
"""
get current epoch
"""
web_address = "https://0l.interblockcha.in:444/epochs"
response = requests.get(web_address)
epochs = response.json()
return epochs | f46af8fe10e7b8dec5368b949c1e338a2c02b340 | 3,605,716 |
from .win32_pipe import Win32PipeInput
from .posix_pipe import PosixPipeInput
def create_pipe_input():
"""
Create an input pipe.
This is mostly useful for unit testing.
"""
if is_windows():
return Win32PipeInput()
else:
return PosixPipeInput() | 80f5e587110dda8cc4d5d0620a4dbd037b7e67c4 | 3,605,717 |
def signup():
"""Takes data from signup form and creates an userobject. Sends user object to signup database function. Returns
signup page with relevant error or confirm email page and authToken"""
if g.loggedIn:
flash('You can not sign up while you are already logged in.', 'danger')
return ... | d48be678e165b495a2fae4d590920ad40d4b6df3 | 3,605,718 |
def select(population, to_retain):
"""Retain those that meet criteria"""
sorted_population = sorted(population)
to_retain_by_sex = to_retain//2
members_per_sex = len(sorted_population)//2
females = sorted_population[:members_per_sex]
males = sorted_population[members_per_sex:]
selected_femal... | 8621bf02dc4ba528b4d7e327826c3d53e893065e | 3,605,719 |
def preview_reply_email(request, review_request_id, review_id, reply_id,
format,
text_template_name='notifications/reply_email.txt',
html_template_name='notifications/reply_email.html',
local_site=None):
"""
Previews... | e730f7c122dbf9221901f49aac8a724a58a98c93 | 3,605,720 |
import os
import yaml
def load_conf(config_path):
"""
Load the configuration file
:return:
"""
try:
with open(os.path.expandvars(os.path.expanduser(config_path))) as config_file:
config = yaml.load(config_file, Loader=yaml.FullLoader)
except FileNotFoundError:
print... | f8c9b3c27ca11286a4b771203eb54826b7bc9a6a | 3,605,721 |
def EditDistance(first, second):
"""Returns edit distance between given strings.
Edit distance is defined as minimal number of edits that transforms first
string into the second one.
Possible operations:
- Remove character.
- Add character.
- Substitute character.
Args:
first: str
secon... | a5b29301dec029c751b1a27ed115801c65270322 | 3,605,722 |
def axis_slicer(n, sl, axis):
"""
Return an indexing tuple for an array with `n` dimensions,
with slice `sl` taken on `axis`.
"""
itup = [slice(None)] * n
itup[axis] = sl
return tuple(itup) | 0fdd64be34428da20c79d8c52a22c916cb5afe19 | 3,605,723 |
def stations_by_distance(stations, p):
"""
Given a list of station objects and a coordinate p,
return a list of tuples, where distance is the distance of the station from the coordinate p
"""
return sorted_by_key(
[(station, haversine(p, station.coord)) for station in stations], 1
) | 27a863e6e6f73047f1c349a1413ef623dc078e9d | 3,605,724 |
def zzx_degree(f):
"""Returns leading degree of f in Z[x]. """
return len(f) - 1 | f24b966a69c998014a54542d906bbbf62f027126 | 3,605,725 |
def get_asset_instance_by_name(scene, name, client=default):
"""
Returns the asset instance of the scene that has the given name.
"""
return raw.fetch_first(
"asset-instances",
{"name": name, "scene_id": scene["id"]},
client=client
) | 4a987640a44a742f4a37627c6608cf6791798430 | 3,605,726 |
import socket
import ssl
def wrap_socket(
conn: socket.socket, keyfile: str,
certfile: str,
) -> ssl.SSLSocket:
"""Use this to upgrade server_side socket to TLS."""
ctx = ssl.create_default_context(
ssl.Purpose.CLIENT_AUTH,
)
ctx.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO... | 8981c86922aa28c6aded189ef425e232e93425b0 | 3,605,727 |
import json
import _io
def dumpjson(obj:dict, name=None) -> str:
""" Dump json(dict) to file """
jstr = json.dumps(obj, indent=4, ensure_ascii=False)
if name:
with _io.open(name, 'w') as f:
f.write(jstr)
return jstr | 1a86b726cb198d4c2d7d8de53f3df9bbc79d5bf2 | 3,605,728 |
def unreviewed_cal(request, start=None, end=None):
""" Calendar view for events that are ready to be reviewed for billing """
context = {'h2': "Events Pending Billing Review", 'listurl': reverse('events:unreviewed'),
'bootcal_endpoint': reverse('cal:api-unreviewed')}
return render(request, 'e... | be348864d4d2c106b289a3f4d63e21e471c24b39 | 3,605,729 |
def get_trace_err(pred_traces, true_trace):
"""
Input shpae [traces_n, rollout_len]
Return shape [1, rollout_len]
"""
# mean across traces (axis=0)
return np.mean((pred_traces - true_trace)**2, axis=0) | b7caa2d50d86a68ea4c872b78671ad8224514ef5 | 3,605,730 |
def style_transfer(content_image, style_image,
content_layer_ids, style_layer_ids,
weight_content=1.5, weight_style=10.0,
weight_denoise=0.3,
num_iterations=120, step_size=10.0):
"""
Use gradient descent to find an image that minimizes ... | e2af8152b7de00c28f88781ef014e4a17203bcb5 | 3,605,731 |
import random
def displace_within_a_circle(point, radius=0.0):
"""
Masked locations are placed anywhere within a circular area around the
original location. Since every location within the circle is equally
likely, masked locations are more likely to be placed at larger distances
compared to smal... | 9f978c057caf297de40b0c7a12796be091e4c032 | 3,605,732 |
def ta_2d(x1, x2, a, w_0, w_1, w_2):
"""2d tanh function."""
return a * np.tanh((w_1 * x1) + (w_2 * x2) + w_0) | ca6cc33787ff9fc818f4d46339caab0ceb0537de | 3,605,733 |
import argparse
def get_args(batch_size=64, image_size=32, n_classes=10, max_iter=100000, sample_size=50000):
"""
Get command line arguments.
Arguments set the default values of command line arguments.
"""
description = "Example of Self-Attention GAN (SAGAN)."
parser = argparse.ArgumentParse... | 96065f41d0744ddef244a515b44d9073dfdf94ad | 3,605,734 |
import time
def get_timestamp_until_hit(path, extra_headers=None):
"""Makes repeated request to the same URL and retries until
it gets a cache hit (or until `num_tries` attempts are made,
in which case an AssertionError is raised).
Return value is a tuple composed of:
hit_value: value of the ... | 246f311a3705190eb323070f1b7b5cedf7fe59f3 | 3,605,735 |
import torch
def convert_rle_to_binary(rles):
"""
Convert a list of rle masks to a list of binary masks
"""
masks = []
for rle in rles:
mask = mask_util.decode(rle)
mask = torch.from_numpy(mask)
masks.append(mask)
return masks | 7f03df9132327fc0a1c8a5c605680a958c8220b2 | 3,605,736 |
import pickle
def generate_predictions(csv_paths, model_paths):
""" Takes in a list of datasets and a list of models and generates predictions for
each dataset with the correct model. Returns a list of outputs for each model"""
def load_models(model_paths):
""" Takes in a list of model paths... | 3d2224b69ab2f88efa6d3c9b2a07716582d8deac | 3,605,737 |
import click
import os
def resolve_color_default(color: ColourTrilean = None) -> ColourTrilean:
"""
Helper to get the default value of the color flag.
If a value is passed it is returned unchanged,
otherwise it's looked up from the current context.
If the environment variable ``PYCHARM_HOSTED`` is ``1``
(whic... | c833c82c713d0d54701b5efd667e92efd2761068 | 3,605,738 |
def is_visible(self, y):
"""Checks whether a given point is within the currently visible area of the markdown area.
The function is used to handle text which is longer than the specified height of the markdown area and
during scrolling.
:param self: MarkdownRenderer
:param y: y-coordinate
:retu... | aa982d8fadf70f970e084ead9be07916d2599217 | 3,605,739 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
# cleanup platforms
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if not unload_ok:
return False
# disable discovery
await discovery.async_stop(h... | dbdb9f24b0095bef7b2df9bda12bc957455adb9c | 3,605,740 |
import struct
def get_response(sock):
""" Read a serialized response message from a socket.
"""
msg = Response()
len_buf = socket_read_n(sock, 4)
msg_len = struct.unpack('>L', len_buf)[0]
msg_buf = socket_read_n(sock, msg_len)
msg.ParseFromString(msg_buf)
return msg | 8570272c5c332fcf946be0b62ca9e993d40c7779 | 3,605,741 |
import scipy
def stochastic_svd(corpus, rank, num_terms, chunksize=20000, extra_dims=None,
power_iters=0, dtype=np.float64, eps=1e-6):
"""
Run truncated Singular Value Decomposition (SVD) on a sparse input.
Return (U, S): the left singular vectors and the singular values of the input
... | ade8ef2aa425abe1a8e9582100bb5ce059445ee1 | 3,605,742 |
import os
import json
def get_team_results(tournament_url: str) -> pd.DataFrame:
""" Use API to get team results or read from disk to save time. If not available on disk API will be called.
"""
tournament_id = tournament_url.split("/")[-1]
result_path = os.path.join(os.path.dirname(__file__), "re... | 190f9e13bb66af53c8e76dc696e8084c1e10ec86 | 3,605,743 |
from typing import Optional
from typing import Callable
import functools
import logging
def error_reporting_v2(*, raise_error: Optional[bool] = True) -> Callable:
"""
Create decorator that adds error reporting to a function.
Reports errors to Stackdriver and to function logs.
Args:
raise_ (O... | 1ce885195a3feb37420e790db412c633a1241618 | 3,605,744 |
def get_all(isdsAppliance, check_mode=False, force=False):
"""
Get all rsyslog objects
"""
return isdsAppliance.invoke_get("Get all rsyslog objects",
module_uri) | 95fd59850e71bbc584b46801434f4cf9443aefd3 | 3,605,745 |
def create_definition(*, db_session: Session = Depends(get_db), definition_in: DefinitionCreate):
"""Create a new definition."""
definition = get_by_text(db_session=db_session, text=definition_in.text)
if definition:
raise ValidationError(
[
ErrorWrapper(
... | ac62e6e2b44f7166cdfc1018fc2986343b75b029 | 3,605,746 |
import logging
import sys
def run(runner, the_config):
"""Main common runner for serial and parallel"""
compdb = compdb_parser.load_compdb(the_config.compdb)
the_summary = summary.get_summary()
if compdb:
the_summary = runner(the_config, compdb)
else:
logging.error("Could not load ... | 60890303432f9fa8ba68e41f57159512c2995d04 | 3,605,747 |
import resource
def _IncreaseSoftLimitForResource(resource_name, fallback_value):
"""Sets a new soft limit for the maximum number of open files.
The soft limit is used for this process (and its children), but the
hard limit is set by the system and cannot be exceeded.
We will first try to set the soft limit... | aa71fa41f721a612e44c7ce9b65a025f2e9d1bba | 3,605,748 |
def c_index_ours(y_pred, y_true, **kwargs):
""" Compute a concordance-index.
The c-index is a measure of accuracy similar to the area under the
ROC (AUC). It is computed by assessing relative risks (orderings of
survival times across patients) where comparisons are restricted based
on censoring. Se... | 19b3f5c816c029b197f23681ae45d5a7edca3973 | 3,605,749 |
from typing import Dict
def coordinate_check(record: Dict, existing_results: VRR) -> VRR:
"""
Context validation to check whether value in the place field matches to the value in the accuracy field
:param record: the record data
:param existing_results: the existing validation result
:return: the ... | fa15ed5cabf88366e84d194130483862e790c974 | 3,605,750 |
import torch
import random
def seed_everything(seed: int):
"""Seeds random state for torch, numpy, and backend devices
:param int seed: the random seed to set
"""
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
return _STRATEGY.seed_everything(seed) | 0c80154479cdaef580bf568b35fe0ab0430db521 | 3,605,751 |
import hashlib
def GetSHA256Hash(filename):
"""Returns the SHA-256 hash value of a file as a hex string."""
hash_function = hashlib.sha256()
return GetHash(filename, hash_function) | 1bbcd877b34db57846f1d0f839998cd95336c754 | 3,605,752 |
import re
from datetime import datetime
def get_race(race, year):
"""レース情報の取得."""
grade_code = race.get('class')[1]
grade_table = {'jpn1': 'JpnⅠ', 'jpn2': 'JpnⅡ', 'jpn3': 'JpnⅢ',
'g1': 'GⅠ', 'g2': 'GⅡ', 'g3': 'GⅢ', 'jpn1Central': 'JpnⅠ',
'g1Local': 'GⅠ'}
grade = g... | beef59e8bff8e9922a4fa89585ce730f54a1fa23 | 3,605,753 |
def get_field_ccd_qid(ra, dec):
""" """
d_ = {}
field_ccds = get_fields_containing_target(ra,dec, inclccd=True)
for field_ccd in field_ccds:
(ramin,decmin),(ramax,decmax) = np.percentile(np.asarray(FIELD_CCDS_GEOSERIE[field_ccd].exterior.xy).T, [0,100], axis=0)
ccdpos=np.asarray([(ra-ram... | 2a7c467d06d214dc680a6087081098a8f2e03f18 | 3,605,754 |
def index():
"""
Home page:
Users can either login or register
"""
return render_template('index.html') | b2493b914944bd218d42ddc7d4d9cede4450c7ec | 3,605,755 |
import logging
import datasets
def create_dataset(student_train_portion,
student_validation_portion,
mentor_portion,
noise_rate,
target_distribution_parameter,
shuffle_files=True):
"""Creates an MNIST data set from TFDS.
... | e45fb6764066e4282c715ad2fa5ec90742001576 | 3,605,756 |
def get_edges(tree):
"""
Get edges from url tree. Where url tree is tuple of (url, list of tuples(
url, list)) etc.
Example tree:
(url, [(url1, [...]),
(url2, [...]).
])
Parameters
----------
tree : tuple
Tree of urls.
Returns
-------
list
Lis... | f0e5d591e1453c6b7507c889a51f9c7064f4be39 | 3,605,757 |
def dd_drawdown_map_nb(record, ts):
"""`map_func_nb` that returns drawdown value of a drawdown."""
valley_val = dd_valley_value_map_nb(record, ts)
start_val = dd_start_value_map_nb(record, ts)
return (valley_val - start_val) / start_val | 808fd208b2e706f9fdd4f2d237b8611a5adda87a | 3,605,758 |
import torch
def vis_logheatmaps(inputs, output_heatmaps, heatmaps, mip_axis=1,
alpha=0.6,
projection_type='mean'):
"""Generate grid of MIP sample slices for labels.
Args:
inputs (np.array): HxWxD array
output_heatmaps (np.array): CxHxWxD array
... | 393072042944c2139895c2418e0471e417b5c9f7 | 3,605,759 |
def is_contain_classes(xml_path,class_names):
"""
这是判断xml文件是否包含指定目标的函数
:param xml_path: xml文件路径
:param class_names: 目标分类数组
:return:
"""
# 解析XML文件
in_file = open(xml_path)
tree = ET.parse(in_file)
root = tree.getroot()
# 遍历所有目标结点,判断是否存在指定目标
flag = False
for obj in roo... | a1b0bb2e918f1668a1b039b09e8ffc741b6b1197 | 3,605,760 |
def request_response(error_type, code, msg):
"""error code response for all endpoints"""
if not msg:
msg = ""
return error_type(getError(code, msg)) | 23f79bbc3bdd91ed2321afe94968528a0376e9b6 | 3,605,761 |
def wigner_ville(psi, dt=1, make_analytic=False, skip=1,
pad=True):
"""Return `(ws, P)` where `P` is the Wigner Ville quasi-distribution for psi.
Assumes that psi is periodic. Note: the frequencies at which `P`
is valid are half the frequencies normally associated with the
wavefunctio... | 76a68ece1b7c7d7045bce2da99bad82600081fcb | 3,605,762 |
def atom_type():
"""Returns this atom type"""
return 'vmhd' | 81f90f2f95729ededd8d1242f4b10ddec8b25fb9 | 3,605,763 |
def _align_subnet_cidrs(occupied_cidr, target_bitmask):
"""Transform the subnet cidr that are smaller than the minimum bitmask to bigger ones."""
correct_cidrs = set()
for subnet_cidr in occupied_cidr:
if _get_bitmask(subnet_cidr) > target_bitmask:
correct_cidrs.add(expand_cidr(subnet_ci... | 146b1f1b1470d5dae56da1e25ca7dd3d7d9a4fa1 | 3,605,764 |
from typing import Tuple
def shrink_1d(
a: np.ndarray, bins: np.ndarray, low=None, high=None, axis=None, assume_sorted=False
) -> Tuple[np.ndarray, np.ndarray]:
"""Select sub-arrays of a `a` and corresponding `bins` for minimal span
of bins, which completely covers the range [`low`..`high`]
both sides... | b8186e1755f321e3757df2e0e8b2394c7b025695 | 3,605,765 |
from typing import Callable
import functools
def model_from_dict(model_dict: dict, exposed_params: dict) -> Callable[[], tensorflow.keras.models.Model]:
"""
Construct a model.
Parameters
----------
model_dict: dict
Config dictionary describing the model
exposed_params: dict
Di... | 2537c8fe39bb3000c4d398b6427e404cb268228d | 3,605,766 |
def asstring(bitArray):
"""
Return string representation of bit array
Parameters:
bitArray (list): an array of bits
Returns:
(string): string form of bitArray
"""
return ''.join([str(bit) for bit in bitArray]) | 23df601aa1b66c89428004d2e1e8a5961066c8be | 3,605,767 |
def crop_shape_from_box(image, shape, box):
"""Crops a specified shape from an image which includes the maximal cropped
image of the box. Performs rescaling if the the box is larger than the
shape.
Args:
image: A numpy array.
shape: A [height, width] shape.
box: A [top, left, bo... | 2ed479fe9fb0d4cd8594d2a111603a87d2d6c940 | 3,605,768 |
def mean_average_precision(predictions, labels, assume_unique=True):
"""Compute the mean average precision on predictions and labels.
Returns the mean average precision (MAP) of all the queries. If a query
has an empty ground truth set, the average precision will be zero and a
warning is generated.
... | 2fbd5dcd53c230020e6059fa7f81872a98130a77 | 3,605,769 |
import json
async def health(request):
"""
Get health and stats about the service.
:return: sanic.response.json
"""
r = dict(
health='green'
)
return json(r) | 1534b3df3fd69fac00d240d71e6206551d9f1f6a | 3,605,770 |
def get_biggest_divisor(n: int) -> int:
"""
Returns the largest divisor, from those generated by get_next_interval_divisor(),
that divides the given number without a remainder.
"""
biggest_divisor = 1
for divisor in get_next_interval_divisor():
if divisor > n:
return biggest_... | 007a0014564d894a3ab36b7b2f20ecd93a4ecf5b | 3,605,771 |
def is_in_fold_innermost_scope_scope(context):
"""Return True if the current context is within a scope marked @fold."""
return 'fold_innermost_scope' in context | 6bed2406d28ce17c09c6dd293fe61e7f70fbf4b2 | 3,605,772 |
def decrypt(data):
"""Decrypt data for use in API calls. 112-bit 3DES EDE CBC is used.
Any padding, i.e. the first 8 bytes and any trailing zeros, are removed."""
assert len(data) % 8 == 0, "Ciphertext is not a multiple of block length"
des = DES3.new(key=KEY, mode=DES3.MODE_CBC, IV=IV)
decrypted ... | 7af37d1d45426a7fdb47c93edfc97dd9bcd13e55 | 3,605,773 |
def get_writer_extensions():
"""
Returns a list of extensions for which writers are available.
:return: the list of extensions
:rtype: list
"""
result = list(get_flow_writers().keys())
result.sort()
return result | 68f048905c78fabfbc27d2ab8f418cfadaca3524 | 3,605,774 |
import collections
def coords_assign(coords, dim, new_name, new_val):
"""Reassign an xray.DataArray-style coord at a given dimension.
Parameters
----------
coords : collections.OrderedDict
Ordered dictionary of coord name : value pairs.
dim : int
Dimension to change (e.g. -1 for l... | ed5210ec2f5399aa8302eadc53e515bdd6722307 | 3,605,775 |
import os
def find_devices(device_mapping):
"""Finds the peripheral devices that are present on the system.
Parameters
----------
device_mapping : dict
A dict whose keys are the Unix group names and whose values are lists of the corresponding
device files.
Returns
-------
... | 5c58a2c67c1ddb43776a54efd1983a365faf2522 | 3,605,776 |
def run():
"""Run the main program"""
assignment_analyser = BlackboardAnalysisTools()
#assignment_analyser.init()
assignment_analyser.run()
return(assignment_analyser.exit_value()) | 39c8cff63f0dbbd96679f39fc230afb0a7275847 | 3,605,777 |
def avg_of_collum(img: np.ndarray, collum: int, ovo=False): # -> int | list
"""Calculates the average pixel value for one collum of an image
Args:
img: The screenshot as np.ndarray
collum: which collum of the image should be analysed?
ovo: output as 'one value only' instead of list... | 585efe20875c35b2894071608e50837b5d0133e4 | 3,605,778 |
def abs(a):
"""
Return abs(a), where a is Tensor.
"""
return Abs()(a)[0] | c38194dec465192b43a63d7a33f92e51b9c7564a | 3,605,779 |
import os
def _valid_path_append(path, *args):
"""
Helper to validate passed path directory and append any subsequent
filename arguments.
Arguments:
path (str): Initial filesystem path. Should expand to a valid
directory.
*args (list, optional): Any filename or pa... | 3f31e8cf4c4db161e14fbf3a7dcc9caf7bc1dddf | 3,605,780 |
def set_paths():
"""
Sets directory paths based on the machine being used
:return: PATH_TO_INPUT, PATH_TO_OUTPUT, PATH_TO_CHECKPOINTS and PATH_TO_VAL
"""
path_to_input = "../data/flaskv3/input/"
path_to_output = "../data/flaskv3/output/"
path_to_cov_output = "../data/flaskv4/output/"
pat... | b590eaba0b1327dfafd69dbf9777669c7cd5505a | 3,605,781 |
def add_clusters(data, clusters):
"""
Adds the cluster predictions to the original data for interpretation.
:param data: DataFrame. The data to have the cluster predictions added on to.
:param clusters: List. The list of cluster predictions to be added to the DataFrame.
"""
addclusters = data
... | 5a91c9af1bccf6ee76d419ceba3274dcecef7535 | 3,605,782 |
def _gini_coefficient(
selection: np.array,
attribute: np.array,
n_percentiles: int
) -> float:
"""Gini coefficient of the selection shared over the attribute."""
# Cut the selected cohort lift into percentiles based on their attribute
percentiles = np.arange(n_percentiles)
perc_idx = pd.qcu... | 93b9354323019054135172af47be6e6100fd65b2 | 3,605,783 |
from ..schema.pipelines.pipeline_ref import GrapheneUnknownPipeline
def get_pipeline_reference_or_raise(graphene_info, pipeline_run):
"""Returns a PipelineReference or raises a UserFacingGraphQLError if a pipeline
reference cannot be retrieved based on the run, e.g, a UserFacingGraphQLError that wraps an
... | 0d78efc3e8796961e771160f271efadadce1b0e7 | 3,605,784 |
def extract_label_from_txt(filename):
"""Get building type and building function."""
with open(filename, 'r') as in_file:
txt = in_file.readline()
split = txt.split(";")
return split[0], split[1][:-1] | d0ed3ea611d631b4dfef6ed7e6637172ed9740e4 | 3,605,785 |
import tqdm
def val(epoch, loader):
"""Validate the net."""
net.eval()
acc_meter = AverageMeter()
epoch_loss_stats = AverageMeter()
bar = tqdm(enumerate(loader))
for batch_idx, sample in bar:
# TODO: Call the val routine for the net
# outputs, label = routines.validation_routi... | 4da2b4d78f3215110148881003fe13d2ca1ba74f | 3,605,786 |
def descenso_gradiente_lotes(x, y, w_0, b_0, alpha, num_iter):
"""
Descenso de gradiente durante num_iter iteraciones para regresión lineal
Parámetros
-----------
x: ndarray de dimension [M, n] con los datos de entrada
y: ndarray de dimension [M,] con los datos de salida
w_0: ndarray de... | d4a08bfaac933c829ff551cc9f7c61f0c127b23a | 3,605,787 |
def n_step(q_values, rewards, kls, discount=0.99):
"""
Discounted n-step Monte Carlo return.
"""
q_estimates = n_step_returns(q_values, rewards, kls, discount=discount)
# get the final n-step return
return q_estimates[-1] | 2e31a238a3bd9e25fe6ce2b77241acac2e8c830d | 3,605,788 |
def compose_gates(cliff, gatelist):
"""
Add gates to a Clifford object from a list of gates.
Args:
cliff: A Clifford class object.
gatelist: a list of gates.
Returns:
A Clifford class object.
"""
for op in gatelist:
split = op.split()
q1 = int(split[1])... | bcbade0ec400b46805f73512a1c2fc64ac866404 | 3,605,789 |
def shlcar3x3(a, x,y,z, sps):
"""
This code returns the shielding field represented by 2x3x3=18 "cartesian" harmonics
The 36 coefficients enter in pairs in the amplitudes of the "cartesian" harmonics a[0]-a[35].
The 12 nonlinear parameters a[36]-a[47] are the scales Pi,Ri,Qi,and Si entering the
ar... | dada9c178c19a0d9bcee4cc6c6a321a4c9315f9a | 3,605,790 |
def is_same_hour(dt1, dt2):
"""
判断两个datetime对象是否是同一时
:param dt1:
:param dt2:
:return:
"""
if (dt1.year == dt2.year) and (dt1.month == dt2.month) and (
dt1.day == dt2.day) and (dt1.hour == dt2.hour):
return True
else:
return False | 76e225db9076bf3d2a9816d495aa9959015d8e61 | 3,605,791 |
def _get_page_url(browser: WebDriver) -> str:
"""Get the URL of the image asset of a jpg image to download.
By default, the image asset returned has very small dimensions. By changing
the zoom parameter, we can get a higher resolution version of the image.
Args:
browser (WebDriver): Selenium b... | 3132dc4bcafa3e1dc558e6ad5fdabbb1d0b5dd89 | 3,605,792 |
import math
def color_distance(from_color, to_color):
"""
Calculate the euclidean distance of two colors in 3D space
"""
return math.sqrt(
(from_color[0] - to_color[0]) ** 2
+ (from_color[1] - to_color[1]) ** 2
+ (from_color[2] - to_color[2]) ** 2
) | b72e9101682bd498ed21e8fb9f73b8f52401b888 | 3,605,793 |
import torch
def computeDiscriminatorLoss(d1Real, d1Fake, gradPenalty):
"""
This function is used to compute Discriminator Loss E[D(x)]
:param d1Real:
:param d1Fake:
:param gradPenalty:
:return:
"""
return (torch.mean(d1Fake) - torch.mean(d1Real)) + (LAMBDA * gradPenalty) | 26220e17acead17880e2867b9d51cec766e382c0 | 3,605,794 |
def vgg16(**kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg["D"]), **kwargs)
return model | 3cc07b4b2c7d40827d00f44c484345b5131e2f20 | 3,605,795 |
def convert_percent(s):
"""
Convert the percentage string to an actual floating point percent
- Remove %
- Divide by 100 to make decimal
http://pbpython.com/pandas_dtypes.html
"""
new_s = s.replace('%', '')
return float(new_s) / 100 | 161f72166105fb8c915b7dfef8cd1ac62a057ac8 | 3,605,796 |
def _GetCellGrad(cell_fn,
cell_grad,
theta,
state0,
inputs,
accumulator_layer,
check_stateful_ops=False,
allow_implicit_capture=False):
"""Returns the gradient function for cell_fn.
Args:
cell... | f23ca11aa951856e763c8c31e9e519ad57e77233 | 3,605,797 |
def transferONTFromContract(toacct, amount):
"""
transfer ONT from contract
:param fromacct:
:param toacct:
:param amount:
:return:
"""
# ONT native contract address
contractAddress = bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01')
... | c8aa0666a68a78cd7eb53b901c342b2156a45347 | 3,605,798 |
import jaxlib.xla_extension as jax_xla
from jax.core import Tracer
def is_tensor(x):
"""
Tests if ``x`` is a :obj:`torch.Tensor`, :obj:`tf.Tensor`, obj:`jaxlib.xla_extension.DeviceArray` or
:obj:`np.ndarray`.
"""
#if is_torch_fx_proxy(x):
# return True
#if is_torch_available():
# ... | f17e64bf4026aeee325cde3f19bbf9a70ddbcc40 | 3,605,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.