content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def calculate_displacement(src_grammar, tgt_grammar):
"""Calculate displacement between 2 grammar. E.g: S -> A B C to S -> B C A has displacement of [1 2 0]"""
src_grammar_lst = src_grammar.split()
tgt_grammar_lst = tgt_grammar.split()
src_grammar_lst = src_grammar_lst[src_grammar_lst.index("->")+1... | 0d14b5757d26c2b8398fe6ecbd94f53d0df70375 | 48,300 |
def create_confusion_matrix(actual, predicted, category):
"""
Calculates the confusion matrix for a give category.
:param actual: The actual labels of the data
:param predicted: The predicted labels of the data
:param category: The category we of the confusion matrix
:return: dictionary, with th... | 34ae6608a2d0293e651a627a21220ec70a54004f | 48,301 |
def GetUnionSelectorTypes(union_type):
"""Returns a list of all acceptable selector types for a given union."""
return _SELECTORS[union_type]['type'] | 91e3d876b9073bd5b6f347fcbd61929337b66d70 | 48,302 |
def efficientnet_b6(
num_classes: int = 1000,
class_type: str = "single",
dropout: float = 0.5,
se_mod: bool = False,
) -> EfficientNet:
"""
EfficientNet B6 implementation; expected input shape is (B, 3, 528, 528)
:param num_classes: the number of classes to classify
:param class_type: ... | 948717d708430d7be33de2a4da1c09fb619b2c5b | 48,303 |
def _save_lidar(file_list, output_file, location, keep_uuid):
"""Saves the Raman Lidar netcdf-file."""
anker = 0
file_data = {key: var for key, var in file_list[anker].data.items()}
file_data['time'].data = np.ma.concatenate([file_list[i].data['time'].data for i in range(len(file_list))])
# becaus... | cdef2f7b6b2bd79c55582a58d8aee155a79c5ce7 | 48,304 |
import traceback
def load_test_config_file(test_config_path, tb_filters=None):
"""Processes the test configuration file provied by user.
Loads the configuration file into a json object, unpacks each testbed
config into its own json object, and validate the configuration in the
process.
Args:
... | bfb2022734a6eb21dd4d3b44dd3131d533612283 | 48,305 |
import tqdm
def spectrogram(signal, sampling_rate, window, step, plot=False,
show_progress=False):
"""
Short-term FFT mag for spectogram estimation:
Returns:
a np array (numOfShortTermWindows x num_fft)
ARGUMENTS:
signal: the input signal samples
samplin... | 2a4bc4a2698275a4441de1fe8aa12db2effcf2ce | 48,306 |
def remove_spikes(data,threshold=None,window=12):
"""remove everything that deviates more than 500kPa from the median of a detrended 1-hour (12 points) window"""
# note that trends of 100kPa/hour are absolutely realistic
# so anything that departs by more than 500kPa from the trend should
# be pre... | 01620e4ef91401ac562c8748a311c015a4bbadcd | 48,307 |
from typing import Sequence
from typing import Union
from typing import Dict
from typing import Any
import typing
def SelectMultiple(
description: str = "",
description_tooltip: str = None,
disabled: bool = False,
index: Sequence[int] = (),
label: Sequence[str] = (),
layout: Union[Dict[str, An... | 17eb86f670069a9a5005a283bf5adf4d413c6ea7 | 48,308 |
import time
def clock(func):
"""
定义装饰器decorator,除了实现原函数功能外,额外提供计时功能
装饰器就是一个函数,它接收函数(原函数),返回函数(新函数)
:param func: 被装饰的函数
:return: 装饰后的函数
"""
def decorator():
t0 = time.perf_counter()
result = func()
elapsed = time.perf_counter() - t0
print("elapsed: ... | 540250a4dfef4c385f208b834e3fea623a00db71 | 48,309 |
def all_acc(y_true, y_pred):
"""
All Accuracy
https://github.com/rasmusbergpalm/normalization/blob/master/train.py#L10
"""
return K.mean(
K.all(
K.equal(
K.max(y_true, axis=-1),
K.cast(K.argmax(y_pred, axis=-1), K.floatx())
),
... | f707ac258d21bb789bc0c4b8e792b8e42ba03e6f | 48,310 |
import json
import subprocess
def main(**kwargs):
"""
Draw a couple of simple graphs and optionally generate an HTML file to upload them
"""
draw_lines()
draw_histogram()
draw_bar_chart()
destination = "-r /report"
if use_html:
generate_html()
command = "dx-build-report... | 208fec7ade0d9113eabe8e00d0704e235874bbd2 | 48,311 |
def generate_identifier(signingkey):
"""Generates encoded version of the public key associated with
signingkey.
Args:
signingkey (str): A private key.
Returns:
str: An encoded 'address' associated with the public key.
"""
return pybitcointools.pubtoaddr(pybitcointools.privtopub... | 6c8311aee007d2732447f27b30b2cc628709bec9 | 48,312 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Mad libs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('positional',
help='Input file',
metavar=... | 9e70e337e4b6a2d97a2f3a67267474f543364856 | 48,313 |
def get_page(paginated_list):
"""
Take a github.PaginatedList.PaginatedList and then iterate through the
pages to get all of its entries
Args:
paginated_list (github.PaginatedList.PaginatedList): PyGithub paginated
list object
Returns:
`list`: All entries in the paginated ... | 0510537b20c18b6b1be5b10ca014e13be7a19a1f | 48,314 |
def acnt2(chain: pv.Chain, wallet: pv.Wallet) -> pv.Account:
"""
acnt2 is the fixture that returns the account of nonce 2.
Args:
chain (pv.Chain): The Chain object.
wallet (pv.Wallet): The wallet object.
Returns:
pv.Account: The account.
"""
return wallet.get_account(ch... | 3156dc4a140f6130682675a92d649d1f5d41d646 | 48,315 |
def _get_acc_data():
""" Датасет для графика акселерометра """
time = now()
datax, datay, dataz = [_get_data_abstract("IMU", x, time) for x in ("xacc", "yacc", "zacc")]
for x, y, z in zip(datax, datay, dataz):
x["y"] /= 1000.0
y["y"] /= 1000.0
z["y"] /= 1000.0
latestUpdateT... | 6c7fbf18bb5992f255a568af15268463d5ed893d | 48,316 |
def git_ref(check=True):
"""
return name for current branch / tag
If `check` is True, the execution end if git root not found.
Otherwise `None` is returned.
"""
branch = _exec("git rev-parse --abbrev-ref HEAD".split(), check)
if branch != "HEAD":
return branch
tag_ref = _exec("g... | 6c4ac95859785404ced853739187bd7da4ebac83 | 48,317 |
def get_metadata_from_asset_name(asset_name: str) -> dict:
"""Get metadata for given asset"""
url = f"{POOL_PM_URL}/asset/{POLICY_ID}.{asset_name}"
response = get_request(url, headers=None)
return response.get("metadata") | 37068d9f3b021dc5c66ef9aa6e6ad13135bb010d | 48,318 |
from pathlib import Path
import os
def save(upload_file, filename, email):
"""
Upload input file (photo) to specific path for individual user.
Save original file and thumbnail file.
:param upload_file: file object
:param filename: secure filename for upload
:param email: user email address
... | 750eab67e6f8a58a6e829ea59f059c77c3167463 | 48,319 |
import tempfile
import sys
def run_gen_srcs(files):
"""
Runs test tools only for interesting files that were changed in this commit.
"""
if len(files) == 0:
return
success = 0 # exit code 0 = success, >0 error.
had_diffs = False
for tool_dict in TOOLS_GEN_SRCS:
tool_ran_at_least_once = False
... | 159a74386c25971be62c0ec66da92139f005fd49 | 48,320 |
import math
def prime(n):
"""Primality test by trial division."""
if n == 2:
return True
elif n < 2 or n % 2 == 0:
return False
else:
return not any(n % x == 0
for x in range(3, math.ceil(math.sqrt(n)) + 1, 2)) | 3504217a7e8149867ec16ddf9c54f4fac736d592 | 48,321 |
import operator
import time
import functools
import asyncio
def rate_monadic_arg(max_rate_hz=30, monad_init="", monad_op=operator.concat):
"""TODO : description + doctest"""
def decorator(coro):
last_call = time.time()
last_arg = monad_init
last_handle = None
@functools.wraps(... | 8ea73f847e653b98692738a07bbcb3422f0ae323 | 48,322 |
def is_sukun(archar):
"""Checks for Arabic Sukun Mark.
@param archar: arabic unicode char
@type archar: unicode
@return:
@rtype:Boolean
"""
return archar == SUKUN | 3ccedfb4b73c7d80bf24e0c9b8d04c6309eb9a29 | 48,323 |
def radio_util(
data # type: "XDR Data"
):
"""Radio Utilization Counter - Type: Counter, Enterprise: 0, Format: 1002"""
sample_data = {} # Cache
sample_data["Elapsed Time Milliseconds"] = int(data.unpack_uint())
sample_data["On Channel Time Milliseconds"] = int(data.unpack_uint())
sample_data["On Channel Busy Ti... | 5e5c90ca511db1babda427ea7218375542f77bce | 48,324 |
import re
from typing import OrderedDict
def getNames(xml):
"""
get person, organization and place tags from PageXML.
"""
content = re.sub("<\?xml version.*?>", "", xml)
try:
root = et.fromstring(content)
except Exception as e:
print(e)
return {"XMLERROR":"XMLERROR"}
... | 5a0ba6ba9b3ec6c303adc1d27680e01dadecd64c | 48,325 |
def get_xls(es_result, column_mapping):
"""
Creates a stream with the Excel file, the column headers, and the result rows
:param es_result: The result of the ElasticSearch search
:param column_mapping (dict): A dict mapping the column names in the original data, to the desired column headers
for th... | 8caa799586ef910818338f0e0e7300df267dbdd0 | 48,326 |
def average(numbers):
"""
:param list[float] numbers: a list of numbers
:returns: the average of the given number sequence. an empty list returns 0.
:rtype: float
"""
return float(sum(numbers)) / max(len(numbers), 1) | d86c6f24733d3032b82cb6c64c02eba37cc34a04 | 48,327 |
import six
def _IsIdentityTypeMapping(type_mappings):
"""\
An identity type mapping is a special case where each of the input types
matches the output type.
"""
for input_type, output_types in six.iteritems(type_mappings):
if output_types != [input_type]:
return False
ret... | 27f13266dc23c5d4bd78a27c240664208d4f8c8f | 48,328 |
def inv_rotate(vec: Vector3, quat: Quaternion):
"""Rotates a vector by the inverse of a unit quaternion.
Args:
vec: (3,) a vector
quat: (4,) a quaternion
Returns:
A vector rotated by quat^{-1}
"""
return rotate(vec, quat_inv(quat)) | f77e301b5feff76bf73850189c48a14c00d61339 | 48,329 |
def play_manche_joueur():
"""
cette fonction propose au joueur de jouier une manche si il fauit 1 , son score est annulé et la fonction retourne -1
Returns:
le total de la cagnote
"""
cagnote=0
if input("voulez vous lancer un dé ? (y pour relancer, ou anykey pour arréter)\n")=="y":
... | 0c0bc49093ba8d602e6617f10d616ad3f290d14f | 48,330 |
def crossProduct(u, v):
"""
Calculates the cross product of two 3d vectors (as 1-d arrays).
"""
return np.cross(u, v) | e6da5b203f6617a7400f9b3f327434f70ca3f686 | 48,331 |
def vgg13_bn(backbone='vgg13_bn', pretrained=False, **kwargs):
"""VGG 13-layer model (configuration "B") with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
kwargs['cfg_key'] = 'B'
kwargs['batch_norm'] = True
kwargs['backbone'] = "vgg13... | a56f6b5d4899c1f6eb02c12d92ad4e2f57228c5d | 48,332 |
from operator import sub
def get_resource_type_by_url(url: str):
"""Get the resource type definition from a resource URL."""
url_parts = urlparse(url)
url_path = url_parts.path
resource_type = sub(r'/(core|rest|identity|auth|product-metadata)/v\d+/([^/]+)/?.*', r'\2', url_path)
if resource_type ==... | 9f525eb5f841d61db29d2ec2413cfa687c2c6287 | 48,333 |
def general_pool_fn(x):
"""
x[0]: function to call
x[1] to x[n]: arguments of the function
"""
return x[0](*x[1:]) | d398378d3d1671f0e58bff2bc8737ff07da0c3e3 | 48,334 |
def getfullname(val):
"""Get the module-qualified name of type or function val."""
return (val.__module__ or '<UNKNOWN_MODULE>') + '.' + getqualname(val) | 3f8e9570219d5dcae45313e5bc530f8892b33a34 | 48,335 |
def dt_hms(d, n=3):
"""
Allow negative times
"""
try:
sign = '+' if d > 0. else '-'
x = abs(d)
h = int(x)
x = (x-h) * 60.
m = int(x)
s = (x-m) * 60.
w = n + 3
return f"{sign}{h:02d}h {m:02d}m {s:0{w}.{n}f}s"
except:
return None | 30c04b23ba304a1d8dffcdbe38035bdde24b1848 | 48,336 |
import scipy
def fmt(y, t_min=0.5, n_fmt=None, kind='cubic', beta=0.5, over_sample=1, axis=-1):
"""The fast Mellin transform (FMT) [1]_ of a uniformly sampled signal y.
When the Mellin parameter (beta) is 1/2, it is also known as the scale transform [2]_.
The scale transform can be useful for audio analy... | b2f97f7d51a13b5fd0b241d001c1fb13e6c6c974 | 48,337 |
def get_file_contents(repo_path, file_path):
"""
Given an absolute file path, return the text contents of that file
as a string.
"""
binary = get_file_contents_binary(repo_path, file_path)
try:
return binary.decode('utf-8')
except UnicodeDecodeError:
return binary.decode('lat... | b6d622724c1bb6675eb0c5ec43093d1bfca4bfbe | 48,338 |
import torch
def generate_param(n_dimensions: int):
"""Simulation of model's parameters"""
nnz = 20
idx = np.arange(n_dimensions)
W = torch.FloatTensor((-1) ** (idx + 1) * np.exp(-idx / 10.)).to(dtype=torch.float64)
W[nnz:] = 0.
return W | d1fd5f13d65de1368e7ccede89028ec46687c505 | 48,339 |
def cleanDf(df, badaa=None):
"""Remove all invalid sequences (containing badaa) from
the alignment
badaa is '-*BX#Z' by default"""
return df.loc[[isvalidpeptide(s, badaa) for s in df.seq]] | 73f485630828ed555502a8e810d3662ffe7512a8 | 48,340 |
def check_ac_holder_match(holder_cert: x509.Certificate, holder: cms.Holder):
"""
Match a candidate holder certificate against the holder entry of an
attribute certificate.
:param holder_cert:
Candidate holder certificate.
:param holder:
Holder value to match against.
:return:
... | 7e3f6b58c647c236cb1bb7617c9e2a34c42661e5 | 48,341 |
def minify_css(s):
"""
Minify CSS code.
@param s: css to minify
@type s: L{str}
@return: the minfied css
@rtype: L{str}
"""
if csscompressor is None:
raise NotImplementedError("Dependency 'csscompressor' required, but not found!")
return csscompressor.compress(
s... | 82f78b63418c51b58b7e392db54d0d471de15fc3 | 48,342 |
def cumsum(a, axis=None, dtype=None, out=None):
"""Returns the cumulative sum of an array along a given axis.
Args:
a (clpy.ndarray): Input array.
axis (int): Axis along which the cumulative sum is taken. If it is not
specified, the input is flattened.
dtype: Data type specifier... | 145fd87072a7a196fb609b9d0d57e2321f0eab10 | 48,343 |
import math
async def async_api_adjust_volume(hass, config, directive, context):
"""Process an adjust volume request."""
volume_delta = int(directive.payload["volume"])
entity = directive.entity
current_level = entity.attributes.get(media_player.const.ATTR_MEDIA_VOLUME_LEVEL)
# read current stat... | c71a67450860181799e9fac56379443b5df9fef2 | 48,344 |
import random
def random_database():
"""
Creates a random database in the testing Postgres instance and returns the
name of the database.
"""
# Setup connection with default credentials for testing.
with connect(dbname='holo', user='holocleanuser', password='abcd1234', host='localhost') as con... | 1fdf929d2531a00e92a3b6801edea5d57cb8d622 | 48,345 |
def fscore(target_mat, decision_mat, beta=1., event_wise=False):
"""
Args:
target_mat: n_hot matrix indicating ground truth events/labels
(num_frames times num_labels)
decision_mat: n_hot matrix indicating detected events/labels
(num_frames times num_labels)
even... | 5bfc11a38d766797cbf5b93aa09b3dca31793f80 | 48,346 |
def _EraseTombstone(device, tombstone_file):
"""Deletes a tombstone from the device.
Args:
device: An instance of DeviceUtils.
tombstone_file: the tombstone to delete.
"""
return device.RunShellCommand(
'rm /data/tombstones/' + tombstone_file, root=True) | 00e6f316062785d7465f501ea743a2dc94864aef | 48,347 |
def graphite_electrolyte_reaction_rate_Kim2011(T, T_inf, E_r, R_g):
"""
Reaction rate for Butler-Volmer reactions between graphite and LiPF6 in EC:DMC
[1].
References
----------
.. [1] Kim, G. H., Smith, K., Lee, K. J., Santhanagopalan, S., & Pesaran, A.
(2011). Multi-domain modeling of lit... | 15efdc98d2f4b63b2d9482c404f465ec5bd52194 | 48,348 |
def initialize_node_details(storage_gui_ip, user, key_file):
""" Initialize node details for cluster definition.
:args: storage_gui_ip (str), user (string), key_file (string)
"""
node_details, node = [], {}
node = {'ip_addr': storage_gui_ip, 'is_quorum': True, 'is_manager': True,
'is_gui... | cb3c82a5c0e9c418fac88f61473b44a60c0d7c12 | 48,349 |
def do_filter(parser, input_list):
"""
Filter flavor by applying parser on the flavor list
:param input_list: list of input data in JSON format
:param parser: jsonpath parser
:return: list of matched flavors in JSON
"""
return [match.value for match in parser.find(input_list)] | 9a5efe4e80a6fdf3afb0cff9616e4c480de8e26d | 48,350 |
import argparse
import typing
def run(
args, _parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser
) -> typing.Optional[int]:
"""Run ``cubi-tk snappy pull-sheet``."""
res: typing.Optional[int] = check_args(args)
if res: # pragma: nocover
return res
logger.info("Starting t... | f488594d915ebc96e98c9d7970010c4fd942f619 | 48,351 |
def module(script_in):
"""Decorate a python function or class as tvm script.
Alias for tvm.script.tir for now.
Returns
-------
output : Union[Function, Module]
The Function or Module in IR.
"""
return tir(script_in) | c9857bdc4a444090928a17f18b980eb03f73c99c | 48,352 |
def shorten_class(class_name: str) -> str:
"""Returns a shortened version of the fully qualilied class name."""
return class_name.replace('org.chromium.',
'.').replace('chrome.browser.', 'c.b.') | 2064e6e0dc159bc130f84ce4a830857455d12ba4 | 48,353 |
from typing import List
def get_words(content: str) -> List[str]:
"""
文字列内に出現する名詞のリスト(重複含む)を取得する関数。
"""
words = [] # 出現した名詞を格納するリスト。
node = tagger.parseToNode(content)
while node:
# node.featureはカンマで区切られた文字列なので、split()で分割して
# 最初の2項目をposとpos_sub1に代入する。posはPart of Speech(品詞)の略... | cc05e06cef47fc3cce4b1ce79c4fd8d0a755cd59 | 48,354 |
def get_hourly_avg(station_num):
"""Returns daily average data for REST API response providing JSON file with data for charts"""
# MySQL query to get average hourly availability for a given station
sql = """SELECT DAYNAME(update_time) AS day, ROUND(AVG(bikes_available)) AS available
FROM bikesdata.... | b9dc28a9033b3e14823303c9637c80c1ff49829e | 48,355 |
import json
def create_initial_parameters(instances, Ns):
"""
Create a list of initial parameters for spectra loaded from task instances.
:param instances:
A list of task instances where spectra were loaded. This should
be length `N` long.
:param Ns:
A list containing the... | 078ecf7ecc6c140d6fe2cb68cac28dca98526b56 | 48,356 |
def load_snps_by_region(chrom, start, end):
"""Retrieve snp information by region"""
index = _get_index_from_chr(chrom)
search_snps = Search().using(es).doc_type('snps').index(index).filter("range", position={"lte": end, "gte":start})
return {snp.position: snp.to_dict() for snp in search_snps.scan() } | e512eade4e5ca6cc8358306e4843258297566eef | 48,357 |
def weight_function(run_params, displacement_norm):
"""Determine motion-dependent prediction weight of given supporter point.
This method determines the weight to apply to each supporter point when
using it for prediction of a target point based on the norm of its
displacement vector. The larger the di... | 2fdea32511ae8b4cedd47e79d7f8517a08a6b457 | 48,358 |
def _read_cp1251_file(fname):
"""
Returns:
Возвращает список и ответ на вопрос - угадали ли мы кодировку?
"""
this_is_it = True
sets = iow.get_utf8_template()
sets['coding'] = 'cp1251'
sets['name'] = fname
# Если не та кодировка - возвращает пустой список
readed_list =... | 55834a71a4607a6f9bf6fc9f8216e6d17eef6bbd | 48,359 |
def mixed_grad_color2gray(rgb_image):
"""EC: Convert an RGB image to gray image using mixed gradients."""
img = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV)
s = img[:, :, 1].reshape((img.shape[0], img.shape[1], 1)) / 255.
v = img[:, :, 2].reshape((img.shape[0], img.shape[1], 1)) / 255.
mask = np.ones_... | f8aefe4c836377f87b6d8ce0c4784da0c4115490 | 48,360 |
def PReadRec (inHis, recno, err):
"""
Read History record
returns string
* inHis = input Python History
* recno = desired record
* err = Python Obit Error/message stack
"""
################################################################
# Checks
if not PIsA(inHi... | e315f91fa46b8ed99071f681dc490630c256c04a | 48,361 |
def remove_leading_garbage_lines_from_reference_section(ref_sectn):
"""Sometimes, the first lines of the extracted references are completely
blank or email addresses. These must be removed as they are not
references.
@param ref_sectn: (list) of strings - the reference section lines
@retu... | 09dc153b064cd8fcf613520ef432e51350928307 | 48,362 |
def ensure_csrf_cookie_cross_domain(func):
"""View decorator for sending a cross-domain CSRF cookie.
This works like Django's `@ensure_csrf_cookie`, but
will also set an additional CSRF cookie for use
cross-domain.
Arguments:
func (function): The view function to decorate.
"""
def... | ecdeae3ebff37976c841887083c53f088f2b8b34 | 48,363 |
def _algorithm_kwargs(request):
"""Auto-parametrizes `_rl_algorithm_cls` for the `trainer` fixture."""
return dict(request.param) | fddb2a376449973f49d5a27cef04b3596e9cc3dd | 48,364 |
from typing import Dict
def convert_tsv_entries_to_dataframe(tsv_dict: Dict, header: str) -> pd.DataFrame:
"""
Converts entries from TSV file to Pandas DataFrame for faster processing.
"""
header_fields = header.strip().split("\t")
data = {header: [] for header in header_fields}
for line in tsv_dict.valu... | 2fbbb125f5dfa8bad2efabc420295f0925d9786e | 48,365 |
def decode_and_upload_base64_file(data, file_name):
""" Function to decode base64 files
Parameters
----------
date : str
string of user inputted graduation date.
Returns
-------
string
string of graduation date only with Month and Year.
"... | 3503ad48de0aa1278c859cd096e735e114eed9c3 | 48,366 |
def calc_sthovl_by_hkl_abc_cosines(
h: float, k: float, l: float, a: float, b: float, c: float,
cos_alpha: float, cos_beta: float, cos_gamma: float):
"""
Calculate sin(theta)/lambda for given reflections h, k, l
and unit cell parameters defined as a, b, c, cos(alpha), cos(beta), cos(gamma).
... | a5b8d01b970fdd5fd09a8b157b925952987a14d7 | 48,367 |
def RE2Str(RE):
"""Helper for del_gnfa_states
---
Given an RE as a tree, return the string equivalent of the RE.
"""
if type(RE) == str:
if (RE == ""):
return '""' # was return '@', but now no more '@'
else:
return RE
elif type(RE) == tuple:
... | 966d4dc06e597518ab7306ea3f5c970cf4534efa | 48,368 |
import json
def list_observations(model):
"""Return a JSON list of observations"""
obs = model.get_observations()
response.content_type = "application/json"
return json.dumps(obs) | a82f1148ee72d5690a7488b26f2030da8cd85911 | 48,369 |
def add_api_config_to_queries(generated_query_strings, search_engines):
"""
Merges the two parameters and returns a list of dicts that include the
api config.
If only 1 API key is provided, it is assumed this is valid for many searches and is used for all queries
If more than 1 is p... | 209b14e98c2cb339f958fc7dfe456a4a40876c8c | 48,370 |
def _get_first_model(structure: PdbStructure) -> PdbStructure:
"""Returns the first model in a Biopython structure."""
return next(structure.get_models()) | fb3431655ef7f83aa50931f96696ffe296bb6501 | 48,371 |
def createDiffLineCV(video, cropx1, cropx2, cropy1, cropy2):
"""
Binarizes video and returns a frame to frame difference trace.
Inputs:
video - list of images
cropx1 - int, crop pixel starting for first dimension
cropx2 - int, crop pixel ending for first dimension
cropy1 - int, crop pixel st... | fb6793f3b44e6b042df97588ceebc178ee8c2bb2 | 48,372 |
def convert_entity_schema(entity_schema):
""" Convert entity schmea to record schema
"""
spots = list()
asocs = list()
spot_asoc_map = dict()
for entity in entity_schema:
spots += [entity]
spot_asoc_map[entity] = list()
return spots, asocs, spot_asoc_map | 6e3cc2bbecbbd88312c1a486142d9e8a50a5e39a | 48,373 |
def get_inchi_key(mol: Molecule) -> str:
"""Get an InChI key from a molecule."""
return inchi.generate(mol).getKey() | 81d4065ee2364ebbdedfa69ebdd450cd372638fc | 48,374 |
def process_raw_input(input, source='html'):
"""
Parameters
----------
input
type
Returns
-------
processed text (str)
"""
if source == 'html':
return '\n'.join(input)
elif source == None:
return input | f1e3b45ed8507b910f18f9a44856e17e530b4119 | 48,375 |
def get_pheno_list(serotype_hits, session):
"""
Function to return phenotype list from list of serotype hits (deduplicated)
:param serotype_hits: list of serotype hits from stage 1 mash analysis
:param session: DB session
:return: list of deduplicated phenotypes or groups
"""
out_res = []
... | 335fafb66dd04be0b20775d086cbafd93900f080 | 48,376 |
def get_review_dates(app_reviews) -> pd.DataFrame:
"""Create a new dataframe, `reviewDates`, with the number of reviews for each app per year"""
review_dates = (
app_reviews.groupby(["appId", "reviewYear"])["appId"]
.count()
.unstack()
.reset_index()
)
app_total_reviews ... | d92f7ed51a9c77f1ada409350d05872920489c3e | 48,377 |
def validate(config):
"""
Validate the beacon configuration
"""
# Configuration for memusage beacon should be a list of dicts
if not isinstance(config, list):
return False, "Configuration for memusage beacon must be a list."
else:
_config = {}
list(map(_config.update, con... | eddeb201e7789fdf3440513ca006813e49930a81 | 48,378 |
def evaluate_conditionals_in_context (properties, context):
""" Removes all conditional properties which conditions are not met
For those with met conditions, removes the condition. Properies
in conditions are looked up in 'context'
"""
base = []
conditional = []
for p in properties... | 96d6012bd4edd9f63b35a4852785c345442f2b6a | 48,379 |
def mmd_t(
dist_xx, dist_xy, dist_yy, batch_size, alpha=1.0, beta=2.0, var_target=None, name='mmd',
do_summary=False, scope_prefix=''):
"""This function calculates the maximum mean discrepancy with t-distribution kernel
The code is inspired by the Github page of following paper:
Binkowski M... | 6c5f935ebba86b2ed42b3039c5454795075fe17a | 48,380 |
def _wsdl2dispatch(options, wsdl):
"""TOOD: Remove ServiceContainer stuff, and replace with WSGI.
"""
kw = dict()
# TODO: make all this handler arch
if options.address is True:
ss = ServiceDescriptionWSA()
else:
ss = ServiceDescription(**kw)
ss.fromWSDL(wsdl)
file_n... | b97a1bce90eee6231286d6d0dc21431beafdb145 | 48,381 |
def reset_from_schedules(scheduler):
""""Reset all scheduler jobs, using information from the JSON object
:param scheduler: the TornadoScheduler instance to modify
:type scheduler: TornadoScheduler
:returns: True in case of success
:rtype: bool"""
ret = False
try:
scheduler.remove_a... | 1bf1bd20bbba7af5fba156c6632d0b86a616feba | 48,382 |
import pandas as pd
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.metrics import precision_recall_curve, average_precision_score
def get_threshold_metrics(y_true, y_pred, drop_intermediate=False,
disease='all'):
"""
Retrieve true/false positive rates and auroc/aup... | be44c49f1d0c8dbb6ef1543a538efb03d3cda3a4 | 48,383 |
from typing import Dict
from typing import Any
import requests
def pull_astronaut_list(url: str ='http://api.open-notify.org/astros.json') -> Dict[str, Any]:
"""
Pull a list of astronauts via API. Defaults to open-notify's API.
Args:
url: the URL to pull data from.
Returns:
A dict co... | d008cd1d62a435086dbd8dc08baaa5323298f11c | 48,384 |
def get_widget_for_attr(traits_ui, attr_name):
""" Return the Qt widget in the UI which displays the attribute specified.
"""
x_editor = traits_ui.get_editors(attr_name)[0]
qt_widget = x_editor.control
return qt_widget | 2bb2959963734bee48d067f41425808412bd2421 | 48,385 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload Bold config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
del hass.data[DOMAIN][entry.entry_id]
return unload_ok | cfab6c4d2e7ff1fdb261b95641128dda0153be7e | 48,386 |
def strip_url(url, origin_only=False):
"""
参考 https://www.w3.org/TR/referrer-policy/#strip-url
去除敏感信息如username
:param url:
:param origin_only:
:return:
"""
if not url:
return None
parsed_url = urlparse(url)
netloc = parsed_url.netloc
if origin_only and (parsed_url.use... | b424909e70d5078292c700a4605b9a493d22cb0a | 48,387 |
def eval_single_file(simulation_output_dir):
"""
number of cells
number of cells detected
"""
sim_dat_dir = simulation_output_dir[0:simulation_output_dir.rindex('/')]
true_barcodes = get_barcodes_set(
'%s/true_barcodes.txt' % (sim_dat_dir))
pred_barcodes = get_barcodes_set(
'%s/threshold_paths.txt' % simul... | 816aed4808fe21abb91b483ea7fc5aedf1c49d2a | 48,388 |
def all(*args, span=None):
"""Create a new expression of the intersection of all conditions in the
arguments
Parameters
----------
args : list
List of symbolic boolean expressions
span : Optional[Span]
The location of this operator in the source code.
Returns
-------... | f0cebfb241c10c2d53c58a8b4fb186e9d65a1b7a | 48,389 |
def plot_all_answer_traces(inputtrace: np.ndarray, colors: list) -> list:
"""
This function plots the answer traces of all tests; one plot per test.
:param inputtrace: Dataframe with the answer trace. Attributes of the dataframe: test, approach, answer, time.
:param colors: List of colors to use for th... | 26e5bcf8378a4b2ad77b202f2c11f8347bfffb31 | 48,390 |
from datetime import datetime
def initialise_library(members, items, item_copies, library):
"""Takes in items that needs to be populated into the library,
and conduct a series of pre-defined events by members (loan, renewal, return)
The Library object after conducting the events is used to initialise... | 0f5021358dd701790be75140673ede4634de1a41 | 48,391 |
def update_cache_bykey(cache_list, new_list, key='id'):
"""
Given a cache list of dicts, update the cache with a 2nd list of dicts by a specific key in the dict.
:param cache_list: List of dicts
:param new_list: New list of dicts to update by
:param key: Optional, key to use as the identifier to upd... | b077a1c40cbf0a8848ff9e017a644c20e1d25199 | 48,392 |
def calc_theor_avg_mass(dictionary, cfg, prec=6, reducing_end=None) -> float:
"""Returns theoretical average mass for glycan in dictionary form"""
reducing_end_tag_mass = 0.0
if reducing_end is not None:
if reducing_end in cfg["reducing_end_tag_avg"].keys():
reducing_end_tag_mass = cfg["... | 32a5aab08463366e8b43d13f2891489d94ab075a | 48,393 |
import inspect
import sys
def is_builtin(key):
"""Test builtin using inspect (some modules not seen
as builtin in sys.builtin_module_names may look builtin
anyway to inspect and in this case we want to filter them
out."""
try:
inspect.getfile(sys.modules[key])
except TypeError:
... | 1834b871b8d4f8d55f6de61052568dffdd2b8474 | 48,394 |
def get_node_info(session, node_id):
"""Wrapper for HAPI_GetNodeInfo
Fill an NodeInfo struct.
Args:
session (int): The session of Houdini you are interacting with.
node_id (int): The node to get.
Returns:
NodeInfo: NodeInfo of querying node
"""
node_info = HDATA.NodeInf... | 16b6200ec083da4cc15f57a02c53e0431cdc56a7 | 48,395 |
def Eliminar_Columnas(df, Dic):
""" Recibe el dataframe y el listado de las columnas que se quieren eliminar
"""
df = df.drop(columns=Dic)
return df | 96c049508f196406807cc9102b87cb4aa4884650 | 48,396 |
def getCurrentUser():
"""
Get the current user associated with whatever email is stored in session
"""
if 'email' not in session:
return None
email = mailsane.normalize(session['email'])
if email.error:
return None
return getUser(str(email)) | 9709c927c3d4fb7e74911859962c521eeaf3e2de | 48,397 |
def wgs84_to_web_mercator(df, lon="LON", lat="LAT"):
"""convert mat long to web mercartor"""
k = 6378137
df.loc[:,"x"] = df[lon] * (k * np.pi/180.0)
df.loc[:,"y"] = np.log(np.tan((90 + df[lat]) * np.pi/360.0)) * k
return df | 94ec56293ecc9510d4f6687b941253be359274ee | 48,398 |
def process_medusa(line):
"""
Process a medusa line and return a dictionary
:param line: A line from a medusa output file
:returns dict: A dictionary based upon the content
{ 'ip' : ip address
'port': port info - can be port # or module name
'user': username,
'pass': password,
... | 406fdaeee3ae91399095a9ae86feb5c3f9d66e60 | 48,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.