content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_contour_verts(cn):
"""unpack the SVM contour values"""
contours = []
# for each contour line
for cc in cn.collections:
paths = []
# for each separate section of the contour line
for pp in cc.get_paths():
xy = []
# for each segment of that section
... | 93dc98e758aca4390adf75afa7ef9bede2d2ac1a | 3,658,200 |
def play(data_type, stream_id, name, start=-2, duration=-1, reset=False):
"""
Construct a 'play' message to start receive audio/video data from publishers on the server.
:param data_type: int the RTMP datatype.
:param stream_id: int the stream which the message will be sent on.
:param name: str the ... | d7c28ba7444e6774427f89d30887cbad97b01cb2 | 3,658,201 |
def _compute_covariances(precisions_chol):
"""Compute covariancess from Cholesky decomposition of the precision matrices.
Parameters
----------
precisions_chol : array-like, shape (n_components, n_features, n_features)
The Cholesky decomposition of the sample precisions.
Returns
------... | 4268a807ed2d6a61e69bd2f07ebbdbf332e030da | 3,658,202 |
def rad2deg(angle):
"""
Convert radian to degree.
Parameters
----------
angle : float
Angle in radians
Returns
-------
degree : float
Angle in degrees
"""
return (180./PI) * angle | dea3270a96cf82bb136ce4f6e873617245a4bac3 | 3,658,203 |
import csv
def parse_kinetics_splits(level):
"""Parse Kinetics-400 dataset into "train", "val", "test" splits.
Args:
level (int): Directory level of data. 1 for the single-level directory,
2 for the two-level directory.
Returns:
list: "train", "val", "test" splits of Kinetics... | ee2521919f9f9c3f499cd28bc6003528eb402d2b | 3,658,204 |
def rotateContoursAbout(contours, about, degrees=90, ccw=True):
"""\
Rotate the given contours the given number of degrees about the point about
in a clockwise or counter-clockwise direction.
"""
rt = Transform.rotationAbout(about, degrees, ccw)
return rt.applyToContours(contours) | c929a8c412f4b3fe9b70c21dde62b0672f575abc | 3,658,205 |
import torch
def coordinate_addition(v, b, h, w, A, B, psize):
"""
Shape:
Input: (b, H*W*A, B, P*P)
Output: (b, H*W*A, B, P*P)
"""
assert h == w
v = v.view(b, h, w, A, B, psize)
coor = torch.arange(h, dtype=torch.float32) / h
coor_h = torch.cuda.FloatTens... | 9eeb906539a61b887216c59faf3ac2928e999d6c | 3,658,206 |
import uuid
def ticket() -> str:
"""生成请求饿百接口所需的ticket参数"""
return str(uuid.uuid1()).upper() | aaf1135d6ef5e61aa65960c5c38007848cbd0b17 | 3,658,207 |
def create_WchainCNOT_layered_ansatz(qc: qiskit.QuantumCircuit,
thetas: np.ndarray,
num_layers: int = 1):
"""Create WchainCNOT layered ansatz
Args:
- qc (qiskit.QuantumCircuit): init circuit
- thetas (np.ndarray): parameters
... | 488950214a26cdcf1812524511561d19baa9dfc9 | 3,658,208 |
import itertools
def birth_brander():
""" This pipeline operator will add or update a "birth" attribute for
passing individuals.
If the individual already has a birth, just let it float by with the
original value. If it doesn't, assign the individual the current birth
ID, and then increment the ... | dd2c1ef2e9ac2f56436e10829ca9c0685439ce6d | 3,658,209 |
def find_center_vo(tomo, ind=None, smin=-50, smax=50, srad=6, step=0.5,
ratio=0.5, drop=20, smooth=True):
"""
Find rotation axis location using Nghia Vo's method. :cite:`Vo:14`.
Parameters
----------
tomo : ndarray
3D tomographic data.
ind : int, optional
Inde... | ff943940a133b88686c6d40cdc09886b050bf181 | 3,658,210 |
def random_fit_nonnegative(values, n):
"""
Generates n random values using a normal distribution fitted from values used as argument.
Returns only non-negative values.
:param values: array/list to use as model fot the random data
:param n: number of random elements to return
:returns: an array o... | 9591b87b36c668681873fda1969d1710e7a2dd8b | 3,658,211 |
def connected_components(weak_crossings=None,
strong_crossings=None,
probe_adjacency_list=None,
join_size=None,
channels=None):
"""Find all connected components in binary arrays of threshold crossings.
Parameter... | d1d4c3393a69e0a30a3bdf2328dd6535aee699d0 | 3,658,212 |
def channel_values(channel_freqs, channel_samples, dt, t):
"""Computes value of channels with given frequencies, samples, sample size and current time.
Args:
channel_freqs (array): 1d array of channel frequencies
channel_samples (array): 2d array of channel samples, the first index being time s... | cdc555a5ab2d21c0dba71f2f24386144796898c1 | 3,658,213 |
import os
import nibabel as nb
import numpy as np
from scipy.fftpack import fft, ifft
def bandpass_voxels(realigned_file, bandpass_freqs, sample_period = None):
"""
Performs ideal bandpass filtering on each voxel time-series.
Parameters
----------
realigned_file : string
Path of a rea... | 772ae195007347ba24670814d907284180a33225 | 3,658,214 |
def get_small_corpus(num=10000):
"""
获取小型文本库,用于调试网络模型
:param num: 文本库前n/2条对联
:return: 默认返回前500条对联(1000句话)的list
"""
list = getFile('/total_list.json')
return list[:num] | 032ea34eaa6b5e1478e3770c91fa3da3214d907b | 3,658,215 |
from tqdm import tqdm_notebook
def groupby_apply2(df_1, df_2, cols, f, tqdn=True):
"""Apply a function `f` that takes two dataframes and returns a dataframe.
Groups inputs by `cols`, evaluates for each group, and concatenates the result.
"""
d_1 = {k: v for k,v in df_1.groupby(cols)}
d_2 = {k: v ... | 082ce61477c116ac421ab086e68b040dfc04ffff | 3,658,216 |
from datetime import datetime
import pytz
def login(request):
"""Logs in the user if given credentials are valid"""
username = request.data['username']
password = request.data['password']
try:
user = User.objects.get(username=username)
except:
user = None
if user is not None:
... | 79add2a805a36cd3339aeecafb7d0af95e42d2e5 | 3,658,217 |
def replace_data_in_gbq_table(project_id, table_id, complete_dataset):
""" replacing data in Google Cloud Table """
complete_dataset.to_gbq(
destination_table=table_id,
project_id=project_id,
credentials=credentials,
if_exists="replace",
)
return None | 1de5464cdce77f94857abe46a93f7b64f5e2dd1e | 3,658,218 |
def default_pubkey_inner(ctx):
"""Default expression for "pubkey_inner": tap.inner_pubkey."""
return get(ctx, "tap").inner_pubkey | 9333a62c0111f28e71c202b5553d7f2a8c4f71ce | 3,658,219 |
def quantize_8(image):
"""Converts and quantizes an image to 2^8 discrete levels in [0, 1]."""
q8 = tf.image.convert_image_dtype(image, tf.uint8, saturate=True)
return tf.cast(q8, tf.float32) * (1.0 / 255.0) | d822ff34b9941c6a812a69766de3483c2348e7da | 3,658,220 |
def get_clients( wlc, *vargs, **kvargs ):
"""
create a single dictionary containing information
about all associated stations.
"""
rsp = wlc.rpc.get_stat_user_session_status()
ret_data = {}
for session in rsp.findall('.//USER-SESSION-STATUS'):
locs... | c4ab5941033632d7f2b95bc23878f0464d12adb7 | 3,658,221 |
def coalmine(eia923_dfs, eia923_transformed_dfs):
"""Transforms the coalmine_eia923 table.
Transformations include:
* Remove fields implicated elsewhere.
* Drop duplicates with MSHA ID.
Args:
eia923_dfs (dict): Each entry in this dictionary of DataFrame objects
corresponds to ... | eb420428dcb2dceeeab1c5bbdceee7c7da2e5c11 | 3,658,222 |
import random
def _throw_object_x_at_y():
"""
Interesting interactions:
* If anything is breakable
:return:
"""
all_pickupable_objects_x = env.all_objects_with_properties({'pickupable': True})
x_weights = [10.0 if (x['breakable'] or x['mass'] > 4.0) else 1.0 for x in all_pickupable_objec... | 03f6c6a99754d79d94df5a4f857ae358db663081 | 3,658,223 |
def plot(
X,
color_by=None,
color_map="Spectral",
colors=None,
edges=None,
axis_limits=None,
background_color=None,
marker_size=1.0,
figsize_inches=(8.0, 8.0),
savepath=None,
):
"""Plot an embedding, in one, two, or three dimensions.
This function plots embeddings. The i... | f6c5ef6084278bcd3eb81c9286af53594aca4a1e | 3,658,224 |
def CausalConvIntSingle(val, time, kernel):
"""
Computing convolution of time varying data with given kernel function.
"""
ntime = time.size
dt_temp = np.diff(time)
dt = np.r_[time[0], dt_temp]
out = np.zeros_like(val)
for i in range(1, ntime):
temp = 0.
if i==0:
temp += val[0]*kernel(time[i]-time[0])*dt... | a4e94bfe2213c428042df4e561f584ffede3f9ab | 3,658,225 |
def sbox1(v):
"""AES inverse S-Box."""
w = mpc.to_bits(v)
z = mpc.vector_add(w, B)
y = mpc.matrix_prod([z], A1, True)[0]
x = mpc.from_bits(y)**254
return x | c10e9d440e1c1149c8d2b0f9fbd3fd5d4868596c | 3,658,226 |
def _get_photon_info_COS(tag, x1d, traceloc='stsci'):
"""
Add spectral units (wavelength, cross dispersion distance, energy/area)
to the photon table in the fits data unit "tag".
For G230L, you will get several 'xdisp' columns -- one for each segment. This allows for the use of overlapping
backgrou... | d1f06d6b8b26894a3297471c74c291cd15b3cb22 | 3,658,227 |
def maximum_value(tab):
"""
brief: return maximum value of the list
args:
tab: a list of numeric value expects at leas one positive value
return:
the max value of the list
the index of the max value
raises:
ValueError if expected a list as input
ValueError if no positive value found
"""
if not(isinstan... | 1c31daf3a953a9d781bc48378ef53323313dc22a | 3,658,228 |
import mpmath
def pdf(x, k, loc, scale):
"""
Probability density function for the Weibull distribution (for minima).
This is a three-parameter version of the distribution. The more typical
two-parameter version has just the parameters k and scale.
"""
with mpmath.extradps(5):
x = mpm... | 77efc3f7ceda57377a412dc7641114cea3562953 | 3,658,229 |
def add_flight():
"""Allows users to add flights."""
if request.method == "GET":
return render_template("add.html", airports=AIRPORTS)
else:
# Move request.form into a dictionary that's a bit shorter to access than request.form
form = dict(request.form)
# Change hour and mi... | 7ac6d73bddfcba7475ff4e293a93fd3fe1fff546 | 3,658,230 |
def rescale_column_test(img, img_shape, gt_bboxes, gt_label, gt_num):
"""rescale operation for image of eval"""
img_data, scale_factor = mmcv.imrescale(img, (config.img_width, config.img_height), return_scale=True)
if img_data.shape[0] > config.img_height:
img_data, scale_factor2 = mmcv.imrescale(im... | 11c7be91988aba926e5d9934443545a5112d2525 | 3,658,231 |
from typing import Union
from typing import List
import asyncio
from typing import Set
import os
async def start_workers(
search_requests: Union[List[SearchIndexRequest], asyncio.Queue]
) -> Set[str]:
"""Runs the pipeline using asyncio concurrency with three main coroutines:
- get results: fetch the searc... | b0cd669af8ebd7127c5bea4455e7e401e0e3ffd7 | 3,658,232 |
def resolvability_query(m, walks_):
"""
:param m: cost matrix
:param walks_: list of 0-percolation followed by its index of redundancy
as returned by percolation_finder
:return: M again untouched, followed by the list of $0$-percolation with
minimal index of redundancy, and with a flag, True if ... | 968acb44a94952187cd91ed50ee2f7c1d1f0f54f | 3,658,233 |
import os
def lock_parent_directory(filename, timeout=10):
"""
Context manager that acquires a lock on the parent directory of the given
file path. This will block until the lock can be acquired, or the timeout
time has expired (whichever occurs first).
:param filename: file path of the parent d... | 2774c61d30d6844ae7c9fa07dd4df2d0ecac2918 | 3,658,234 |
import math
def dsh(
incidence1: float, solar_az1: float, incidence2: float, solar_az2: float
):
"""Returns the Shadow-Tip Distance (dsh) as detailed in
Becker et al.(2015).
The input angles are assumed to be in radians.
This is defined as the distance between the tips of the shadows
in the ... | 5aef1c9d7ffeb3e8534568a53cf537d26d97324a | 3,658,235 |
def similarity(vec1, vec2):
"""Cosine similarity."""
return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2)) | 22a97fc08b4a8d7b662d0ba38eb6338aad587ca2 | 3,658,236 |
import _warnings
def epv00(date1, date2):
""" Earth position and velocity, heliocentric and barycentric, with
respect to the Barycentric Celestial Reference System.
:param date1, date2: TDB as a two-part Julian date.
:type date1, date2: float
:returns: a tuple of two items:
* heliocentr... | bb2c97517966168beb07e1732231bb0388eca0f3 | 3,658,237 |
def algorithm_conflict(old_config, new_config):
"""Generate an algorithm configuration conflict"""
return conflicts.AlgorithmConflict(old_config, new_config) | 8f9a1dcbf90b38efd69e028a35591d4d424d72c4 | 3,658,238 |
def nin():
"""
:return:
"""
def nin_block(num_channels, kernel_size, strides, padding):
blk = nn.Sequential()
blk.add(nn.Conv2D(num_channels, kernel_size, strides, padding, activation='relu'),
nn.Conv2D(num_channels, kernel_size=1, activation='relu'),
nn... | 8641d6b34256168d09d2ab3c6fa0d4a0aff71410 | 3,658,239 |
def factorial(n):
"""
Return the product of the integers 1 through n.
n must be a nonnegative integer.
"""
return product(range(2, n + 1)) | 132b772d27e661816979ea9a5f2fa3b53114b55c | 3,658,240 |
def get_status_lines(frames, check_transposed=True):
"""
Extract status lines from the given frames.
`frames` can be 2D array (one frame), 3D array (stack of frames, first index is frame number), or list of array.
Automatically check if the status line is present; return ``None`` if it's not.
I... | 8bc68246b0c4987836414810a0308a2034b16368 | 3,658,241 |
def quote():
"""Get stock quote."""
if request.method == "POST":
quote = lookup(request.form.get("symbol"))
if quote == None:
return apology("invalid symbol", 400)
return render_template("quoted.html", quote=quote)
# User reached route via GET (as by clicking a link or... | fb9d4b54e97a4d7b104f3c0d361347b99db68195 | 3,658,242 |
import json
def stats(api, containers=None, stream=True):
"""Get container stats container
When stream is set to true, the raw HTTPResponse is returned.
"""
path = "/containers/stats"
params = {'stream': stream}
if containers is not None:
params['containers'] = containers
try:
... | 8e8da5ab96ab14871e3a5de363d8cae66fba5701 | 3,658,243 |
def add_engineered(features):
"""Add engineered features to features dict.
Args:
features: dict, dictionary of input features.
Returns:
features: dict, dictionary with engineered features added.
"""
features["londiff"] = features["dropofflon"] - features["pickuplon"]
features["... | 56efe3ad922f5068c91ac702366416210e95dd74 | 3,658,244 |
def test_3tris():
"""3 triangles"""
conv = ToPointsAndSegments()
polygons = [
[[(0, 0), (1, 0), (0.5, -0.5), (0, 0)]],
[[(1, 0.5), (2, 0.5), (1.5, 1), (1, 0.5)]],
[[(2, 0), (3, 0), (2.5, -0.5), (2, 0)]],
]
for polygon in polygons:
conv.add_polygon(polygon)
return ... | fc9504e9c3ca0ae251ed67f8c99530ac6a1de73c | 3,658,245 |
def program_modules_with_functions(module_type, function_templates):
""" list the programs implementing a given set of functions
"""
prog_lsts = [program_modules_with_function(module_type, function_template)
for function_template in function_templates]
# get the intersection of all of ... | c3cfd6ee6c9fdcca3926015016e5d28a2a1f599d | 3,658,246 |
def tasmax_below_tasmin(
tasmax: xarray.DataArray,
tasmin: xarray.DataArray,
) -> xarray.DataArray:
"""Check if tasmax values are below tasmin values for any given day.
Parameters
----------
tasmax : xarray.DataArray
tasmin : xarray.DataArray
Returns
-------
xarray.DataArray, [... | c112dcf5b1a89f20151daaea8d56ea8b08262886 | 3,658,247 |
import torch
def laplace_attention(q, k, v, scale, normalize):
"""
Laplace exponential attention
Parameters
----------
q : torch.Tensor
Shape (batch_size, m, k_dim)
k : torch.Tensor
Shape (batch_size, n, k_dim)
v : torch.Tensor
Shape (batch_size, n, v_dim)
s... | 600ac2f75e5396dfe6e169776425229ffedbc884 | 3,658,248 |
def instantiate(class_name, *args, **kwargs):
"""Helper to dynamically instantiate a class from a name."""
split_name = class_name.split(".")
module_name = split_name[0]
class_name = ".".join(split_name[1:])
module = __import__(module_name)
class_ = getattr(module, class_name)
return class_... | d5906c835de9c2e86fbe3c15a9236662d6c7815d | 3,658,249 |
def fawa(pv_or_state, grid=None, levels=None, interpolate=None):
"""Finite-Amplitude Wave Activity according to Nakamura and Zhu (2010).
- If the first parameter is not a `barotropic.State`, `grid` must be
specified.
- `levels` specifies the number of contours generated for the equivalent
latit... | 91ca98bcb5abf71100ec9716f11c5cd38688836d | 3,658,250 |
def bmm_update(context, bmm_id, values, session=None):
"""
Updates Bare Metal Machine record.
"""
if not session:
session = get_session_dodai()
session.begin()
bmm_ref = bmm_get(context, bmm_id, session=session)
bmm_ref.update(values)
bmm_ref.save(session=session)
return... | 71c73582c9f6b96ffc5021598c8ef017ccb5af83 | 3,658,251 |
from datetime import datetime
def to_unified(entry):
"""
Convert to a unified entry
"""
assert isinstance(entry, StatementEntry)
date = datetime.datetime.strptime(entry.Date, '%d/%m/%Y').date()
return UnifiedEntry(date, entry.Reference, method=entry.Transaction_Type, credit=entry.Money_In,
... | d6eca8cbd970931569a2ad740298578c1106e7c9 | 3,658,252 |
def edit_profile():
"""
POST endpoint that edits the student profile.
"""
user = get_current_user()
json = g.clean_json
user.majors = Major.objects.filter(id__in=json['majors'])
user.minors = Minor.objects.filter(id__in=json['minors'])
user.interests = Tag.objects.filter(id__in=json['i... | 4548c4621f31bbd159535b7ea0768167655b4f5b | 3,658,253 |
import six
def _stringcoll(coll):
"""
Predicate function to determine whether COLL is a non-empty
collection (list/tuple) containing only strings.
Arguments:
- `coll`:*
Return: bool
Exceptions: None
"""
if isinstance(coll, (list, tuple)) and coll:
return len([s for s in c... | 9490a973900e230f70fea112f250cfe29be3a8bc | 3,658,254 |
import contextlib
def create_user_db_context(
database=Database(),
*args, **kwargs):
"""
Create a context manager for an auto-configured :func:`msdss_users_api.tools.create_user_db_func` function.
Parameters
----------
database : :class:`msdss_base_database:msdss_base_database.core.Databa... | 2bafe1f31f19c2b115d54e61c124f06368694b6b | 3,658,255 |
from pathlib import Path
import textwrap
def config(base_config):
""":py:class:`nemo_nowcast.Config` instance from YAML fragment to use as config for unit tests."""
config_file = Path(base_config.file)
with config_file.open("at") as f:
f.write(
textwrap.dedent(
"""\
... | 3ed4253f660a87e8b24392b4eb926b387067010f | 3,658,256 |
def __check_complete_list(list_, nb_max, def_value):
"""
make sure the list is long enough
complete with default value if not
:param list_: list to check
:param nb_max: maximum length of the list
:param def_value: if list too small,
completes it with this value
:return: boolean,... | 9d439cd3eeea04e7a3e0e59aa4fe0bbb875bdfe4 | 3,658,257 |
import pickle
def _fill_function(func, globals, defaults, closure, dct):
""" Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func().
"""
func.func_globals.update(globals)
func.func_defaults = defaults
func.func_dict = dct
... | 7ac454b7d6c43f49da1adf32522c03d28d88e6b7 | 3,658,258 |
import os
def symlink_gfid_to_path(brick, gfid):
"""
Each directories are symlinked to file named GFID
in .glusterfs directory of brick backend. Using readlink
we get PARGFID/basename of dir. readlink recursively till
we get PARGFID as ROOT_GFID.
"""
if gfid == ROOT_GFID:
return ""... | 5cede0058a3d1fa6697dfc84eac4c1315a9a531f | 3,658,259 |
import PIL
def resize_img(img, size, keep_aspect_ratio=True):
"""resize image using pillow
Args:
img (PIL.Image): pillow image object
size(int or tuple(in, int)): width of image or tuple of (width, height)
keep_aspect_ratio(bool): maintain aspect ratio relative to width
Returns:
... | b3ddc2c929fa530f2af612c3021802f7bd1ed285 | 3,658,260 |
from typing import Tuple
def calculate_clip_from_vd(circuit: DiodeCircuit, v_d: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
:returns: v_in, v_out
"""
Rs = circuit.Rs
Is = circuit.diode.Is
n = circuit.diode.n
Vt = circuit.diode.Vt
Rp = circuit.Rp
Rd = circuit.Rd
Id = Is * (np.exp(v_d / (n * Vt)) - 1.0... | ec60231622c06f1a972af050c0403e8247aa75ed | 3,658,261 |
def tex_coord(x, y, n=8):
""" Return the bounding vertices of the texture square.
"""
m = 1.0 / n
dx = x * m
dy = y * m
return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m | 0776dd61aa83b9c9d8afe7574607022c9f7c2b77 | 3,658,262 |
def uniindtemp_compute(da: xr.DataArray, thresh: str = "0.0 degC", freq: str = "YS"):
"""Docstring"""
out = da - convert_units_to(thresh, da)
out = out.resample(time=freq).mean()
out.attrs["units"] = da.units
return out | 640a50e2a4ff61192f97e31c782be58437d301d0 | 3,658,263 |
def verify_parentheses(parentheses_string: str) -> bool:
"""Takes input string of only '{},[],()' and evaluates to True if valid."""
open_parentheses = []
valid_parentheses_set = {'(', ')', '[', ']', '{', '}'}
parentheses_pairs = {
')' : '(',
']' : '[',
'}' : '{'
}
if le... | 2e2c07314d474b582f12af8cf53a311c0fa323c1 | 3,658,264 |
import time
def _stableBaselineTrainingAndExecution(env, typeAgent, numberOptions, mode):
""""Function to execute Baseline algorithms"""
if typeAgent == 2:
model = A2C(MlpPolicy, env, verbose=1)
else:
model = PPO2(MlpPolicy, env, verbose=1)
print("Training model....")
startTime =... | 7fd91b28ab475fb43ea7e6af4ca17302863e269a | 3,658,265 |
def string_to_hexadecimale_device_name(name: str) -> str:
"""Encode string device name to an appropriate hexadecimal value.
Args:
name: the desired name for encoding.
Return:
Hexadecimal representation of the name argument.
"""
length = len(name)
if 1 < length < 33:
he... | 53d5c5a221a2c3dac46c5fb15d051d78592b109b | 3,658,266 |
def createTeam(
firstIndex, secondIndex, isRed, first = 'DefensiveAgent', second = 'OffensiveAgent'):
"""
This function should return a list of two agents that will form the
team, initialized using firstIndex and secondIndex as their agent
index numbers. isRed is True if the red team is being created, ... | b99e8f548b6e6166517fb35a89f5381ef6d7692b | 3,658,267 |
def str_dice(die):
"""Return a string representation of die.
>>> str_dice(dice(1, 6))
'die takes on values from 1 to 6'
"""
return 'die takes on values from {0} to {1}'.format(smallest(die), largest(die)) | 29eb7f6aa43e068e103016bbc8c35699fbf4a3ea | 3,658,268 |
import pyregion
def pyregion_subset(region, data, mywcs):
"""
Return a subset of an image (`data`) given a region.
Parameters
----------
region : `pyregion.parser_helper.Shape`
A Shape from a pyregion-parsed region file
data : np.ndarray
An array with shape described by WCS
... | 03578a1957b8cbbae573588f85f24f8f528dc05b | 3,658,269 |
def transformer_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder",
nonpadding=None,
save_weights_to=None,
make_image_summary=True):
"""A stack of tr... | 0f56315a972acc235dba7ec48c8b83b84bd6b3f1 | 3,658,270 |
import os
def update(event, context):
"""
Place your code to handle Update events here
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events.
"""
region = os.environ['AWS_REGION']
prefix_list_name = event['ResourceProp... | cc5762bbd6fb79f6ec4823d706139c2d4abb3a31 | 3,658,271 |
import re
def compute_dict(file_path):
"""Computes the dict for a file whose path is file_path"""
file_dict = {}
with open(file_path, encoding = 'utf8') as fin:
for line in fin:
line = line.strip()
txt = re.sub('([^a-zA-Z0-9\s]+)',' \\1 ',line)
txt = re.sub('([\... | 821e29181aad781279b27174be0fd7458b60481f | 3,658,272 |
def get_scale(lat1, lon1, var, desired_distance, unit='miles'):
"""
Calculate the difference in either latitude or longitude that is equivalent
to some desired distance at a given point on Earth. For example, at a specific
point, how much does latitude need to change (assuming longitude is constant) to
be equal ... | 258d95b1372d1b863f121552abb2ba6047f5aaad | 3,658,273 |
from typing import Union
from pathlib import Path
async def connect_unix(path: Union[str, PathLike]) -> UNIXSocketStream:
"""
Connect to the given UNIX socket.
Not available on Windows.
:param path: path to the socket
:return: a socket stream object
"""
path = str(Path(path))
return... | 825d69aa19afd593b355063639cbcd91cb23e9fa | 3,658,274 |
def isMatch(s, p):
""" Perform regular simple expression matching
Given an input string s and a pattern p, run regular expression
matching with support for '.' and '*'.
Parameters
----------
s : str
The string to match.
p : str
The pattern to match.
Returns
-------... | 92cd3171afeb73c6a58bbcd3d3ea6d707401cb09 | 3,658,275 |
def cepheid_lightcurve_advanced(band, tarr, m0, period, phaseshift, shape1, shape2, shape3, shape4, datatable=None):
"""
Generate a Cepheid light curve. More flexibility allowed.
band: one of "B", "V", "I"
tarr: times at which you want the light curve evaluated
m0: mean magnitude for the light curve... | 7e9a94f4e59f3da31c8c21a6e35822a0ac0d8051 | 3,658,276 |
def app_list(context):
"""
Renders the app list for the admin dashboard widget.
"""
context["dashboard_app_list"] = admin_app_list(context["request"])
return context | 699aa55403169f87c26fc9655d8c6dcb29aa14d2 | 3,658,277 |
def path_depth(path: str, depth: int = 1) -> str:
"""Returns the `path` up to a certain depth.
Note that `depth` can be negative (such as `-x`) and will return all
elements except for the last `x` components
"""
return path_join(path.split(CONFIG_SEPARATOR)[:depth]) | c04899974560b2877db313fa0444203cc483a2b0 | 3,658,278 |
def read_config_file(filename, preserve_order=False):
"""
Read and parse a configuration file.
Parameters
----------
filename : str
Path of configuration file
Returns
-------
dict
Configuration dictionary
"""
with open(filename) as f:
return parse_config... | 6a0aab4ae0da3abdddf080c98ee69eb92d2d8d04 | 3,658,279 |
def languages_list_handler():
"""Get list of supported review languages (language codes from ISO 639-1).
**Example Request:**
.. code-block:: bash
$ curl https://critiquebrainz.org/ws/1/review/languages \\
-X GET
**Example Response:**
.. code-block:: json
{
... | 5b8791ad5d71a94486d96379f62ed9ebf850ec59 | 3,658,280 |
def corpus_subdirs(path):
""" pathの中のdir(txt以外)をlistにして返す """
subdirs = []
for x in listdir(path):
if not x.endswith('.txt'):
subdirs.append(x)
return subdirs | 645f198f78795dbc5c14b7cfd400fa1e94dc9244 | 3,658,281 |
def edit_string_for_tags(tags):
"""
Given list of ``Tag`` instances or tag strings, creates a string
representation of the list suitable for editing by the user, such
that submitting the given string representation back without
changing it will give the same list of tags.
Tag names which contai... | a05b6cb12e36304096d076e015077f1ec1cc3432 | 3,658,282 |
from typing import Optional
def convert_postgres_array_as_string_to_list(array_as_string: str) -> Optional[list]:
"""
Postgres arrays are stored in CSVs as strings. Elasticsearch is able to handle lists of items, but needs to
be passed a list instead of a string. In the case of an empty array, ret... | cc64fe8e0cc765624f80abc3900985a443f76792 | 3,658,283 |
def generate_prime_number(min_value=0, max_value=300):
"""Generates a random prime number within the range min_value to max_value
Parameters
----------
min_value : int, optional
The smallest possible prime number you want, by default 0
max_value : int, optional
The largest possible... | 539f74fcdba2c366b0fe13b0bc0fab6727300ec1 | 3,658,284 |
def sort_extended_practitioner(practitioner):
"""
sort on date latestDate
Then alpha on other practitioners
:param practitioner:
:return: practitioner
"""
uniques = []
for p in practitioner:
if find_uniques(p, uniques):
uniques.append(p)
return uniques | 476d9adf9d93b88f20166b1e95715aaa54bd67f9 | 3,658,285 |
def lti13_login_params_dict(lti13_login_params):
"""
Return the initial LTI 1.3 authorization request as a dict
"""
utils = LTIUtils()
args = utils.convert_request_to_dict(lti13_login_params)
return args | 026e65c132666816f774a05f6977dac9ab194b77 | 3,658,286 |
def calcShannonEnt(dataset):
"""
计算数据集的熵
输入:数据集
输出:熵
"""
numEntris = len(dataset)
labelCounts = {}
for featVec in dataset:
currentLabel = featVec[-1] #每行数据中的最后一个数,即数据的决策结果 label
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
l... | 9b64d0ad0bb517deb77c24f3c08e004d255daa68 | 3,658,287 |
import array
def get_boundaries_medians(things, lowers=[], uppers=[]):
"""Return the boundaries and medians of given percentage ranges.
Parameters:
1. things: a list of numbers
2. lowers: lower percentage limits
3. uppers: upper percentage limits
Returns:
lower, median, upper
... | d83365ad2d9598dc19c279a6b20424746f53d6ce | 3,658,288 |
def getMeanBySweep(abf, markerTime1, markerTime2):
"""
Return the mean value between the markers for every sweep.
"""
assert isinstance(abf, pyabf.ABF)
pointsPerSecond = abf.dataRate
sweepIndex1 = pointsPerSecond * markerTime1
sweepIndex2 = pointsPerSecond * markerTime2
means = []
... | 8051d67c832c9b331798f896b8f98c2673770a94 | 3,658,289 |
import json
def handler(event, context):
"""
Params:
-------
event (dict):
content (dict):
Both params are standard lambda handler invocation params but not used within this
lambda's code.
Returns:
-------
(string): JSON-encoded dict with top level keys for each of the possib... | 21d49c8bdf174633ec33f64dd77d16485e694f1d | 3,658,290 |
def add_prefix(key):
"""Dummy key_function for testing index code."""
return "id_" + key | 96dda0bd57b4eb89f17c8bb69ad48e3e1675a470 | 3,658,291 |
def schedule_conv2d_nhwc_tensorcore(cfg, outs):
"""TOPI schedule callback"""
s = te.create_schedule([x.op for x in outs])
def _callback(op):
if "conv2d_nhwc_tensorcore" in op.tag:
schedule_nhwc_tensorcore_cuda(cfg, s, op.output(0))
traverse_inline(s, outs[0].op, _callback)
retu... | 318be211f02469c1e971a9303f48f92f88af5755 | 3,658,292 |
import tqdm
def simulate(config, show_progress=False):
"""Simulate incarceration contagion dynamics.
Parameters
----------
config : Config
Config object specifying simulation parameters.
Returns
-------
dict
Dictionary specifying simulated population of agents.
"""
... | b5b813c1038d6b473ff3f4fa6beccdad2615f2af | 3,658,293 |
import cel_import
def get_event_log(file_path: str = None, use_celonis=False):
"""
Gets the event log data structure from the event log file.
Dispatches the methods to be used by file tyoe
:param use_celonis: If the attribute is set to true the event log will be retrieved from celonis
:param file_... | 9b77a2bed9d6551cc2d0e4eb607de0d81b95c6f3 | 3,658,294 |
def find_peak(corr, method='gaussian'):
"""Peak detection algorithm switch
After loading the correlation window an maximum finder is invoked.
The correlation window is cut down to the necessary 9 points around the maximum.
Afterwards the maximum is checked not to be close to the boarder of the correlat... | 685eb87cefc6cd2566a9e9d40f827a1fea010b73 | 3,658,295 |
import os
def mesh_plot(
mesh: PyEITMesh,
el_pos,
mstr="",
figsize=(9, 6),
alpha=0.5,
offset_ratio=0.075,
show_image=False,
show_mesh=False,
show_electrode=True,
show_number=False,
show_text=True,
):
"""plot mesh structure (base layout)"""
# load mesh structure
... | ba82a9ceebd6b8470b3fb441204cd0d8155e5cdb | 3,658,296 |
def binaryToString(binary):
"""
从二进制字符串转为 UTF-8 字符串
"""
index = 0
string = []
rec = lambda x, i: x[2:8] + (rec(x[8:], i - 1) if i > 1 else '') if x else ''
fun = lambda x, i: x[i + 1:8] + rec(x[8:], i - 1)
while index + 1 < len(binary):
chartype = binary[index:].index('0') # 存放字... | 2044109d573abe7c9428b64b289b5aa82ec4d624 | 3,658,297 |
import functools
import logging
def disable_log_warning(fun):
"""Temporarily set FTP server's logging level to ERROR."""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
logger = logging.getLogger('pyftpdlib')
level = logger.getEffectiveLevel()
logger.setLevel(logging.ERRO... | 6990a2a1a60ea5a24e4d3ac5c5e7fbf443825e48 | 3,658,298 |
def create_csv_step_logger(save_dir: pyrado.PathLike, file_name: str = "progress.csv") -> StepLogger:
"""
Create a step-based logger which only safes to a csv-file.
:param save_dir: parent directory to save the results in (usually the algorithm's `save_dir`)
:param file_name: name of the cvs-file (with... | 355c205cf5f42b797b84005c1485c2b6cae74c2e | 3,658,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.