content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def api_ping():
"""
api ping
"""
return jsonify({"message": "pong"}) | 49478b5375b1adabdad0485bed2c5970949e3732 | 62,200 |
def fe_input_user_data_repack(input_model: InputModel, input_user_shapes: [None, list, dict, np.ndarray],
freeze_placeholder: dict, framework: str, input_user_data_types=dict(), ):
"""
Restructures user input cutting request. Splits ports out of node names.
Transforms node ... | 0a2e5459105297df9130c380c3693fcec0245496 | 62,201 |
from typing import Callable
from typing import Hashable
from typing import Any
def max_by(d: D, *, keyfunc: Callable[..., Hashable], **kwds: Any) -> NumDict:
"""
Find maximum values in d grouped by keyfunc.
Maps each l in the range of keyfunc to the max of all d[k] such that
keyfunc(k) is equal ... | a225136da9d9b8d97bc16a234293675fbf3fc851 | 62,202 |
import socket
import time
def socket_backoff_connect(family, socktype, proto, addr, timeout, attempts):
"""connect will backoff if the response is not ready for a pseudo random number greater than zero and less than
51e-6, 153e-6, 358e-6, 768e-6, 1587e-6, 3225e-6, 6502e-6, 13056e-6, 26163e-6, 52377e-6
... | 0428072c50a6252bd2ecfe0c4097f84e3c7183ea | 62,203 |
import sh
def device_list():
"""
Get udid from iPhone and iPad plugged into the computer
Returns a list
"""
# TODO: separate iPhone and iPad
raw = sh.sed(sh.system_profiler("SPUSBDataType"), "-n", "-e",
'/iPad/,/Serial/p', "-e", '/iPhone/,/Serial/p')
devices = sh.awk(
... | 93a63a2b471fb2c5c3caa9b4120593383a95874b | 62,204 |
import os
import torch
import re
def get_visible_devices_global_ids():
"""Return the global indices of the visible devices"""
if "CUDA_VISIBLE_DEVICES" not in os.environ:
return list(range(torch.cuda.device_count()))
visible_devices = os.environ["CUDA_VISIBLE_DEVICES"]
visible_devices = re.sp... | c6ca4d2c2eadbef1f4353ac70937cce34734aa03 | 62,205 |
def reverse(start, end):
"""
takes in 2 nodes a start and end
swaps all nodes
iterating over start to end
"""
# set a prev to the end
prev = end
# set a next_starting_node to the start.next
next_starting_node = start.next
# set a current_node
current_node = start.next
... | a68b32868a6b94bfc856624a2fbebb8d9c8d639a | 62,206 |
import sqlite3
import atexit
def init_background_tasks(app):
"""
不同 job 之间的间隔应大于 1 分钟, 否则会导致某些 job 不被执行.
job 的执行函数第一个参数为当前的 app
"""
with app.app_context():
c = get_db()
c.execute('BEGIN EXCLUSIVE')
mutex = c.execute("select * from misc where key = 'mutex'").fetchone()
... | 35d423c2c6e63ff4b0031e874cf69fdd1da4a873 | 62,207 |
import os
def getAnnotationPath() -> str:
"""Return folder where annotation data is stored."""
__checkBase()
return os.path.join(FIRED_BASE_FOLDER, ANNOTATION_FOLDER_NAME) | dbdaa50a25e4a3977ce97d4c5cf19ae9e0c79ea6 | 62,208 |
def n_pixels(seeing_fwhm):
"""Calculate number of pixels in aperture extraction region.
Uses the SNR-maximizing extraction radius
(1.346 FWHM)--see LSST SNR doc eq. 19
seeing_fwhm: float
seeing in arcsec
"""
npix_extract = np.pi * (0.673 * seeing_fwhm / PIXEL_SCALE)**2.
... | 4544c7e70b12f6fa5e438532f093d706e4c7df90 | 62,209 |
def get_frequency_counts(classification):
"""
Get the raw and fractional class frequency counts for an `xarray.Dataset`.
Intended to be used with outputs from the `*_cluster_dataset()` functions.
Parameters
----------
classification: xarray.Dataset
An `xarray.Dataset` with a `classi... | 5c09d1af4cb9d22dcefaa299dadef775fe96af0e | 62,210 |
def embed_backward(dx, cache):
"""Inputs: dx (N,T,D), cache. Outputs: dW_embed (V,D).
Only need to compute dW_embed as output"""
inputs, W = cache
dW = np.zeros_like(W)
np.add.at(dW, inputs, dx)
return dW | 81510ce2cbe35a9e2fdf713e4c47d10a84986330 | 62,211 |
def generator_function(context: DurableOrchestrationContext):
"""Orchestrator function for testing retry'ing semantics
Parameters
----------
context: DurableOrchestrationContext
Durable orchestration context, exposes the Durable API
Returns
-------
List[str]:
Output of acti... | 42150e7949da9d78796b64ada29c5077b899f39d | 62,212 |
import os
import copy
import logging
import json
def evaluate_sensitivity(
*,GEOM_PARAMS_OPTIMAL : dict,
name : str, DO_EVAL : bool,
problem : optimization.Problem,
SENSITIVITY_RANGE : float,
NUM_PTS : float,
) -> dict:
"""
Evaluate sensitivity w.r.t. a single parameter.
"""
sensit... | 768464c20d1936d8b12cd6deb104a18daf2d582d | 62,213 |
def add_traits(base, names, trait_type=None):
""" Add traits to a traited class.
All traits are set to Undefined by default
"""
if trait_type is None:
trait_type = traits.Any
undefined_traits = {}
for key in names:
base.add_trait(key, trait_type)
undefined_traits[key] = ... | 3b17b08b4b63595acb25104d0221555e8758bc75 | 62,214 |
import readcounter
import os
def version():
"""Read program version from file."""
version_file = open(os.path.join(readcounter.__path__[0], 'VERSION'), "r")
_version = version_file.readline().strip()
version_file.close()
return _version | fa97ce604845da96c66d89a05784633ddb4adc88 | 62,215 |
def conv_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient ... | 0c70d2f833b017832069ff7ad459b538ab988190 | 62,216 |
def translate_blocks(blocks):
"""Translate code blocks into the machine code.
Args:
blocks (dict): dictionary of blocks indexed by offsets
Returns:
str: assembly code
"""
def fill_instruction(instruction, block):
template = TRANSLATION_TABLE[instruction["instruction"].name]... | e6293b394d191bba5e33f0ceb01011ae9dac1d19 | 62,217 |
def _get_vel_list():
"""Get the tuple from which a zombie's velosity will be determined
Example:
>>> Options.speed = 4
>>> Tile.length = 32
>>> _get_vel_list()
(2, 4, 2, 1)
>>> Options.speed = 9
>>> _get_vel_list()
(4, 8, 4, 2)
"""
base_speed = Options.speed / 4
ts = base... | c04e2d745580d219bdb5900c0bef017c624b6c45 | 62,218 |
def mnodeAfterRequest(response):
"""
Closes the persistence layer associated with this mnode request
Args:
response: The response
Returns:
The response
"""
L = flask.current_app.logger
L.debug("mnodeAfterRequest")
if "op" in flask.g:
try:
flask.g.op.... | f4de8cf093a0b8a1504231be5db26b9f672cbba5 | 62,219 |
def create_cifar10_data(gray):
"""加载cifar10数据集"""
cifar_path = "cifar10"
images, labels = load_CIFAR10(cifar_path)
# 转灰度
image_num = images.shape[0]
if gray == True:
images_gray = rgb2gray(images)
# numpy array使用连续内存块,所以应一开始就定义好大小,然后根据索引对其赋值
features = np.zeros((len(image... | 4c639bf24f0a6898dbf6b4cc411620a218207f1f | 62,220 |
import math
def get_circle_centre(points, radius):
"""returns the cg of a circle (and angle of sector) given two points and a radius"""
l = distance(points[0], points[1])
s = line_slope(points)
phi = math.pi - 2 * math.acos(l / (2 * radius))
midpoint = (0.5*(points[0][0]+points[1][0]), 0.5*(points... | f01c907cec2d3192400733e55dd72f3b02da8fb7 | 62,221 |
def get_bird_data():
"""
Fetches the full Oregon eBird dataset and filters data based on
relevant columns and months
Args: None
Returns:
bird1 (pd dataframe): Cleaned eBird data from repo
"""
print("Retrieving Bird Data...")
bird1 = pd.read_csv("phoenix/data/ebird_app_data.csv... | aed894d0b31c83d0d5bcc9166dde333e2d3b3f3c | 62,222 |
def string_from_uuid(uuid_obj):
"""Returns standard hexadecimal string for uuid; same as str(uuid_obj).
arguments:
uuid_obj (uuid.UUID object): the uuid which is required in hexadecimal string format
returns:
string (40 characters: 36 lowercase hexadecimals and 4 hyphens)
"""
return... | 903f3b257854900f2b534658dbfa4e504812c67b | 62,223 |
import collections
def create_dict_subclass(name, hash_func, slots, doc):
"""
Creates a dict subclass named name, using the hash_function to index
hash_length items. Doc should be any additional documentation added to the
class.
"""
hash_length = len(slots)
# Returns array index -- raise... | fed11ef89b7695e2564703929d088d4baf829362 | 62,224 |
def psnr2d(img1, img2, max_val=None, name='psnr2d'):
"""Computes the peak signal-to-noise ratio (PSNR) between two 2D images.
This function operates on batches of multi-channel inputs and returns a PSNR
value for each image in the batch.
Arguments:
img1: A `Tensor`. First batch of images. Must have rank >... | 6677bc0d766cab0d75255d2fec06b6c46b8aae0a | 62,225 |
import typing
def get_row_history(row: 'md_table.Table') \
-> 'typing.Dict[md_column.Column, typing.Dict[str, typing.Any]]':
"""
Gets the history for the specified row.
This returns a dict, indexed by Column, with values being another dict with `old` and `new` keys
that represent the old and ... | 42fb6a5c76fc3936a6bc0a3d5b40b76057a24c22 | 62,226 |
def decoding(sprobs, samples, params, mask=None):
"""Generate decoded sequence from seqs"""
if mask is None:
mask = [1.] * len(sprobs)
flat_sprobs = []
for _sprobs, _m in zip(sprobs, mask):
if _m < 1.:
continue
for start_prob in _sprobs:
flat_sprobs.appe... | e660a85af689759daacb9b553751fe7eb168dda7 | 62,227 |
import unicodedata
def is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, fo... | 756e86b4a56a44409494c4f6cf81cb61f278d636 | 62,228 |
def _test_all():
"""Run lint and tests.
:return: exit code
"""
return _lint() + _test() | 2b82157b0de0ddc7ae471756879dceaf51b28055 | 62,229 |
def hassio_update(config, supervisor):
"""Create scheduler task for update of supervisor hassio."""
async def _hassio_update():
"""Check and run update of supervisor hassio."""
if config.last_hassio == supervisor.version:
return
_LOGGER.info("Found new HassIO version %s.", c... | 644c72423185e7a3f91dec49c92e02a0b06a9905 | 62,230 |
def strlist_vsort(alist):
"""Same as `strlist` except sorted according to version-representation"""
alist = strlist(alist)
alist = sorted(alist, key=lambda x: LooseVersion(x))
return alist | e7e14b0a7d157252c724fa09b26d71fb3eaf7aad | 62,231 |
from datetime import datetime
def sync_all_message():
"""
获取数据
"""
now = datetime.datetime.now()
now_height = datetime_to_height(now)
height = 31884
log = MigrateLog.objects(version="s1").first()
if log:
height = int(log.message_content.get("height") or height) - 1
# messag... | c923dd1ecb97e8153a3265e9dca7566f225d346e | 62,232 |
import math
def make_run_function(rhs,
ordered_params,
offset,
scaling_vector,
returning="linear",
use_numba=True,
nb_nopython=True,
rescaling_epsilon=1e-6,
... | adca0104ecd013296abe023d29ef56c736ea4837 | 62,233 |
def data_context_notification_context_notif_subscriptionuuid_notification_channel_namevalue_name_get(uuid, value_name): # noqa: E501
"""data_context_notification_context_notif_subscriptionuuid_notification_channel_namevalue_name_get
returns tapi.common.NameAndValue # noqa: E501
:param uuid: Id of notif-s... | 6b3603f5c7ecff1b8bd857ffc73906f47fd1254c | 62,234 |
def calc_resp(password_hash, server_challenge):
"""calc_resp generates the LM response given a 16-byte password hash and the
challenge from the type-2 message.
@param password_hash
16-byte password hash
@param server_challenge
8-byte challenge from type-2 message
... | fc23b12a38bc6b216c3e60400bae2e6fb187a65f | 62,235 |
def get_dist_info(df, dists):
"""
:param df: any object having shape attribute (e.g. pandas Dataframe, numpy array).
:param dists: the output of from "scipy.spatial.distance.pdist" function.
:return: pandas Dataframe with ['pair','dist'] columns representing the row indices and distances between th... | 2b2bbb329852e6ce5aa34867ac9650a89db22b06 | 62,236 |
import logging
def run_inference_queue_kdd(N, T, num_segments, sim_opts_gen, log_q_high, log_q_low, num_procs=None):
"""Run inference for the given sim_opts_gen by sweeping over 'q' and
running the simulation for different seeds."""
if num_procs is None:
num_procs = mp.cpu_count() - 1
in_que... | a24fbdcf5ed853b054f0fc7a34e7aeb5638fd6e3 | 62,237 |
def ImageLoad_torch(data, ensemble_n, resize_layers, is_silent):
"""
input:
data -- np array (H, W, 3)
p -- rescale factor. e.g. p=0.4: (720, 1280) --> (288, 512)
"""
normalize = transforms.Normalize(mean = [0.485, 0.456, 0.406],
std = [0.229, 0.224, ... | c2eaaff658ab1775b3a4f2d64373e4f0e69e1400 | 62,238 |
def _select_action_policy(policy_seq, action_seq):
"""
:param policy_seq: policy for every [batch,tick,action]
:param action_seq: actions taken on every [batch,tick]
:return: returns policy for selected actions of shape [batch, tick]
"""
batch_i = np.arange(policy_seq.shape[0])[:, None]
time... | d20c90960071f27bffd13b369e71345c91e64b29 | 62,239 |
def create_setWeight(col: str, weight: str, lemex: str):
"""
:return str: format of 'setweight(col, weight, lemex)' \n
Check postgresql text search setweight function to see the syntax
"""
return """setweight(%s, '%s', '%s')""" % (col, weight, lemex) | 965b25a5ccb8f3c68ecc3742a512dd7c28dac0a4 | 62,240 |
import rasterio
def extractByMaskReturnList(flRasterName, gdMask):
"""
Takes a Raster Image and a Geopandas dataframe and returns
[outImage,outMeta,outTransform]
"""
with rasterio.open(flRasterName) as src:
outImage, outTransform = rasterio.mask.mask(
src, gdMask.geometry, cro... | 4bc89eb3a4be1297ce0b3b383fea5ccba2f7900c | 62,241 |
def create_transforms(input_config):
"""Create transforms from configuration
Parameters
----------
input_config : dict
Dictionary containing the configuration options for input pre-processing.
Returns
-------
train_transforms : list
List of transforms to be applied to the i... | 42fe6268c1834d0453e0707f8c564635612a1f82 | 62,242 |
import os
from sys import path
import re
def detect_files():
"""
Detect if there is a phsd.dat file in the folder
OR folders denoted as job_#
OR ask if nothing is found
"""
# get all files/folders in path
entries_all = os.listdir(str(path))
# where to read the files
path_input = ... | 726f582e3fb2f83b1eef362733c9488a16466ac3 | 62,243 |
def lgamma(expr):
"""
---------------------------------------------------------------------------
Natural Logarithm of the expression Gamma.
Parameters
----------
expr: object
Expression.
Returns
-------
str_sql
SQL expression.
"""
expr = format_magic(expr)
return str_sql("LN(({} - 1)!)".forma... | ffcaf35e1f08bc8e618ac93ad52d913b2b9356e2 | 62,244 |
def share_snapshot_instance_create(context, snapshot_id, values):
"""Create a share snapshot instance for an existing snapshot."""
return IMPL.share_snapshot_instance_create(
context, snapshot_id, values) | 702bfacc37d2c0a74a19c49f49b07829801df316 | 62,245 |
def reduce_precision_tf(x, npp):
"""
Reduce the precision of image, the tensorflow version.
"""
npp_int = npp - 1
x_int = tf.rint(tf.multiply(x, npp_int))
x_float = tf.div(x_int, npp_int)
return x_float | 5e43afb35ad9bdf93f2951e62b16df39294b8309 | 62,246 |
def compute_cell_size(npz_file, method='median', by_image=True):
"""Computes the typical cell size from a stack of labeled data
Args:
npz_file: Paired X and y data
method: one of (mean, median) used to compute the cell size
by_image: if true, cell size is reported for each image in npz_... | 6124ff2fabb8bed7d3a840da5cc5eb4826e966e1 | 62,247 |
from scipy.ndimage.morphology import binary_dilation
def overlay_davis(image,mask,colors=[255,0,0],cscale=2,alpha=0.4):
""" Overlay segmentation on top of RGB image. from davis official"""
# import skimage
colors = np.reshape(colors, (-1, 3))
colors = np.atleast_2d(colors) * cscale
im_overlay = ... | c7c94e61597b4d150f0a7997442ba62542912e5a | 62,248 |
def calc_delta(Y, Ygrid, X, m, fy=None, xr=None):
"""Plischke et al. (2013) delta index estimator (eqn 26) for d_hat."""
N = len(Y)
if fy is None:
fy = gaussian_kde(Y, bw_method="silverman")(Ygrid)
if xr is None:
xr = rankdata(X, method="ordinal")
abs_fy = np.abs(fy)
d_hat = 0
... | 94d0c26d853ae0c3172f99521feceec118c01f12 | 62,249 |
def create_model(vocab_size, embedding_dim=50):
"""Create a model.
Args:
vocab_size(int): vocabulary size.
embedding_dim(int): embedding dimension.
Returns:
model: model object.
"""
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim,... | cabccf77c59aebc0727230bda33afc6831bb2b4b | 62,250 |
from tensorflow_addons.layers import StochasticDepth
def replace_add_with_stochastic_depth(model, survivals=(1, 0.8)):
"""
- [Deep Networks with Stochastic Depth](https://arxiv.org/pdf/1603.09382.pdf)
- [tfa.layers.StochasticDepth](https://www.tensorflow.org/addons/api_docs/python/tfa/layers/StochasticDep... | 0dff0124c1d8ff336dbaee57bef59aa89e36cb89 | 62,251 |
from pathlib import Path
from typing import Tuple
from typing import Dict
import json
def parse_fsh_generated(path: Path) -> Tuple[Dict, Dict, Dict, Dict, Dict, Dict]:
"""
Parse json files generated from FSH through SUSHI.
Goal: Extract structure definitions, instances, value set and dependencies from ge... | 76d280dd82a748ff9749b689a6e1b41023a04f5f | 62,252 |
def get_event_bpt_hea(*args):
"""
get_event_bpt_hea(ev) -> ea_t
"""
return _ida_idd.get_event_bpt_hea(*args) | 366713a10d6c12cab153b8fdbb8a86ed60d64250 | 62,253 |
import torch
def quat_from_xyz(xyz):
"""
Construct 3D rotation from the imaginary component
"""
w = (1.0 - xyz.norm()).unsqueeze(-1)
assert bool((w >= 0).all()), "xyz has its norm greater than 1"
return torch.cat([xyz, w], dim=-1) | df62a104cb2a983095576cc71241869d94c0efd9 | 62,254 |
def update_team_area(path, team, include_sub_areas=None, set_as_default=False,
organization=None, project=None, detect=None):
"""(PREVIEW) Update team area.
:param set_as_default: Set as default team area path. Default: False
:type set_as_default: bool
"""
if include_sub_areas i... | 7cb2572ea2446cdc0b9e2038ab490936a5bd7cdb | 62,255 |
import itertools
def ip_sort(a_str,b_str):
"""Fast IP address sorting function"""
for a,b in itertools.izip(a_str.split('.'), b_str.split('.')):
if a == b:
continue
if len(a) == len(b):
return cmp(a,b)
return cmp(int(a), int(b))
return 0 | 1f26d57973c69244c2a9cf7dddb36bf5fb8af64e | 62,256 |
def gradient(output_str):
""" Reads the molecular gradient (in Cartesian coordinates) from
the output file string. Returns the gradient in atomic units.
:param output_str: string of the program's output file
:type output_str: str
:rtype: tuple(tuple(float))
"""
# Try to rea... | 005e2b39ecffd0878a5da3c91c5f46fb1cacdb0c | 62,257 |
def plot_imbalances(imbalances, logplot=False):
"""
Information Imbalance Plane plot, see [1].
Arguments
---------
imbalances : dict
Dictionary storing the imbalances for each
number of retained features. Structured as:
imbalances --- 0 --- 'A_B... | d197f09f6502842a58e4898e703b4b8424379463 | 62,258 |
import re
def camelcase_to_snakecase(name):
"""
Convert a name in camel case to snake case.
Arguments:
name -- The name to convert.
Returns:
The name in snake case.
"""
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower() | 2143c89b7cd4c836040246ecbaa7fe8474c3ca76 | 62,259 |
def dCitySEIR(vector,t,params):
"""
建立城市之间流动模型的SEIR
:param vector:
:param t: time
:param params:R0,Di,De,Lsi,Lei,Lii,Lri,Lo
:return:dF
"""
S,E,I1,I2,R = vector
R0,Di,De,Da,Lsi,Lei,Li1i,Li2i,Lri,Lo= params
N = S+E+I1+I2+R
I = I1+I2
t = np.ceil(t)
dSdt = -(R0/Di)*S*I/N ... | 023fea7779f3a6526eaf54738e430121728873f9 | 62,260 |
def gethostname(data, *args, **kwargs):
"""Description: Method to find hostname in show
command output, uses symbols '# ', '<', '>' to find hostname
"""
REs = [ # ios-xr prompt re must go before ios privilege prompt re
{'juniper': '\n\S*@(\S+)>.*(?=\n)'}, # e.g. 'some.user@router-fw-host>'... | c476b32dd24f59c661bda02aeef637b3b9295f8f | 62,261 |
def calculateinterval(cdsinterval, txregion):
"""
calculate the interval which were included
:param cdsinterval:
:param txregion:
:return:
"""
assert txregion[0] < txregion[1], "start site not smaller than end site in the given region"
cdsinterval = list(map(list, sorted(cdsinterval, key... | e3eb87fb65dd32db640a3432a2924aa50ee2e72c | 62,262 |
from typing import Optional
def top_k(
input: oneflow_api.BlobDesc,
axis: int = -1,
k: int = 1,
sorted: bool = True,
name: Optional[str] = None,
) -> oneflow_api.BlobDesc:
"""Finds the indices of the k largest entries at specified axis, the difference between other framework is that oneflow on... | 8a6486e4d6327f1f2dad4bbfe153637a63cec5b4 | 62,263 |
from typing import List
from typing import Tuple
from typing import Union
def read_expected_file(path: str) -> List[Tuple[Union[str, float], ...]]:
"""Reads and parses resource file."""
types = str, float
with open(path, "r") as file:
expected_fermionic_op = [tuple(t(e) for t, e in zip(types, line... | 1d5228edffd8fa2486b41187f4a10b24209e52fc | 62,264 |
import six
def plot_fleur_mn(nodelist, save=False):
"""
This methods takes any amount of AiiDA node as a list and starts
the standard visualisation for it, if it finds one.
Some nodes types it tries to display together if it knows how to.
and if they are given as a list.
param: save showed t... | d6447506fada827ae15661a81ad3e000e3363a5c | 62,265 |
import math
def enrich(df, logging):
"""Adds columns to dataframe from a GPX file.
- delta_t: time in seconds between GPX points (typically constant)
- t: time in seconds from the first GPX point (cumulative of delta_t)
- delta_2d: 2D distance travelled between two consecutive GPX points
- delta_... | a745dbfa09a4892e097286027569aade3b90b96d | 62,266 |
def main(self):
"""
to run:
kosmos 'j.data.bcdb.test(name="base")'
"""
def test(name, schema, sqlite=True):
def print_objects(objs):
result = {}
for obj in objs:
result[obj.nr] = obj.name
print(result)
return result
... | 5cff0ddccd44891573a5dec8100b4534d70f5295 | 62,267 |
import time
def do_price_MC(M_io, Lp, Cu, price_data, Nruns = 10):
"""Performs a Monte Carlo based on price variations.
Input:
M_io The Characteristation multiplier matrix, tehcnically C.dot(S).dot(L_io)
Lp Lenontief inverse of the LCA A-matrix
Cu Unscaled Cut off... | b23b7ff2925cf0a2a597c5b0911926c94147d5b2 | 62,268 |
def G1DListCrossoverUniform(genome, **args):
"""
The G1DList Uniform Crossover
Each gene has a 50% chance of being swapped between mom and dad
"""
sister = None
brother = None
gMom = args["mom"]
gDad = args["dad"]
sister = gMom.clone()
brother = gDad.clone()
sister.resetSt... | 45105ea4fba2ceaf6bc7387297c01e5d972902f7 | 62,269 |
def no_space_conjunction(tag1, tag2):
"""If two tags represent one number and one letter."""
if tag1 == 'L' and tag2 == 'N':
return True
elif tag1 == 'N' and tag2 == 'L':
return True
else:
return False | ec3fa6c2aa0f54cc2cd2f92676d932880d572506 | 62,270 |
import binascii
def ShortName(ShortName):
"""
Get AD for the short name of device.
"""
l = binascii.hexlify((len(ShortName)+1).to_bytes(1, 'little')).decode('utf-8') # converts the length to a hex representation in a byte in String format
pl = ''
for i in to_hex(bytes(ShortName, 'utf-8')).spli... | 974c0b0d3f4cc6b210081c868379fc0e31b51234 | 62,271 |
def get_permission_table_data(instance, request_user, actions=['view', 'change', 'delete', 'share']):
"""Prepare data for a permission table.
Parameters
----------
instance: Model
Model instance for which the permission table should be generated.
request_user: User
User for which th... | 0d570b9129a5343abf1e403e25eacf4893623dc8 | 62,272 |
def _guess_ndvar_data_type(info):
"""Guess which type of data to extract from an mne object.
Checks for the presence of channels in that order: "mag", "eeg", "grad".
If none are found, a ValueError is raised.
Parameters
----------
info : dict
MNE info dictionary.
Returns
-----... | 9f1823d8484f0595644d5ca8e937be4a18b3fedf | 62,273 |
import os
def get_home(view=None):
"""Returns home dir."""
home = get_setting('home', None)
if home:
echo("Have 'home' setting")
return home
window = sublime.active_window()
sublime_vars = window.extract_variables()
# When try project path
home = sublime_vars.get('pr... | 3bce74601f7811de1c41ad2485111609d689c11b | 62,274 |
from unittest.mock import patch
def create_aliases_duplicate_patcher(client, guid_mock, signed_url_mock):
"""
Same as valid_upload_file_patcher except /aliases requests are mocked
as returning a 500
"""
patches = []
data_upload_mocked_reponse = {
"guid": guid_mock,
"url": sign... | 92afc0d789df6bb0131dbbaa1ae287c8bb0eef62 | 62,275 |
def new_map_entry(dp_id, dp_port, re_id, name):
"""
returns instance of FIBMap
"""
port = FIBCPort(id=dp_id, port=dp_port)
link = FIBCLink(re_id=re_id, name=name)
return FIBMap(port=port, link=link) | 1da6297f08e8dd8040e153828270edd23dc7d121 | 62,276 |
def exact_match(predictions: np.ndarray, actuals: np.ndarray, question_ids: np.ndarray):
"""Compute the exact match (EM) for a sequence of predictions and actual labels"""
unique_questions = set(question_ids)
q_actuals = list(zip(question_ids, actuals))
q_predictions = list(zip(question_ids, prediction... | 05a4a021496f40052ade640fd82343e828a0f2e3 | 62,277 |
def center_button(label):
"""Quickfix to center buttons, not allowed natively from Streamlit"""
col1, col2, col3, col4, col5 = st.beta_columns((0.3, 0.3, 1, 0.3, 0.3))
with col1:
pass
with col2:
pass
with col4:
pass
with col5:
pass
with col3:
return s... | 05b364dd074230b3473ee23544a1636873249ac0 | 62,278 |
from typing import List
from typing import cast
def description_patch(value: str, timestamp: str,
register: Register) -> List[rsf.Command]:
"""
Composes the pair of RSF commands for a description patch.
"""
key = f"register:{register.uid}"
data = cast(Record, register.metalo... | 568aaae65399e52fdacd3853c7b9f27f539561e3 | 62,279 |
def get_date_range(start_date, end_date):
""" https://stackoverflow.com/a/7274316 """
delta = end_date - start_date
date_range = [(start_date + timedelta(days=i)).strftime('%Y%m%d') for i in range(delta.days + 1)]
return date_range | 7427e65718cb0b806a8171e9e67c5a26876a2edd | 62,280 |
def get_package_requirements(requirement_type: str):
"""
Load in extra_requirements.json from the package
"""
requirements = {
"numpy": ["core"],
"requests": ["core"],
"pytest": ["test"],
"sphinx-rtd-theme>=0.5.0": ["test"],
"imageio": ["encoders-image-tfhub"]... | 4c3607de3accb145eb7855915dedc61bbba41a90 | 62,281 |
def generate_randao_reveal(
privkey: int, slot: Slot, state: BeaconState, config: Eth2Config
) -> BLSSignature:
"""
Return the RANDAO reveal for the validator represented by ``privkey``.
The current implementation requires a validator to provide the BLS signature
over the SSZ-serialized epoch in whi... | 83568f698b30e0b1608dad8a8758934395f6d4f9 | 62,282 |
def isAnyNode(input):
"""
This function check input is a AnyNode object.
:param input: unknown type object
"""
return isinstance(input, AnyNode) | 4897a5d2598a07a9c9595055686b65ae13c6e9b7 | 62,283 |
def speechProc(fName, numFrames, fps, kuro = False, return_extras = False):
"""Inputs an audio file and processes audio feature vectors that coincide in time with the source video frames. The audio feature vectors are based on Mel frequency cepstral coefficients (MFCCs). Because the sampling rate in the audio file ... | ff8eb2d50522f214a5a8e8c5a746e72b32b6b29e | 62,284 |
def pretty_print_options(message):
"""
Some modifications for pretty printing.
Use uppercase for first letter in text and a single dot for the end if there isn't one already.
:param message: String
:return: String
"""
# check for html
if message[0:1] == '<':
pos = message.inde... | 09552f39b4862bff9b35c52ef2f2b21f9fa20161 | 62,285 |
from functools import reduce
def find_common_set_of_column_names(dfs):
"""Returns a sorted list of common columns names."""
cols = [set(df.columns) for df in dfs]
return sorted(list(reduce(set.intersection, map(set, cols)))) | 77cf55ace97fbab3ad2e32c3656f5df883b2db7b | 62,286 |
def make_softmax_tests(options):
"""Make a set of tests to do softmax."""
test_parameters = [{
"dtype": [tf.float32],
"input_shape": [[1, 3, 4, 3], [2, 3]],
"dim": [-1, 0],
}, {
"dtype": [tf.float32],
"input_shape": [[4, 7]],
"dim": [-1, 1],
}]
def build_graph(parameters)... | 79e0b97dc61bc90f1feb12e6b30723cdf1c0c873 | 62,287 |
def monthly_returns(returns, eoy=True, compounded=True, prepare_returns=True):
"""Calculates monthly returns"""
if isinstance(returns, _pd.DataFrame):
warn("Pandas DataFrame was passed (Series expeted). "
"Only first column will be used.")
returns = returns.copy()
returns.co... | ae06d364885492c1638c0d0cdb47a2a3bc3d4ebc | 62,288 |
import os
def seperate_audio(course, week, source_dir="SOURCE", export_dir="SOURCE"):
"""
EN: Takes course and week parameters. Seperates audio and deskshare of the course on the week.
TR: course-->ders ve week-->hafta parametrelerini alır. audio ve deskshare dosyalarını ayırır.
"""
week = str(week)
try:
clip =... | 06a9a172de4f0c02bcf65a7ec723d83576b6169b | 62,289 |
def disjoint_union(G, H):
""" Return the disjoint union of graphs G and H.
This algorithm forces distinct integer node labels.
Parameters
----------
G,H : graph
A NetworkX graph
Returns
-------
U : A union graph with the same type as G.
Notes
-----
A new graph is c... | 76670731ca6c46df944486bd0e66a9fbae888869 | 62,290 |
import numpy
def voigt(omega, cent, delta, gamma=0.0):
"""Normalized Voigt line shape for absorption
"""
z = (omega - cent + 1j*gamma)*numpy.sqrt(numpy.log(2.0))/delta
return numpy.sqrt(numpy.log(2.0))*\
numpy.real(special.wofz(z)) \
/(numpy.sq... | d69312797ccc4ac0c026e6ae4f0c6139354bc7c6 | 62,291 |
def add_new_handler_object_via_bulk(data, rowData, request, errors,
is_validate_only=False, cache={}, obj=None):
"""
Bulk add wrapper for the add_new_handler_object() function.
"""
(result,
retVal) = add_new_handler_object(data, rowData, request,
... | c09e29312112fd8dcea9cb03596c0bff6da0cb60 | 62,292 |
def get_long_description():
"""
:return: The description for the plugin type.
"""
return """Infrastructure plugins use different techniques to identify the
remote operating system, HTTP daemon, Web Application Firewalls, remote users
and any other information that is related to the target web ap... | cbf895c9312d9336c33f9afffb7d1113e30ea093 | 62,293 |
import os
def get_conf():
"""read ini file and get config parameters
"""
env_var = 'PNSCONF'
conf_file = os.getenv(env_var, None)
if not conf_file:
raise Exception('environment variable `%s` for configuration file is not set' % env_var)
conf = ConfigParser()
if os.path.exists(conf_... | 8c6c336bb5ffeff5ba894597ab6ffaf1677823c5 | 62,294 |
from typing import List
from typing import Dict
def evaluate_det(
ann_frames: List[Frame],
pred_frames: List[Frame],
config: Config,
) -> Dict[str, float]:
"""Load the ground truth and prediction results.
Args:
ann_frames: the ground truth annotations in Scalabel format
pred_frame... | c28e0cdc58b42b9132a3f1262ca82b40e473c72d | 62,295 |
def batch_norm_mean_only(x,
n_out,
is_training,
reuse=None,
gamma=None,
beta=None,
axes=[0, 1, 2],
scope="bnms",
name="b... | 905bd3f1c59449906dbfcac6f584c6c03e56a369 | 62,296 |
import uuid
import sys
def register(**kwargs):
""" Add this process as a new peer registering it in the grid network.
Returns:
peer: Peer Network instance.
"""
if not kwargs:
args = args = {"max_size": None, "timeout": 444, "url": DEFAULT_NETWORK_URL}
else:
... | 7718e2fa0ca8ab08ae156ef09da9cb95916615bf | 62,297 |
def navigation(request):
"""Fetches data required to render navigation menu.
The main menu contains the list of user categories to choose.
Here is the query to fetch them.
"""
context = {}
if hasattr(request, "user_categories"):
context.update(
{
"user_categ... | 5641d35f47d4ae6c7045db81ceaaebae12b541d9 | 62,298 |
from typing import cast
def makeTusClient() -> Erc20Web3Client:
"""
Return an initialized client to interact with the TUS
token contract
"""
tusContract = cast(Address, "0xf693248F96Fe03422FEa95aC0aFbBBc4a8FdD172")
return makeErc20Client(
"Avalanche",
nodeUri,
tusContra... | 38057a020ad83034ab30ae9217047f735df79d10 | 62,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.