content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def runLineageProfiler(species,array_type,exp_input,exp_output,codingtype,compendium_platform,modelSize=None,customMarkers=False,geneModels=False,permute=False,useMulti=False):
""" This code differs from LineageProfiler.py in that it is able to iterate through the LineageProfiler functions with distinct geneModels
... | 4a9155da428bf5a70abc1181163e91156cf0d982 | 58,247 |
import itertools
from typing import OrderedDict
import operator
from datetime import datetime
def parse_cdrs(cdr_list, config_settings):
"""Parse list of CDRInstance to generate & return list of CDRException for CDRInstances where termination
cause code isn't in the list of exclusions or MoS/CCR is worse than... | ab2acdaa779d7ba7b5878a2e6cd85ed20cc68ec5 | 58,248 |
def calculate_angle_difference(alpha, beta):
"""
Return min angle in rad between two give angles in range <-pi, pi>
"""
diff = alpha - beta
diff = clip_angle(diff)
return diff | c073cf88402c84ab59ad9e739bd775483650cc5f | 58,249 |
import requests
def make_ecobee_request(request_type, url, **kwargs):
"""
Wrapper around making arbitrary GET and POST requests to remote Ecobee API
:return: Ecobee API response using provided request content
"""
# Generate appropriate grequests object
if request_type.lower() in ["get", "post"... | d1af35212fba25a3e27b205dba6bc631e2989e27 | 58,250 |
import warnings
import copy
def combine_ins(ins1, ins2, inplace=False):
"""
This utility function combines INS for the same obs that have been averaged
over different baselines.
Args:
ins1: The first spectrum for the combination
ins2: The second spectrum for the combination
in... | 18e8e3f208642eef1c66c03dab653ff5c76b45df | 58,251 |
import http
def ope_titre_detail(request, pk):
"""
view, une seule operation mais pour les comptes titres
@param request:
@param pk: id de l'ope
"""
ope = get_object_or_404(Ope_titre.objects.select_related(), pk=pk)
if request.method == 'POST':
# date_initial = ope.date#inutile
... | 650c5c812c1ec044fbcdbed2b74d38945f6104d6 | 58,252 |
def get_coordinate(title):
"""
Extract coordinates from ocrx coordinates string
:param title: ocrx coordinate string
:return: dictionary contains ``xmin``, ``ymin``, ``xmax``, ``ymax``
"""
match = BBOX_COORDINATES_PATTERN.search(title)
return {
'xmin': int(match.group(1)),
'y... | e2363040fd6ac5f44b5e24cb65b529f2e5c9dc05 | 58,253 |
import pandas
def asks(orders: pandas.DataFrame) -> pandas.DataFrame:
"""
Get orders of type "ask".
Args:
orders: dataFrame of orders
"""
return orders[orders.side == 'ask'] | e5a2799e35cab1888403ee8480f0535db5e1c73d | 58,254 |
def bm_group_load(name, path):
"""a wrapper to download, process and load benchmark group
Args:
name (str): the rough benchmark group name
path (str): the benchmark group path to save/retrieve
Returns:
str: exact benchmark group name
"""
name = bm_download_wrapper(name, path)
return name | bf9d116db8b10eca296b21c33465941232ae72df | 58,255 |
def GetAssetCreationTime(primStack, assetIdentifier):
"""Finds the weakest layer in which assetInfo.identifier is set to
'assetIdentifier', and considers that an "asset-defining layer". We then
retrieve the creation time for the asset by stat'ing the layer's
real path.
Returns a triple of strings:... | c6a0585128815ad6f9938ede3fc9cbc1dded1b8d | 58,256 |
def calc_hvac_energy(surface_area, building_type, Tin, Tout):
"""
Heat Transfer Equation
Notes
-----
Q = U x SA x (Tin - Tout)
Q - Heat lost or gained due to outside temperature (kJ·h−1)
U - Overall heat transfer coefficient (kJ·h−1·m−2·°C... | 1616196b36f6c512763362292ceb296ad4acbf96 | 58,258 |
import types
def goes_flare_class(gcls):
"""Convert GOES classes into a number to aid size comparison. Units are
watts per meter squared."""
def calc(gcls):
powers_of_ten = {'A':1e-08, 'B':1e-07, 'C':1e-06, 'M':1e-05, 'X':1e-04}
power = gcls[0].upper()
if power in powers_of_ten:
... | b98d09154dafc0bdd4b67df8477110acece1ad92 | 58,259 |
def helpMe():
"""
Render the help page
"""
return render_template('home/help.html', title="Help") | 4659534574ddcbd05c34c8cb0d9b479701aa3f91 | 58,260 |
import shlex, subprocess
def RunShellCommand(command):
""" Run a shell command in subprocess.
params: command with arguments to run
returns: (exit_code, stdout, stderr)
"""
cmd_args = shlex.split(command)
output_str = ""
exit_code = 0
try:
output_str = subprocess.check_... | 4a3534491ceed74f2371550d2b0748f0af31e7f0 | 58,261 |
import requests
import io
import time
def download_data(url):
"""
Args:
url:
Returns:
pandas dataframe
"""
attempt = 0
while attempt < MAX_ATTEMPTS:
try:
response = requests.get(url)
if response.status_code == 200:
print("\tReq... | ff1d4cb787abb49209d2b5d87fc847968921c184 | 58,262 |
def measure_total_snapshot_creation_time(snap_name, start_time):
"""
Measure Snapshot creation time based on logs
Args:
snap_name (str): Name of the snapshot for creation time measurement
start_time (str): start time, starting from which the logs are searched
Returns:
float: Cr... | 57e5c407db2aaec17954438789fc45abb810da6c | 58,263 |
def filter_records_for_filetypes(records: dict, return_types: list):
""" Find the records that have all the requested filetypes. e.g. get all subdirectories with labels """
valid_records = {}
for k, v in records.items():
# k is the key for this record, e.g. experiment00_mouse00
# v is the di... | 4c79d8646534875c4b64e0e851fc6e4b6676746b | 58,264 |
def mass_ks_test(x, y):
"""mass-univariate two-sample kolmogorov-smirnov test
Args:
x ([type]): 1D numpy array
y ([type]): 1D numpy array
"""
pvals = []
num_dims = x.shape[1]
for dim in range(num_dims):
_, p_val = ks_2samp(x[:, dim], y[:, dim])
pvals.append(... | 480aa574e9a1fd719453d1c792244fd3f3a62862 | 58,265 |
import torch
def cmn(data, axis=1, is_tensor=False):
"""Apply mean normalization on input sequences for every dimensions.
axis is the dimension in which we perform normalization. """
if is_tensor:
data2 = data - torch.mean(data, dim=axis, keepdim=True)
else:
data2 = data - np.mean(data... | d9dd3ba9d43a56a48ed06e3be5ef041be3ad1cea | 58,267 |
def getValidData(filelist=[]):
"""过滤集合中空的元素."""
valifile = []
for fp in filelist:
if fp != None:
valifile.append(fp)
return valifile | 57bccc440a056deee3bd16a4785823ab4f0845c2 | 58,268 |
import functools
import six
def wrap_wsme_controller_exception(func):
"""This decorator wraps controllers method to manage wsme exceptions:
In case of expected error it aborts the request with specific status code.
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
r... | 71e4c5f6bdd963bb2180db576144a14f40ff04b2 | 58,270 |
import typing
def _init_ctz_db_and_table(n: int) -> typing.Tuple[int, typing.List[int]]:
"""Setup for fast ctz of ints with up to 2**n bits.
This code initializes the De Bruijn sequence (as an integer) and
the lookup table needed to do constant time (1 multiply and some
bit twiddling) ctz, as describ... | b9bbd5dfa085ade0fb8a8369ab683016ce3d0418 | 58,271 |
def _plot_dendrogram(dendrogram_list, active_sites, cluster_indicies_dict):
"""
Plots a dendrogram from the hierarchical clustering
Parameters
----------
dendrogram_list
active_sites
cluster_indicies_dict
Returns
-------
"""
sns.set_style("white")
fig, ax = plt.subplots... | 2af3ef55f91a50ba6381a84d387357fb7574453c | 58,272 |
def xrdataset(filenames,aggdims,no_mf=True):
""" filenames: shape 2 list [dim y [dim x]] ; aggdims = [dimy,dimx] """
ncs = []
for names in filenames:
#tmes, tmeb = time.clock(), time.time()
if no_mf:
ncc = [xr.open_dataset(name) for name in names]
ncs.append( \
... | eb788aa0dfdf7b91f7509dc1df7aaad0427ca9c8 | 58,273 |
from typing import TextIO
from typing import Tuple
def _read_table(f06_file: TextIO, line: str, i: int,
log: SimpleLogger) -> Tuple[str, np.ndarray, str, int]:
"""
'0 TABLE MKLIST LINES CONTAINING BINARY ZERO HAVE BEEN DELETED.\n'
''
''
'0RECORD NO. 0'... | 893265cf4790a275cf6226d2fe31aace54143dc6 | 58,274 |
def sorted_dict(d : dict) -> dict:
"""
Sort a dictionary's keys and values and return a new dictionary
"""
try:
return {key: value for key, value in sorted(d.items(), key=lambda item: item[1])}
except Exception as e:
return d | ec8b38805ee26f2d2e2fe0d876c8cbda88098026 | 58,275 |
def getWordsUnder(wordList, targetLength):
""" return list of words of a specified length in the list """
return [word for word in wordList if len(word) < targetLength] | ba49461ab90d32a97cdd9db3a8785cdc95579463 | 58,276 |
def helpers(request):
"""return a dict of app helpers"""
return dict(
app_url=request.app.url,
app_menu=request.app.menu,
app_name=request.app.name,
app_class=zoom.utils.id_for(request.app.name.strip()),
app_description=request.app.description,
app_keywords=reques... | 6411bf8eb508daf2417dfdae67a46a6c724f9572 | 58,278 |
import configparser
def export_story_as_config(from_slide, with_fields):
""" Returns the story items for a story slide in the config format
Each slide contains placeholder with a text frame which in turn contains
paragraphs with text. Only ASCII characters are allowed in the story text
files to overc... | 529893dc5b238e86a9480d983afe5a229d762dd0 | 58,279 |
def mean_value_2d(f, psi, x_range, y_range, M):
"""
Short summary.
Parameters
----------
f : type
Description of parameter `f`.
psi : type
Description of parameter `psi`.
x_range : type
Description of parameter `x_range`.
y_range : type
Description of par... | 030518250a18cc61974b4615c4d2f80b0bd032f7 | 58,280 |
def get_percentage(new, last):
"""
:param new: float
New value
:param last: float
Last value
:return: float in [0, 100]
Percentage increase (or decrease) since last value
"""
ratio = abs(get_ratio(new, last))
percentage = min(ratio * 100.0, 100.0) # in bounds
pe... | 374d8f51bda7a9152b33674749b2b499480f00e8 | 58,282 |
def get_info(city, route):
"""取得該城市符合條件的所有路線基本資料"""
return jsonify(info.main(city, route)) | 5dce8e5e9cdad4b8e7a56c0370722de39171abb1 | 58,283 |
from datetime import datetime
def get_payouts(num_days=None, payout_status=None,
start_date=None, end_date=None, sandbox=False, **kwargs):
"""Get payout using the Sell Finances API.
Arguments
num_days: Only return payouts from the last num_days
payout_status: Only return payou... | 8b46a0760eb03db2cc18035b6d80b1ef7a4e04ed | 58,284 |
def get_base_deck_nodes(bridge: Bridge, ctx: BuildContext) -> DeckNodes:
"""Deck nodes without refinement."""
deck_grid = get_deck_grid(bridge=bridge, ctx=ctx)
nodes = []
for z in deck_grid[1]:
nodes.append([])
for x in deck_grid[0]:
nodes[-1].append(ctx.get_node(x=x, y=0, z=... | d0c0050ca9a570189e4cf660b2f2be1d3e5b2795 | 58,285 |
from operator import inv
def fim_for_single_t(xpdot1, Vold, sigma, nx, ntheta,A):
"""
:param xpdot:
:param sigma:
:return: FIM1
"""
xpdot = xpdot1
FIM1 = Vold#np.zeros([2, 2])
for i in range(1):
xp_r = reshape(xpdot, (nx, ntheta))
# vv = np.zeros([ntheta[0], ntheta[0], 1 + ... | 0a0a364e935781a99def0864aa42986ee5f8694a | 58,286 |
def get_project_image_count(project, with_all_subfolders=False):
"""Returns number of images in the project.
:param project: project name or folder path (e.g., "project1/folder1")
:type project: str
:param with_all_subfolders: enables recursive folder counting
:type with_all_subfolders: bool
:... | db3806bc4e74aedf4feef686bdf63259e98b9067 | 58,287 |
def compute_short_chain(number):
"""Compute a short chain
Arguments:
number {int} -- Requested number for which to compute the square
Returns:
int -- Value of the square/short chain for the given number
"""
return number * number | 7ce09da632cdc19a1b785121ff60b60c0dd719a9 | 58,288 |
def generate_default_ok_responses():
"""
Generate default ok responses for http requests
"""
default_ok_responses = generate_default_response()
default_ok_responses["200"] = {
"$ref": "#/components/responses/Ok"
}
return default_ok_responses | 2089319050027e1c3dfe62917dc5249924021f58 | 58,289 |
def sort_by_type_and_size(layer_nodes):
"""
对关键路径中的叶子节点按照资源类型和大小进行排序
Args:
leaf_nodes: 叶子节点列表
Returns:
排好序的叶子节点列表
"""
document_list = []
stylesheet_list = []
font_list = []
script_list = []
for node in layer_nodes:
if node['mime_type'] == 'text/html':
... | 02026778cfe0ff1481e24a9b2f9304fb2a5a4fc3 | 58,290 |
def delete_sms(overrides=None):
"""
Delete Sms
Args
overrides (dict):
msg_id: ';' (empty), 'X;' (one) 'X;Y;Z;' (many)
"""
defaults = {
'goformId': 'DELETE_SMS',
'msg_id': '',
}
data = _update_params(defaults, overrides)
return post(data) | 56464a4c7d8852977a16dff26de6596557078559 | 58,292 |
def unescape_html(html):
"""
*Unescape a string previously escaped with cgi.escape()*
**Key Arguments:**
- ``dbConn`` -- mysql database connection
- ``log`` -- logger
- ``html`` -- the string to be unescaped
**Return:**
- ``html`` -- the unescaped string
"""
###... | cafa4eb7ecc68b6221250947173c579e125ede07 | 58,293 |
def get_lth_sparsity(save_round, n_rounds, target_sparsity, end_epoch):
"""
save_round: when to save the weight; 1 onwards
n_rounds: number of pruning cycles to do
target_sparsity: the sparsity percentage to achieve by the end of the iteration
end_epoch: total number of epochs to train for where pruning is el... | b4bae2bbd53858f1daa177bbf242c72c3a243e33 | 58,294 |
def is_connected_to_prev(res1, res2) -> bool:
"""
Return the bond distance between two residues using Numpy array math.
:param res1: Bio.PDB.Residue.Residue
:param res2: Bio.PDB.Residue.Residue
:rtype: float
"""
distance = atomic_distance(res1, res2, 'N', 'C')
if distance <= float(1.8):
... | f181bd84cb509b069c4b66d492ac11fce2921517 | 58,295 |
def get_lr(optimizer):
"""get learning rate from optimizer
Args:
optimizer (torch.optim.Optimizer): the optimizer
Returns:
float: the learning rate
"""
for param_group in optimizer.param_groups:
return param_group['lr'] | fc8293cc29c2aff01ca98e568515b6943e93ea50 | 58,296 |
def autodetect_format(content: str) -> str:
"""Return format identifier for given fragment or raise FormatAutodetectionError."""
formats = set()
for impl in FORMAT_IDENTIFIER_TO_FORMAT_CLASS.values():
guess = impl.guess_format(content)
if guess is not None:
formats.add(guess)
... | b4bac8830b23c1b048bfdd90686f8891ce10cb4a | 58,298 |
import json
def create_index(es, indexname, mapping=None):
"""
Create a index based upon the configured base indexname. It will increment an appendend 5 digit number to version the different index instances.
Args:
es : elasticsearch instance
indexname (str): configured base indexname
... | 28eec9c0c81a8735e3308d414165e77b3f2f4534 | 58,299 |
from typing import List
from typing import Tuple
def carree2pix(coord: List[float],
area: List[Tuple[float]],
image_size: List[int],
origin: str = "upper") -> tuple:
""" Convert Carree lat/long to image poxel position
Arguments:
coord(List[float]): (lat, l... | deebeab299f61bc28536cf44d98ae3a247615c36 | 58,300 |
def get_interval_scores(
target_exon,
left_region_start,
right_region_end,
interlap_scores,
gene_name,
interval_size,
):
"""
get_interval_scores
===================
This method is to get regional constraint scores from left to right by a set interval. This method uses the exon s... | d0574c95e114f30b974949f61885afa6ab8f672e | 58,304 |
def axis_angle_to_quaternion(axis, theta):
""" Convert a rotation axis / angle pair to a quaternion
Parameters
----------
axis : float
The Rotation Axis
theta : float
The Angle
Returns
-------
array_like
The Quaternion (w, x, y, z)
"""
# make sur... | 8837b353e2e37e8122cd907f3dfac1fc0a007551 | 58,305 |
def refcount_table_clusters(current):
"""Fuzz refcount table clusters header field."""
constraints = UINT32_V
return selector(current, constraints) | e7f2a5e0ad1fb9ab035c4bdb54e584777b999f6f | 58,306 |
def get_form_target():
"""
Returns the target URL for the comment form submission view.
"""
if get_comment_app_name() != DEFAULT_COMMENTS_APP \
and hasattr(get_comment_app(), "get_form_target"):
return get_comment_app().get_form_target()
else:
return reverse("comments-pos... | 64466d524e8d15d6592e89a08b744f3d6d234c22 | 58,308 |
def custom_reduce(cls, states):
"""For customizing object serialization in `__reduce__`.
Object states provided here are used as keyword arguments to the
`._rebuild()` class method.
Parameters
----------
states : dict
Dictionary of object states to be serialized.
Returns
-----... | 9afc74471feed1f89c77bee86f235fae7109b678 | 58,309 |
def compute_curvature(*args, **kwargs):
"""
Computes the curvature of the energy of a system as a function
of the number of electrons in the system E(N).
Args:
args (:class:`exatomic.core.universe.Universe`): unis in ascending electron order
neut (int): index of args corresponding to th... | 393a44605724c54f1ae13efbf61314b702e40bd7 | 58,310 |
def tt_s_p(session,s_p,uncert):
""" tt_s_p(session,s_p,uncert)
Look up the distance for an S-P travel time observation and return all the nodes within
the s_p +/- uncert
Returns the TTtable3D_object
"""
nodes = session.query(TTtable3D).filter(TTtable3D.s_p<=s_p+uncert).filter(TTtable3D.s_p>=s_p-uncert... | 682bd14034ccc400c710971c6e5a26caf5516ce1 | 58,311 |
def admin_index():
"""Admin Index
"""
return render_template('index.html') | abe52416d02b00f7e2a90c5a68d05aec78025007 | 58,312 |
def _square_wave_samples(freq, rate, amp, num):
"""
Generates a set of audio samples taken at the given sampling rate
representing a square wave oscillating at the given frequency with
the given amplitude lasting for the given duration.
:param float freq The frequency of oscillation of the square... | ba6c72032f08455d8064a5ce6e54e1d8d63873fa | 58,313 |
def mybio_to_pymol_selection(entity):
"""Transform an :class:`~luna.MyBio.PDB.Entity.Entity` instance into a Pymol selection-expression,
which can then be used to select atoms in a Pymol session.
Parameters
----------
entity : :class:`~luna.MyBio.PDB.Entity.Entity`
An entity to be transform... | 1952af51b67676f2bf19775b52d5f721ae1e62cc | 58,314 |
def compositionalActflowRandomSplitLOOBaselineCV(ncvs, svm_mat, nov_svm_mat, prc_svm_mat, labels, subjarray, featsel=True, nproc=5):
"""
Runs cross validation for an across-subject SVM analysis
"""
ntasks = len(np.unique(labels))
nsamples = svm_mat.shape[0]
nsubjs = nsamples/ntasks
sub... | 9ab037d36beba8996faf380dd3805220182f3b16 | 58,315 |
def parse_pv(repo, text):
"""Return a CPV instance from either a cpv or a pv string.
If a pv is passed it needs to match a single cpv in repo.
"""
try:
return cpv.CPV.versioned(text)
except errors.InvalidCPV:
restrict = parse_match(f"={text}")
result = None
for match... | 42414f2dc9b84095f9184fd8bf3c65d7fa591d48 | 58,316 |
def get_contact_list(txt):
"""Returns contacts (from autosuggest)"""
txt = txt.replace('%', '')
if len(txt) < 3:
return None
out = filter(None, frappe.db.sql_list("""select email from (
select distinct email_id as email, 2 as doctype,
if (locate( %(_txt)s, concat(first_name, " ", last_name)), locate( %(_txt... | bb1f1f84854ede4b7fb75d08a7de435a65914d1f | 58,317 |
def connect_to(name):
"""Creates a node instance based on an entry from the config
This function will retrieve the settings for the specified connection
from the config and return a Node instance. The configuration must
be loaded prior to calling this function.
Args:
name (str): The name ... | aae624892447618194374061cf316ce2112d6275 | 58,318 |
def tone2_to_normal(tone2, v_to_u=False):
"""将 :py:attr:`~pypinyin.Style.TONE2` 风格的拼音转换为
:py:attr:`~pypinyin.Style.NORMAL` 风格的拼音
:param tone2: :py:attr:`~pypinyin.Style.TONE2` 风格的拼音
:param v_to_u: 是否使用 ``ü`` 代替原来的 ``v``,
当为 False 时结果中将使用 ``v`` 表示 ``ü``
:return: Style.NORMAL 风格的拼音... | 768cd8c4bd97d2a630a776d7f69941319c269692 | 58,320 |
def month_to_str_int(m):
"""Converts a month to an int form, str type, with a leading zero"""
mi = month_to_int(m)
if mi < 10:
ms = "0{}".format(mi)
else:
ms = str(mi)
return ms | 8a75338e41bdb63c6f13b916688cee83bd4a220b | 58,321 |
def tree_figure_rotations(figure):
"""
Find all rotations of a pentomino
@param {dict} set of points on the tree
@return {dict} 8 sets of points on the tree, corresponding to all
rotations of the tree that are possible.
"""
return tuple(_shift_pent(_rotation_info(figure))) | d900b1d21650328a3ba7a0e2cabfbc76cd39eeeb | 58,322 |
import numba
import threading
import functools
def performance_function(
_func: callable = None,
*,
worker_count: int = None,
compilation_mode: str = None,
**decorator_kwargs,
) -> callable:
"""A decorator to compile a given function and allow multithreading over an multiple indices.
NOTE... | 41a16c37ce344b59cf662d0c40802f018ee737c8 | 58,323 |
def test_dataset_ints(lengths):
"""Create a test dataset of int64 tensors of shape [length]."""
def generator():
"""Sample generator of sequences of shape [length] of type int64."""
for length in lengths:
x = np.zeros([length], dtype=np.int64)
yield (x, x) # Inputs and targets are the same here... | e8c0a62f22e903ff5014d0c61b24f9b641f804ce | 58,324 |
from typing import Optional
import torch
def _convbot(
sent: Optional[str],
prev_resp: Optional[str] = "",
max_length: int = 1000,
do_sample: bool = True,
top_p: float = 0.95,
top_k: int = 0,
temperature: float = 0.75,
):
"""Generate a response."""
# sent_ids = tokenizer.encode(sen... | 256bbb2a305cfb3b50e773e8e10c0c937aaaca03 | 58,325 |
def render_block(data, pgm, param):
"""
render one single block
"""
param = np.round(param).astype(np.int32)
bsz = data.shape[0]
for i in range(bsz):
loop_free = decode_pgm(pgm[i], param[i])
cur_pgm = loop_free[:, 0]
cur_param = loop_free[:, 1:]
for j in range(len... | 267508fcde570e03154c6b8c52f225d69154b8ce | 58,326 |
def q2torque( q, dq, ddq , manipulator ):
"""
Parameters
----------
q : numpy array float 3 x l
dq : numpy array float 3 x l
ddq : numpy array float 3 x l
manipulator : pyro object
Returns
-------
tau : numpy array float 3 x l
"""
# Time discretization
l... | ac0f32a8be67d778c925d213817e3a6c98a76ef1 | 58,327 |
def apply_filters(query, filter_spec, do_auto_join=True):
"""Apply filters to a SQLAlchemy query.
:param query:
A :class:`sqlalchemy.orm.Query` instance.
:param filter_spec:
A dict or an iterable of dicts, where each one includes
the necesary information to create a filter to be ap... | e45940fba31ab81e1d30c5c621971c081b7d0efd | 58,328 |
from typing import Union
def _get_user_id(column: str, value: str) -> Union[int, bool]:
"""Get user id from any user detail and its column.
:param str value: Any user value stored in the database
:param str column: Database column of the given user value
:returns: user id on success
"""
wit... | 00d605bba346311441c5995c51152bc33f955a5d | 58,329 |
import re
def convert_col_string_to_list(colstr, with_format=True):
"""Convert a string of columns to list of columns.
"""
columns = re.findall(r'\$\S+\{.*\}|[^,\s]+', colstr)
if not with_format:
columns = remove_column_format(columns)
return columns | 0458ee5adbc1f19518d60b6c276864e77a6f5ed7 | 58,330 |
def mad(arr):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
med = np.median(arr)
return np.median(np.abs(arr - med)) | 0954682f2b0f5440ebfd9b9ab8f40d1f218a5472 | 58,331 |
def update_rooms_slider(area):
"""
Update rooms slider to sensible values.
"""
return [1, min(int(area / 30) + 1, 6)] | af721d72b9d122d2d129797453cee2801e45eec9 | 58,333 |
def random_molecule(draw, molecule_class=Molecule, max_nodes=5, max_meta=None):
"""
Strategy that builds a molecule.
Parameters
----------
draw:
Internal for hypothesis.
molecule_class: type
The class of molecule to build, :class:`vermouth.molecule.Molecule` by
default.
... | 58ef6c3c22ce1b225e43de8c187ccafd3c2e4e00 | 58,334 |
def find_changes(vals, threshold=None, change_pct=0.02, max_interval=None):
"""Returns an array of index values that point at the values in the 'vals'
array that represent signficant changes. 'threshold' is the absolute amount
that a value must change before being included. If 'threshold' is None,
'c... | e6c66d3636f80ee310dcb7ae790bb30a27598aaa | 58,335 |
def configure_optimizer():
"""
Configure the optimizer for Bootleg.
Args:
config: config
"""
# Specify parameter group for Adam BERT
def grouped_parameters(model):
no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"]
return [
{
"params": ... | 81f767bb819e235feb178f88b486475b8dc4c7dd | 58,336 |
def generateDaltonInputFileText(XYZ: xyz.xyz_to, charge: int) -> str:
"""Makes the text for a Dalton input file
Args:
charge (int): The charge of the molecule
Returns:
str: Returns the file text
"""
if not hasattr(XYZ, 'atoms'):
print(f'''You need to process the xyz file us... | 06c48516f7ba8cab3e26ec0d36910615e9b8a6da | 58,337 |
from typing import List
import math
def standard_deviation(xs: List[float]) -> float:
""" The standard deviation is the square root of the variance """
return math.sqrt(variance(xs)) | 6558087203aade8f8e5233c7f6ca2a1d7a8130f9 | 58,339 |
import inspect
import copy
def fit_ec_model(data,model,init_params=None,normalize='deg',alpha=0,n_restarts=10,est_HFR=True,weighting='modulus',return_result=False,simplex_params={},random_seed=None,**est_HFR_kw):
"""
Fit equivalent circuit model using Nelder-Mead downhill simplex method.
Adds random noise to the i... | be10779709ac9024c83f12e7c98b23f6f4d42541 | 58,340 |
def close_run(exit_status=None, reason=None):
"""
Mark the end of the current 'run'. Emit a RunStop document.
Yields
------
msg : Msg
Msg('close_run')
exit_status : {None, 'success', 'abort', 'fail'}
The exit status to report in the Stop document
reason : str, optional
... | 07305eace0003fe1760b1bab301c7039df6d6f7d | 58,341 |
def retrieve_row_by_pk(session, pk, _class):
"""Retrieve a row from the database based on it's PK components"""
q = session.query(_class) # Build the base query statement
pkey_cols = _class.__table__.primary_key.columns
# Iterating for the case where the PK is composite
for pk_col, pk_value in zip(... | f25ba01e1b437bbe45740f52e9f028d8071be374 | 58,342 |
def comp_nb_radial_wire(self):
"""Return number of adjacent wires in radial direction
Parameters
----------
self : CondType12
A CondType12 object
Returns
-------
Nwppc_rad: int
Number of adjacent wires in radial direction
"""
return int(sqrt(self.Nwppc)) | 039b54e22641e0d3cd59995e2ce5af5c222a53e4 | 58,345 |
def evaluate(board):
"""Evaluate a checkers board via a simple linear heuristic.
Args:
board: a string representing a board.
Returns:
an integer which is positive if black has te upper hand (negative
for red).
"""
bcount = 30 * board.count('B') + 20 * board.count('b')
i... | b609caff503fce13c6280e3253be2281c4a6eb32 | 58,346 |
from typing import Optional
def jobs_list_command(client: Client, args: dict):
"""
This function returns a list of all existing jobs.
:param client: Demisto client
:param args: command's arguments
:return: CommandResults object
"""
id_list: list = argToList(args.get("id_list", []))
gro... | aff97e7b540472bb9f0d2f7225964c150a5db820 | 58,347 |
def get_mode(array):
"""Find the mode in the array"""
mode = None
if isinstance(array, np.ndarray):
counter = np.bincount(array.flatten())
mode = int(np.argmax(counter))
return mode | c1bfba16b2906a9c0b5db2b9d3285570c65b8ea0 | 58,348 |
def login_link(request):
"""
This assumes your login link is the Shibboleth login page for your server
and uses the 'target' url parameter.
"""
full_path = quote(request.get_full_path())
login = reverse('shibboleth:login')
ll = "%s?target=%s" % (login, full_path)
return { 'login_link': ... | 0b99095c989d04f5c425d5e9c4e5ee55f57665e2 | 58,349 |
from datetime import timedelta
def convert_df_shifttime(df: pd.DataFrame, second: int):
"""
shift time by second
Parameters
----------
df :
second :
Returns
-------
"""
time_shifted = df.index + timedelta(seconds=second)
new_df = pd.DataFrame(data=df.values, columns=df.c... | 12c615adf1052c3cd4c9896d3deff0e922885dcd | 58,350 |
def group_rename(request, group_id):
"""Rename a group.
"""
if request.method != 'POST':
raise Http404
new_name = request.POST.get('new_name', '')
next = request.META.get('HTTP_REFERER', SITE_ROOT)
group_id = int(group_id)
try:
rename_group_with_new_name(request, group_id, ... | 45dc07a9f9dd7e961fb77540b7fde95d77bc55ca | 58,352 |
def placeholder_inputs(batch_size):
"""建立兩個tf placeholder來存於輸入值及標籤.
These placeholders are used as inputs by the rest of the model building
code and will be fed from the downloaded data in the .run() loop, below.
Args:
batch_size: The batch size will be baked into both placeholders.
Returns:
images... | b58d587dd597a370b2798446092749fb6f83e331 | 58,353 |
def reorder_atoms(mol):
"""Reorders hydrogen atoms to appear following their heavy atoms in a molecule.
Args:
mol (Mol): A molecule (RDKit format)
Returns:
new_Mol (mol): A molecule with hydrogens after the corresponding heavy atoms.
"""
# Create a list ... | cc21313d211d588228f2a57e120ed4c7c0311e29 | 58,354 |
def hinge_loss_layer(feat_anc, feat_easy, feat_hard, loss_weight, mask, name):
"""Loss layer."""
with tf.name_scope(name): # pylint: disable=not-context-manager
def _structured_loss(dist_mat, batch_size, margin):
# positive distance
easy_dist = tf.matrix_diag_part(dist_mat)
... | 9ce4dcd77e83f4528bd5dcb5d29885c3ead6296b | 58,355 |
def read_data_to_dataframe(_path,**kwargs):
"""
Helper function that reads csv and feather formats and outputs
pandas dataframe
"""
if _path.lower().endswith('.csv'):
print('csv!')
return pd.read_csv(_path,**kwargs)
elif _path.lower().endswith('.feather'):
return pd.rea... | b6ee651199a773fcfacb56e8bc9bf4d182f7235d | 58,356 |
import re
def split_interface(interface_regex, value):
"""
convert an interface based on the given regular expression to a dictionary with all components, e.g.
regex: .*(?P<chassis>\d+)\/(?P<module>\d+)\/(?P<port>\d+).*
value: interface gi1/2/3
will return
{
"chassis... | 39f852333e065f80405cc603600a5673bfaf0d5f | 58,357 |
import torch
def laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.Tensor) -> torch.Tensor:
"""Returns orientation of the LAFs, in radians. Useful to create kornia LAFs from OpenCV keypoints.
Args:
xy: tensor [BxNx2].
scale: tensor [BxNx1x1].
ori: tensor [BxN... | c0b627b02cbb743a7155bb912b24ad00ee25bcc2 | 58,358 |
from operator import or_
def or_many_condition(condition: list):
""" 有时候or能比in产生更好的性能,例如
filter(or_many_condition([UserDB.id == i for i in user_ids]))
会比
filter(UserDB.id.in_(user_ids))
性能更加好
"""
if len(condition) == 0:
return True
if len(condition) == 1:
return co... | a707919908c42f3db62a74290a61cd8586c31213 | 58,360 |
def apwidth(img, ap_uorder_interp, offsetlim=(-8, 8), ap_npix=10, method='max'):
""" automatically find ap_width for a given ap_npix """
img = np.array(img)
ap_width_max = offsetlim[1] - offsetlim[0] + 1
assert 1 <= ap_npix <= ap_width_max
# determine SNR of each offset
ofst, medsnr_lnsum = a... | 2006b2d3293981902a4e553bba29e453d473cf12 | 58,361 |
def data_value(value: str) -> float:
"""Convert to a float; some trigger values are strings, rather than
numbers (ex. indicating the letter); convert these to 1.0."""
if value:
try:
return float(value)
except ValueError:
return 1.0
else:
# empty string
... | 24087c1733be5932428a63811abbb54686836036 | 58,362 |
def batch_gather(values, indices):
"""Gather slices from values.
Args:
values: a tensor in the shape of [batch_size, length, depth].
indices: a tensor in the shape of [batch_size, slice_count] where
slice_count < length.
Returns:
a tensor in the shape of [batch_size, slice_count, depth].
""... | ec57c5483e4cd561bf9d7c4583b1a980562d6460 | 58,363 |
def _prepare_signature_outputs(names: list, dtype_layer, shape,
model_keys):
"""
Inference Engine Api does not report outputs shapes,
for signature format consistency with TF Serving theres returned a
dummy shape==(1,1,1).
To be fixed in the future.
"""
signatu... | 26b97ae126f8a759e970199967f5233513f431a1 | 58,365 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.