content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def get_assay_description(assay_id, summary=True, attempts=10):
""" Get the description of an assay in JSON format.
Parameters
----------
assay_id : int
The id of the bioassay.
summary : bool, optional
If true returns a summary of the d... | 13ff3620a1ef3e7aa1c12bd5a9b5aa88b2fb297f | 3,655,337 |
def acos(expr):
"""
Arc cosine -- output in radians.
It is the same that :code:`arccos` moodle math function.
"""
return Expression('acos({0})'.format(str(expr))) | d064caaa037de619266e322f85ae09c2ba7d9d16 | 3,655,338 |
from datetime import datetime
def annotate_genes(gene_df, annotation_gtf, lookup_df=None):
"""
Add gene and variant annotations (e.g., gene_name, rs_id, etc.) to gene-level output
gene_df: output from map_cis()
annotation_gtf: gene annotation in GTF format
lookup_df: DataFrame with va... | 562ef01380075a3e12eeaecdd6ab1e2285ddbc4f | 3,655,339 |
import torch
def y_gate():
"""
Pauli y
"""
return torch.tensor([[0, -1j], [1j, 0]]) + 0j | c0da0112233773e1c764e103599a591bb7a4a7f5 | 3,655,340 |
import tarfile
def extract_tarball(tarball, install_dir):
"""Extract tarball to a local path"""
if not tarball.path.is_file():
raise IOError(f"<info>{tarball.path}</info> is not a file!")
try:
with tarfile.open(tarball.path, "r:gz") as f_tarball:
extraction_dir = [
... | da9deeb71da36c7c01611f3be7965a8c4a22dc41 | 3,655,341 |
def compose_matrix(scale=None, shear=None, angles=None, translation=None, perspective=None):
"""Calculates a matrix from the components of scale, shear, euler_angles, translation and perspective.
Parameters
----------
scale : [float, float, float]
The 3 scale factors in x-, y-, and z-direction.... | a186919f8b6fc47637e7c20db30fbdd8e461e059 | 3,655,342 |
def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items())) | d88a68720cb9406c46bdef40f46e461a80e588c0 | 3,655,343 |
def EucDistIntegral(a, b, x):
"""[summary]
Calculate Integrated Euclidean distance.
Args:
a (float): a value
b (float): b value
x (float): x value
Returns:
val: Integration result
"""
asq = a * a
bsq = b * b
xsq = x * x
dn = (6 * (1 + asq)**(3 ... | 3da541356636e8be7f9264d9d59a29dd003c082b | 3,655,344 |
def _VarintSize(value):
"""Compute the size of a varint value."""
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value ... | 4bd9b1c8d362f5e72e97f9f2c8e0d5711065291f | 3,655,345 |
import requests
def send_to_hipchat(
message,
token=settings.HIPCHAT_API_TOKEN,
room=settings.HIPCHAT_ROOM_ID,
sender="Trello",
color="yellow",
notify=False): # noqa
"""
Send a message to HipChat.
Returns the status code of the request. Should be 200.
"""
payload = {
... | 138abbf59f561a4c5d21aea9976856dbd7a581ca | 3,655,346 |
from cStringIO import StringIO
import cgi
def input(*requireds, **defaults):
"""
Returns a `storage` object with the GET and POST arguments.
See `storify` for how `requireds` and `defaults` work.
"""
def dictify(fs): return dict([(k, fs[k]) for k in fs.keys()])
_method = defaults.pop('_m... | 0b3fcd9142dbcd3309b80837c6fc53abdf4aaad6 | 3,655,347 |
def nodes_and_edges_valid(dev, num_nodes, node_names, rep):
"""Asserts that nodes in a device ``dev`` are properly initialized, when there
are ``num_nodes`` nodes expected, with names ``node_names``, using representation ``rep``."""
if not set(dev._nodes.keys()) == {"state"}:
return False
if not... | ad6dbfdfd92114c9b041617a91ad30dbe8a8189f | 3,655,348 |
def is_android(builder_cfg):
"""Determine whether the given builder is an Android builder."""
return ('Android' in builder_cfg.get('extra_config', '') or
builder_cfg.get('os') == 'Android') | 74b1620ba2f6fff46495174158f734c5aa8da372 | 3,655,349 |
def twoSum(self, numbers, target): # ! 这个方法可行
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
numbers_dict = {}
for idn, v in enumerate(numbers):
if target - v in numbers_dict:
return [numbers_dict[target - v] + 1, idn + 1]
numbers_dict[v] = ... | e2b93828b5db7256b9a1e90e7e21adad1ce0b4de | 3,655,350 |
def not_after(cert):
"""
Gets the naive datetime of the certificates 'not_after' field.
This field denotes the last date in time which the given certificate
is valid.
:return: Datetime
"""
return cert.not_valid_after | 4f084146908d70af5c2cdfa5151f0c26533ac7fe | 3,655,351 |
from datetime import datetime
def parse_time_string(time_str: str) -> datetime.time:
"""Parses a string recognizable by TIME_REGEXP into a datetime.time object. If
the string has an invalid format, a ValueError is raised."""
match = TIME_REGEXP.match(time_str)
if match is None:
raise ValueErr... | 3238abcc6edb5a37c4a3d615b71e9dde6344f0ac | 3,655,352 |
def get_roc_curve(y_true, y_score, title=None, with_plot=True):
"""
Plot the [Receiver Operating Characteristic][roc] curve of the given
true labels and confidence scores.
[roc]: http://en.wikipedia.org/wiki/Receiver_operating_characteristic
"""
fpr, tpr, thresholds = sklearn.metrics.roc_curve(... | 7635af1705c6bdaccce1e1c5e99719645026d436 | 3,655,354 |
from datetime import datetime
def read_err_songs():
""" read song data from xml file to a list of dictionaries """
songfile = open('/home/gabe/python/selfishmusic/errors.xml')
soup = BS.BeautifulSoup(songfile.read())
songsxml = soup.findAll('song')
songs = []
for song in songsxml:
sd =... | 287c205c054045b3a88b74cf008e5a21037f9727 | 3,655,355 |
def word_value(word: str) -> int:
"""Returns the sum of the alphabetical positions of each letter in word."""
return (0 if word == '' else
word_value(word[:-1]) + alpha.letter_index_upper(word[-1])) | b964faa5a5792e003fb0859c1ffb0b25e63f6a75 | 3,655,356 |
def status():
"""
Returns json response of api status
Returns:
JSON: json object
"""
status = {
"status": "OK"
}
return jsonify(status) | d515e0628bb4c77ad83b0a26b758a3686663d329 | 3,655,357 |
def celcius_to_farenheit(x):
"""calculate celcius to farenheit"""
farenheit = (9*x/5) + 32
return farenheit | fa0041451c82b20283e4f20b501a6042ab19ec95 | 3,655,358 |
def CheckFlags(node_name, report_per_node, warnings, errors,
flags, warning_helper, error_helper):
"""Check the status flags in each node and bookkeep the results.
Args:
node_name: Short name of the node.
report_per_node: Structure to record warning/error messages per node.
Its type ... | 63bac7bfa4e3fa9c3cc462f5400d68116dfb898d | 3,655,359 |
def EnrollmentTransaction():
"""
:return:
"""
return b'\x20' | 05adff34b6cf100d95e16ab837b38b26b6315b6a | 3,655,360 |
def sentinel_id(vocabulary, return_value=None):
"""Token ID to use as a sentinel.
By default, we use the last token in the vocabulary.
Args:
vocabulary: a t5.data.vocabularies.Vocabulary
return_value: an optional integer
Returns:
an integer
"""
if return_value is not None:
return return_va... | 08ad1116b7f41ba7070359675a0133f14b9917bd | 3,655,361 |
from datetime import datetime
import urllib
import hmac
import hashlib
import base64
def create_signature(api_key, method, host, path, secret_key, get_params=None):
"""
创建签名
:param get_params: dict 使用GET方法时附带的额外参数(urlparams)
:return:
"""
sorted_params = [
("AccessKeyId", api_key),
... | 3e38bc883da9f5ebb311e1498f8cc73d1754c38b | 3,655,362 |
def measure_fwhm(image, plot=True, printout=True):
"""
Find the 2D FWHM of a background/continuum subtracted cutout image of a target.
The target should be centered and cropped in the cutout.
Use lcbg.utils.cutout for cropping targets.
FWHM is estimated using the sigmas from a 2D gaussian fit of the... | c2fdb3a10ffa575ffe6fdeb9e86a47ffaefea5c2 | 3,655,363 |
from .mappia_publisher import MappiaPublisherPlugin
def classFactory(iface): # pylint: disable=invalid-name
"""Load MappiaPublisher class from file MappiaPublisher.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
return MappiaPublisherPlugin() | 1802094cb49c01b0c9c5ed8b45d3c77bcd9b746a | 3,655,364 |
def mongo_insert_canary(mongo, db_name, coll_name, doc):
""" Inserts a canary document with 'j' True. Returns 0 if successful. """
LOGGER.info("Inserting canary document %s to DB %s Collection %s", doc, db_name, coll_name)
coll = mongo[db_name][coll_name].with_options(
write_concern=pymongo.write_co... | d82fe021db76972be19394688a07e9426bff82b7 | 3,655,365 |
from typing import Type
def is_dict_specifier(value):
# type: (object) -> bool
""" Check if value is a supported dictionary.
Check if a parameter of the task decorator is a dictionary that specifies
at least Type (and therefore can include things like Prefix, see binary
decorator test for some exa... | e18ad83a1b79a8150dfda1c65f4ab7e72cc8c8c8 | 3,655,366 |
def parse_star_count(stars_str):
"""Parse strings like 40.3k and get the no. of stars as a number"""
stars_str = stars_str.strip()
return int(float(stars_str[:-1]) * 1000) if stars_str[-1] == 'k' else int(stars_str) | d47177f26656e6dc33d708a0c4824ff677f3387a | 3,655,367 |
import shutil
def is_libreoffice_sdk_available() -> bool:
""" do we have idlc somewhere (we suppose it is made available in current path var.) ? """
return shutil.which("idlc") is not None | 83f8b158bcf97aa875280b20e177895432116d21 | 3,655,368 |
def set_metrics_file(filenames, metric_type):
"""Create metrics from data read from a file.
Args:
filenames (list of str):
Paths to files containing one json string per line (potentially base64
encoded)
metric_type (ts_mon.Metric): any class deriving from ts_mon.Metric.
For ex. ts_mon.Gau... | 372ec1fcb4b50711b35e40936e63839d75689dee | 3,655,369 |
def sortino_ratio_nb(returns, ann_factor, required_return_arr):
"""2-dim version of `sortino_ratio_1d_nb`.
`required_return_arr` should be an array of shape `returns.shape[1]`."""
result = np.empty(returns.shape[1], dtype=np.float_)
for col in range(returns.shape[1]):
result[col] = sortino_rati... | 2dfd6be1b7d3747c87484b22eb0cc0b0271c93a6 | 3,655,370 |
import re
def format_env_var(name: str, value: str) -> str:
"""
Formats environment variable value.
Formatter is chosen according to the kind of variable.
:param name: name of environment variable
:param value: value of environment variable
:return: string representation of value in appropria... | 030b16b897f2222d8465143b462f99ba344ba1eb | 3,655,371 |
from typing import Counter
def evenly_divisible(n):
""" Idea:
- Find factors of numbers 1 to n. Use DP to cache results bottom up.
- Amongst all factors, we have to include max counts of prime factors.
- For example, in in 1 .. 10, 2 has to be included 3 times since 8 = 2 ^ 3
"""
max_count... | 68301a33751c2f3863092450235ca5c24b28379e | 3,655,372 |
def do_open(user_input):
"""identical to io.open in PY3"""
try:
with open(user_input) as f:
return f.read()
except Exception:
return None | 72037207adecb2758c844c2f0c7233d834060111 | 3,655,374 |
def likely_solution(players):
""" Return tuples of cards with the
number of players who don't have them
"""
likely = likely_solution_nums(players)
return sorted([(ALLCARDS[n], ct) for n, ct in likely],
key=lambda tp: tp[1], reverse=True) | f0531f3188a38ec1b70ca48f95c9cfdc71d723b5 | 3,655,375 |
def cns_extended_inp(mtf_infile, pdb_outfile):
"""
Create CNS iput script (.inp) to create extended PDB file
from molecular topology file (.mtf)
Parameters
----------
mtf_infile : str
Path to .mtf topology file
pdb_outfile : str
Path where extended .pdb file will be stored
... | c850137db9a22fd48559228e3032bcd510c9d69b | 3,655,376 |
def index(request, response_format='html'):
"""Sales index page"""
query = Q(status__hidden=False)
if request.GET:
if 'status' in request.GET and request.GET['status']:
query = _get_filter_query(request.GET)
else:
query = query & _get_filter_query(request.GET)
or... | afb47a5c9094c9ff125c05c3588712d1875c69f3 | 3,655,377 |
def team_points_leaders(num_results=None, round_name=None):
"""Returns the team points leaders across all groups, as a dictionary profile__team__name
and points.
"""
size = team_normalize_size()
if size:
entries = score_mgr.team_points_leaders(round_name=round_name)
else:
entries... | 56b72b28f74f94e428b668b785b3dbd5b0c7c378 | 3,655,379 |
def with_color(text, color, bold=False):
"""
Return a ZSH color-formatted string.
Arguments
---------
text: str
text to be colored
color: str
ZSH color code
bold: bool
whether or not to make the text bold
Returns
-------
str
string with ZSH color... | 40c194d9de76ab504a25592cfb13407cb089da0a | 3,655,380 |
def sample_test():
"""Return sample test json."""
return get_sample_json("test.json") | 9d135d4fd2f7eb52d16ff96332811e4141139a12 | 3,655,381 |
import warnings
from io import StringIO
def dataframe_from_inp(inp_path, section, additional_cols=None, quote_replace=' ', **kwargs):
"""
create a dataframe from a section of an INP file
:param inp_path:
:param section:
:param additional_cols:
:param skip_headers:
:param quote_replace:
... | 8eaefdc08c7de3991f5a85cfe5001a6dcd0aaf7b | 3,655,382 |
def compositional_stratified_splitting(dataset, perc_train):
"""Given the dataset and the percentage of data you want to extract from it, method will
apply stratified sampling where X is the dataset and Y is are the category values for each datapoint.
In the case each structure contains 2 types of atoms, th... | b57a0b7d651e6f9be4182fec8c918438dcae9b7a | 3,655,383 |
def is_inside_line_segment(x, y, x0, y0, x1, y1):
"""Return True if the (x, y) lies inside the line segment defined by
(x0, y0) and (x1, y1)."""
# Create two vectors.
v0 = np.array([ x0-x, y0-y ]).reshape((2,1))
v1 = np.array([ x1-x, y1-y ]).reshape((2,1))
# Inner product.
prod = v0.transp... | b653c542d3d573857199d90257e9e36e6c45ccdc | 3,655,384 |
def transition_soil_carbon(area_final, carbon_final, depth_final,
transition_rate, year, area_initial,
carbon_initial, depth_initial):
"""This is the formula for calculating the transition of soil carbon
.. math:: (af * cf * df) - \
\\frac{1}{(1 ... | bfbf83f201eb8b8b0be0ec6a8722e850f6084e95 | 3,655,385 |
def _snr_approx(array, source_xy, fwhm, centery, centerx):
"""
array - frame convolved with top hat kernel
"""
sourcex, sourcey = source_xy
rad = dist(centery, centerx, sourcey, sourcex)
ind_aper = draw.circle(sourcey, sourcex, fwhm/2.)
# noise : STDDEV in convolved array of 1px wide annulus... | 6f055444163c03d0bcc61107db2045b968f06b52 | 3,655,388 |
def create_pipeline(training_set, validation_set, test_set):
"""
Create a pipeline for the training, validation and testing set
Parameters: training_set: Training data set
validation_set: Validation data set
test_set: Test data set
Returns: bat... | a6af6ff83180a0a11bfc3bacefd6a2e2261aaeed | 3,655,389 |
from typing import Tuple
from typing import Any
def invalid_request() -> Tuple[Any, int]:
"""Invalid request API response."""
return jsonify({API.Response.KEY_INFO: API.Response.VAL_INVALID_REQUEST}), 400 | 76a81f8c85014822f4fa306c917a06d92a89ea70 | 3,655,390 |
from pathlib import Path
from typing import List
from typing import Dict
from typing import Any
def _add_hyperparameters(
ranges_path: Path, defaults_path: Path
) -> List[Dict[str, Any]]:
"""Returns a list of hyperparameters in a format that is compatible with the json
reader of the ConfigSpace API.
... | 9609d3f31ffaee69148360966b1040f1970399b3 | 3,655,391 |
def setup(app):
"""Setup extension."""
app.add_domain(StuffDomain)
app.connect("builder-inited", generate_latex_preamble)
app.connect("config-inited", init_numfig_format)
app.add_css_file("stuff.css")
app.add_enumerable_node(
StuffNode,
"stuff",
html=(html_visit_stuff... | 3c7a5d36c835e7339876cdf88673d79e5f76b590 | 3,655,392 |
from pathlib import Path
import typing
def has_checksum(path: Path, csum: str,
csum_fun: typing.Optional[Checksum] = None) -> bool:
"""
:return: True if the file at the path `path` has given checksum
"""
return get_checksum(path, csum_fun=csum_fun) == csum | e9bed6e0d82745113412e6dace5869aa32aa4fc9 | 3,655,393 |
import numpy as np
def remove_outliers(column):
"""
:param column: list of numbers
:return:
"""
if len(column) < 1:
return []
clean_column = []
q1 = np.percentile(column, 25)
q3 = np.percentile(column, 75)
#k = 1.5
k = 2
# [Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)]
lowe... | 04c1e736e27ffeaef528f25fd303d0f27c3a94ac | 3,655,394 |
def read_photons(photonfile, ra0, dec0, tranges, radius, verbose=0,
colnames=['t', 'x', 'y', 'xa', 'ya', 'q', 'xi', 'eta', 'ra',
'dec', 'flags']):
"""
Read a photon list file and return a python dict() with the expected
format.
:param photonfile: Name of ... | c83958f8ae541e5df564c5ce53dd40593c9dfc3e | 3,655,396 |
def normElec(surf, electrode, normdist, NaN_as_zeros=True):
"""
Notes
-----
When `normway` is a scalar, it takes the normal of the points of the mesh which are closer
than `normway`. However, some points have a normal of (0, 0, 0) (default assigned
if the vertex does not belong to any triangle).... | d449f4518c589a2a68b64ca812d964cb6249694e | 3,655,397 |
def filter_sources(sources, release):
"""Check if a source has already been consumed. If has not then add it to
sources dict.
"""
source, version, dist, arch = parse_release(release)
if source not in sources.keys():
sources[source] = {version: {dist: [arch]}}
return True
elif ver... | 661d379291170a4994c0813d24820007e47bd092 | 3,655,398 |
from typing import Union
from typing import Dict
from typing import Any
async def train(model, *args: Union[BaseSource, Record, Dict[str, Any]]):
"""
Train a machine learning model.
Provide records to the model to train it. The model should be already
instantiated.
Parameters
----------
... | 9a8e1648247a8eb3c8354c324ac2c48a52617899 | 3,655,399 |
def setup_model_and_optimizer(args):
"""Setup model and optimizer."""
print ("setting up model...")
model = get_model(args)
print ("setting up optimizer...")
optimizer = get_optimizer(model, args)
print ("setting up lr scheduler...")
lr_scheduler = get_learning_rate_scheduler(optimizer, arg... | 9283ec825b55ff6619ac2ee2f7ac7cce9e4bced7 | 3,655,401 |
def ensure_str(origin, decode=None):
"""
Ensure is string, for display and completion.
Then add double quotes
Note: this method do not handle nil, make sure check (nil)
out of this method.
"""
if origin is None:
return None
if isinstance(origin, str):
return origi... | 0409bc75856b012cf3063d9ed2530c2d7d5bf3e4 | 3,655,402 |
from typing import Union
from typing import Dict
from typing import Any
from typing import Optional
def restore(
collection: str, id: Union[str, int, Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
"""Restrieve cached data from database.
:param collection: The collection to be retrieved. Same name as API ... | a0b2ccb995661b5c3286dee3b3f5f250cb728011 | 3,655,403 |
def encode_bits(data, number):
"""Turn bits into n bytes of modulation patterns"""
# 0000 00BA gets encoded as:
# 128 64 32 16 8 4 2 1
# 1 B B 0 1 A A 0
# i.e. a 0 is a short pulse, a 1 is a long pulse
#print("modulate_bits %s (%s)" % (ashex(data), str(number)))
shift = number-... | 0299a30c4835af81e97e518e116a51fa08006999 | 3,655,404 |
from typing import Tuple
def _tf_get_negs(
all_embed: "tf.Tensor", all_raw: "tf.Tensor", raw_pos: "tf.Tensor", num_neg: int
) -> Tuple["tf.Tensor", "tf.Tensor"]:
"""Get negative examples from given tensor."""
if len(raw_pos.shape) == 3:
batch_size = tf.shape(raw_pos)[0]
seq_length = tf.sh... | 9cef1cf3fc869108d400704f8cd90d432382ac2e | 3,655,406 |
def load_pdb(path):
"""
Loads all of the atomic positioning/type arrays from a pdb file.
The arrays can then be transformed into density (or "field") tensors before
being sent through the neural network.
Parameters:
path (str, required): The full path to the pdb file being voxelized.
... | aa7fe0f338119b03f00a2acb727608afcd5c1e0d | 3,655,409 |
def __filter_handler(query_set, model, params):
"""
Handle user-provided filtering requests.
Args:
query_set: SQLAlchemy query set to be filtered.
model: Data model from which given query set is generated.
params: User-provided filter params, with format {"query": [...], ...}.
... | c91b7d55795399f453106d0dda52e80a0c998075 | 3,655,411 |
def split_data_set(data_set, axis, value):
"""
按照给定特征划分数据集,筛选某个特征为指定特征值的数据
(然后因为是按该特征进行划分了,该特征在以后的划分中就不用再出现,所以把该特征在新的列表中移除)
:param data_set: 待划分的数据集,格式如下,每一行是一个list,list最后一个元素就是标签,其他元素是特征
:param axis: 划分数据集的特征(特征的序号)
:param value: 需要返回的特征的值(筛选特征的值要等于此值)
:return:
>>>myDat ... | f90fdffee3bbee4b4477e371a9ed43094051126a | 3,655,412 |
import ast
import six
import types
import inspect
import textwrap
def get_ast(target_func_or_module):
"""
See :func:``bettertimeit`` for acceptable types.
:returns: an AST for ``target_func_or_module``
"""
if isinstance(target_func_or_module, ast.AST):
return target_func_or_module
if... | 929a8f1b915850c25369edf0dcf0dc8bc2fe16e9 | 3,655,413 |
from typing import List
from re import T
from typing import Callable
from typing import Tuple
def enumerate_spans(sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]]... | 68df595e4fd55d2b36645660df6fa9198a8d28ef | 3,655,414 |
def fixed_mu(mu, data, qty, comp='muAI', beads_2_M=1):
"""
"""
return fixed_conc(mu*np.ones([len(data.keys())]), data, qty, comp=comp,
beads_2_M=beads_2_M) | f7241e8b1534d5d537a1817bce4f019e5a4081a7 | 3,655,415 |
def error_nrmse(y_true, y_pred, time_axis=0):
""" Computes the Normalized Root Mean Square Error (NRMSE).
The NRMSE index is computed separately on each channel.
Parameters
----------
y_true : np.array
Array of true values. If must be at least 2D.
y_pred : np.array
Array of pr... | 39461cdf0337c9d681d4247168ba32d7a1cbd364 | 3,655,416 |
import shutil
def rmdir_empty(f):
"""Returns a count of the number of directories it has deleted"""
if not f.is_dir():
return 0
removable = True
result = 0
for i in f.iterdir():
if i.is_dir():
result += rmdir_empty(i)
removable = removable and not i.exists()... | f2dba5bb7e87c395886574ca5f3844a8bab609d9 | 3,655,417 |
def generic_exception_json_response(code):
"""
Turns an unhandled exception into a JSON payload to respond to a service call
"""
payload = {
"error": "TechnicalException",
"message": "An unknown error occured",
"code": code
}
resp = make_response(jsonify(payload), co... | fc2f0edfc774a56e6b6ccfc8a746b37ad19f6536 | 3,655,418 |
def UnN(X, Z, N, sampling_type, kernel="prod"):
"""Computes block-wise complete U-statistic."""
def fun_block(x, z):
return Un(x, z, kernel=kernel)
return UN(X, Z, N, fun_block, sampling_type=sampling_type) | 962788706d3b4d71a0f213f925e89fd78f220791 | 3,655,419 |
def delete_card(request):
"""Delete card"""
return delete_container_element(request) | 128b521ed89077ebae019942147fc3b4af1a5cdf | 3,655,420 |
def get_plot_grid_size(num_plots, fewer_rows=True):
"""
Returns the number of rows and columns ideal for visualizing multiple (identical) plots within a single figure
Parameters
----------
num_plots : uint
Number of identical subplots within a figure
fewer_rows : bool, optional. Default... | e83f14db347cd679e9e7b0761d928cd563444712 | 3,655,422 |
def check_source(module):
"""
Check that module doesn't have any globals.
Example::
def test_no_global(self):
result, line = check_source(self.module)
self.assertTrue(result, "Make sure no code is outside functions.\\nRow: " + line)
"""
try:
source = module.__... | 6bc012892d6ec7bb6788f20a565acac0f6d1c662 | 3,655,423 |
def pre_processing(X):
""" Center and sphere data."""
eps = 1e-18
n = X.shape[0]
cX = X - np.mean(X, axis=0) # centering
cov_mat = 1.0/n * np.dot(cX.T, cX)
eigvals, eigvecs = eigh(cov_mat)
D = np.diag(1./np.sqrt(eigvals+eps))
W = np.dot(np.dot(eigvecs, D), eigvecs.T) # whitening matrix
... | 802ce958c6616dcf03de5842249be8480e6a5a7c | 3,655,424 |
def get_as_tags(bundle_name, extension=None, config="DEFAULT", attrs=""):
"""
Get a list of formatted <script> & <link> tags for the assets in the
named bundle.
:param bundle_name: The name of the bundle
:param extension: (optional) filter by extension, eg. "js" or "css"
:param config: (optiona... | ec54184ff2b13bd4f37de8395276685191535948 | 3,655,425 |
def devpiserver_get_credentials(request):
"""Search request for X-Remote-User header.
Returns a tuple with (X-Remote-User, '') if credentials could be
extracted, or None if no credentials were found.
The first plugin to return credentials is used, the order of plugin
calls is undefined.
"""
... | bc6ccaa52b719c25d14784c758d6b78efeae104d | 3,655,427 |
def vader_sentiment(
full_dataframe,
grading_column_name,
vader_columns=COLUMN_NAMES,
logger=config.LOGGER
):
"""apply vader_sentiment analysis to dataframe
Args:
full_dataframe (:obj:`pandas.DataFrame`): parent dataframe to apply analysis to
grading_column_name ... | 43572857ecc382f800b243ee12e6f3fe3b1f5d5a | 3,655,428 |
def _overlayPoints(points1, points2):
"""Given two sets of points, determine the translation and rotation that matches them as closely as possible.
Parameters
----------
points1 (numpy array of simtk.unit.Quantity with units compatible with distance) - reference set of coordinates
points2 (numpy ar... | c3d1df9569705bcee33e112596e8ab2a332e947e | 3,655,429 |
def return_request(data):
"""
Arguments:
data
Return if call detect: list[dist1, dist2, ...]:
dist = {
"feature": feature
}
Return if call extract: list[dist1, dist2, ...]:
dist = {
"confidence_score": predict p... | 11887921c89a846ee89bc3cbb79fb385382262fa | 3,655,430 |
def get_recent_messages_simple(e: TextMessageEventObject):
"""
Command to get the most recent messages with default count.
This command has a cooldown of ``Bot.RecentActivity.CooldownSeconds`` seconds.
This command will get the most recent ``Bot.RecentActivity.DefaultLimitCountDirect`` messages withou... | 58d03a4b34254dc532ad6aa53747ea730446cd31 | 3,655,431 |
def parse_systemctl_units(stdout:str, stderr:str, exitcode:int) -> dict:
"""
UNIT LOAD ACTIVE SUB DESCRIPTION
mono-xsp4.service loaded active... | d9e7e4c71f418311799345c7dacfb9655912475f | 3,655,432 |
def resnet_model_fn(is_training, feature, label, data_format, params):
"""Build computation tower (Resnet).
Args:
is_training: true if is training graph.
feature: a Tensor.
label: a Tensor.
data_format: channels_last (NHWC) or channels_first (NCHW).
params: params for the model to... | 70f30b4c5b4485ed1c4f362cc7b383cb192c57c4 | 3,655,433 |
def permutate_touched_latent_class(untouched_classes, class_info_np, gran_lvl_info):
"""untouch certain class num latent class, permute the rest (reserve H(Y))"""
# get untouched instance index
untouched_instance_index = []
for i in untouched_classes:
index = np.where(class_info_np == i)[0]
... | ebae2213508260474a9e9c581f6b42fd81006a22 | 3,655,434 |
from datetime import datetime
import pytz
def get_interarrival_times(arrival_times, period_start):
"""
Given a list of report dates, it returns the list corresponding to the interrival times.
:param arrival_times: List of arrival times.
:return: List of inter-arrival times.
"""
interarrival_ti... | b6d345ff73e16d8c7502509ddd36e2a1d7f12252 | 3,655,435 |
def _indexOp(opname):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def wrapper(self, other):
func = getattr(self.view(np.ndarray), opname)
return func(other)
return wrapper | a9bdccca9d0bc1ffa2334132c6cfd4b965b95878 | 3,655,436 |
def safe_log(a):
"""
Return the element-wise log of an array, checking for negative
array elements and avoiding divide-by-zero errors.
"""
if np.any([a < 0]):
raise ValueError('array contains negative components')
return np.log(a + 1e-12) | 7ac5f01272f4c90110c4949aba8dfb9f783c82b9 | 3,655,437 |
def make_batch_keys(args, extras=None):
"""depending on the args, different data are used by the listener."""
batch_keys = ['objects', 'tokens', 'target_pos'] # all models use these
if extras is not None:
batch_keys += extras
if args.obj_cls_alpha > 0:
batch_keys.append('class_labels')... | a86c2a5cff58f811a67cbdd5eed322c86aa3e0e0 | 3,655,441 |
from typing import List
def magic_split(value: str, sep=",", open="(<", close=")>"):
"""Split the value according to the given separator, but keeps together elements
within the given separator. Useful to split C++ signature function since type names
can contain special characters...
Examples:
... | 9f152c9cfa82778dcf5277e3342b5cab25818a55 | 3,655,443 |
def update_group_annotation(name=None, annotation_name=None, x_pos=None, y_pos=None, angle=None, opacity=None,
canvas=None, z_order=None, network=None, base_url=DEFAULT_BASE_URL):
"""Update Group Annotation
Updates a group annotation, changing the given properties.
Args:
... | fd515728ee3a3dece381bb65e2c6816b9c96b41e | 3,655,444 |
import urllib
def _extract_properties(properties_str):
"""Return a dictionary of properties from a string in the format
${key1}={value1}&${key2}={value2}...&${keyn}={valuen}
"""
d = {}
kv_pairs = properties_str.split("&")
for entry in kv_pairs:
pair = entry.split("=")
key = ur... | 4f22cae8cbc2dd5b73e6498d5f8e6d10e184f91c | 3,655,445 |
from typing import Any
def first_fail_second_succeed(_: Any, context: Any) -> str:
""" Simulate Etherscan saying for the first time 'wait', but for the second time 'success'. """
context.status_code = 200
try:
if first_fail_second_succeed.called: # type: ignore
return '{ "status": "1"... | 5feb3188bdee2d0d758584709df13dc876c37391 | 3,655,446 |
def get_ipsw_url(device, ios_version, build):
"""Get URL of IPSW by specifying device and iOS version."""
json_data = fw_utils.get_json_data(device, "ipsw")
if build is None:
build = fw_utils.get_build_id(json_data, ios_version, "ipsw")
fw_url = fw_utils.get_firmware_url(json_data, build)
... | 75b9d85d93b03b1ebda681aeb51ac1c9b0a30474 | 3,655,447 |
from typing import Any
def escape_parameter(value: Any) -> str:
"""
Escape a query parameter.
"""
if value == "*":
return value
if isinstance(value, str):
value = value.replace("'", "''")
return f"'{value}'"
if isinstance(value, bytes):
value = value.decode("utf... | 00b706681b002a3226874f04e74acbb67d54d12e | 3,655,448 |
def Get_Query(Fq):
""" Get_Query
"""
Q = ""
EoF = False
Ok = False
while True:
l = Fq.readline()
if ("--" in l) :
# skip line
continue
elif l=="":
EoF=True
break
else:
Q += l
if ";" in ... | a1850799f7c35e13a5b61ba8ebbed5d49afc08df | 3,655,449 |
def get_path_segments(url):
"""
Return a list of path segments from a `url` string. This list may be empty.
"""
path = unquote_plus(urlparse(url).path)
segments = [seg for seg in path.split("/") if seg]
if len(segments) <= 1:
segments = []
return segments | fe8daff2269d617516a22f7a2fddc54bd76c5025 | 3,655,450 |
import typing
from pathlib import Path
def get_config_file(c: typing.Union[str, ConfigFile, None]) -> typing.Optional[ConfigFile]:
"""
Checks if the given argument is a file or a configFile and returns a loaded configFile else returns None
"""
if c is None:
# See if there's a config file in th... | 6e176167a81bccaa0e0f4570c918fcb32a406edb | 3,655,451 |
def get_index():
"""Redirects the index to /form """
return redirect("/form") | e52323397156a5a112e1d6b5d619136ad0fea3f0 | 3,655,453 |
def _register_network(network_id: str, chain_name: str):
"""Register a network.
"""
network = factory.create_network(network_id, chain_name)
cache.infra.set_network(network)
# Inform.
utils.log(f"registered {network.name_raw} - metadata")
return network | 8e9b84670057974a724df1387f4a8cf9fc886a56 | 3,655,454 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.