content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def move_images(df, label_column, current_path, destination_path):
"""
Moves images from combined folder to new folder based on data splits
df: dataframe containing image IDs to move
label_column: name of column containing labels
current_path: path to where the images are currently stored
de... | 57302f03423f3f7a78432e464c94cdd06ebeec51 | 73,900 |
import os
def load_abalone(return_X_y=False, give_pandas=False):
"""
Loads the abalone dataset where the goal is to predict the gender of the creature.
:param return_X_y: If True, returns ``(data, target)`` instead of a dict object.
:param give_pandas: give the pandas dataframe instead of X, y matric... | 95b4c4ddc442c0817c3cac96bf0fce38277c4284 | 73,901 |
def parse_conn_uri(s):
"""Split uri to parts:
sheme, use, password, host, port, path.
Absent parts replaced with None
Arguments:
s {[str]} -- [uri]
Returns:
[UriParts] -- [Parsed uri]
"""
match = RE_URI_TEMPLATE.match(s)
if not match:
raise ValueError(f"... | 0f261b5fc340b56eafd3be431054f5c3fd70a59b | 73,902 |
def calculate_PCF(coords, r_max, eu_side):
# calculate Pair Correlation Function (PCF) for evidence units represented by their coordinates
"""
Compute the two-dimensional pair correlation function, also known
as the radial distribution function, for a set of circular particles
contained in a square region of a ... | f18fdd1deac7cd09a7f72b8756c81d427fdeb301 | 73,903 |
import FreeCAD
import Part
def fix_rectangle_sketch():
"""Return unit square sketch function object."""
def aux_rectangle_sketch(x_length=1, y_length=1, x_start=0, y_start=0):
"""Helper function to drop a simple unit square sketch.
The segments are carefully ordered.
"""
v... | 08c87e930704033b3f04018f5aa51f8918bc6b15 | 73,904 |
def get_batch_data(cur_samples, is_training=False):
"""
Returns the training samples and labels as numpy array
"""
batch_src_max_len, batch_trg_max_len = get_max_len(
cur_samples) # call get_max_len(): find the max length of src and target per batch
batch_trg_max_len += 1 # may be EOS rela... | 9c0e96d3bb891c2281321e91f53cc8a5e8029537 | 73,905 |
from typing import Any
import dataclasses
import yaml
def human_repr(o: Any) -> str:
"""Convert the given object to a meaningful representation.
The output is similar to YAML.
"""
if dataclasses.is_dataclass(o):
return str(o)
if isinstance(o, ArgsMixin):
return format_args_mixin(... | 66c5812f5563e431629eb2591ba36ef90859f4a9 | 73,906 |
def chi_squared_independence_test(arr, convert_to_table=False, yates_correction=False):
"""
Chi Squared Test of Independence
Answers the question: Did these data come from different distributions? Or are the differences due to chance?
You'll notice on a 2x2 contingency table, the p-value is the same a... | 9b0e923dfc38a3ec9524ab64604a5d81d53adb4a | 73,907 |
def binarize_output(out):
"""Get (0, 1) array from a batch of vectors, using threshold at half their mean"""
out_mean = np.mean(out, axis=out.ndim - 1)
# noinspection PyArgumentList
threshold = (out_mean.max() - out_mean.min()) / 2
return np.where(out_mean > threshold, 1, 0) | 64c06b0d3d60fb1b604197214872b03e2e4d2917 | 73,908 |
import argparse
def parse_arguments():
"""
Parses arguments of the form:
sudoku.py <board name>
"""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--board",
help="Desired board name",
type=str,
... | 47fac843b497a4cea9cd44bb6734023ecf4f9ddc | 73,909 |
import inspect
def get_callable_parameters(callable_: callable):
"""Given a callable object (functions, lambda or methods) get all it's parameters,
each parameter annotation (a: str, b: int), default value (a=1, b=2) and kind (positional, keyword, etc).
If no annotation or default value None.
Example:
def say_... | e9f232b209087ecaf77b5d82d1ac19f43bf937cb | 73,910 |
def index(request):
"""Timesheet entry view utilizes Form defined in models.py"""
if request.method == 'POST':
form = TimesheetForm(request.POST)
if form.is_valid():
form.save()
else:
return render(request, 'timesheets/index.html', {'form': form})
return rend... | 695eb551df7d88c3bdcd5ad4e98a8de47d4c5b98 | 73,911 |
import collections
import functools
def get_config():
"""Generates the config for the experiment."""
name = 'graph_indep_binary_new'
n_stages = 20
shape = 2
scale = 0.5
tol = 0.001
alpha = 0.2
beta = 0.5
langevin_batch_size = 100
langevin_step_count = 200
langevin_step_size = 0.0005
epsilon = ... | 3e3a2a68d7e003587b07c5a9ece01829c0985ede | 73,912 |
from typing import List
from pathlib import Path
import os
def _read_input() -> List[str]:
"""Read the input file."""
travel_map = []
current_path = Path(os.path.dirname(os.path.realpath(__file__)))
image_path = current_path / "resources" / "day3_puzzle_input.txt"
with image_path.open("r", encodin... | 730bc045309e5fccb39a806ef534898687ff4b0a | 73,913 |
def If(if_node, satisfied_node, unsatisfied_node=None, *elseifs):
"""Node to return satisfied if if_node else unsatisfied
Args:
if_node (Node): input booleans
satisfied_node (Node): input to return if true
unsatisfied_node (Node): input to return if False
elseifs (Tuple(Node)): ... | 0537421ba4310b81165533a13068f77947dfd23f | 73,914 |
def calc_aca_from_targ(targ, y_off, z_off, si_align=None):
"""
Calculate the PCAD (ACA) pointing attitude from target attitude and
Y,Z offset (per OR-list).
:param targ: science target from OR/Obscat (Quat-compliant object)
:param y_off: Y offset (deg, sign per OR-list convention)
:param z_off:... | 3ccd1611df9a0b6c8f42a9e627b27872be36a63c | 73,915 |
def generate_anchor_bases(base_size, ratios, scales):
"""
Generate all anchors bases
:param base_size:
:param ratios:
:param scales:
:return:
"""
# generate same shapes on every location
px, py = (base_size - 1) * 0.5, (base_size - 1) * 0.5
anchor_bases = []
for r in ratios:... | a7cc8e5c61dbba41bce45719376e7320edcf0f20 | 73,916 |
def get_gallery_images(context):
"""
Returns a list of img related objects selected as 'gallery'
"""
try:
obj = get_context_object(context)
return obj.image_set.filter(img_type='gallery')
except:
return [] | edb239ab0e3cabcac6d2ec1681412cff43a2b7ba | 73,917 |
def getdata(fn, *args, **kwargs):
"""Get the FITS data.
Small wrapper around `astropy.io.fits.getdata` to auto-determine
the FITS extension. This will return the data associated with the
image.
>>> fits_fn = getfixture('solved_fits_file')
>>> d0 = getdata(fits_fn)
>>> d0
array([[2215, ... | 7c716417fce16331b831d5db461e69a04ad73bb6 | 73,918 |
def get_community_repo() -> Repository:
"""Return main mock repo."""
return Repository(
name="mock-qiskit-terra-with-success-dev-test",
url="https://github.com/MockQiskit/mock-qiskit-wsdt.terra",
description="Mock description for repo. wsdt",
licence="Apache 2.0",
labels=... | 5544dac45514b6468571444294ea469f400d5a8c | 73,919 |
from typing import Dict
from typing import Any
import pickle
def serialize_dlv2_checkpoint(dlv2_checkpoint: Dict[str, Any]) -> bytes:
"""
Handling the checkpoint conversion from DataLoader V2 format to bytes format.
"""
return pickle.dumps(dlv2_checkpoint) | ae5c42d0daea42e61ff77c8b52aba30586657e7c | 73,920 |
def generate_otb_mat_cell(res, gts):
""" Creates the MAT content.
Args:
res: Nx4 array: predicted bounding boxes.
gts: Nx4 array: ground truth bounding boxes.
Returns:
A MAT cell to be saved.
"""
attr_dict = {}
attr_dict['res'] = res
attr_dict['type'] = 'rect'
attr_di... | 5d11e18cbe88bf20776062cc48adbff76b3cd6f3 | 73,921 |
def get_random_cohort(course_key):
"""
Helper method to get a cohort for random assignment.
If there are multiple cohorts of type RANDOM in the course, one of them will be randomly selected.
If there are no existing cohorts of type RANDOM in the course, one will be created.
"""
course = courses... | 4fdf161d15f7f48f84549c13cf8e56858f36d6d0 | 73,922 |
def read_multi_tiff(path, start_z=None, stop_z=None):
"""
path - Path to the multipage-tiff file
returns images stacked on axis 0
"""
try:
img = Image.open(path)
if start_z is not None:
img_itr = ImageSequence.Iterator(img)
img_itr.position = start_z
... | 7b5ce0ea1806f834c1f40b7131a7e680c8921f29 | 73,923 |
def Outputs(running_info):
"""
Convenience proxy function to allow returning the outputs generated by a process
"""
if isinstance(running_info, Future):
# Create the correct information from the future
rinfo = RunningInfo(RunningType.PROCESS, running_info.pid)
return Action(rinfo... | 482822bcb2af40986c223efbe2b44b8ebd069ee3 | 73,924 |
import time
import os
def ssh_output(cmd):
""" Runs an SSH command and returns the stdout/stderr/returncode.
:param cmd: command to run
:type cmd: str
:rtype: (str, str, int)
"""
print('SSH COMMAND: {}'.format(cmd))
# ssh must run with stdin attached to a tty
proc, master = popen_tt... | bfa207b033ea447c04c58d3c9911c4bd6f25dbf9 | 73,925 |
import json
def authenticate_url():
"""
:return:
"""
crate_logger.info("authentication flow initiated.")
bottle_app.oauth = setup_oauth(r_c, conf_obj, store_tokens_callback)
auth_code = bottle.request.POST.get("code")
return json.dumps(
[
el.decode(encoding="utf-8", er... | f8c206bbeff74a633521c959b6034fd7f2194041 | 73,926 |
def load_placer_with_does(filepath, defaults={"do_permutation": True}):
""" load placer settings
Args:
filepath: a yaml file containing the does and placer information
Returns:
a dictionnary of DOEs with:
{
doe_name1: [(component_factory_name, parameters), ...]
... | 6dd0b9c69405036428d48fa03605c90c3f8094d8 | 73,927 |
def validate_login(username=None, password=None):
""" Validate Credentials """
# False if Invalid Credentials
return bool(username == DASH_USERNAME and password == DASH_PASSWORD) | 15b0ca74c9a47a23ffb6fd2e8ea8cc243fc525ea | 73,928 |
def modify_correlation_clusters(correlation_matrix, N_realizations, N_trials, N_exc, N_cluster):
"""
Modifies the correlation matrix to between only clusters
:param correlation_matrix: correlation matrix
:param N_realizations: number of realizations
:param N_trials: number os trials per realizations
:param N_exc:... | 44f029b32a242d727a170635274c58221dcfc987 | 73,929 |
def net_heating(
dlw_sfc: xr.DataArray,
dsw_sfc: xr.DataArray,
ulw_sfc: xr.DataArray,
ulw_toa: xr.DataArray,
usw_sfc: xr.DataArray,
usw_toa: xr.DataArray,
dsw_toa: xr.DataArray,
shf: xr.DataArray,
surface_rain_rate: xr.DataArray,
surface_temperature: float = _FREEZING_TEMPERATURE... | 1df9239cd494e99acc19efeded6becb85f11ab43 | 73,930 |
def diff_struct(o1, o2):
"""Return difference of structs.
If their type differs, returns (o1,o2) (old value/new value)
If they are lists, returns diff_seqs(o1,o2)
If they are tuples, returns diff_seqs(o1,o2)
If they are dicts, returns diff_dicts(o1,o2)
"""
if o1 is o2:
return False
... | 06abd8d4810b0204f2f14216791f11732757459a | 73,931 |
import math
def calculate_free_offers(item, quantity, basket):
"""removes discounted items from basket"""
discounted_price_total = 0
quantity_remaining = quantity
for q, free_item_basket in free_offer_table[item].items():
free_multiples = math.floor(quantity_remaining / q)
print(free... | 5dfe25ceaaf93998bfe0512bd40ae50871b85909 | 73,932 |
import os
import imp
def _import_from(mod, path, mod_dir=None):
"""
Imports a module from a specific path
:param mod:
A unicode string of the module name
:param path:
A unicode string to the directory containing the module
:param mod_dir:
If the sub directory of "path" i... | 87318df47d4d672aeb68663cfecfc1bdebed09a6 | 73,933 |
import json
def merge_json_changes(model_class, model, form, field_name):
"""
Merge changes from json form field to model field
:param model_class: Model class
:param model: Model instance
:param form: form wrapper
:param field_name: field name in model and form
:return: True if there were... | 5c0efef42158cddb3276104b3a399bf85a241992 | 73,934 |
def GetGroupList(setting):
"""
Get all avilable group definition from setting
@return:
configargparse.parse_args() result
"""
groups = set()
for name in setting:
dev = setting[name]
format_, group = GetFieldDef(dev, fields="format_, group")
if group is not N... | d95f68d25cec9fdba54e13098e4f66656246ef7f | 73,935 |
def _reduced_form_vectors(box_vectors):
"""Get reduced vectors from vectors.
Adapted from HOOMD-Blue's documentation on periodic boundary conditions:
https://hoomd-blue.readthedocs.io/en/stable/box.html
"""
v1 = box_vectors[0, :]
v2 = box_vectors[1, :]
v3 = box_vectors[2, :]
lx = np.li... | 5300af6f8ad2ff39432d86dc0de99f46a6c938a6 | 73,936 |
def process_list_data_sources(data):
"""
Returns a Pandas DataFrame from the API call.
:return: A pandas DataFrame.
"""
lines = [{'name': x, 'description': y} for x, y in data]
return pd.DataFrame(lines) | 16b0513ed8d809632eaa5b9f30d838be3cc9dd27 | 73,937 |
import time
import os
from datetime import datetime
import calendar
def display_ndvi_profiles_with_mean_profile_of_the_crop_with_std(parcel_id, crop, plot_title, out_tif_folder_base,
logfile, mean_profile_folder,
... | a0f8d0e2a03439d66c3299487465cebb7609a063 | 73,938 |
def to_geojson(shapes, buildings):
"""Converts the shapes into geojson.
This function will combine the burn scar region and buildings into geojson.
Burn scar polygon in red, buildings polygon all in blue."""
#append burn scar region polygons to geojson
if type(shapes) == list:
results = ({
... | fb0d417ab3c049d4b89e14dea1f15a3f40f42803 | 73,939 |
def logout(request):
"""
退出
:param request:
:return:
"""
request.session.clear()
return redirect('/login.html') | 8f9426e84a9db34eb61dd7acec4f26f87f4c2121 | 73,940 |
def demo(span=27.4, period=12.345678, mean=17, amplitude=1.0):
"""
Demonstration of the TESS noise calculator,
by default on a faint and highly-variable star.
"""
# create times at a half hour spacing
t = np.arange(0, span, 0.5 / 24.0)
n = len(t)
# create a (perfectly smooth) noiseless... | 444339d19d9f50b46eee305ae4def4f60f4f65f6 | 73,941 |
def approx_kde(data, bins=500, bw=0.075):
"""A fast approximation to kernel density estimation."""
stds = 3 #use a gaussian kernel w/ this many std devs
counts, be = np.histogram(data, bins=bins)
db = be[1]-be[0]
pad = 0.5*bins*bw*stds*db
pbe = np.arange(db, pad, db)
x_out = np.concatenate((... | 04dd6e0c4abe286b49933c1bb41ec9d18d793e47 | 73,942 |
def moving_average_convergence_divergence(
df: pd.DataFrame, window_slow: int = 26, window_fast: int = 12, window_signal: int = 9
) -> pd.DataFrame:
"""
This function is a trend-following momentum indicator that shows the relationship between two moving averages at different windows:
The MACD is usually... | 52d2511af5a73b55290acd18d38917eea19ff6e6 | 73,943 |
import numpy
def label_ids(array):
"""
Returns (sorted ndarray of) unique positive elements of array.
Made obsolete by segment.extractIds?
"""
# get all unique elements and keep those that are positive
all = numpy.unique(array)
pos = all.compress(all>0)
return pos | 10158dbfea6e5512ee3d81f6c51cfb7a3828bdf1 | 73,944 |
def getMeltCurveData(excelFile, sampleData):
"""
Grabs melt curve data & merges w/ sample-specific information
"""
meltData = parseQuantStudioSheet(excelFile, "Melt Curve Raw Data")
meltData.dropna(thresh = 3, inplace = True)
strCols = ['Well', 'Well_Position']
intCols = ['Reading']
flo... | 97c8e3accb1703103561942bfcf4ec2e11d14a6c | 73,945 |
def cast_to_complex(tensor):
"""Casts a floating-point tensor to the corresponding complex dtype.
In other words, cast `float32` to `complex64` and `float64` to `complex128`.
If the tensor is already complex, it retains its type.
Args:
tensor: A `Tensor`.
Returns:
The cast tensor.
"""
return tf... | 3ad2c01b11ce599cf01fbc92f1aed0569afdb8f0 | 73,946 |
def vyhodnot(pole):
"""1-D piškvorky se hrají na řádku s dvaceti políčky.
Hráči střídavě přidávají kolečka (o) a křížky (x)."""
if 'xxx' in pole and 'ooo' in pole:
return '!'
elif 'xxx' in pole:
return 'x'
elif 'ooo' in pole:
return 'o'
elif '-' not in pole:
retu... | c647d7f5891ba50d495a0aae5ead57b83594969d | 73,947 |
import re
def get_product(title):
"""Extract protein product from sequence title.
Parameters
----------
title : str
original title which reads "product [organism]"
Returns
-------
str
product
Notes
-----
NCBI protein product xyz [organism]
"""
title =... | 7754e3b90f2119716e64c6a3f60e82c5a6cf8033 | 73,948 |
def split_and_save(
audio,
destination,
prefix,
clip_duration=5,
clip_overlap=1,
final_clip=None,
dry_run=False,
):
""" Split audio into clips and save them to a folder
Arguments:
audio: The input Audio to split
destination: A folder to write clips to
... | 3cd7993dd25e437c3a455290cf339525683b4520 | 73,949 |
def get_manager(): # noqa: E501
"""Returns display
# noqa: E501
:rtype: List[Rotator]
"""
return render_template("manager.html") | 18859f509cd9330cd6617cf3dada833f8329b198 | 73,950 |
from sklearn.model_selection import StratifiedKFold
def sklearn_kfold(xys: np.array, n_splits: int=5, shuffle: bool=False, random_state: int=None):
"""
StratifiedKFold of sklearn, 留一K折交叉验证数据获取
Args:
xys: np.array, corpus
n_splits: int, number of folds. must be at least 2.
shuffle: ... | 9a58ed9bd0998efbd91104973d772008626394ba | 73,951 |
def phone_brands(df):
"""
>>> import pandas as pd
>>> df = pd.read_csv(r'../data.csv')
>>> phone_brands(df)
{'others': 1912, 'Huawei': 1977, 'LG': 622, 'Apple': 2910, 'Xiaomi': 1491, 'Samsung': 4738, 'Motorola': 584, 'OPPO': 542, 'Vivo': 575}
"""
brands = {}
brands['others'] = 0
# ge... | 19bc556d0882d5efa73f88f4f58f8090f6ed3fe1 | 73,952 |
def get_c_type_from_numpy_dtype(dtype_specified):
"""
Get the ctype corresponding to a given numpy.dtype
:param: dtype_specified - the numpy.dtype
:return: the ctype corresponding the the dtype_specified. None unable to match
"""
typemap = {}
for t in (c_byte, c_s... | 57c3bf6104c0c68e9c1986ce9f5809937b36abb9 | 73,953 |
def geometric_sum(n):
"""
calculate the geometric sum of n-1
:param n:
:return:
"""
if n < 1:
return 1
else:
return 1 / (pow(2, n)) + geometric_sum(n - 1) | 6e482e16fdbbc833ef56e72779fcfbab155cbfcb | 73,954 |
def choose_display():
"""
prompt user to choose scale bar display
"""
choices = ["d","theta","both"]
temp_choice = "false"
while temp_choice not in choices:
temp_choice = input("Please choose the scale to display.\nd, theta, both\n")
if temp_choice not in choices:
... | 8f03dbfbbf250881ecb6a27e4de332bdac4dfcd2 | 73,955 |
from ucscsdk.mometa.aaa.AaaDomainGroup import AaaDomainGroup
def locale_domaingroup_assign(handle, locale_name, name,
domaingroup_dn="domaingroup-root", descr=None,
**kwargs):
"""
assigns a locale to domaingroup
Args:
handle (UcscHandle)... | 990f1d14df59dbac011ae2f0ad0c2c9dc1efc69e | 73,956 |
def f_activation(z):
"""
Numerically stable version of the sigmoid function (reference:
http://fa.bianp.net/blog/2019/evaluate_logistic/#sec3.)
"""
a = np.zeros_like(z)
idx = (z >= 0.0)
a[idx] = 1.0 / (1.0 + np.exp(-z[idx]))
idx = np.invert(idx)
a[idx] = np.exp(z[idx]) / (1.0 + np.... | 9bfb48642988519ce74c0b2f2aa9c8b6cc99cac2 | 73,957 |
def getAllCombinations(cond_):
"""Returns all possible combinations of features for training on"""
lst = [
"total_bytes",
"max_bytes",
"1->2Bytes",
"2->1Bytes",
"1->2Pkts",
"2->1Pkts",
"total_pkts",
"number_ms",
"pkt_ratio",
"time_s... | 9d4324170dcb21779290398ad744dec32fff30be | 73,958 |
def model_12(GPUS = 1):
""" two dense layers: 1000, 800 """
model = Sequential()
model.add(Convolution3D(60, kernel_size = (3, 3, 3), strides = (1, 1, 1), input_shape = (9, 9, 9, 20))) # 32 output nodes, kernel_size is your moving window, activation function, input shape = auto calculated
model.add(BatchNormali... | 73ee7710831e4739e668df7d6844e74df64c93a0 | 73,959 |
def _tensor_to_jax(value: Tensor) -> DeviceArray:
"""Converts a PyTorch Tensor into a Jax DeviceArray."""
tensor = torch_dlpack.to_dlpack(value)
tensor = jax_dlpack.from_dlpack(tensor)
return tensor | ee666be90a332de6dc0798cf9fce8f672b1e0f1f | 73,960 |
def profile(column: Column):
"""
Performs summary of single column object
Parameters:
column: Column object to profile
Outputs:
profile dataframe
"""
col_full = ".".join((column.ds_name, column.name))
profile_init = pd.DataFrame.from_dict(column.get_summary(), orient="index")... | 7098a80e07c6a89f79687308d73584d102f237f8 | 73,961 |
def make_rmg_database_object() -> RMGDatabase:
"""
Make a clean RMGDatabase object.
Returns: RMGDatabase
A clean RMG database object.
"""
rmgdb = RMGDatabase()
return rmgdb | 7cc195b48e64a6472bd4b7f3d4b55974a390b2f4 | 73,962 |
def edit_application(request, club_name):
"""Edits current application for a club with an updated statement"""
club_applied = Club.objects.get(club_name=club_name)
application = Application.objects.get(user=request.user, club=club_applied)
form = ApplicationForm(instance=application)
if request.meth... | be0c7687d0458e8df8f969de9457978ae22d762b | 73,963 |
import tempfile
import os
def reproject_tif(original_filepath, tif_bytes, dst_crs,
sampling_method, no_data_value=None):
"""Reproject tif to a destination CRS
Reprojects a GeoTiff to a new CRS using rasterio, saving the reprojected
GeoTiff to a new temporary location.
Args:
o... | 35e93ebaf4a7944ae24bb2555ffeb28ba21519d2 | 73,964 |
def reverse_bits(n, width=8):
"""Reverse bit order (not the fastest way)"""
b = '{:0{width}b}'.format(n, width=width)
return int(b[::-1], 2) | d001babf6d3219ff9de7994e2719ebafe9561208 | 73,965 |
def xf_screenname(name):
"""Insure user screen name is prefixed with '@'."""
return '@' + name if name[0] != '@' else name | 6229a22907c4b1c11b75f5cd0218e056d46111eb | 73,966 |
from typing import Optional
import os
def get_token(docker_image: pierone.api.DockerImage) -> Optional[dict]:
"""
Attempt to get existing token.
If that fails, try to login to pierone and then get the token.
:return: {'access_token': ...,
'creation_time': ...,
'expires_in': ... | 052f54b9cc84534277fc4d9875f57b7f3c7bc2a2 | 73,967 |
import ast
def p_pyatom_dict(p, kv_pairs=2): # [key: value, ...], [:]
"""pyatom : LBRACKET dictents RBRACKET
pyatom : LBRACKET COLON RBRACKET"""
if kv_pairs != ':':
keys, values = map(list, zip(*kv_pairs))
else:
keys, values = [], []
return lambda: ast.Dict(keys, values) | 81a50745298106c9919c080629851fb57b5f1d1f | 73,968 |
import json
def GetComment(request):
"""
接收畅言的评论回推, post方式回推
:param request:
:return:
"""
arg = request.POST
data = arg.get('data')
data = json.loads(data)
title = data.get('title')
url = data.get('url')
source_id = data.get('sourceid')
if source_id not in ['message']:
... | 02af6f8d96d8eb4a9ae8d2849b726a3c97c73cb6 | 73,969 |
def IsInsitu():
"""Returns True if executing in an insitu environment, else false"""
global ActiveDataDescription
if vtkInSituInitializationHelper.IsInitialized():
# Catalyst 2.0
return True
# Legacy Catalyst
return ActiveDataDescription is not None | ee0c01f32c3ec3c14eab8426c2781c17451aba10 | 73,970 |
def CreateBackup(backup_ref,
description=None,
labels=None,
retain_days=None,
delete_lock_days=None,
client=None):
"""Creates a backup resource by calling Backup for GKE service and returns a LRO."""
if client is None:
client =... | cdef7e750231d970c4267c2490a6ee46116ce232 | 73,971 |
import os
def get_parent_dir(n=1):
"""returns the n-th parent dicrectory of the current
working directory"""
current_path = os.path.dirname(os.path.abspath(__file__))
for _ in range(n):
current_path = os.path.dirname(current_path)
return current_path | 0179c65bf124bf53ee9e61a51481f39a55314764 | 73,972 |
def test_materializer_source_execution_parameter_changes_when_materializer_changes():
"""Tests that changing the step materializer changes the materializer
source execution parameter."""
@step
def some_step() -> int:
return 1
class MyCustomMaterializer(BuiltInMaterializer):
pass
... | fd502a40e9b34189ebdb7f499270e1f1b74bc7fc | 73,973 |
import math
def coefficients(deriv, acc):
"""
Calculates the finite difference coefficients for given derivative order and accuracy order.
Assumes that the underlying grid is uniform. This function is available at the `findiff`
package level.
:param deriv: int > 0: The derivative order.
... | 64c2bf67fb3e8fa0c46219021c5106ad9cbb3edd | 73,974 |
from typing import List
from typing import Dict
from typing import Any
def compare_numbers_subset(
record_1: List[Dict], record_2: List[Dict], options: Dict[str, Any]
) -> Dict[str, Any]:
"""One set of numbers must be a complete subset of the other
without leading zeroes.
"""
meta = {'function': '... | cd55bdf2da9c8aca478cb1a5fae4e13649a38f98 | 73,975 |
def add_join_id_column(spark_session, df_src, df_weights, src_col_name, weights_col_name):
"""
:param spark_session: the spark session
:param df_src: spark datafarme which need to be updated with join_id
:param df_weights: spark datafarme with weights_col_name and 'join_id'
:param src_col_name:
... | 85e30ab799ade621a37e33ebbbea6659c8e72565 | 73,976 |
def c(*args: str) -> str:
"""Joins all strings together"""
return "".join(args) | d3361fa1e62814b9023aaa219f0f38131d20a778 | 73,977 |
def WaveformQuality_ClassName():
"""WaveformQuality_ClassName() -> char const *"""
return _DataModel.WaveformQuality_ClassName() | aa22f1f200ea2cee8b1339d9bf4460b90b0f05c5 | 73,978 |
def diff_matrix_permutation(node_tuples, ref_axis):
"""Return a :mod:`numpy` array *permutation* of integers so that::
diff_matrices[ref_axis] == diff_matrices[0][permutation][:, permutation]
.. versionadded:: 2020.1
"""
ntup_index_lookup = {nt: i for i, nt in enumerate(node_tuples)}
if r... | 0cb8eac86f86e993d7120e838049595237fd367b | 73,979 |
import time
from sys import path
def apply_super_resolution_model_to_image(
image,
model,
target_range=(-127.5, 127.5),
batch_size=32,
regression_order=None,
verbose=False,
):
"""
Apply a pretrained deep back projection model for super resolution.
Helper function for applying a pr... | d905ecdb3ee0a3b32dd798ee916029ca2007701a | 73,980 |
import torch
def separation_loss_p(x, delta):
"""Computes the separation loss.
Args:
xyz: [batch, num_kp, 3] Input keypoints.
delta: A separation threshold. Incur 0 cost if the distance >= delta.
Returns:
The seperation loss.
"""
bs = x.size(0)
num_kp_p = x.size(1)
t1_p ... | f277c84ecd14fe50b967937bb8b4f8d5f2b98118 | 73,981 |
def resize_image(img):
"""
Resizes an image into four different sizes.
Parameters
----------
img: A `PIL.Image` to be resized.
Returns
-------
A list of four resized `PIL.Image`s.
"""
width, height = img.size
larger_dimension = width if width > height else height
scale... | ccc9ccda435e93de35a9c6afc024c7b0057c3de0 | 73,982 |
def disturbance(q, dq, w, β=β):
"""TODO: docstring."""
β = jnp.asarray(β)
ϕ, dx, dy = q[2], dq[0], dq[1]
sinϕ, cosϕ = jnp.sin(ϕ), jnp.cos(ϕ)
R = jnp.array([
[cosϕ, -sinϕ],
[sinϕ, cosϕ]
])
v = R.T @ jnp.array([dx - w, dy])
f_ext = - jnp.array([*(R @ (β * v * jnp.abs(v))),... | 3e413b2bf546ab06f99e431817f952386162d042 | 73,983 |
def match_reqs(reqs_str: str):
"""
Match the requests string.
Extract the request operations and the possible version string.
"""
if not reqs_str:
raise ValueError("input string is empty.")
if ',' in reqs_str:
reqs_map = map(str.strip, reqs_str.split(','))
reqs = list(re... | 2323eae43645d4287ca0b25324ba9eee47bcbcf0 | 73,984 |
from typing import Iterator
from typing import Mapping
import json
import time
def json_success_handler(results: Iterator[Mapping]) -> str:
"""A success handler which returns results in a JSON-formatted response.
Args:
results: The results of all checks which were executed for a checker.
... | 4c2db51f412864135e4d89ce386e2b78eeaab3da | 73,985 |
def scan_object( uri, resource, partial_path ):
"""
Scans an object for a matching URI
Args:
uri: The URI to find
resource: The object to scan
partial_path: An array of strings containing the path discovered for the current resource
Returns:
True if there's a match; Fal... | f52d754b38da43ef345596353ae96009d9bf89fb | 73,986 |
def sp_batch_map_coordinates(inputs, coords):
"""Reference implementation for batch_map_coordinates"""
coords = coords.clip(0, inputs.shape[1] - 1)
mapped_vals = np.array([
sp_map_coordinates(input, coord.T, mode='nearest', order=1)
for input, coord in zip(inputs, coords)
])
return m... | 4cdee840b878b09588a9df31c56eedb422d1b567 | 73,987 |
def func_xy_ab_args(x, y, a=2, b=3, *args):
"""func.
Parameters
----------
x, y: float
a, b: int
args: tuple
Returns
-------
x, y: float
a, b: int
args: tuple
"""
return x, y, a, b, args, None, None, None | 663517ea56949bdcc72bc92278aa667d614f0311 | 73,988 |
def limit(iterator, n=None):
"""Produce a limited stream of values from an iterator.
If `n` is 0 or None, don't limit the iterator at all.
:param iterator: An iterator of values.
:param n: The maximum number of values to produce.
:yield: The first (at most) `n` values from the iterator.
"""
... | 757669e4f6b28efcd5e811e64c416d87312d2e39 | 73,989 |
def mc_eta_to_m1m2(mc, eta):
"""Convert eta to m2 and m1 >= m2."""
if eta <= 0.25 and eta > 0.:
root = np.sqrt(0.25 - eta)
fraction = (0.5 + root) / (0.5 - root)
m1 = mc * (pow(1 + 1.0 / fraction, 0.2) / pow(1.0 / fraction, 0.6))
m2 = mc * (pow(1 + fraction, 0.2) / pow(fraction, ... | b0e5ec1ee42fc618b974d5f6d6a8deb62d2c110e | 73,990 |
import json
def compute():
#TODO: CM provider must "change the documentation with the information of his CM
""" compute the Calculation module (CM)from the main web services (MWS)-
the main web service is sending
---
parameters:
- name: inputs_raster_selection
in: pat... | 0a8fc035ed456bfdbaad429d6ad00dbd0c16d26c | 73,991 |
def create_notebook(body): # noqa: E501
"""create_notebook
:param body:
:type body: dict | bytes
:rtype: ApiNotebook
"""
if connexion.request.is_json:
body = ApiNotebook.from_dict(connexion.request.get_json()) # noqa: E501
api_notebook = body
error = store_data(api_noteboo... | fc0219b7ffde4d091ca5af02f7f3b0ed5959bcfe | 73,992 |
def find_second_pair(n, min_pair_found):
"""Finds a second pair of pentagonal m, m<n so that P[m] + P[n] in P and
P[n] - P[m] in P"""
for m in range(n-1, 0, -1):
pair = m, n
if min_pair_found and D_tuple(pair) > D_tuple(min_pair_found):
return None
if S_tuple(pair) in P a... | d875049036fe62d80208a14a2941424d1dc50f1b | 73,993 |
import os
def get_editor(repo):
"""
Returns the editor from env vars.
"""
return (repo.git.config("core.editor") or
os.environ.get("GIT_EDITOR") or
os.environ.get("VISUAL") or
os.environ.get("EDITOR", "vi")) | af29d1e52afea67d90460c0727a742b7d8146a78 | 73,994 |
def scatter_points(region, size, random_state=None, extra_coords=None):
"""
Generate the coordinates for a random scatter of points.
The points are drawn from a uniform distribution.
Parameters
----------
region : list = [W, E, S, N]
The boundaries of a given region in Cartesian or geo... | 793c4c219acf424f2bba1523e983619d45f56318 | 73,995 |
def GenerateRgbToHsvColorMap():
""" Generate a map from all Animal Crossing RGB colors to their respective HSV values
"""
mapping = {}
for hsv_color in GenerateHsvACColors():
mapping[HsvToRgb(hsv_color)] = hsv_color
return mapping | 69a67f0b67a66ac934ae9b97c9533c4800feb6e9 | 73,996 |
def create_hparams(flags):
"""Create training hparams."""
return contrib_training.HParams(
# Data
src=flags.src,
tgt=flags.tgt,
train_prefix=flags.data_dir + flags.train_prefix,
test_prefix=flags.data_dir + flags.test_prefix,
vocab_prefix=flags.data_dir + flags.vocab_prefix,
... | 3d36986a96a3e8f2f57ecbcc847652deaa3a5177 | 73,997 |
from typing import List
from typing import Dict
def load_mappings() -> List[Dict[str, str]]:
"""Load the mappings table."""
return _load_table(get_resource_file_path("mappings.tsv")) | 54036ff66ea140c0b85af889166e51d5d23f3ecd | 73,998 |
def atribuir_ponto(dificuldade):
"""
Esta função cria um arquivo de texto contendo o score do usuário e também realiza a operação de adição de pontos do
score do mesmo. Caso o arquivo contendo o score do usuário não exista, ele cria um novo, porém este é inicializado
em 0.
:param dificuldade: Modo d... | e5df9054dcb871c8455e16e73910d7d2937189a3 | 73,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.