content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import platform
def get_os():
"""
if called in powershell returns "powershell"
if called in cygwin returns "cygwin"
if called in darwin/osx returns "osx"
for linux returns "linux"
"""
env = os.environ
p = platform.system().lower()
terminal = p
operating_system = ... | 843dc64f40b50e7adc45f1f4c092550c578cddd3 | 3,655,400 |
def setup_model_and_optimizer(args):
"""Setup model and optimizer."""
print ("setting up model...")
model = get_model(args)
print ("setting up optimizer...")
optimizer = get_optimizer(model, args)
print ("setting up lr scheduler...")
lr_scheduler = get_learning_rate_scheduler(optimizer, arg... | 9283ec825b55ff6619ac2ee2f7ac7cce9e4bced7 | 3,655,401 |
def ensure_str(origin, decode=None):
"""
Ensure is string, for display and completion.
Then add double quotes
Note: this method do not handle nil, make sure check (nil)
out of this method.
"""
if origin is None:
return None
if isinstance(origin, str):
return origi... | 0409bc75856b012cf3063d9ed2530c2d7d5bf3e4 | 3,655,402 |
from typing import Union
from typing import Dict
from typing import Any
from typing import Optional
def restore(
collection: str, id: Union[str, int, Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
"""Restrieve cached data from database.
:param collection: The collection to be retrieved. Same name as API ... | a0b2ccb995661b5c3286dee3b3f5f250cb728011 | 3,655,403 |
def encode_bits(data, number):
"""Turn bits into n bytes of modulation patterns"""
# 0000 00BA gets encoded as:
# 128 64 32 16 8 4 2 1
# 1 B B 0 1 A A 0
# i.e. a 0 is a short pulse, a 1 is a long pulse
#print("modulate_bits %s (%s)" % (ashex(data), str(number)))
shift = number-... | 0299a30c4835af81e97e518e116a51fa08006999 | 3,655,404 |
import io
import os
def compute_session_changes(session, task=None, asset=None, app=None):
"""Compute the changes for a Session object on asset, task or app switch
This does *NOT* update the Session object, but returns the changes
required for a valid update of the Session.
Args:
session (di... | 2705a9ef6fe0afbfa375f03c28915c6f84c2211b | 3,655,405 |
from typing import Tuple
def _tf_get_negs(
all_embed: "tf.Tensor", all_raw: "tf.Tensor", raw_pos: "tf.Tensor", num_neg: int
) -> Tuple["tf.Tensor", "tf.Tensor"]:
"""Get negative examples from given tensor."""
if len(raw_pos.shape) == 3:
batch_size = tf.shape(raw_pos)[0]
seq_length = tf.sh... | 9cef1cf3fc869108d400704f8cd90d432382ac2e | 3,655,406 |
import os
def remove(store_config, shardid): # FIXME require config instead
"""Remove a shard from the store.
Args:
store_config: Dict of storage paths to optional attributes.
limit: The dir size limit in bytes, 0 for no limit.
use_folder_tree: Files organ... | a02f686f34707b0cfd940a2990f0a561ba7e33d3 | 3,655,407 |
from typing import Union
from typing import Optional
import sqlite3
import os
def init_db(path: Union[str, 'os.PathLike'] = db_constants.DB_PATH) -> Optional[sqlite3.dbapi2.Connection]:
"""Initialises the DB. Returns a sqlite3 connection,
which will be passed to the db thread.
"""
# TODO: change savi... | 5faced34ef7ee8698ed188801efe90c26f05ae16 | 3,655,408 |
def load_pdb(path):
"""
Loads all of the atomic positioning/type arrays from a pdb file.
The arrays can then be transformed into density (or "field") tensors before
being sent through the neural network.
Parameters:
path (str, required): The full path to the pdb file being voxelized.
... | aa7fe0f338119b03f00a2acb727608afcd5c1e0d | 3,655,409 |
from typing import List
import os
def validate_workspace(
workspace_option: str, available_paths: List[str] = list(WORKSPACE_PATHS.values())
) -> str:
"""Validate and return workspace.
:param workspace_option: A string of the workspace to validate.
:type workspace_option: string
:param available_... | d84e60aa5073333503b62361d77c32c4823a9da8 | 3,655,410 |
def __filter_handler(query_set, model, params):
"""
Handle user-provided filtering requests.
Args:
query_set: SQLAlchemy query set to be filtered.
model: Data model from which given query set is generated.
params: User-provided filter params, with format {"query": [...], ...}.
... | c91b7d55795399f453106d0dda52e80a0c998075 | 3,655,411 |
def split_data_set(data_set, axis, value):
"""
按照给定特征划分数据集,筛选某个特征为指定特征值的数据
(然后因为是按该特征进行划分了,该特征在以后的划分中就不用再出现,所以把该特征在新的列表中移除)
:param data_set: 待划分的数据集,格式如下,每一行是一个list,list最后一个元素就是标签,其他元素是特征
:param axis: 划分数据集的特征(特征的序号)
:param value: 需要返回的特征的值(筛选特征的值要等于此值)
:return:
>>>myDat ... | f90fdffee3bbee4b4477e371a9ed43094051126a | 3,655,412 |
import ast
import six
import types
import inspect
import textwrap
def get_ast(target_func_or_module):
"""
See :func:``bettertimeit`` for acceptable types.
:returns: an AST for ``target_func_or_module``
"""
if isinstance(target_func_or_module, ast.AST):
return target_func_or_module
if... | 929a8f1b915850c25369edf0dcf0dc8bc2fe16e9 | 3,655,413 |
from typing import List
from re import T
from typing import Callable
from typing import Tuple
def enumerate_spans(sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]]... | 68df595e4fd55d2b36645660df6fa9198a8d28ef | 3,655,414 |
def fixed_mu(mu, data, qty, comp='muAI', beads_2_M=1):
"""
"""
return fixed_conc(mu*np.ones([len(data.keys())]), data, qty, comp=comp,
beads_2_M=beads_2_M) | f7241e8b1534d5d537a1817bce4f019e5a4081a7 | 3,655,415 |
def error_nrmse(y_true, y_pred, time_axis=0):
""" Computes the Normalized Root Mean Square Error (NRMSE).
The NRMSE index is computed separately on each channel.
Parameters
----------
y_true : np.array
Array of true values. If must be at least 2D.
y_pred : np.array
Array of pr... | 39461cdf0337c9d681d4247168ba32d7a1cbd364 | 3,655,416 |
import shutil
def rmdir_empty(f):
"""Returns a count of the number of directories it has deleted"""
if not f.is_dir():
return 0
removable = True
result = 0
for i in f.iterdir():
if i.is_dir():
result += rmdir_empty(i)
removable = removable and not i.exists()... | f2dba5bb7e87c395886574ca5f3844a8bab609d9 | 3,655,417 |
def generic_exception_json_response(code):
"""
Turns an unhandled exception into a JSON payload to respond to a service call
"""
payload = {
"error": "TechnicalException",
"message": "An unknown error occured",
"code": code
}
resp = make_response(jsonify(payload), co... | fc2f0edfc774a56e6b6ccfc8a746b37ad19f6536 | 3,655,418 |
def UnN(X, Z, N, sampling_type, kernel="prod"):
"""Computes block-wise complete U-statistic."""
def fun_block(x, z):
return Un(x, z, kernel=kernel)
return UN(X, Z, N, fun_block, sampling_type=sampling_type) | 962788706d3b4d71a0f213f925e89fd78f220791 | 3,655,419 |
def delete_card(request):
"""Delete card"""
return delete_container_element(request) | 128b521ed89077ebae019942147fc3b4af1a5cdf | 3,655,420 |
import os
def build_estimator(tf_transform_dir, config, hidden_units=None):
"""Build an estimator for predicting the tipping behavior of taxi riders.
Args:
tf_transform_dir: directory in which the tf-transform model was written
during the preprocessing step.
config: tf.contrib.learn.RunConfig defin... | 474aeffb6c44b50a9e81c8db7b340489230a9216 | 3,655,421 |
def get_plot_grid_size(num_plots, fewer_rows=True):
"""
Returns the number of rows and columns ideal for visualizing multiple (identical) plots within a single figure
Parameters
----------
num_plots : uint
Number of identical subplots within a figure
fewer_rows : bool, optional. Default... | e83f14db347cd679e9e7b0761d928cd563444712 | 3,655,422 |
def check_source(module):
"""
Check that module doesn't have any globals.
Example::
def test_no_global(self):
result, line = check_source(self.module)
self.assertTrue(result, "Make sure no code is outside functions.\\nRow: " + line)
"""
try:
source = module.__... | 6bc012892d6ec7bb6788f20a565acac0f6d1c662 | 3,655,423 |
def pre_processing(X):
""" Center and sphere data."""
eps = 1e-18
n = X.shape[0]
cX = X - np.mean(X, axis=0) # centering
cov_mat = 1.0/n * np.dot(cX.T, cX)
eigvals, eigvecs = eigh(cov_mat)
D = np.diag(1./np.sqrt(eigvals+eps))
W = np.dot(np.dot(eigvecs, D), eigvecs.T) # whitening matrix
... | 802ce958c6616dcf03de5842249be8480e6a5a7c | 3,655,424 |
def get_as_tags(bundle_name, extension=None, config="DEFAULT", attrs=""):
"""
Get a list of formatted <script> & <link> tags for the assets in the
named bundle.
:param bundle_name: The name of the bundle
:param extension: (optional) filter by extension, eg. "js" or "css"
:param config: (optiona... | ec54184ff2b13bd4f37de8395276685191535948 | 3,655,425 |
def psql(statement, timeout=30):
"""Execute a statement using the psql client."""
LOG.debug('Sending to local db: {0}'.format(statement))
return execute('psql', '-c', statement, timeout=timeout) | 86eb9775bf4e3da3c18b23ebdf397747947914c9 | 3,655,426 |
def devpiserver_get_credentials(request):
"""Search request for X-Remote-User header.
Returns a tuple with (X-Remote-User, '') if credentials could be
extracted, or None if no credentials were found.
The first plugin to return credentials is used, the order of plugin
calls is undefined.
"""
... | bc6ccaa52b719c25d14784c758d6b78efeae104d | 3,655,427 |
def vader_sentiment(
full_dataframe,
grading_column_name,
vader_columns=COLUMN_NAMES,
logger=config.LOGGER
):
"""apply vader_sentiment analysis to dataframe
Args:
full_dataframe (:obj:`pandas.DataFrame`): parent dataframe to apply analysis to
grading_column_name ... | 43572857ecc382f800b243ee12e6f3fe3b1f5d5a | 3,655,428 |
def _overlayPoints(points1, points2):
"""Given two sets of points, determine the translation and rotation that matches them as closely as possible.
Parameters
----------
points1 (numpy array of simtk.unit.Quantity with units compatible with distance) - reference set of coordinates
points2 (numpy ar... | c3d1df9569705bcee33e112596e8ab2a332e947e | 3,655,429 |
def return_request(data):
"""
Arguments:
data
Return if call detect: list[dist1, dist2, ...]:
dist = {
"feature": feature
}
Return if call extract: list[dist1, dist2, ...]:
dist = {
"confidence_score": predict p... | 11887921c89a846ee89bc3cbb79fb385382262fa | 3,655,430 |
def get_recent_messages_simple(e: TextMessageEventObject):
"""
Command to get the most recent messages with default count.
This command has a cooldown of ``Bot.RecentActivity.CooldownSeconds`` seconds.
This command will get the most recent ``Bot.RecentActivity.DefaultLimitCountDirect`` messages withou... | 58d03a4b34254dc532ad6aa53747ea730446cd31 | 3,655,431 |
def parse_systemctl_units(stdout:str, stderr:str, exitcode:int) -> dict:
"""
UNIT LOAD ACTIVE SUB DESCRIPTION
mono-xsp4.service loaded active... | d9e7e4c71f418311799345c7dacfb9655912475f | 3,655,432 |
def resnet_model_fn(is_training, feature, label, data_format, params):
"""Build computation tower (Resnet).
Args:
is_training: true if is training graph.
feature: a Tensor.
label: a Tensor.
data_format: channels_last (NHWC) or channels_first (NCHW).
params: params for the model to... | 70f30b4c5b4485ed1c4f362cc7b383cb192c57c4 | 3,655,433 |
def permutate_touched_latent_class(untouched_classes, class_info_np, gran_lvl_info):
"""untouch certain class num latent class, permute the rest (reserve H(Y))"""
# get untouched instance index
untouched_instance_index = []
for i in untouched_classes:
index = np.where(class_info_np == i)[0]
... | ebae2213508260474a9e9c581f6b42fd81006a22 | 3,655,434 |
from datetime import datetime
import pytz
def get_interarrival_times(arrival_times, period_start):
"""
Given a list of report dates, it returns the list corresponding to the interrival times.
:param arrival_times: List of arrival times.
:return: List of inter-arrival times.
"""
interarrival_ti... | b6d345ff73e16d8c7502509ddd36e2a1d7f12252 | 3,655,435 |
def _indexOp(opname):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def wrapper(self, other):
func = getattr(self.view(np.ndarray), opname)
return func(other)
return wrapper | a9bdccca9d0bc1ffa2334132c6cfd4b965b95878 | 3,655,436 |
def safe_log(a):
"""
Return the element-wise log of an array, checking for negative
array elements and avoiding divide-by-zero errors.
"""
if np.any([a < 0]):
raise ValueError('array contains negative components')
return np.log(a + 1e-12) | 7ac5f01272f4c90110c4949aba8dfb9f783c82b9 | 3,655,437 |
import os
import sys
def parse_treepath(k=23):
"""Parse treepath results"""
results = {}
treepath_file = "treepath.k{}.csv".format(k)
if not os.path.isfile(treepath_file):
print("No treepath results found", file=sys.stderr)
return
with open(treepath_file, 'rb') as f:
f.rea... | e43ed769ee13813953b92dfe093f169107d6ec72 | 3,655,438 |
from typing import List
from typing import Dict
from functools import reduce
def deduplicate(
timeseries: List[TimeseriesEntry], margins: Dict[str, float] = {},
) -> List[TimeseriesEntry]:
""" Remove duplicates from the supplied `timeseries`.
Currently the deduplication relies on `timemseries` being form... | de61b31250c5fd4317becfb4bca1d582d4b7e465 | 3,655,439 |
import os
import textwrap
import time
def build_windows_subsystem(profile, make_program):
""" The AutotoolsDeps can be used also in pure Makefiles, if the makefiles follow
the Autotools conventions
"""
# FIXME: cygwin in CI (my local machine works) seems broken for path with spaces
client = TestCl... | 0e8b1902c8eff0d902af991b4299b954518b75d5 | 3,655,440 |
def make_batch_keys(args, extras=None):
"""depending on the args, different data are used by the listener."""
batch_keys = ['objects', 'tokens', 'target_pos'] # all models use these
if extras is not None:
batch_keys += extras
if args.obj_cls_alpha > 0:
batch_keys.append('class_labels')... | a86c2a5cff58f811a67cbdd5eed322c86aa3e0e0 | 3,655,441 |
import collections
from re import DEBUG
def init_dic_OP(universe_woH, dic_atname2genericname, resname):
"""Initialize the dictionary of result (`dic_op`).
Initialize also the dictionary of correspondance
between residue number (resid) and its index in dic_OP (`dic_corresp_numres_index_dic_OP`).
To c... | ce981df06717387286171b172c0400e42747dbfc | 3,655,442 |
from typing import List
def magic_split(value: str, sep=",", open="(<", close=")>"):
"""Split the value according to the given separator, but keeps together elements
within the given separator. Useful to split C++ signature function since type names
can contain special characters...
Examples:
... | 9f152c9cfa82778dcf5277e3342b5cab25818a55 | 3,655,443 |
def update_group_annotation(name=None, annotation_name=None, x_pos=None, y_pos=None, angle=None, opacity=None,
canvas=None, z_order=None, network=None, base_url=DEFAULT_BASE_URL):
"""Update Group Annotation
Updates a group annotation, changing the given properties.
Args:
... | fd515728ee3a3dece381bb65e2c6816b9c96b41e | 3,655,444 |
import urllib
def _extract_properties(properties_str):
"""Return a dictionary of properties from a string in the format
${key1}={value1}&${key2}={value2}...&${keyn}={valuen}
"""
d = {}
kv_pairs = properties_str.split("&")
for entry in kv_pairs:
pair = entry.split("=")
key = ur... | 4f22cae8cbc2dd5b73e6498d5f8e6d10e184f91c | 3,655,445 |
from typing import Any
def first_fail_second_succeed(_: Any, context: Any) -> str:
""" Simulate Etherscan saying for the first time 'wait', but for the second time 'success'. """
context.status_code = 200
try:
if first_fail_second_succeed.called: # type: ignore
return '{ "status": "1"... | 5feb3188bdee2d0d758584709df13dc876c37391 | 3,655,446 |
def get_ipsw_url(device, ios_version, build):
"""Get URL of IPSW by specifying device and iOS version."""
json_data = fw_utils.get_json_data(device, "ipsw")
if build is None:
build = fw_utils.get_build_id(json_data, ios_version, "ipsw")
fw_url = fw_utils.get_firmware_url(json_data, build)
... | 75b9d85d93b03b1ebda681aeb51ac1c9b0a30474 | 3,655,447 |
from typing import Any
def escape_parameter(value: Any) -> str:
"""
Escape a query parameter.
"""
if value == "*":
return value
if isinstance(value, str):
value = value.replace("'", "''")
return f"'{value}'"
if isinstance(value, bytes):
value = value.decode("utf... | 00b706681b002a3226874f04e74acbb67d54d12e | 3,655,448 |
def Get_Query(Fq):
""" Get_Query
"""
Q = ""
EoF = False
Ok = False
while True:
l = Fq.readline()
if ("--" in l) :
# skip line
continue
elif l=="":
EoF=True
break
else:
Q += l
if ";" in ... | a1850799f7c35e13a5b61ba8ebbed5d49afc08df | 3,655,449 |
def get_path_segments(url):
"""
Return a list of path segments from a `url` string. This list may be empty.
"""
path = unquote_plus(urlparse(url).path)
segments = [seg for seg in path.split("/") if seg]
if len(segments) <= 1:
segments = []
return segments | fe8daff2269d617516a22f7a2fddc54bd76c5025 | 3,655,450 |
import typing
from pathlib import Path
def get_config_file(c: typing.Union[str, ConfigFile, None]) -> typing.Optional[ConfigFile]:
"""
Checks if the given argument is a file or a configFile and returns a loaded configFile else returns None
"""
if c is None:
# See if there's a config file in th... | 6e176167a81bccaa0e0f4570c918fcb32a406edb | 3,655,451 |
import logging
def get_logger(tag: str) -> Logger:
"""
Produces logger with given message tag
which will write logs to the console and file stored in LOG_FILE_PATH directory
:param tag: tag for messages of the logger
:return: logger object
"""
logger = logging.getLogger(tag)
logger.se... | baebbd8b6724a00c52a730897a22d7df3092e94d | 3,655,452 |
def get_index():
"""Redirects the index to /form """
return redirect("/form") | e52323397156a5a112e1d6b5d619136ad0fea3f0 | 3,655,453 |
def _register_network(network_id: str, chain_name: str):
"""Register a network.
"""
network = factory.create_network(network_id, chain_name)
cache.infra.set_network(network)
# Inform.
utils.log(f"registered {network.name_raw} - metadata")
return network | 8e9b84670057974a724df1387f4a8cf9fc886a56 | 3,655,454 |
from pathlib import Path
def file(base_path, other_path):
"""
Returns a single file
"""
return [[Path(base_path), Path(other_path)]] | 3482041757b38929a58d7173731e84a915225809 | 3,655,455 |
import io
def get_md_resource(file_path):
"""Read the file and parse into an XML tree.
Parameters
----------
file_path : str
Path of the file to read.
Returns
-------
etree.ElementTree
XML tree of the resource on disk.
"""
namespaces = Namespaces().get_namespaces... | 809ea7cef3c9191db9589e0eacbba4016c2e9893 | 3,655,456 |
def fmin_style(sfmin):
"""convert sfmin to style"""
return Struct(
is_valid=good(sfmin.is_valid, True),
has_valid_parameters=good(sfmin.has_valid_parameters, True),
has_accurate_covar=good(sfmin.has_accurate_covar, True),
has_posdef_covar=good(sfmin.has_posdef_covar, True),
... | 44ecba0a25c38a5a61cdba7750a6b8ad53d78c3d | 3,655,457 |
def xirr(cashflows,guess=0.1):
"""
Calculate the Internal Rate of Return of a series of cashflows at irregular intervals.
Arguments
---------
* cashflows: a list object in which each element is a tuple of the form (date, amount), where date is a python datetime.date object and amount is an integer o... | a6adbd091fd5a742c7b27f0816021c2e8499c42f | 3,655,458 |
def check_rt_druid_fields(rt_table_columns, druid_columns):
"""
对比rt的字段,和druid物理表字段的区别
:param rt_table_columns: rt的字段转换为druid中字段后的字段信息
:param druid_columns: druid物理表字段
:return: (append_fields, bad_fields),需变更增加的字段 和 有类型修改的字段
"""
append_fields, bad_fields = [], []
for key, value in rt_tab... | 1c60f49e4316cf78f1396689a55d9a1c71123fe8 | 3,655,459 |
from operator import ne
def is_stuck(a, b, eta):
""" Check if the ricci flow is stuck. """
return ne.evaluate("a-b<eta/50").all() | 53f4bb934cc48d2890289fda3fdb3574d5f6aa4c | 3,655,460 |
def make_map(mapping):
"""
Takes a config.yml mapping, and returns a dict of mappers.
"""
# TODO: Is this the best place for this? Should it be a @staticmethod,
# or even part of its own class?
fieldmap = {}
for field, config in mapping.items():
if type(config) is str:
... | e388bb3789690e443fd17814071e4c24faa12d90 | 3,655,461 |
from typing import Sized
def stable_seasoal_filter(time_series: Sized, freq: int):
"""
Стабильный сезонный фильтр для ряда.
:param time_series: временной ряд
:param freq: частота расчета среднего значения
:return: значения сезонной составляющей
"""
length = len(time_series)
if length ... | fb4997b637d5229ee7f7a645ce19bbd5fcbab0bc | 3,655,462 |
import os
def load_dataset(dataset, batch_size=512):
"""Load dataset with given dataset name.
Args:
dataset (str): name of the dataset, it has to be amazoncat-13k, amazoncat-14k,
eurlex-4.3k or rcv1-2k
batch_size (int): batch size of tf dataset
Returns:
... | f62f7bd4681811e86e075fa9c9439352bb5bd56e | 3,655,463 |
def make_str_lst_unc_val(id, luv):
"""
make_str_lst_unc_val(id, luv)
Make a formatted string from an ID string and a list of uncertain values.
Input
-----
id A number or a string that will be output as a string.
luv A list of DTSA-II UncertainValue2 items. These will be printed
a... | c65b9bb0c6539e21746a06f7a864acebc2bade03 | 3,655,464 |
def plot_faces(ax, coordinates, meta, st):
"""plot the faces"""
for s in st.faces:
# check that this face isnt in the cut region
def t_param_difference(v1, v2):
return abs(meta["t"][v1] - meta["t"][v2])
if all(all(t_param_difference(v1, v2) < 2 for v2 in s) for v1 in s):
... | a7eef2d209f7c15d8ba232b25d20e4c751075013 | 3,655,465 |
import typing
def translate_null_strings_to_blanks(d: typing.Dict) -> typing.Dict:
"""Map over a dict and translate any null string values into ' '.
Leave everything else as is. This is needed because you cannot add TableCell
objects with only a null string or the client crashes.
:param Dict d: dict ... | 1a6cfe2f8449d042eb01774054cddde08ba56f8c | 3,655,466 |
import json
def HttpResponseRest(request, data):
"""
Return an Http response into the correct output format (JSON, XML or HTML),
according of the request.format parameters.
Format is automatically added when using the
:class:`igdectk.rest.restmiddleware.IGdecTkRestMiddleware` and views decorators... | 56682e808dcb9778ea47218d48fb74612ac44b5d | 3,655,467 |
def build_server_update_fn(model_fn, server_optimizer_fn, server_state_type,
model_weights_type):
"""Builds a `tff.tf_computation` that updates `ServerState`.
Args:
model_fn: A no-arg function that returns a `tff.learning.TrainableModel`.
server_optimizer_fn: A no-arg function th... | c0b8285a5d12c40157172d3b48a49cc5306a567b | 3,655,468 |
def madgraph_tarball_filename(physics):
"""Returns the basename of a MadGraph tarball for the given physics"""
# Madgraph tarball filenames do not have a part number associated with them; overwrite it
return svj_filename("step0_GRIDPACK", Physics(physics, part=None)).replace(
".root", ".tar.xz"
... | a0a8bacb5aed0317b5c0fd8fb3de5382c98e267d | 3,655,469 |
def _mk_cmd(verb, code, payload, dest_id, **kwargs) -> Command:
"""A convenience function, to cope with a change to the Command class."""
return Command.from_attrs(verb, dest_id, code, payload, **kwargs) | afd5804937a55d235fef45358ee12088755f9dc9 | 3,655,470 |
def getobjname(item):
"""return obj name or blank """
try:
objname = item.Name
except BadEPFieldError as e:
objname = ' '
return objname | f8875b6e9c9ed2b76affe39db583c091257865d8 | 3,655,471 |
def process_fire_data(filename=None, fire=None, and_save=False, timezone='Asia/Bangkok', to_drop=True):
""" Add datetime, drop duplicate data and remove uncessary columns.
"""
if filename:
fire = pd.read_csv(filename)
# add datetime
fire = add_datetime_fire(fire, timezone)
# drop dup... | 767bb77db2b3815a5646f185b72727aec74ee8d8 | 3,655,472 |
def create_controllable_source(source, control, loop, sleep):
"""Makes an observable controllable to handle backpressure
This function takes an observable as input makes it controllable by
executing it in a dedicated worker thread. This allows to regulate
the emission of the items independently of the ... | 2092de1aaeace275b2fea2945e8d30f529309874 | 3,655,473 |
def getE5():
"""
Returns the e5
Args:
"""
return E5.get() | 35526332b957628a6aa3fd90f7104731749e10ed | 3,655,474 |
def triangulate(pts_subset):
"""
This function encapsulates the whole triangulation algorithm into four
steps. The function takes as input a list of points. Each point is of the
form [x, y], where x and y are the coordinates of the point.
Step 1) The list of points is split into groups. Each g... | 55e145a44303409a4e1ede7f14e4193c06efd769 | 3,655,475 |
def get_session(region, default_bucket):
"""Gets the sagemaker session based on the region.
Args:
region: the aws region to start the session
default_bucket: the bucket to use for storing the artifacts
Returns:
`sagemaker.session.Session instance
"""
boto_session = boto3.S... | 1bfbea7aeb30f33772c1b748580f0776463203a4 | 3,655,476 |
def intp_sc(x, points):
"""
SCurve spline based interpolation
args:
x (list) : t coordinate list
points (list) : xyz coordinate input points
returns:
x (relative coordinate point list)
o (xyz coordinate points list, resplined)
"""
sc = vtk.vtkSCurveSpline(... | 13df2e19c91ff0469ce68467e9e4df36c0e4831b | 3,655,477 |
def backend():
"""Publicly accessible method
for determining the current backend.
# Returns
String, the name of the backend PyEddl is currently using.
# Example
```python
>>> eddl.backend.backend()
'eddl'
```
"""
return _BACKEND | b811dd6a760006e572aa02fc246fdf72ac7e608c | 3,655,478 |
import json
def query_collection_mycollections():
"""
Query Content API Collection with access token.
"""
access_token = request.args.get("access_token", None)
if access_token is not None and access_token != '':
# Construct an Authorization header with the value of 'Bearer <access t... | 98b8a75ea515255fde327d11c959f5e9b6d9ea43 | 3,655,479 |
def xmlbuildmanual() -> __xml_etree:
"""
Returns a empty xml ElementTree obj to build/work with xml data
Assign the output to var
This is using the native xml library via etree shipped with the python standard library.
For more information on the xml.etree api, visit: https://docs.python.org/3... | e08d83aca4b140c2e289b5173e8877e3c3e5fee1 | 3,655,480 |
def graclus_cluster(row, col, weight=None, num_nodes=None):
"""A greedy clustering algorithm of picking an unmarked vertex and matching
it with one its unmarked neighbors (that maximizes its edge weight).
Args:
row (LongTensor): Source nodes.
col (LongTensor): Target nodes.
weight (... | c586ffd325697302a2413e613a75fe4302741af6 | 3,655,481 |
def _get_serve_tf_examples_fn(model, tf_transform_output):
"""Returns a function that parses a serialized tf.Example."""
model.tft_layer = tf_transform_output.transform_features_layer()
@tf.function
def serve_tf_examples_fn(serialized_tf_examples):
"""Returns the output to be used in the serving signature... | 801bfde2b72823b2ba7b8329f080774ca9aa536f | 3,655,482 |
import decimal
def get_profitable_change(day_candle):
""" Get the potential daily profitable price change in pips.
If prices rise enough, we have: close_bid - open_ask (> 0), buy.
If prices fall enough, we have: close_ask - open_bid (< 0), sell.
if prices stay relatively still,... | 94adc63d984e7797590a2dd3eb33c8d98b09c76e | 3,655,483 |
import os
from pathlib import Path
import glob
import re
def load_all_functions(path, tool, factorize=True, agents_quantities=False, rewards_only=False, f_only=False):
""" Loads all results of parameter synthesis from *path* folder into two maps - f list of rational functions for each property, and rewards list o... | 262fdd5ad796889028e61541cc0347b3263407c8 | 3,655,484 |
def run_epoch():
"""Runs one epoch and returns reward averaged over test episodes"""
rewards = []
for _ in range(NUM_EPIS_TRAIN):
run_episode(for_training=True)
for _ in range(NUM_EPIS_TEST):
rewards.append(run_episode(for_training=False))
return np.mean(np.array(rewards)) | d9f5e33e00eaeedfdff7ebb4d3a7731d679beff1 | 3,655,485 |
def _max_pool(heat, kernel=3):
"""
NCHW
do max pooling operation
"""
# print("heat.shape: ", heat.shape) # default: torch.Size([1, 1, 152, 272])
pad = (kernel - 1) // 2
h_max = nn.functional.max_pool2d(heat, (kernel, kernel), stride=1, padding=pad)
# print("h_max.shape: ", h_max.shape... | 68edc979d78ee2fc11f94efd2dfb5e9140762a0e | 3,655,486 |
def getBool(string):
"""
Stub function, set PshellServer.py softlink to PshellServer-full.py for full functionality
"""
return (True) | de7f6a4b124b6a1f6e1b878daf01cc14e5d5eb08 | 3,655,487 |
from typing import Counter
def multi_dists(
continuous,
categorical,
count_cutoff,
summary_type,
ax=None,
stripplot=False,
order="ascending",
newline_counts=False,
xtick_rotation=45,
xtick_ha="right",
seaborn_kwargs={},
stripplot_kwargs={},
):
"""
Compare the di... | 84302dfc359c62c67ef0757ea7c0841e5292b19d | 3,655,488 |
import xdg
def expand_xdg(xdg_var: str, path: str) -> PurePath:
"""Return the value of an XDG variable prepended to path.
This function expands an XDG variable, and then concatenates to it the
given path. The XDG variable name can be passed both uppercase or
lowercase, and either with or without the ... | 13b8885a08c384d29636c5f5070a86e05c30b43a | 3,655,489 |
def follow_index(request):
"""Просмотр подписок"""
users = request.user.follower.all()
paginator = Paginator(users, 3)
page_number = request.GET.get('page')
page = paginator.get_page(page_number)
return render(request, 'recipes/follow_index.html',
{'page': page, 'paginator': pa... | 00851ccffde0e76544e5732d0f651f6e00bc45d4 | 3,655,490 |
def test_drawcounties_cornbelt():
"""draw counties on the map"""
mp = MapPlot(sector="cornbelt", title="Counties", nocaption=True)
mp.drawcounties()
return mp.fig | 8bba5c33c374bf3f4e892bc984b72de22c97e38d | 3,655,491 |
import torch
def atomic_degrees(mol: IndigoObject) -> dict:
"""Get the number of atoms direct neighbors (except implicit hydrogens) in a molecule.
Args:
IndigoObject: molecule object
Returns:
dict: key - feature name, value - torch.tensor of atomic degrees
"""
degrees = []
fo... | 114431622574985bd016276a7a809560c896e1bc | 3,655,492 |
def hotspots(raster, kernel, x='x', y='y'):
"""Identify statistically significant hot spots and cold spots in an input
raster. To be a statistically significant hot spot, a feature will have a
high value and be surrounded by other features with high values as well.
Neighborhood of a feature defined by t... | ab091924bb36576e338c38d752df3f856de331cb | 3,655,493 |
import os
def create_from_image(input_path, output_path=None,
fitimage="FITDEF",
compress="NORMAL",
zoom=0, # %; 0=100%
size=Point(0, 0), # Point (in mm), int or str; 1,2..10=A3R,A3..B5
align=("CENTER", "CENTER"), # LEFT/CENTER/RIGHT, TOP/CENTER/BOTTOM
maxpapersize="... | 68328baeaae8fa804f2182592158b9e1de7e8cba | 3,655,494 |
import configparser
import logging
def _read_config(filename):
"""Reads configuration file.
Returns DysonLinkCredentials or None on error.
"""
config = configparser.ConfigParser()
logging.info('Reading "%s"', filename)
try:
config.read(filename)
except configparser.Error as ex:
... | bb1282e94500c026072a0e8d76fdf3dcd68e9062 | 3,655,495 |
def view_share_link(request, token):
"""
Translate a given sharelink to a proposal-detailpage.
:param request:
:param token: sharelink token, which includes the pk of the proposal
:return: proposal detail render
"""
try:
pk = signing.loads(token, max_age=settings.MAXAGESHARELINK)
... | 9d88375f1f3c9c0b94ad2beab4f47ce74ea2464e | 3,655,496 |
from sklearn.pipeline import Pipeline
def create(pdef):
"""Scikit-learn Pipelines objects creation (deprecated).
This function creates a list of sklearn Pipeline objects starting from the
list of list of tuples given in input that could be created using the
adenine.core.define_pipeline module.
P... | 552014c652d7de236ba917592108315acfd9c694 | 3,655,497 |
def pressure_differentiable(altitude):
"""
Computes the pressure at a given altitude with a differentiable model.
Args:
altitude: Geopotential altitude [m]
Returns: Pressure [Pa]
"""
return np.exp(interpolated_log_pressure(altitude)) | a6a9e7dcc38ac855f3ba5c9a117506a87a981217 | 3,655,498 |
def create_optimizer(hparams, global_step, use_tpu=False):
"""Creates a TensorFlow Optimizer.
Args:
hparams: ConfigDict containing the optimizer configuration.
global_step: The global step Tensor.
use_tpu: If True, the returned optimizer is wrapped in a
CrossShardOptimizer.
Returns:
A Tens... | 9ff18644fe513e3d01b297e30538c396546746ab | 3,655,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.