content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs):
"""
Wrapping the isochrone and kernel simulate functions.
"""
mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus)
lon, lat = kernel.simulate(len(mag_1))
return mag_1, mag_2, lon, lat | a9522074bc64722f0991e3ac5747abe8fe6b226d | 3,620,700 |
import torch
import copy
import time
def run_base(
experience,
device,
use_interactive_logger: bool = False
):
"""
Runs Naive (from BaseStrategy) for one experience.
"""
def create_sub_experience_list(experience):
"""Creates a list of sub-experiences from an experi... | d7c866a24ca3cb6d4d9cde526475a52668306bfb | 3,620,701 |
def check_negation(text, NEGATION_MAP):
"""
Utility function to check negation of an emotion
:param text: text chunk with the emotion term
:return: boolean value for negation
"""
neg_word_list = NEGATION_MAP
neg_match = False
for neg_word in neg_word_list:
if neg_word.strip() in ... | 020b7f692264754d8b76111c709cc31710ba6339 | 3,620,702 |
import argparse
def init_args():
"""
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument('--net', type=str, help='The network you used', default='xception')
parser.add_argument('--dataset', type=str, help='The dataset', default='ilsvrc_2012')
parser.add_argument('--weights... | 5d81aee6852b7f4dc145e4ede2b23cf37ead22ff | 3,620,703 |
def latex_to_unicode(string):
"""Returns a unicode representation from latex strings used by pyFAI.
.. note:: The latex string could be removed from the pyFAI core.
:param str string: A latex string to convert
:rtype: str
"""
string = string.replace("$", u"")
string = string.replace("^{-2}... | 2ef821cfc99ea6241b3d6bea95109f36f6cb135f | 3,620,704 |
def return_viewer(structure: Structure, labels: list = None):
"""Returns nglview viewer with oxidationstates labels"""
coords = structure.cart_coords # - atoms.get_center_of_mass()
visualizer = nv.show_pymatgen(structure, center=False, dis=False)
visualizer.clear_representations()
visualizer.compon... | c7d3b560d4340e69cb5cc96a6315e92163d9d3e3 | 3,620,705 |
import copy
import logging
def load_teacher_models(file_list, num_classes, config, strategy):
"""Loads teacher models for distillation."""
teacher_config = copy.deepcopy(config)
teacher_config.proj_dim = -1
num_teacher_models = len(file_list)
teacher_models = [[]] * num_teacher_models
for i in range(num_t... | a8e6b97bcc64bec7aab2428134e971a1b17eab2c | 3,620,706 |
def _tree_to_json(clf, features, labels, node_index=0):
"""Structure of rules in a fit decision tree classifier
Parameters
----------
clf : DecisionTreeClassifier
A tree that has already been fit.
features, labels : lists of str
The names of the features and labels, respectively.
... | 02689b1d0ccd6b5fb39def7e69a07a87770afd5d | 3,620,707 |
def align(q, p):
"""Align
Aligns the desired formation p onto the current swarm state q.
This is a wrapper to decide if we should do 2D or 3D Arun.
in:
q dxn np.array (d is 2D or 3D) - current state
p dxn np.array - desired formation
out:
paligned dxn... | d6dccc655fa58ec89252fed9e7dff8e6b6f317c1 | 3,620,708 |
def api_simulationData(simulation_type, simulation_id, pretty=False, section=None):
"""First entry point for a simulation
Might be non-session simulation copy (see `simulation_db.CopyRedirect`).
We have to allow a non-user to get data.
"""
#TODO(pjm): pretty is an unused argument
#TODO(robnagle... | e1dc2e6634ad3c52c425c637382cf7147d5be93c | 3,620,709 |
def find_bean_by_name(jsn, nme):
"""
Extracts a bean of the given name from jmx metrics json object.
"""
if 'beans' not in jsn:
return None
else:
return next((b for b in jsn['beans'] if b['name'] == nme), None) | 826115bff5a5c1a4ee58560a55641ccf99c1541f | 3,620,710 |
def convert_datetime_to_timestamp(dt):
"""Convert pandas datetime to unix timestamp"""
return int(dt.timestamp()) | f9cf6223bfabfa54c00835b56bdce2d5b268afe7 | 3,620,711 |
from typing import Counter
def archive(request, name=None, slug=None, year=None, month=None):
"""
Parameters
----------
name:
Tag name
slug:
Tag slug
year:
Article year (published_date)
month:
Article month (published_date), most likely in norwegian written ... | ae3e663bd6e354faa6bd77031115c9219efcf926 | 3,620,712 |
def get_indicator_type_value_pair(field):
"""
Extracts the type/value pair from a generic field. This is generally used on
fields that can become indicators such as objects or email fields.
The type/value pairs are used in indicator relationships
since indicators are uniquely identified via their ty... | 1750558782b91017061176176dda94c83c3dee6a | 3,620,713 |
import os
import ssl
def vertica_python_conn(config: dict,
account: str='user',
server: str='vertica',
use_ssl: bool=False):
"""
Generate vertica_python configuration object from configuration.
Args:
config -- dictionary that opt... | 5152d90e71dee5a0b88c042392a2a7032920d222 | 3,620,714 |
def doc_arg(name, brief):
"""argument of doc_string"""
return " :param {0}: {1}".format(name, brief) | 8a341c7ef0b437ba9ec035001e71952e3793eea8 | 3,620,715 |
def var_usage_namespace_region(view, var_usage):
"""
Returns the namespace Region of var_usage, or None.
For some (odd) reason, a var_usage might not have name row & col.
"""
try:
name_row_start = var_usage["name-row"]
name_col_start = var_usage["name-col"]
name_row_end = ... | 22c946fe81a634973ebb2860ab48d0873f24d43e | 3,620,716 |
def _ordinals_to_nn(ordinal, nn=False):
"""Ordinals 1-99 int to string. Reverse in separate func calling on this func. Parsing and returning strings of the type "9." will be the task of a higher func"""
if type(ordinal) is int:
if ordinal < 10 and ordinal != 0:
if nn == False:
... | b7dbc45271a3a8ab8b6f699824f79ff3089eec4a | 3,620,717 |
import itertools
def decode_message(G, coded_msg):
"""
Function that decodes given message using the given generator matrix.
Firsly we create all combinations of length n, where n is the number of rows of the matrix, of zeros and ones.
Then each combinations is transposed and multiplied by the generat... | 46813bf132dd3d1d7ec3904048c6a6ca4487b708 | 3,620,718 |
def assign_colors(classes):
"""
Assigns colors to specific classes
:param classes: ``Dict[class_id, "name of class"]``, dictionary of class names
:return: ``Tuple(Tuple(R,G,B))``, list of colors format RGB
"""
colors = np.random.randint(80, 255, size=(len(classes), 3), dtype='int32')
# bio
... | a4be89e156b73943660ce1d1d4e6ed76e00550c1 | 3,620,719 |
def lib_to_orig_opt_rep(s):
"""
Translates an option from the form used by Tidy python to the form used by the Tidy utility.
"""
if gen_utils.is_bool_type(s):
if s:
return 'yes'
return 'no'
return s | ab6aa0d0cca62dc389ff6535928c8c967d7da8f3 | 3,620,720 |
def example_project(tmp_path):
""" a minimal project
"""
my_module = tmp_path / "my_module"
starter_content = my_module / "starter_content"
starter_content.mkdir(parents=True)
(tmp_path / "README.md").write_text("# My Module\n")
(my_module / "__init__.py").write_text("__version__ = '0.0.0\n... | 9063c3f317abc66116bd79656c4fd16e96095e4f | 3,620,721 |
from azext_devops.devops_sdk.v5_0.wiki.models import WikiPageCreateOrUpdateParameters
def update_page(wiki, path, version, comment=_DEFAULT_PAGE_UPDATE_MESSAGE, content=None, file_path=None,
organization=None, project=None, detect=None):
"""Edit a page.
:param wiki: Name or Id of the wiki.
... | 40756d18c33dd50a5168202e6b09cb23bf52a81e | 3,620,722 |
def uu_query_STK_SHAREHOLDER_FLOATING_TOP10():
"""
十大流通股东
获取上市公司前十大流通股东的持股情况,包括持股数量,所持股份性质,变动原因等
:param :query(finance.STK_SHAREHOLDER_FLOATING_TOP10):表示从finance.STK_SHAREHOLDER_FLOATING_TOP10这张表中查询上市公司前十大流通股东的持股情况,还可以指定所要查询的字段名,格式如下:query(库名.表名.字段名1,库名.表名.字段名2),多个字段用英文逗号进行分隔;query函数的更多用法详见:sqlalchemy.o... | bbc5005db2bc36f6bf54bc8f776a178b9f33b365 | 3,620,723 |
def parallelize(data, method):
"""
Helper method for parallelization
"""
cores = mp.cpu_count()
data_split = np.array_split(data, cores)
pool = mp.Pool(cores)
data = pd.concat(pool.map(method, data_split))
pool.close()
pool.join()
return data | 295af584a0e0804d4b4c290ae9e6c358855d481f | 3,620,724 |
def foo():
"""
example function documentation
an example doctest is included below
returns: None
>>> x = foo()
>>> x
'foo'
"""
return "foo" | 81300580771ac0fa31b8c701d322a48997683c9c | 3,620,725 |
def string_date(mnthDay, year):
"""Return a string date as 'mm/dd/yyyy'.
Argument format:
'mm/dd' string
'yyyy'"""
return(mnthDay + '/' + str(year)) | e85bf9f0e72735be04009c6b685f2788a5c46d47 | 3,620,726 |
def check_who_queued(user):
"""
Returns a function that checks if the song was requested by user
"""
def pred(song):
if song.requested_by and song.requested_by.id == user.id:
return True
return False
return pred | e53a1434077ec7b97e237d1ff8bcc8c2454c4015 | 3,620,727 |
def wrap_coroutine_in_current_trace_context(coro):
"""Wraps the coroutine in the currently active span."""
trace_span_yields = _current_span_yields()
async def _wrapped():
with _with_span_yields(trace_span_yields):
return await coro
return _wrapped() | 880cdc58764b1bdc72124ce7f54aa669feaa2031 | 3,620,728 |
def masked_greater_equal(x, value, copy=True):
"""
Mask an array where greater than or equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x >= value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>... | 04dac911d5a20314fc0d6aaf02f6291d37bf27e9 | 3,620,729 |
import os
import re
import stat
def most_recent_unique_file(datadir):
"""Returns most recent file of 'unique' type in datadir.
A 'unique' has form <timestamp,secs>.<hostname>.<i-node>.
Returns only the filename of the file, not the entire path.
"""
absdatadir = os.path.abspath(datadir)
if no... | 7ababc9b55618f3fb541ef88a4a435ff58158324 | 3,620,730 |
from joblib import Parallel, delayed
import os
def GISfast(start_idx,
stop_idx,
params,
train_states):
"""Fast version of Greedy Iterative Search
This search procedure assumes the output layer is a linear layer
Args:
start_idx (int): Start index in the list of... | 75dbfcb7d8271d1d9ef734092d464e3b508292fe | 3,620,731 |
def _get_lines(filename):
"""Returns a list of lines from 'filename', joining any line ending in \\
with the following line."""
with open(filename, "r") as f:
lines = []
accum = ""
for line in f:
if line.endswith("\\\n"):
accum += line[:-2]
els... | 83b2184eedfb21d27f310f9f2229d05d69ac8b92 | 3,620,732 |
def CSMToBinary(D, Kappa):
"""
Turn a cross-similarity matrix into a binary cross-simlarity matrix, using partitions instead of
nearest neighbors for speed
:param D: M x N cross-similarity matrix
:param Kappa:
If Kappa = 0, take all neighbors
If Kappa < 1 it is the fraction of mutual... | aedb0a982c43f375de96c65aa42a49a9749c85be | 3,620,733 |
import cmd
def create_runner(path, commands, logfile, run_async=False, name='re.runner'):
"""Create a bash script for executing `commands` sequentially in remote system
Parameters
----------
path : str
Path in remote device, from where `commands` should be executed
commands : list
A list of command... | cdcfb5d9e5e87b973e1720dac5d6669227eef5ba | 3,620,734 |
import re
def replace_punctuation_and_whitespace(text):
"""Replace occurrences of punctuation (other than . - _) and any consecutive white space with ."""
rx = re.compile(r"[^\w\s\-.]|\s+")
return rx.sub(".", text) | b539ec796c1b69176e0da132ee88f9695b745fb2 | 3,620,735 |
import urllib
def url_quote(s, charset='utf-8', safe='/:'):
"""URL encode a single string with a given encoding."""
if isinstance(s, unicode):
s = s.encode(charset)
elif not isinstance(s, str):
s = str(s)
return urllib.quote_plus(s, safe=safe) | 103818444593d43f22e60b2648ffffebe0dcf28e | 3,620,736 |
import re
def remove_symbols(text):
""" Removes all symbols and keep alphanumerics """
whitelist = []
return [re.sub(r'([^a-zA-Z0-9\s]+?)',' ',word) for word in text if word not in whitelist] | 54e3706a275f5c5ff58a924a04249066d014f393 | 3,620,737 |
import re
def is_url(string):
"""
Function used to check if a string is a valid URL
:param string: element to be checked
:return: True if string is an URL, False otherwise
"""
global IS_URL_REGEX
return re.match(IS_URL_REGEX, string) is not None | 657fea6e566ef59222637f8828d5216428d95306 | 3,620,738 |
import torch
def merge_tokens(token_dict, idx_cluster, cluster_num, token_weight=None):
"""Merge tokens in the same cluster to a single cluster.
Implemented by torch.index_add(). Flops: B*N*(C+2)
Return:
out_dict (dict): dict for output token information
Args:
token_dict (dict): dict ... | 099b37ab04bfeb78b0e7a6a15bbff5bf46f4ba91 | 3,620,739 |
def arrayfy(data, stats, vocab):
"""
Create data-arrays from the nested-list form of data
data: The data in nested list form
stats: The stats file dumped from preprocessing
vocab: The vocab file dumped from preprocessing
"""
context_len,dec_ip_len,dec_op_len,sent_len=get_len(data... | 69a444398f35cb30670958ce619fe32a89fc31a0 | 3,620,740 |
def filter_out_length_of_one(word):
"""
Filters out all words of length 1
:param word: Input word
:return: None if word is of length 1, else the original word
"""
if len(word) > 1:
return True
return False | c89fda6b560811a178a5a2d2c242d54fba27d071 | 3,620,741 |
from matplotlib import pyplot as plt
def plot_histograms(frame, img_array):
"""Creates histogram widget and plots it.
Converts image arrays to histograms for display
Args:
frame (Tk Frame): frame to put histograms of images
img_array (np array): np array containing image data
Return... | dfc10cc2e8bead5a7793d08c86994b3461ddb86a | 3,620,742 |
def _make_view_conditionalupdate(update, param, grad, delta, view_func, eps):
"""
produces a test and an update vector, if the test is true then one should use the update vector
works with a view of the parameters
"""
param_view = view_func(param)
grad_view = view_func(grad)
cond = _is_scale... | b1eac2feee7b66e36514022f9e0066b6164dc251 | 3,620,743 |
def forbidden(e):
"""
Informs the user that he/she is forbidden from accessing a resource.
Parameters
----------
e : str
A custom error message
Returns
-------
json
JSON representation of the error message
"""
error_code = HTTPStatus.FORBIDDEN.value
resp... | 7fecd7f56b5b81dcd0a10800998190ebe0087162 | 3,620,744 |
def eval_env(env, model, n_episodes, render_mode='none'):
"""
Evaluate a model against an environment over N games.
"""
results = {
'reward': np.zeros(n_episodes),
}
with Bar('Eval', max=n_episodes) as bar:
for k in range(n_episodes):
done, state = False, None
... | 0a640cff1829d6604d20cbe58c17c646162284cf | 3,620,745 |
def bmesh_join(list_of_bmeshes, list_of_matrices, *, normal_update=False, bmesh):
"""takes as input a list of bm references and outputs a single merged bmesh
allows an additional 'normal_update=True' to force _normal_ calculations.
"""
bm = bmesh.new()
add_vert = bm.verts.new
add_face = bm.face... | 07d7f3401d170ed4afc3f6a795258710fe263aba | 3,620,746 |
import re
import os
def make_peg_parser(input_filename, embeds, module_name=None):
"""Creates the secondary PEG parser file which overrides Grako's defaults
with Multiparser's own customizations.
"""
with open(input_filename, 'r', encoding='utf8') as f:
grammar = f.read()
match = re.sear... | 965b8e01af4839501ac488a8431a804290582f81 | 3,620,747 |
def send_typing_action(func):
"""Sends typing action while processing func command."""
@wraps(func)
def command_func(update, context, *args, **kwargs):
context.bot.send_chat_action(
chat_id=update.effective_message.chat_id, action=ChatAction.TYPING
)
return func(update, ... | e716ee7d6470015a91ef279c0e6ed325c66e1db0 | 3,620,748 |
def generate_example_2():
"""
Generates example appropriate for testing footprint calculations
:return:
"""
shn = HetNet(params={
'r': {},
'b': {},
'g': {}
})
shn.add_node('r1', dict(color='r'))
shn.add_node('r2', dict(color='r'))
shn.add_node('b1', dict(colo... | 623bdc65261ddfdfc336279836d9fd7525eb4abd | 3,620,749 |
def extract_toc(source, setting_key="default", body_only=True, initial_header_level=None, silent=True):
"""
Extract the TOC from the rendered content by the parser
This is very tricky, we add the ``contents`` directive to the document,
parse it again (sic) with docutils, then parse it with Element... | 504785b7db1b39b8ede94f6f1c1f3b5c4ed07f8d | 3,620,750 |
def ordered_variants_and_indices(labels):
"""
Get the ordered variant labels, where the labels are sorted by chromosome
and position, and the indices corresponding to the sort,
Parameters
----------
labels : list(tuple(str))
The list of variant labels. Each label is a tuple of
(... | 5d8d7ea0aba1844736d0a8b220603e2444fa8ccb | 3,620,751 |
def run_customized_training(strategy,
bert_config,
max_seq_length,
max_predictions_per_seq,
model_dir,
steps_per_epoch,
steps_per_loop,
... | 55402309cd0c808378394a697f9d5352c3e46896 | 3,620,752 |
def _extract_users(status: dict) -> list:
"""Extract the list of users connected to the server."""
try:
return [user["name"] for user in status.raw["players"]["sample"]]
except KeyError:
return [] | 3d106c595390dc138a9d5307c6f31f45e0d628f9 | 3,620,753 |
import json
def read_json(jsonfile):
"""Read a json file into a dictionary
Args:
jsonfile: the name of the json file to read
Returns:
the contents of the JSON file as a dictionary
>>> from click.testing import CliRunner
>>> test = dict(a=1)
>>> with CliRunner().isolated_filesyst... | da5b7bddc42b14a6547071fe528a1c051d35356c | 3,620,754 |
from typing import Union
def vgg19(
inputs: tf_compat.Tensor,
training: Union[bool, tf_compat.Tensor] = True,
num_classes: int = 1000,
class_type: str = None,
kernel_initializer=tf_compat.glorot_uniform_initializer(),
bias_initializer=tf_compat.zeros_initializer(),
beta_initializer=tf_comp... | 01a9efd67923301063cf18881d78da24965be3e4 | 3,620,755 |
from typing import Dict
from typing import Any
def create_table(
query_path: str,
query_params: Dict[str, Any],
destination_project: str,
destination_dataset: str,
destination_table: str,
partition_field: str) -> str:
"""Creates a Bigquery table from a parameterized .sql file.
This method... | 21a4fc611ee6341ca7e8d2c681673bb251022d3e | 3,620,756 |
from typing import List
import torch
def filter_inf_n_nan(tensors: List[torch.Tensor], return_indexes: bool = False):
"""Filters out inf and nans from any tensor.
This is usefull when there are instability issues,
which cause a small number of values to go bad.
Args:
tensor (List): tensor to ... | 9aa999072efdfb59eab6ac0154bfffc57bf5a67f | 3,620,757 |
def bytescale(data, cmin=None, cmax=None, high=255, low=0):
"""
Byte scales an array (image).
Byte scaling means converting the input image to uint8 dtype and scaling
the range to ``(low, high)`` (default 0-255).
If the input image already has dtype uint8, no scaling is done.
Parameters
----... | 4369e5e0ecc16b38d3561632dfebb00840489806 | 3,620,758 |
import cupy
def cupy_cuda_MemoryPointer(nb_arr):
"""Return cupy.cuda.MemoryPointer view of a numba DeviceNDArray.
"""
addr = nb_arr.device_ctypes_pointer.value
size = nb_arr.alloc_size
mem = cupy.cuda.UnownedMemory(addr, size, nb_arr)
return cupy.cuda.MemoryPointer(mem, 0) | f08535ce472b330d8fa6a563d5a4ba9a3803ff40 | 3,620,759 |
import struct
import base64
def InterpretData(regType, data, dataExpand):
"""
Returns the most sensible interpretation of a registry binary blob
according to its registry type. Here is the mapping:
REG_SZ UTF-8 string
REG_EXPAND_SZ UTF-8 string
REG_MULTI_SZ... | 5dfdeebaa89292ac4039b60222bb8d2c1c14b636 | 3,620,760 |
def debye(rho_bulk, charge, permittivity=79, temperature=298.15):
"""Calculate the Debye length.
The Dybe length indicates at which distance a charge will be screened off.
Arguments:
rho_bulk: dictionary of the bulk number densites for each ionic species [1/m^3]
charge: dictionary of the charge of each ionic spec... | cfe4cd7424f5b9891e95d0cd9dcabefb835cc0f2 | 3,620,761 |
def zero_float(string):
"""Try to make a string into a floating point number and make it zero if
it cannot be cast. This function is useful because python will throw an
error if you try to cast a string to a float and it cannot be.
"""
try:
return float(string)
except:
return 0 | 075a49b53a0daf0f92072a5ec33f4b8240cc6885 | 3,620,762 |
import re
def _special_att_handling(attype, col_args): # noqa: C901
""" laundry list of special handling that sqlalchemy
does to convert between a Postgres type and a Sqlalchemy type """
kwargs = {}
if attype == 'uuid':
kwargs = {'as_uuid': True}
args = ()
elif attype == 'numeri... | e9feabb792001c66a9679a3a5931cb00c96dcf83 | 3,620,763 |
def transonic_airliner(display=None,
Propulsion=1,
EngineDia=2.9,
FuselageScaling=[55.902, 55.902, 55.902],
NoseLengthRatio=0.182,
TailLengthRatio=0.293,
WingScaleFactor=44.56,
... | 402c3af0d0d7e8d75345eec8ace5b282422e6bd7 | 3,620,764 |
def branch_color():
"""Return red if the current branch is dirty, yellow if the dirtiness can
not be determined, and green if it clean. These are bold, intense colors
for the foreground.
"""
dwd = dirty_working_directory()
if dwd is None:
color = '{BOLD_INTENSE_YELLOW}'
elif dwd:
... | fb0d8197b985b9e94a03e20dcb472e8ade638f60 | 3,620,765 |
def checksum(data) -> int:
"""
Found on: http://www.binarytides.com/raw-socket-programming-in-python-linux/. Modified to work in python 3.
The checksum is the 16-bit ones's complement of the one's complement sum
of the ICMP message starting with the ICMP Type (RFC 792).
:param data: data to built ch... | af8ba70fa53f95514bc6e8118440ba607c17d794 | 3,620,766 |
def streaming_mean_absolute_error(predictions, labels, weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Computes the mean absolute error between the labels and predictions.
The `str... | c5d5f009f5f074ccd421982e56a86497b52564c0 | 3,620,767 |
def _number_convert(match):
"""
Convert number with an explicit base
to a decimal integer value:
- 0x0000 -> hexadecimal
- 16'h0000 -> hexadecimal
- 0b0000 -> binary
- 3'b000 -> binary
- otherwise -> decimal
"""
prefix, base, number = match.groups()
if prefix is not None:
... | adef8f8f80342fbcd79c461068eb04f99427f88c | 3,620,768 |
def detection_targets_graph(proposals, gt_class_ids, gt_boxes, config):
"""Generates detection targets for one image. Subsamples proposals and
generates target class IDs, bounding box deltas, and masks for each.
Inputs:
proposals: [N, (z1, y1, x1, z2, y2, x2)] in normalized coordinates. Might be zero p... | 9fc35295d3e52373f3b5cf0230904ade4f6f34fb | 3,620,769 |
def Enum(name,names,values=None):
"""
Create a new enum class with the given names and values.
Parameters:
[name] A string denoting the name of the enum.
[names] A list of strings denoting the names of the individual enum values.
[values] (optional) A list of integer values of the enums. ... | 66cd78441a3e2bbc5bfac6c79f632e1a45dc7e62 | 3,620,770 |
def prefetch(max_prefetch=1):
"""
Decorator for wrapping a function which returns a generator with `BackgroundGenerator`.
A new instance of `BackgroundGenerator` is created every time the decorated function is called.
Parameters
----------
max_prefetch : int, optional, default: 1
... | 2a29849b48b4aedffcad3eccd35d2648c051f3d6 | 3,620,771 |
def set_batch_anomaly_score_args(args, fields=None,
dataset_fields=None):
"""Return batch anomaly score args dict
"""
batch_anomaly_score_args = {
"name": args.name,
"description": args.description_,
"tags": args.tag,
"header": args.predictio... | 3e13f7b1e18ccfb481ab5ca04bb6a1c7c863e51c | 3,620,772 |
import os
def pgengine(request):
"""Create a sqlalchemy engine for a PostgreSQL DB."""
envFile = request.param
if os.environ.get('DBCONNECTION', None) is None:
with open(envFile) as envVars:
for line in envVars:
var, val = line.split('=', 1)
var = var.st... | 521ce24acd5de746059e7754cea8a4024d803e1d | 3,620,773 |
import io
import os
def get_next_expid(n=None):
"""
Return the next exposure ID to use from {proddir}/etc/next_expid.txt
and update the exposure ID in that file.
Use file locking to prevent multiple readers from getting the same
ID or accidentally clobbering each other while writing.
Args:
... | 9cdb24b880ef2e788ab0cfe1f4e4ce30c87b5454 | 3,620,774 |
import requests
import sys
def get_scientific_name(taxon_id):
"""Get scientific name for input taxon_id.
:param taxon_id: NCBI taxonomy identifier
:return scientific_name: scientific name of sample that distinguishes its taxonomy
"""
# endpoint for scientific name
url = 'http://www.ebi.ac.uk/... | 5cab933a3cc6ab2602e680c3db2ed129c3f85b94 | 3,620,775 |
import secrets
from datetime import datetime
def push_span(node, trace_id, parent_id, service_name):
"""Pushes to Honeycomb a span corresponding to a given test result object and returns its randomly generated ID."""
span_id = secrets.token_hex(16)
ev = libhoney.new_event()
ev.add_field("service_name"... | 06e56963271da6324499f2927906c05f3eea53e0 | 3,620,776 |
def expected_ts(ts_id):
"""
Returns a ts composed of expected slope results (having same id as gen_ts method)
:param ts_id: Identifier of the TS to get expected results (see content below for the structure)
:type ts_id: int
:return: the TS data points
:rtype: np.array
"""
if ts_id == ... | 11396514747afbfc296333c292a0b923c8912972 | 3,620,777 |
import io
import csv
def export_data_csv():
""" Build a CSV file with the Client data from the database
:return: The CSV file in StringIO
"""
result = query_client.get_all_clients()
output = io.StringIO()
writer = csv.writer(output)
line = ['Numéro client', 'Nom du client', 'Adresse ma... | afb619009c5c213f5d682b14e83a16ea296b975f | 3,620,778 |
def phi_cdf(phi, eps):
"""The cumulative distribution of a given azimuthal angle :math:`phi` given
a distance between neighboring beads of :math:`\Epsilon = ds/l_p`."""
f0, fpi = phi_Z_0_1_(eps)
return (phi_indef_(phi, eps) - f0)/(fpi - f0) | 7a6604528635f6c86079fba78a966fa290f57acf | 3,620,779 |
def _detect_global_scope(node, frame, defframe):
""" Detect that the given frames shares a global
scope.
Two frames shares a global scope when neither
of them are hidden under a function scope, as well
as any of parent scope of them, until the root scope.
In this case, depending from something ... | b41aabc73460c127971db2cb65b4531e5a947345 | 3,620,780 |
def _determine_column_type(data_types):
"""Given a set of Python column types, returns either 'number' or 'string'."""
# Allow None which will be converted to NaN.
if all(
issubclass(t, (_numbers.Number, type(None))) and not issubclass(t, bool)
for t in data_types):
return 'number'
return 'strin... | 1108b3b9c8e811771f8db97a8a0a06f844b6c329 | 3,620,781 |
def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
data = pd.read_csv(filename, parse_dat... | a385de1c9d3d6f807d9fdcb336ac9eab7b3982be | 3,620,782 |
def _discrete_extkalman_update(time, randvar, data, measmod, **kwargs):
"""
"""
mpred, cpred = randvar.mean(), randvar.cov()
if np.isscalar(mpred) and np.isscalar(cpred):
mpred, cpred = mpred * np.ones(1), cpred * np.eye(1)
jacob = measmod.jacobian(time, mpred, **kwargs)
meascov = measmo... | ff09b3d61823d02bf5e8eb44ba51ef8a8fb26ff5 | 3,620,783 |
def rating_calc(item, ocurrences, last_ocurrences, total_ocurrences):
""" Calculates the rating of the target language.
"""
rating = ocurrences / total_ocurrences
if item in last_ocurrences:
rating *= 2
if last_ocurrences and item == last_ocurrences[-1]:
rating *= 4
return rating | fa93bd9c44b612231cd7dd486909fa2654e34288 | 3,620,784 |
def render_home_page():
"""The home page.
Returns
-------
Rendered template
A rendered template for the home page.
"""
return render_template(page_constants.HED_TOOLS_HOME_PAGE) | e5d6d62db45995b5958ccb81dcf80c5363b36809 | 3,620,785 |
def process(sentence):
"""Pre-process sentence(s) for BERT. Returns:
- tokenized text (with [CLS] and [SEP] tokens)
- segment sentence ids ([0s & 1s])
- indexed tokens """
tokenized_text = ["[CLS]"] + tokenizer.tokenize(sentence) + ["[SEP]"]
tokenized_text = tokenized_text[:512]
... | 5e15f39983bc5c882449753f20da294904dfae18 | 3,620,786 |
async def get_group_membership_by_id(group_id, rest_client=None):
"""
Get the membership list of a group.
This is a paginated request that is fairly slow when linked with LDAP.
Args:
group_id (str): group id
Returns:
list: usernames
"""
start = 0
inc = 50
ret = []
... | 6a2eb81d5cb4191132f755925083fbe80055533e | 3,620,787 |
from pathlib import Path
def make_tissue2subtissue2sample_id(rawdir: str) -> pd.DataFrame:
"""Construct multi-indexed pd.Series that maps each tissue-subtissue
combination to the corresponding column names"""
sample_id_df = pd.read_csv(
Path(rawdir) / "GTEx_Analysis_v8_Annotations_SampleAttributes... | 56d48deef9650514440cea344d9924edc635ca0d | 3,620,788 |
def get_file_name(path: str):
""" gets 'folder1/folder2/folder3/file_name.extension"
return file_name
"""
# validation
if type(path) != str:
path = str(path)
if not is_valid_path(path):
raise InvalidPathError
# /validation
sep = get_path_sep(path)
if "." not in... | be6b308e66ab7ec32a22000837c929aa3ce6c0f6 | 3,620,789 |
import hashlib
def makeKey(password, salt):
"""make master key"""
if not hasattr(password, 'decode'):
password = password.encode('utf-8')
if not hasattr(salt, 'decode'):
salt = salt.lower()
salt = salt.encode('utf-8')
# Here we use 100,000 iterations since that is the default t... | 59819fc96f3ad5e4627c5acccf3ba2acf99ee49d | 3,620,790 |
def compute_df_orbit_param(trajectory_df, cpu_count, ram_dir):
"""
Compute the orbital elements of a set of trajectories. Computation are done in parallel.
Parameters
----------
trajectory_df : dataframe
the set of trajectories, the following columns are required : "ra", "dec", "dcmag", "fi... | 81d8b2dfa763b696482fa1666c978bff588c3512 | 3,620,791 |
def run_episode(environment, agent, is_training=False):
"""Run a single episode."""
timestep = environment.reset()
while not timestep.last():
action = agent.step(timestep, is_training)
new_timestep = environment.step(action)
if is_training:
agent.update(timestep, action, new_timestep)
ti... | dcec7609b33cf2f13ca6753c2dfd614252189b51 | 3,620,792 |
from typing import List
from typing import Any
import re
def determine_col_names_from_input(exprs: List[str], cols: List[str], force: Any = False):
"""
Takes a list of (possibly wildcarded) input column names and a list of actual column names
and determines which, if any, actual column names are matches. ... | b406281d35caa69719682bacab708f03c981f6c3 | 3,620,793 |
def detect(net, im):
""" """
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
# Visualize d... | 64a89663eacb2c26fdfaa2715f6c8d91fd972107 | 3,620,794 |
def HellingsDownsCoeff(phi, theta):
"""
Calculate Hellings and Downs coefficients from two lists of sky positions.
Parameters
----------
phi : array, list
Pulsar axial coordinate.
theta : array, list
Pulsar azimuthal coordinate.
Returns
-------
ThetaIJ : array
... | 186d4096a3bab27dc4e896c79eb6efc1c67a6071 | 3,620,795 |
import time
def prediction_times(models, X, Y):
"""
Get predictions times for different models
:param models: dictionary of models (models must contain predict function)
:type models: dict
:param X: data for prediction
:type X: array
:param Y: true values
:type Y: array
:return: p... | 1b9d5b24845eecb7fa24eb82310e69ec4b315e50 | 3,620,796 |
def fill_dates_daily(X, date_column='date'):
""" Add missing days in time series
:param X: pd.DataFrame with column `date_column`
:param date_column: columns with dates
:return: pd.DataFrame
"""
X = pd.DataFrame(X)
X[date_column] = pd.to_datetime(X[date_column])
idx = pd.date_range(star... | 213f609465d04ebc7796c8bafff747d02947d3ef | 3,620,797 |
def pandas_df_to_temporary_csv(tmp_path):
"""Provides a function to write a pandas dataframe to a temporary csv file with function scope."""
def _pandas_df_to_temporary_csv(pandas_df, sep=",", filename="temp.csv"):
temporary_csv_path = tmp_path / filename
pandas_df.to_csv(temporary_csv_path, se... | 5ec9b3072928e3cdbe067dfcb33010b2a51a267b | 3,620,798 |
def is_polar_hydrogen(atom_name: str, res_name: str) -> bool:
"""Check if the atom in a given residue has polar hydrogens.
Parameters:
atom_name: str
Name of the atom
res_name: str
Residue name
"""
if atom_name in POLAR_HYDROGENS[res_name]:
return True
... | 0a3a072b3b3394fb2ba89f2cb9a885f1d185fecf | 3,620,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.