content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def dunn_individual_word(total_words_in_corpus_1,
total_words_in_corpus_2,
count_of_word_in_corpus_1,
count_of_word_in_corpus_2):
"""
applies Dunning log likelihood to compare individual word in two counter objects
:pa... | 54594190fa72c5a410fbb128b29ca08a9d9f5031 | 658,821 |
def evg_project_str(version):
"""Return the evergreen project name for the given version."""
return 'mongodb-mongo-v{}.{}'.format(version.major, version.minor) | 39aa0021bec397b6a340ce9c2f755f6d4cebf28b | 658,822 |
import argparse
def check_arg(args=None):
"""
Parse command line arguments provided via command line.
See the manual for argparse online for more information
"""
parser = argparse.ArgumentParser(description='Merge router-parser results with network-discovery results')
parser.add_argument('--ro... | 8028447fe704d02c77fdb4b9828e7bf8158ac43d | 658,823 |
def heuristic(current, target):
"""calculating the estimated distance between the current node and the targeted node
-> Manhattan Distance"""
result = (abs(target[0] - current[0]) + abs(target[1] - current[1]))
# print(result)
return result | cbba3d2db5f42ca0cd28ea8106ea89dbf81cd0ab | 658,824 |
def rdkitSubstrMatches(targetRdkitMol, refRdkitMol, *args, **kwargs):
"""
Matches two rdkit mol object graphs with each other.
Outputs a list of tuples of corresponding atoms indices.
Arguments:
----------
targetRdkitMol : object
target rdkit molecule object
refRdkitMol : object
... | e443d1060847c17b3033faeb0b373f803c2cb909 | 658,825 |
import re
def get_jump_pattern(stripped, function_name):
"""
Return regexp pattern used to identify jump assembly lines. Support
for stripped and non-stripped versions.
Need to match non-stripped lines:
'0x00007ffff7fbf124 <+68>: jmp 0x7ffff7fbf7c2 <test_function+1762>'
and stripped lines:
... | 642ba2c00fc739f5bc338ad37c481b2056c95412 | 658,826 |
import torch
def median_heuristic_batch(dnorm2, device):
"""Compute median heuristic (batched version).
Inputs:
dnorm2: (n x n x b) tensor of \|X - Y\|_2^2
Return:
(b, ) tensor of med( \|X_i - Y_j\|_2, 1 \leq i < j \leq n )
"""
dnorm2 = dnorm2.permute(2, 0, 1) # batch x n x n
i... | ef2f287dea56005f2df5965d22d2afbb11330696 | 658,828 |
def vo_from_fqan(fqan):
"""
Get the VO from a full FQAN
Args:
fqan: A single fqans (i.e. /dteam/cern/Role=lcgadmin)
Returns:
The vo + group (i.e. dteam/cern)
"""
components = fqan.split('/')[1:]
groups = []
for c in components:
if c.lower().startswith('role='):
... | eb0b8fed163fd4c49750d71a0a0b568b39525322 | 658,829 |
import torch
def array_to_tensor(array, device):
"""Convert numpy array to tensor."""
return torch.FloatTensor(array).to(device) | 1ef9df3bdf1a77bcbc846926a28d7ef8fe29315c | 658,830 |
def math_expression_type(text):
"""
Custom Type which expects a valid math expression
:param str text: the text which was matched as math expression
:returns: calculated float number from the math expression
:rtype: float
"""
return float(eval(text)) | 81d038bce4c39add28b24a690b7e55b3dd2e7b2f | 658,831 |
def task_hello():
"""hello"""
def python_hello(targets):
with open(targets[0], "a") as output:
output.write("Python says Hello World!!!\n")
return {
'file_dep': ["existing.txt"],
'actions': [python_hello],
'targets': ["output1.txt"],
'clean': True,
} | 30bd6aa23eb2fd7d1b988f55470df3cf7b7e8c53 | 658,832 |
def overlaps(region_1, region_2):
"""
Find if two regions overlaps
a region is defined as dictionary with
chromosome/contig, start- and end position given
Args:
region_1/region_2(dict): dictionary holding region information
Returns:
overlapping(bool)... | 0ec48814f9200666db82bba29ff2de7915e7e19f | 658,833 |
def load_module(module_path, symbols=()):
"""Loads a module by given module path
:param module_path: module path
:param type: str
"""
return __import__(module_path, globals(), locals(), symbols) | 1bbdde4a86a14afd83ca351ac1acd04bb42f172b | 658,835 |
def remove_duplicate_nested_lists(l):
""" removes duplicates from nested integer lists
"""
uniq = set(tuple(x) for x in l)
L = [ list(x) for x in uniq ]
return L | 0473918bfa6a6522f703eee27288cee69442df94 | 658,836 |
def strategy_best(cookies, cps, history, time_left, build_info):
"""
Buy item with best value of cps to price
"""
#Clone BuildInfo object
upgrades = build_info.clone()
#Calculate item's value
chosen_item = ""
chosen_value = 0.0
#Compare item values and choose one with best value
... | 1d763aba86b63453e7824b9bdf40489aa1d4930a | 658,837 |
def filter_web_planner(item):
"""Filters out items that you should not be able to use in a world planner - be it broken items or illegals."""
if item.ID % 2 == 1:
return False
if item.Type == 0 or item.Type == 1 or item.Type == 4 or item.Type == 8 or item.Type == 19 \
or item.Type == 20 or item.Type == 37 or ite... | efaf3294830b7afc74bed2f6664960f494024928 | 658,838 |
def preprocess_prediction_data(data, tokenizer):
"""
It process the prediction data as the format used as training.
Args:
data (obj:`List[List[str, str]]`):
The prediction data whose each element is a text pair.
Each text will be tokenized by jieba.lcut() function.
... | 8389ef9e6d69ebfa976d7763c8d358a850746959 | 658,839 |
import math
from datetime import datetime
def convert_julian_frac(julian_frac, year):
"""
julian_frac is string in the form of a float
"""
frac, julian_day = math.modf(float(julian_frac)+1)
#The drifters reported both 0 and 356 for julian days in the calendar year
#When I get access to source ... | baf223a6b37b1f70bcad0ca7a75b1b74235b0098 | 658,840 |
def box_with_period(request):
"""
Like `box`, but specific to PeriodDtype for also testing PeriodArray
"""
return request.param | 6122ed4f00cbf89cbf314c3cf6894ac79cbca136 | 658,841 |
import math
def circumference_area(radius):
"""Returns the area of a circumference"""
radius = float(radius)
if (radius < 0.0):
raise ValueError('Negative numbers are not allowed')
return radius**2 * math.pi | cb40983991a8c17161df7ab74299f0ee82011fe1 | 658,842 |
def _himmelblau(coord):
"""See https://en.wikipedia.org/wiki/Himmelblau%27s_function."""
x, y = coord[..., 0], coord[..., 1]
return (x**2 + y - 11)**2 + (x + y**2 - 7)**2 | 314168360f6a2bfafe4fe15aff37e82b3eaea7f9 | 658,843 |
def approx_Q_top(A, B, T, sigma=1, C=None):
"""
Approximate expression for the (a)symmetric top partition function. The expression is adapted from Gordy and Cook,
p.g. 57 equation 3.68. By default, the prolate top is used if the C constant is not specified, where B = C.
Oblate case can also be specified... | d79c6dbf4cb00db05279bcf7d4cd4eb2bb9edcb4 | 658,844 |
def uniform_disk(a):
"""Return the standard uncertainty for a uniform disk
:arg float a: the radius
Convert the radius of a uniform disk distribution ``a``
to a standard uncertainty.
See reference: B D Hall, *Metrologia* **48** (2011) 324-332
**Example**::
>>> z = ucom... | 3e58c456af3b619d2aaeb02910b976195f1dfb66 | 658,845 |
import os
def resolve_target(source, target):
"""
Resolve the target path with source value. If the target is a
valid filename it would be returned as such. If the target is a
valid directory, name of the file would be extracted from the source
path and created the final absolute path of the targe... | a6ea17e69b4e60cf7f59038fc2e61348de1eee36 | 658,846 |
def check_items_exist(res) -> bool:
"""Checks whether any product returned."""
return True if len(res['hits']['hits']) > 0 else False | f5adc0b88570b728571551fa4dc111d4fc72246c | 658,847 |
import re
def obj_check_attr(obj, attr, dict):
"""
Return True/False if attr (namespace/scene) is to be included in import/export
obj: Namespace or Scene object
attr: Which attribute to check ('namespace' or 'scene')
dict: Dictionary of namespace or scene from config
"""
if obj[attr] in di... | af8c874da41ceaa94da260c4cccca0b84383da4d | 658,848 |
import argparse
def parse_args():
"""Processes command line arguments
"""
parser = argparse.ArgumentParser(description='Generate AWS IAM roles and groups with associated policies.')
parser.add_argument('--group', action='store_true', help='Creates group identities')
parser.add_argument('--role', a... | 67dca860bb20f1c8134a69be6fd9f06ab65c121c | 658,849 |
import numpy
def rmse(labels, predictions):
""" The root mean square error function """
n = len(labels)
differences = numpy.subtract(labels, predictions)
return numpy.sqrt(1.0/n * (numpy.dot(differences, differences))) | 1c878284f1f0aacd8e9edd84042823f42f1a3d0e | 658,850 |
import requests
from bs4 import BeautifulSoup
def pick_selections():
"""Creates list of teams to be provided as pick options"""
page = requests.get("https://www.sportsinteraction.com/soccer/england/premier-league-betting/")
soup = BeautifulSoup(page.content, 'html.parser')
matches = soup.find_all(clas... | a03fa8852acbadcad2c908ab4a9c8bfbfcb518cd | 658,851 |
def classes(*names, convert_underscores=True, **names_and_bools):
"""Join multiple class names with spaces between them.
Example
-------
>>> classes("foo", "bar", baz=False, boz=True, long_name=True)
"foo bar boz long-name"
Or, if you want to keep the underscores:
>>> classes("foo", "bar... | 5054c2973d3495c6796974fae13f06832d1eae51 | 658,852 |
import itertools
def do_combinations(edges):
"""
Input is a list of directed edge
Output is a form that is digestable by Justicia, generally applied combinations on parents
"""
dependency_dic = {}
for a,b in edges:
# direction a -> b
if(b not in dependency_dic):
dep... | 27ba1106c8251e91e0a9e026d24b87b8b64c0f13 | 658,853 |
from pathlib import Path
import subprocess
def preview_extract(d: Path, outdir: Path, codedir: Path):
"""Create lossy AVI preview of extracted data"""
cmd = ['python', 'Convert_HDF5_to_AVI.py',
str(outdir/d.stem/(d.stem+'extracted.h5')),
str(outdir/d.stem/(d.stem+'extracted.avi'))]
... | bd4720269aa7e0e07d23e1046c0120c1dc0c8e82 | 658,854 |
from typing import Union
import os
from pathlib import Path
def get_annotation_dir(root: Union[str, os.PathLike]):
"""returns annotation directory given a root directory"""
return Path(root) / "annotations" | 229cd9d8e4948e14bb2972a2d7865a3c93aac526 | 658,856 |
import os
def make_relative_path(source, dest, dest_is_directory=True):
"""
Make a filename relative, where the filename is dest, and it is
being referred to from the filename source.
>>> make_relative_path('/usr/share/something/a-file.pth',
... '/usr/share/another-plac... | 668f17c52c18ac3b3dedc0d9c643a156e20edb60 | 658,857 |
def format_image_results(registry_response_dict):
"""
Response attribute content is formatted correctly for the Images
:param response: response object with content attribute
:return: dict of various images
"""
if not isinstance(registry_response_dict, dict):
raise TypeError('registry_r... | 141c5d6cae8d7d7dbfa1051ac9fd4927f2a47fe3 | 658,860 |
import pickle
def load_features():
"""
Load all the features of users and books.
:return: (U, V), U representing features matrix for users and V representing features matrix for books.
"""
with open('features/users.pickle', 'rb') as f:
U = pickle.load(f)
with open('features/books.pick... | 42257b3e77141fc2e21c6715a4c7fa44171552f4 | 658,861 |
def datetime_to_int(datetime):
"""Convert datetime to 17 digit integer with millisecond precision."""
template = (
'{year:04d}'
'{month:02d}'
'{day:02d}'
'{hour:02d}'
'{minute:02d}'
'{second:02d}'
'{millisecond:03d}'
)
priority = int(
templ... | ded2579fd21f3c0a3c7639e3654757a389b994a1 | 658,862 |
def init_theta(np):
""" thetaの初期値の決定 """
# 行は状態0~7、列は移動方向で↑、→、↓、←を表す
return np.array([[np.nan, 1, 1, np.nan], # snp.nan
[np.nan, 1, np.nan, 1], # s1
[np.nan, np.nan, 1, 1], # s2
[1, 1, 1, np.nan], # s3
[np.na... | 9a9b82ae499613ea7c6ea105ba448ed8b29881e9 | 658,863 |
def ComputeLabelX(Array):
"""Compute label x coordinate"""
X = min(Array)+ (max(Array)-min(Array))/2
return X | 4e8e3fa5ab4558e6c2762caa025566e75805cdc6 | 658,864 |
def str2re(s):
"""Make re specific characters immune to re.compile.
"""
for c in '.()*+?$^\\':
s = s.replace(c, '['+c+']')
return s | d22ee77640a34ae7aa43d913edc8132ab20452b1 | 658,865 |
def int_to_bytes(x):
""" 32 bit int to big-endian 4 byte conversion. """
assert x < 2 ** 32 and x >= -(2 ** 32)
return [(x >> 8 * i) % 256 for i in (3, 2, 1, 0)] | 954112ca5ef4b48f1563cdff12eb5699e1609d14 | 658,867 |
import os
import json
def get_config():
"""
Obtain the celery config
:return: The configuration jsonj
"""
cfg_path = os.environ.get("NLP_CELERY_CONFIG")
if cfg_path is None:
cdir = os.path.curdir
cfg_path = os.path.sep.join([cdir, 'config', 'default.json'])
with open(cf... | 92a56746f5a026f69c363a363b77470d9eb1d470 | 658,868 |
import subprocess
def cmd_exists(cmd):
""" Returns: bool, True if 'cmd' is in PATH, False otherwise."""
return subprocess.call("type " + cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) == 0 | f321fd774ffe90f2f4d38bbc68dfe004ad9acca0 | 658,869 |
def get_tree_max_id(value, list_id=[]):
"""
得到最大Tree max id
"""
if not value:
return 0 # the first node id
if isinstance(value, list):
for content in value: # content -> dict
children = content.get('children')
if children:
get_tree_max_id(ch... | eec4fce086d643f28f0577a7cbb2b480fb5b9907 | 658,870 |
import imp
import unittest
def skipIfModuleNotInstalled(*modules):
"""Skipping test decorator - skips test if import of module
fails."""
try:
for module in modules:
imp.find_module(module)
return lambda func: func
except ImportError:
return unittest.skip("Test skipp... | 97171016735c54336602282878d9052f1091b2e1 | 658,871 |
def voter_address_retrieve_doc_template_values(url_root):
"""
Show documentation about voterAddressRetrieve
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, ... | 29c57a36f3be535cd6c79de2508102693478f239 | 658,872 |
def _arrow_to_numpy(arrow_table, schema):
"""Helper function that converts an Arrow Table to a dictionary
containing NumPy arrays. The memory buffers backing the given Arrow Table
may be destroyed after conversion if the resulting Numpy array(s) is not a
view on the Arrow data.
See https://arrow.ap... | ff2de73450162c66fb690162eee18360ee835f47 | 658,873 |
def delay_feedback_gain_for_t60(delay_samp, fs, t60):
"""
Calculate the gain needed in a feedback delay line
to achieve a desired T60
Parameters
----------
delay_samp : int
The delay length in samples
fs : float
Sample rate
t60 : float
The desired T60 [seconds]
... | 281eacb60e453dd2c38b94d0a6446ea4093974c3 | 658,875 |
def get_test_mode_user(prefix='', rconn=None):
"""Return user_id of test mode, or None if not found"""
if rconn is None:
return
try:
test_user_id = int(rconn.get(prefix+'test_mode').decode('utf-8'))
except:
return
return test_user_id | 894f8c1eeff85471864876491acad5ac59f9781a | 658,876 |
import functools
import time
def retry(max_tries=3, delay=0.1, exceptions=(KeyError, IndexError)):
"""A function decorator for re-trying an operation. Useful for MongoDB
which is only eventually consistent.
"""
def wrapper(f):
@functools.wraps(f)
def wrap(*args, **kwargs):
... | bc4f1121120e1980bb511a1c763799bef03f3e8c | 658,877 |
def sum_key(value, key):
"""Sums up the numbers in a 'column' in a list of dictionaries or objects.
Positional arguments:
value -- list of dictionaries or objects to iterate through.
Returns:
Sum of the values.
"""
values = [r.get(key, 0) if hasattr(r, 'get') else getattr(r, key, 0) for r ... | 1f04d340cc40d19282e96d60aa4bdd6ecc9c451f | 658,878 |
import os
def strongRandom( size ):
"""
Return `size' bytes of strong randomness suitable for cryptographic use.
"""
return os.urandom(size) | 1814eef8fa803b034e384ffcefe61f857bbfca4c | 658,880 |
def get_components(cf, exp, ap_filt):
"""Helper function for defining combined signals."""
return {'sim_powerlaw' : {'exponent' : exp, 'f_range' : ap_filt},
'sim_oscillation' : {'freq' : cf}} | 17f0003bb9a51338af2c119908c6e92b36dfc8da | 658,881 |
def interval_toggle(swp_on, mode_val, dt):
"""change the interval to high frequency for sweep"""
if dt <= 0:
# Precaution against the user
dt = 0.5
if mode_val == "single":
return 1000000
else:
if swp_on:
return dt * 1000
else:
return 10000... | d6a103b04a9da1ab47163f11905e3ebe36432a0f | 658,882 |
def query_create_fact_table() -> str:
"""[this returns the query used for creating fact table. It uses the immigration and temperature tables' view.]
Returns:
str: [query to extract fact table.]
"""
# defining query for creating fact table by joining temperature and immigration data
query =... | 36a5ba7f305d4695f479191684a8b34b14f80459 | 658,883 |
import shutil
def get_free_space_bytes(folder):
""" Return folder/drive free space (in bytes)
"""
try:
total, _, free = shutil.disk_usage(folder)
return total, free
except:
return 0, 0 | 5ae19815e953ba25053a7f9236b4e5c1f86d4875 | 658,884 |
import os
def relativize_path(path, rootdir):
"""
:API: public
"""
# Note that we can't test for length and return the shorter of the two, because we need these
# paths to be stable across systems (e.g., because they get embedded in analysis files),
# and this choice might be inconsistent across systems.... | 48c7847c38ba4e7decddabcce15db1b43d3113ad | 658,886 |
def load_tipracks(protocol, tiprack_list, labware_dict):
"""
Creates a list of the pipette tip labware.
@param protocol:
@param tiprack_list:
@param labware_dict:
@return:
"""
tiprack_labware = []
for slot in tiprack_list:
if slot not in protocol.loaded_labwares:
... | e54882ef6ea97e1baafe7760a81fea9dbf41f319 | 658,887 |
import os
def get_poetry_venv(python_version: str) -> str:
"""
Return the path to a poetry venv.
Arguments:
python_version: The version to get the virtual environment for.
Returns:
The path to the Poetry virtual environment.
"""
current_venv = os.environ["VIRTUAL_ENV"]
if... | 17fcf11e452d2188c770f12e3d602a8466c3f73d | 658,888 |
def filter_df(df,col,word):
"""Filters out any entries that do not have word(string regex) in the columns specified (col)"""
return df[df[col].str.contains(word,na=False)] | 327eea8c751db9021e89c4a038ddef06af0f9e6e | 658,889 |
def difference(list_1, list_2):
""" Deterministically find the difference between two lists
Returns the elements in `list_1` that are not in `list_2`. Behaves deterministically, whereas
set difference does not. Computational cost is O(max(l1, l2)), where l1 and l2 are len(list_1)
and len(list_2), respe... | 4b263ac97a203f2fc148b5b178e2d14c456b1bf7 | 658,890 |
def get_stats_per_domain(tool_summary_dict, domain):
"""
Produce a summary statistics per domain (Neuroinformatics, Bioinformatics, MRI, EEG...) of the identified variables of interest. # noqa: E501.
:param tool_summary_dict: dictionary with the variables of interest for the summary
:type tool_summar... | 0e91c62e754af0ed814daab81dc18a8b9b47c4a7 | 658,891 |
def error_message_from_snowflake_error(e):
"""
Return formatted error message from contents of a Snowflake error
parameter: (snowflake.connector.errors.Error) e
The Snowflake error object
returns:
Formatted error message
"""
err_msg = 'Snowflake DB error code: {}\n'.format(e.er... | 30e3900784f4ac578330ef418cd984fda99dd828 | 658,893 |
def add_none_params(params, list_added):
"""
Some time we get error when get the non exist keys, so add it using this code
:param params: params
:param list_added: list keys you want to add
:return:
"""
for p in list_added:
try:
params[p]
except KeyError:
... | bad547559160db469dfff7327d445011e2684f57 | 658,894 |
def write_header(dot_H_code_filename):
"""
#pragma once
#ifndef __HOME_TRAIN_DATA_H_
#define __HOME_TRAIN_DATA_H_
#include <string>
#include <vector>
#include <map>
//using namespace std;
"""
filename = dot_H_code_filename.replace(".", "_")
filename = filename.upper()
filename = "__" + filename +... | 399783ea9f3fa818eafba373ba04ea4dfe6d97df | 658,895 |
def scale_dimensions(width, height, longest_side):
""" Calculates image ratio given a longest side
returns a tupple with ajusted width, height
@param width: integer, the current width of the image
@param height: integer, the current height of the image
@param longest_side: the longest side of t... | 957a87747476bdf4325edad786a99f05a27917d3 | 658,896 |
def xorNA(x):
"""Return x if x is not None, or return 'NA'."""
return str(x) if x is not None else 'NA' | 9df8db1bfe91ffdc8795d2886b4823a3f6840b07 | 658,897 |
from typing import Counter
def _has_repeat_tri(grams):
"""
:param grams:
:return:
"""
tri_grams = [tuple(grams[i:i+3]) for i in range(len(grams)-2)]
cnt = Counter(tri_grams)
return not all((cnt[g] <= 1 for g in cnt)) | cffd120ab1ebcfc5c301fb3188d1a32dafff1d80 | 658,898 |
def update_dcid(dcid, prop, val):
"""Given a dcid and pv, update the dcid to include the pv.
Args:
dcid: current dcid
prop: the property of the value to add to the dcid
val: the value to add to the dcid
Returns:
updated dcid as a string
"""
val_dcid = val.split(":")[-... | c61136ee6e93a73ea269396fb0f71fd3d161b101 | 658,899 |
def genderint_to_string(dataframe,
gender_integer_map):
"""Transforms gender encoded as an integer to a string
INPUT:
dataframe: DataFrame that includes gender encoded as an integer
gender_integer_map: Dictionary that describes the mapping of a
... | 3c64f862e5418aed6850cb232d95611dec6b7eb3 | 658,900 |
def get_score(baseid: int, stat_dict: dict) -> str:
"""
Calculate whether a given base id is 'good', 'warning' or 'failure'
A warning will be issued if the lower quartile for any base is less than 10,
or if the median for any base is less than 25.
A failure will be issued if the lower quartile for a... | 70523821004bd3ddd492b48d8a77c56ee05d3491 | 658,901 |
import torch
def similarity_mask(feat_all, bsz, opt, pos_pairs, cur_step, labels, phase):
"""Calculate the pairwise similarity and the mask for contrastive learning
Args:
feat_all: all hidden features of shape [n_views * bsz, ...].
bsz: int, batch size of input data
opt: arguments
... | 4f3149419a272bea264cf100329cd2b468c97d53 | 658,902 |
import random
def random_math_quiz() -> str:
"""
058
Make a maths quiz that asks five questions by randomly generating two whole numbers to make the question
(e.g. [num1] + [num2]). Ask the user to enter the answer. If they get it right add a point to their score. At
the end of the quiz, tell them... | b7bd477f279149e70ed970a6ba246d4ec4cae4fe | 658,903 |
def _create_index_for_annotation_row(row):
"""Parse the row from annotation file to get chrom and positions.
Parameters
----------
row: pd.DataFrame row
Row of annotation dataframe
Returns
-------
index: array_like
Array of 1-based positions on chromosome
"""
co... | e76c38a62fa3e237acfa97092f182739244d6081 | 658,904 |
def compat_layer(original_impl):
"""Set class which should be unified to common interface
:param original_impl: implementation of specific service API
:type original_impl: cls
"""
def wrapper(cls):
cls._meta_init()
cls._meta_set("impl", original_impl)
return cls
return w... | d8fe0eb5903f64c57ed78b29ccf12a56da0158f2 | 658,905 |
def to_list(obj):
"""Convert a list-like object to a list.
>>> to_list([1, 2, 3])
[1, 2, 3]
>>> to_list("a,b,c")
['a', 'b', 'c']
>>> to_list("item")
['item']
>>> to_list(None)
[]
"""
if isinstance(obj, (list, tuple)):
return obj
elif isinstance(obj, str):
... | 8c24c7bd3dae4eca58dae03fa60e3b4f204f7bbb | 658,906 |
def stock_payoff(S,PP):
"""This function takes Spot price range(S), and purchase price(PP) of the stock as inputs
and returns stock payoff """
return (S-PP) | 199d492d98d47f457de8ef41b2c910aa3fcbdb58 | 658,907 |
import math
def log(a,b):
"""
Returns the logarithm of a to the base b.
"""
return math.log(a,b) | c0f139d9881a80d78abf427d1ca33e7d611c7a10 | 658,908 |
def get_max_score(scores):
""" gets maximum score from a dictionary """
max_value = 0
max_id = -1
for i in scores.keys():
if scores[i] > max_value:
max_value = scores[i]
max_id = i
return max_id | 93a70e6ec5c002617aed96f588b9d36a7471799e | 658,909 |
def select_files(flist, pattern):
""" Remove fnames from flist that do not contain 'pattern'. """
return [fname for fname in flist if pattern in fname] | 797cc2f0ff27f1527cf37581d03aa43d1d39808f | 658,910 |
def build_request_metrics(fe_ec2):
"""Build EC2 Requests Queued metrics"""
metrics = []
for instance in fe_ec2:
metric = ["System/Windows", "RequestsQueued",
"InstanceId", instance.get('InstanceId')]
metrics.append(metric)
return metrics | 120c760026e45ec8388ca1621c216fdf3f8df642 | 658,911 |
import os
def git_config_file(tmp_path, monkeypatch):
"""Create a temporary git config file, and monkeypatch $GIT_CONFIG to point to it."""
config_file = tmp_path / "git_config"
config_file.touch()
monkeypatch.setitem(os.environ, "GIT_CONFIG", str(config_file))
return config_file | 20d7831edf6098c623ac77c00529831a4f4122c5 | 658,912 |
def _convert_to_off(df):
"""Creates 'Note_off_c' events where needed.
Parameters
----------
df : pandas.DataFrame
Index: RangeIndex
Columns:
Name: 2, dtype: str
Name: 5, dtype: int64
"""
if df[5] == 0 and df[2] == "Note_on_c":
return "Note_off_c"... | d4a044bc26624ea021702a06aa2dbb8652a141cf | 658,913 |
def code_message(G, msg):
"""
The way the message is coded is simple as we only need to multiply the message with the generator matrix and
take modulo 2 of the result.
:param G: a generator matrix in systematic form
:param msg: message we wish to code
:return:
"""
return msg.dot(G) % 2 | 0895416b6004f798233a46b3a0410c743bd14cbc | 658,914 |
import subprocess
def execute_command(command):
"""Executes in shell."""
proc = subprocess.Popen(command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
r... | 0102d736e9b473da88c8c13309a834acff3fae13 | 658,915 |
def create_popup_table(df, locale):
"""
Provides html of a table to display inside the tooltip of a country.
"""
series = df.loc[locale][5:].sort_values(ascending=False)
popup_html = f"<b><a target='_parent' href='/details?locale={df.loc[locale]['locale2']}'>"
popup_html += f"{df.loc[locale]['na... | 4b03e52076a5634a286dfac5885c92c547fe99e5 | 658,916 |
def reverse_byte(byte):
"""
Fast way to reverse a byte on 64-bit platforms.
"""
#return (byte * 0x0202020202L & 0x010884422010L) % 1023
return(byte * 0x0202020202 & 0x010884422010) % 1023 | 12bc4294276d96dc4742b79220478a688ce6b143 | 658,917 |
import pandas as pd
import json
def check_expected_files(layout, config):
"""Checks files in BIDS project match user defined expectations.
This method checks the number of data set files against a user customized
configuration file. Returns two data frames: summary_df, problem_df.
Parameters
-... | cce7813f9816746d454c9a870d3f1b3cb4324f8f | 658,918 |
import json
import pickle
def eval_npy(truth_file, prediction_file):
"""Main fucntion."""
instances = []
with open(truth_file) as f:
for line in f.read().splitlines():
if line:
instances.append(json.loads(line))
with open(prediction_file, "rb") as f:
predictions = pickle.load(f)
asser... | 76dc60e707a37fb7421fcb553e59a126eebf7288 | 658,919 |
import re
def friendly_symbol_name(obj) -> str:
"""Return a friendly symbol name for obj."""
if str(type(obj)) == "<class 'function'>":
obj = obj.__module__ + "." + obj.__name__
obj_name = obj.__name__ if re.match("(<class 'module'>)", str(type(obj))) else obj
return re.sub(
"(<|class|... | 80d5d52a8b416a6f634272b37786f2042247ae94 | 658,920 |
def cast_value(value):
"""Cast Value.
Takes in a value with a desired type and attempts to cast it to that type.
"""
actual_value = str(value['value'])
actual_type = value['type']
try:
if actual_type == 'int':
new_value = int(actual_value)
elif actual_type == 'float... | db4c095471be660be118015b9f37252d3e02b7f7 | 658,922 |
import logging
def _build_stream_formatter() -> logging.Formatter:
"""Default formatter for log messages. Add timestamps to log messages."""
return logging.Formatter(
fmt="[%(levelname)s %(asctime)s] %(output_name)s: %(message)s",
datefmt="%m-%d %H:%M:%S",
) | 7d004696fd1db895f843cc02c6d885f90c2a99c0 | 658,923 |
import math
def tdewpoint_from_relhum(t, h):
"""Compute the Dewpoint temperature.
Parameters
----------
t: array
temperature [C].
h : array
relative humidity [%].
Returns
-------
array
Dewpoint temperature at current timestep.
Example
-------
tdewpoint_from_relhum(20,50) == 9.27... | d8a6212f44dd1dd602908bfd00d9fa2a7559b912 | 658,924 |
def birthdays(string):
""" Takes a multiline string and returns the numbers that represent
the same dates."""
# Break the string up into an array, sort it and filter out the junk.
kt_list = string.split()
kt_sorted = sorted(kt_list)
kt_filtered = [x for x in kt_sorted if x != '']
# Here we a... | 387496a708f674e125f6535a9c1d0acd894d470a | 658,925 |
def evaluate_model_tokens(labels, predicted):
"""
Function that extracts stats on token-basis
Input: array of true labels, array of predicted labels
Output: stats for the two given arrays
"""
stats = {'FP': 0, 'TP': 0, 'FN': 0}
for idx, label in enumerate(labels):
if label == 1 ... | bb4eceadf963fa6f76d8f3c22766b1cece039398 | 658,927 |
def process_word_source(w, eobj):
""" Calculate displacements of word for source timepoint tuples. """
return eobj.process_word(w, 0) | 1781648e43efd0cd954834a126c0ab879cd3ffb7 | 658,929 |
import re
def reWarning(label):
"""Given a label, return a `re` that looks for warned items with that label.
A warned item is an item with a CSS class `warning` in it.
Parameters
----------
label: string
Usually the title of an item
"""
return re.compile(
r"""\bclass=['"... | fe4bb2a77a0c94d10caa55fbec9ab4a59bd2bdce | 658,931 |
def label_seq(data):
"""
Input:
data: dictionary of text, begin_sentences, end_sentences
Output:
a sequence of labels where each token from the text is assiciated with a label:
regular token --> O
begin sentences token --> BS
end sentences token --> ES
... | aebfe545599f185f09f342f4bef622453db3115f | 658,932 |
def convert_to_underscore(record, timestamp_key):
""" Convert - to _ """
underscore_record = {}
for key, value in record.items():
underscore_record[key.replace("-", "_")] = value
return underscore_record | a0691788c0c54eea42c60f9cc0ea4cf78cc8b7b8 | 658,933 |
import inspect
def get_classes_in(__module, predicate=None, return_name=False):
"""Gets all class symbols stored within a Python module.
:param __module: The module to get the classes from.
:type __module: :class:`types.ModuleType`
:param predicate: A callable to pass to inspect.getmembers to filter ... | 4405687d254878e83ae1d68dce34867beeabb713 | 658,934 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.