content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gen_cluster(cid):
"""Generate contents of ECS Cluster page"""
data = awscli('ecs', 'describe-clusters', '--clusters', cid)
data = data['clusters'][0]
srvs = awscli('ecs', 'list-services', '--cluster', cid)
srvs = srvs['serviceArns']
cnts = awscli('ecs', 'list-container-instances', '--cluster... | 5,288,300 |
def chacha20_doubleround(s):
"""Apply a ChaCha20 double round to 16-element state array s.
See https://cr.yp.to/chacha/chacha-20080128.pdf and https://tools.ietf.org/html/rfc8439
"""
QUARTER_ROUNDS = [(0, 4, 8, 12),
(1, 5, 9, 13),
(2, 6, 10, 14),
... | 5,288,301 |
def get_all_edl_modules():
"""Get name and relative path of the modules in edl project
"""
res = {}
for k, v in sys.modules.items():
if hasattr(v, '__file__'):
if v is not None:
try:
if v.__file__ and 'site-packages' in getattr(v, '__file__'):
... | 5,288,302 |
def _get_prog_string(output_string):
""" obtains the string containing the version name and number
"""
pattern = app.capturing(
('Psi4' + app.SPACE +
app.one_or_more(app.NONNEWLINE) + app.SPACE +
'release'))
prog_string = apf.first_capture(pattern, out... | 5,288,303 |
def test_trigram_words():
""" Test case"""
handler = open(file_trigram_name, encoding="utf8")
for word in handler:
for character in word.strip():
if character is '_':
continue
assert character in URDU_ALPHABETS, F"Incorrect word: {word} and char: {character}"
... | 5,288,304 |
def test_data_access(water_meter):
"""Make sure we can load and access data."""
domain, _cloud = water_meter
api = Api(domain=domain, verify=False)
api.login('test', 'test@arch-iot.com')
data = api.device('d--0000-0000-0000-00d2').get()
assert data['slug'] == 'd--0000-0000-0000-00d2'
dat... | 5,288,305 |
def download(i):
"""
Input: {
components - pre-loaded components from bootstrapping
or
cid [str] - CK CID of format (repo UOA:)module UOA:data UOA
(can use wildcards)
(version) [str] - assign version
(force) [bo... | 5,288,306 |
def mergeH(rects):
"""Return `rects` with horizontally adjacent rectangles with the same Y coordinates merged
"""
byY = defaultdict(list)
for r in rects:
byY[r.Y0].append(r)
merged = []
for y in sorted(byY):
yrects = byY[y]
r0 = yrects[0]
for r in yrects[1:]:
... | 5,288,307 |
def main():
"""Executes the module"""
args = parse_args()
extension = os.path.splitext(args.in_path)[1]
if extension.lower() == ".zip":
process_zip(args.in_path, args.categories, args.shape, args.out_path_prefix)
else:
process_dir(args.in_path, args.categories, args.shape, args.out_p... | 5,288,308 |
def new_ff_l2addr_status(dp_id, addrs):
"""
Create FFL2AddrStatus message
"""
return pb.FFL2AddrStatus(
dp_id=dp_id,
addrs=addrs,
) | 5,288,309 |
def get_gts_based_on_difficulty(dataset, img_idx):
"""Returns lists of ground-truth based on difficulty.
"""
# Get all ground truth labels
all_gt_objs = obj_utils.read_labels(dataset.label_dir, img_idx)
# Filter to dataset classes
gt_objs = dataset.kitti_utils.filter_labels(all_gt_objs)
# ... | 5,288,310 |
def get_batch_centroid_id(batch_centroid):
"""Returns a batchcentroid/id.
"""
return get_resource(BATCH_CENTROID_RE, batch_centroid) | 5,288,311 |
def get_optional_interfaces():
"""Return the optional interfaces that should be checked if the relavent
relations have appeared.
:returns: {general_interface: [specific_int1, specific_int2, ...], ...}
"""
optional_interfaces = {}
if relation_ids('ha'):
optional_interfaces['ha'] = ['clust... | 5,288,312 |
def demo():
"""The Nevermined Federated Learning demo.
This demo showcases the nevermined Federated Learning capabilities.
FLow:
1. Setup nevermined
2. Setup accounts
3. Publish compute to the data assets
4. Publish algorithm
5. Publish workflows
6. Order com... | 5,288,313 |
def cdlhangingman(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of hanging man for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string)... | 5,288,314 |
def gast_to_code(gast, out_lang, lvl=0):
"""
gast router that takes generic ast and the output language
that the gast needs to be converted to and executes the
conversion recursively
out_lang correspond to the language codes defined in datastructure:
javascript: js
python: py
"""
con... | 5,288,315 |
def skill(name: str) -> Callable:
"""Wrap function to transform it into Skill object."""
def wrapper(func: Callable) -> Skill:
return Skill(name, func)
return wrapper | 5,288,316 |
def rotate(arr, n, p):
"""Rotates an array.
Args:
arr: The array to be rotated.
n: The size of arr.
p: The number of rotations to be performed.
Returns:
An array rotated p times.
Raises:
ValueError: If p > n.
"""
if p > n:
raise ValueError("The n... | 5,288,317 |
def world2Pixel(geoMatrix, x, y):
"""
Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
the pixel location of a geospatial coordinate
"""
ulX = geoMatrix[0]
ulY = geoMatrix[3]
xDist = geoMatrix[1]
yDist = geoMatrix[5]
rtnX = geoMatrix[2]
rtnY = geoMatrix[4]
pixel = int((x - ul... | 5,288,318 |
def _derivative(f, a, method='central', h=0.01):
"""
Compute the difference formula for f'(a) with step size h.
copied from:
https://personal.math.ubc.ca/~pwalls/math-python/differentiation/differentiation/
Parameters
----------
f : function
Vectorized function of one variable
... | 5,288,319 |
def bed_get_exon_intron_annotations_from_gtf(tr_ids_dic, in_bed,
in_gtf, eia_out,
stats_dic=None,
id2ucr_dic=False,
own_exon_bed=False,
... | 5,288,320 |
def forbidden_request() -> dict:
"""
Returns a generic forbidden request response back.
Used when the token given is not authorized to act on resources.
"""
return return_response(403, responses[403]) | 5,288,321 |
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Huawei Solar Number entities Setup."""
if not entry.data.get(CONF_ENABLE_PARAMETER_CONFIGURATION):
_LOGGER.info("Skipping number setup, as parameter configuration is ... | 5,288,322 |
def maybe_download_data(data_dir):
"""Download data sets if necessary.
Args:
data_dir: Path to where data should be downloaded.
Returns:
Paths to the training and test data files.
"""
if not os.path.isdir(data_dir):
os.makedirs(data_dir)
training_data_path = os.path.join(data_dir,
... | 5,288,323 |
def test_min_edit_distance_insert():
"""
Tests that the insert cost functions correctly. Forced to insert by making
the source string empty.
"""
assert 1234 == min_edit_distance("", "a", insert_cost=lambda char: 1234) | 5,288,324 |
def recursion_constants(max_n):
"""
Calculates the values useful for performing the scalar potential algorithm
"""
k = _gen_2d_array(max_n, max_n, 0)
for n in range(1, max_n):
for m in range(n + 1):
k[m][n] = (((n - 1) * (n - 1)) - (m ** 2)) / (
(2.0 * n - 1) * (2... | 5,288,325 |
def return_malware():
"""Return malware list per platform"""
if platform.system() == "Windows":
return windows_malware_list
else:
return linux_malware_list | 5,288,326 |
def tokenize(text) -> list:
"""
Parses input and returns valid input as typed tokens
If token starts with a:
* character -> word (this will be messed up if b' or r' is introduced
* number -> int || float
Currently does not handle special characters
"""
stack = []
tokens... | 5,288,327 |
def encode(query, doseq=False, safe='', encoding=None,
errors=None, quote_via=quote_plus):
"""Wrapper for urllib.parse.encode"""
return urlencode(query, doseq=doseq, safe=safe,
encoding=encoding, errors=errors, quote_via=quote_via) | 5,288,328 |
def get_session(url, key, secret):
"""Get a :class:`tempoiq.client.Client` instance with the given session
information.
:param String url: Backend's base URL, in the form
"https://your-url.backend.tempoiq.com"
:param String key: API key
:param String secret: API secret
:r... | 5,288,329 |
def get_diffusion_plot_analysis_features(data):
"""Returns all the features associated with the diffusion plot analysis, that is: DTXC, DTYC, DTRC, X2, Y2, R2, DXS, DYS, DRS, HXS, HYS, HRS, DXL, DYL, DRL, HXL, HYL, HRL"""
DTXC, DTYC, DTRC, X2, Y2, R2, DXS, DYS, DRS, HXS, HYS, HRS, DXL, DYL, DRL, HXL, HYL, ... | 5,288,330 |
def main():
"""Main function"""
global commands, args
parser = argparse.ArgumentParser(description="Viewer for crystals vs trucks.")
input_parser = parser.add_mutually_exclusive_group(required=True)
input_parser.add_argument(
"-i",
"--input",
metavar="PATH",
type=str,... | 5,288,331 |
def make_resampled_models(lbda_obs, grid_param_list, model_grid=None,
model_reader=None, em_lines={}, em_grid=None,
dlbda_obs=None, instru_fwhm=None, instru_idx=None,
filter_reader=None, interp_nonexist=True):
"""
Returns a cube of ... | 5,288,332 |
def parseCmd():
"""Parse command line arguments
Returns:
dictionary: Dictionary with arguments
"""
parser = argparse.ArgumentParser(description='Renames the transcripts and genes of a GTF file.')
parser.add_argument('--gtf', type=str, required=True,
help='Path to a gene prediciton f... | 5,288,333 |
def insert_in_bst(root, node):
"""
Insert node in the binary search tree
:param root: root node of the binary search tree
:type root: TreeNode
:param node: node to insert
:type node: TreeNode
:return: root node
:rtype: TreeNode
"""
if root is None:
root = node
else:
... | 5,288,334 |
def _get_serializer_field_type(field: Field) -> Tuple[str, Optional[Type]]:
"""
Get typescript type from trivial serializer field.
"""
field_type: str
dependency = None
if type(field) in DRF_FIELD_MAPPING:
field_type = DRF_FIELD_MAPPING[type(field)]
elif isinstance(field, ModelSerial... | 5,288,335 |
def encode_sequence_into_fasta_file(seq, ofname):
"""writes sequences into fasta file
"""
with open(ofname, "w") as wf:
for i, seq_here in enumerate(seq):
print('>{}'.format(i), file=wf)
print(seq_here, file=wf) | 5,288,336 |
def format_bytes(b):
"""Format bytes as human-readable text."""
kb = 1024
mb = kb*1024
gb = mb*1024
if b < kb:
return '%s b' % b
elif b < mb:
return '{0:.2f} kb'.format(float(b) / kb)
elif b < gb:
return '{0:.2f} mb'.format(float(b) / mb)
else:
return '{0:.2f} gb'.format(float(b) / gb) | 5,288,337 |
def find_anagrams(s):
"""
:param s: user input string
:return: number and a list of anagrams found
"""
dict_lst = read_dictionary(s)
anagram_lst = []
helper(s, '', len(s), dict_lst, anagram_lst, [])
print(str(len(anagram_lst)), ' anagrams:', anagram_lst) | 5,288,338 |
def get(name):
"""
Return the :term:`doclist` of the `Page` specified by `name`
"""
page = dataent.get_doc('Page', name)
if page.is_permitted():
page.load_assets()
docs = dataent._dict(page.as_dict())
if getattr(page, '_dynamic_page', None):
docs['_dynamic_page'] = 1
return docs
else:
dataent.res... | 5,288,339 |
def is_repo(path):
"""Check if the path is in a git repo"""
if path is None:
return False
if not shutil.which('git'):
return False
out = subprocess.run(['git', '-C', str(path), 'rev-parse'],
stdout=subprocess.PIPE,
stderr=subprocess.PIP... | 5,288,340 |
def import_mat_to_conmat(mat_file, data_field_name='F',
orig_channel_names_file=None,
orig_channel_coords_file=None):
"""Import mat to conmat."""
import os
import numpy as np
from nipype.utils.filemanip import split_filename as split_f
from scipy.io... | 5,288,341 |
def test_points_patch_extractor_jp2(
sample_jp2, patch_extr_jp2_csv, patch_extr_jp2_read
):
"""Test PointsPatchExtractor for jp2 image."""
locations_list = pathlib.Path(patch_extr_jp2_csv)
saved_data = np.load(str(pathlib.Path(patch_extr_jp2_read)))
data = read_points_patches(
pathlib.Path(... | 5,288,342 |
def hard_update(source_vars: Sequence[tf.Variable], target_vars: Sequence[tf.Variable]) -> None:
"""Copy source variables to target variables.
Arguments:
source_vars {Sequence[tf.Variable]} -- Source variables to copy from
target_vars {Sequence[tf.Variable]} -- Variables to copy data to
"""... | 5,288,343 |
def create_custom_dataset(
datapath,
savepath,
dataset_name="custom",
set_types=["train", "valid", "test"],
folder_names={
"source1": "source1",
"source2": "source2",
"mixture": "mixture",
},
):
"""
This function creates the csv file for a custom source separation... | 5,288,344 |
def initiate_correct_model(model_name=None, model_path=None, **model_parameters):
"""
Either specify a model path to continue training and existing model or specify a model name to initiate a new model.
Returns a initiated model of type tf.keras.Model
"""
# Validate input
if model_name is None a... | 5,288,345 |
def search(
cli_state,
format,
begin,
end,
advanced_query,
use_checkpoint,
or_query,
include_all,
**kwargs,
):
"""Search for alerts."""
output_header = ext.try_get_default_header(
include_all, _get_default_output_header(), format
)
formatter = OutputFormatter(... | 5,288,346 |
def create_app(config_mode=None, config_file=None):
""" Creates the Flask application
Kwargs:
config_mode (str): The configuration mode. Must be a `class` in
`config.py`. One of ('Production', 'Development', 'Test',
'Docker')
config_file (str): The configuration file.
... | 5,288,347 |
def jupyter_cell_to_script():
"""
script to make a jupyter notebook cell into an independent python script using template.py
""" | 5,288,348 |
def test_write_svgtree():
"""A ParentedTree can be converted into an SVG image using svgling."""
tree = DGParentedTree("foo", ["bar", "baz"])
# write SVG to file
temp_file = NamedTemporaryFile()
temp_file.close()
rstc.write_svgtree(tree, temp_file.name)
with open(temp_file.name, 'r') as... | 5,288,349 |
def computeBootstrap(data, pointingID):
"""Compute the 95% Bootstrap CI from a list of annotations
@param data tuple of np.array containing (accs, annotTCTs, trialTCTs)
@param pointingID the pointingID to look at
@return a tuple (acc_avg, acc_std, tct_trial_avg, tct_trial_std, tct_annot_avg, tct_annot_s... | 5,288,350 |
def set_up_box_environment():
"""
Sets up a demo Box environment.
"""
box_client = get_box_client()
clients_folder = box_client.folder("0").create_subfolder("BoxWorks Clients")
print(f"Created Clients folder with ID {clients_folder.response_object['id']}")
client_folder = box_client.folder... | 5,288,351 |
def from_meshio(mesh):
"""Convert a :class:`meshio.Mesh` to :class:`toughio.Mesh`.
Parameters
----------
mesh : meshio.Mesh
Input mesh.
Returns
-------
toughio.Mesh
Output mesh.
"""
if mesh.cell_data:
version = get_meshio_version()
if version[0] >= ... | 5,288,352 |
def register_decoder(name=None):
"""Register a decoder. name defaults to function name snake-cased."""
def decorator(decoder_fn, registration_name=None):
"""Register & return decoder_fn with registration_name or default name."""
decoder_name = registration_name or default_name(decoder_fn)
... | 5,288,353 |
def reorder_files(path: str) -> None:
"""
Remove any subdirectories in the given path and reorder the files in the
directory adding the name of the directory to the filename
"""
for dir in os.listdir(path):
dir_path = os.path.join(path, dir)
if os.path.isdir(dir_path):
fo... | 5,288,354 |
def _CalcPanelLocalApparentWindSph(alphas, betas, angular_rate_b,
apparent_wind_speed, panel, params):
"""Calculates local apparent wind at each sampling point on a panel.
Args:
alphas: Angle-of-attacks [rad] represented as a (...,) ndarray.
betas: Sideslip angles [rad] r... | 5,288,355 |
def cross_validate(model, train, test=None, k=5):
"""Calculates mean error using k-fold cross-validation."""
train = train.sample(frac=1, random_state=360) # Shuffles rows.
k = k if test is None else 1
chunks = np.array_split(train, k)
mean_rmse = 0
for i in range(0, k):
if VALIDATING:... | 5,288,356 |
def composite_difference_composite(original, other):
""" Subtract all elements that belong to other from original.
This is a tricky one, as we have to subtract one tree from another.
Good thing we can iterate over both trees in linear time and perform the entire difference operation
in linear time... | 5,288,357 |
def calcular_puntos (boolean,cant_punt,difficult):
"""resta o suma segun si se equivoco o no en las coincidencias y segun la dificultad elegida"""
if boolean:
x = sumar_puntos(cant_punt,difficult)
else:
x = restar_puntos(cant_punt,difficult)
return x | 5,288,358 |
def conv2d(images, kernels, padding="SAME", strides=[1, 1]) -> core.Variable:
"""2D convolution, with same api as tf.nn.conv2d [1].
Args:
images: A `Variable` of shape [n_images, imheight, imwidth, n_channels].
kernels: A `Variable` of shape [kernheight, kernwidth, channels_in, channels_out].
... | 5,288,359 |
def getVelocity(data):
""" Calculate velocity of a given set of values using linear regression.
Arguments:
data An iterable of numbers.
Returns:
velocity The estimates slope.
"""
sumY = sumXY = 0
for x, y in enumerate(data):
sumY... | 5,288,360 |
def freeze_layer(layer):
"""
Freeze a layer, so its weights won't be updated during training
:param layer:
:return:
"""
for param in layer.params:
layer.params[param].discard('trainable')
return layer | 5,288,361 |
def serialize_example(row):
"""
Creates a tf.Example message ready to be written to a file.
"""
# Create a dictionary mapping the feature name to the tf.Example-compatible
# data type.
fp = preprocess_fp(row[0])
year = preprocess_year(row[2])
feature = {
"floorplan": _floats_ar... | 5,288,362 |
def setup_logging(logger, debug=False): # pragma: no cover
"""Configures logging for the module"""
fmt_str = "%(asctime)s: %(levelname)s:" \
" %(module)s.%(funcName)s():%(lineno)d: %(message)s"
console_handler = logging.StreamHandler(stream=sys.stdout)
console_handler.addFilter(LessThan... | 5,288,363 |
def parse_from_text(text_path, dtype_list, path_list):
""" dtype_list is a tuple, which represent a list of data type.
Example:
The file format like:
a/1.jpg 3 2.5
a/2.jpg 4 3.4
dtype_list: (str, int, float)
path_list: (true, false, false)
Returns:
res: according to the dtype_lis... | 5,288,364 |
def parse_cached(cached_credentials):
"""Parse existing csv file
Requires first 4 columns to be TeamNum, Password, Code, Color [in hex]
"""
teamnums = []
passwords = []
codes = []
with open(cached_credentials) as f:
f.readline()
for line in f:
tokens = line[:-1].... | 5,288,365 |
def preprocess(
transcript_list: TextIO, lid_model: str, mptable_file: str, recipe_file: str
) -> None:
"""Preprocess parliament transcripts in TRANSCRIPT_LIST using given file arguments.
LID_MODEL predicts language (fi/sv/both) for those statements that do not have a language label
in the XMLs.
M... | 5,288,366 |
def ubytes(n_spin_orbitals, i, state):
"""
Remove electron at orbital i in state.
Parameters
----------
n_spin_orbitals : int
Total number of spin-orbitals in the system.
i : int
Spin-orbital index
state : bytes
Product state.
Returns
-------
state_new :... | 5,288,367 |
def tf_grad(t_scalar_func):
"""Maps a TF scalar-function to its TF gradient-function."""
def f_grad(t_pos):
tape = tf.GradientTape()
with tape:
tape.watch(t_pos)
t_val = t_scalar_func(t_pos)
grad = tape.gradient(t_val, t_pos)
assert grad is not None, '`None` gradient.'
return grad
... | 5,288,368 |
def cleanup_flows(bridge_name, interface):
"""
flows of which ports do not exist any more get removed (generic cleanup)
@param bridge_name:
"""
flowports = list_ports_in_of()
activeports = [int(get_vswitch_port(x)) for x in list_ports(interface)]
ap = set(activeports)
todelete = [x for x... | 5,288,369 |
def parse_tpkl_depreciated(filename):
"""
A function to parse custom recarray objects.
This variation is dependent upon table.py from the Anfinrud Lab
Parameters:
filename (str): path of file to be analyzed
Returns:
Trace:custom object built to hold a single scattering curve and
... | 5,288,370 |
def time_to_string(time):
"""Converts a datetime instance to a string"""
if time is None:
return time
if time == "now":
time = datetime.now()
return mktime(time.timetuple()) | 5,288,371 |
def spacecraft_valid_id(request):
"""
AJAX method for checking whether a given identifier is in use or not within
the database.
:param request: The GET HTTP request.
:return: '{ isValid: "true/false", value: "$GET.value" }
"""
requested_id = request.GET['value']
if not requested_id:
... | 5,288,372 |
def url_for(endpoint, **kw):
"""
NB: Altered flask functions
Assembly url_for is an alias to the flask url_for, with the ability of
passing the function signature to build the url, without knowing the endpoint
:param endpoint:
:param kw:
:return:
"""
_endpoint = None
if isinstan... | 5,288,373 |
def reentrant_redis_locks():
"""Decorator/context manager to enable reentrant redis locks
This is useful for tests that do things like acquire a lock and
then, before the lock is released, fire off a celery task (which
will usually be executed synchronously due to
`CELERY_TASK_ALWAYS_EAGER`) that a... | 5,288,374 |
def include_original(dec):
""" Meta decorator, which make the original function callable
(via f._original() )
"""
def meta_decorator(f):
decorated = dec(f)
decorated._original = f
return decorated
return meta_decorator | 5,288,375 |
def test_consistency(key):
"""Test defaults consistency."""
units = set(_handle_default('units'))
other = set(_handle_default(key))
au_keys = set('stim exci syst resp ias chpi'.split())
assert au_keys.intersection(units) == set()
if key in ('color', 'scalings_plot_raw'):
assert au_keys.i... | 5,288,376 |
def test_no_overlaps(balanced):
"""
Test that the final tree doesn't contain any overlaps
"""
for i in balanced:
for j in balanced:
if i != j:
assert i not in morton.find_ancestors(j)
assert j not in morton.find_ancestors(i) | 5,288,377 |
def get_related_model(model, relationname):
"""Gets the class of the model to which `model` is related by the attribute
whose name is `relationname`.
"""
if hasattr(model, relationname):
attr = getattr(model, relationname)
if hasattr(attr, 'property') \
and isins... | 5,288,378 |
def retrieve_all(database_connection: mysql.connector.connect
) -> List[Dict]:
"""Returns a list of OrderedDicts with scorekeeper details for all
scorekeepers
Arguments:
database_connection (mysql.connector.connect)
"""
scorekeeper_ids = info.retrieve_all_ids(database_connec... | 5,288,379 |
def main(
newick_tree_input: Path,
metadata_input: Path,
pangolin_report: Path = typer.Argument(..., help="Pangolin lineage report CSV"),
ref_name: str = typer.Option("MN908947.3", help="Reference/outgroup name"),
leaflist: Path = typer.Option(Path('leaflist'), help='List of leaves/taxa to filter fo... | 5,288,380 |
def proper_paranthetics(string):
"""
Evaluate whether open and closed parentheses match in proper order.
Return 1 if there are unclosed open parens.
Return 0 if parens are balanced.
Return -1 if there are close parens not preceded by open parens.
"""
paren_stack = Stack()
for char in st... | 5,288,381 |
def parse_csv(data):
""" Parses LiteX CSV file.
Args:
data (list): list of CSV file lines
"""
# scan for CSRs first, so it's easier to resolve CSR-related constants in the second pass
for _type, _name, _address, _, __ in data:
if _type == 'csr_base':
peripherals[_name] ... | 5,288,382 |
def test_delete_directory():
"""Deletes the created directory."""
shutil.rmtree(dataset_path)
assert os.path.exists(dataset_path) is False | 5,288,383 |
def sqexpcov(n: int, w: float, var: float = 1.0):
"""Construct square exponential covariance matrix
Args:
n: size of the matrix
w: scale
var: variance
Returns:
"""
# i, j = meshgrid(arange(n), arange(n))
# return var * exp(- w * (i - j) ** 2)
return var * exp(-w * ... | 5,288,384 |
def test_from_string(source_data_str, dattr_obj):
""" Testing alternate constructor `from_string()`. """
try:
assert DictAttr.from_string(source_data_str) == dattr_obj
except Exception as e:
print("~" * 100)
traceback.print_exc(file=sys.stdout)
print("~" * 100)
assert... | 5,288,385 |
def create_email_addresses_in_group(email_group_id):
"""
Create new /email_addresses in a certain email_group
---
Method: POST
@param: email_group_id int
@param: email_addresses str // if many, divided by comma
"""
request_data = request.json
# get email_group
email_group = Emai... | 5,288,386 |
def make_config(
src_path: str,
dst_path: str,
*,
data: OptAnyByStrDict = None,
exclude: OptStrSeq = None,
include: OptStrSeq = None,
skip_if_exists: OptStrSeq = None,
tasks: OptStrSeq = None,
envops: OptAnyByStrDict = None,
extra_paths: OptStrSeq = None,
pretend: OptBool = N... | 5,288,387 |
def add_new_entry():
"""Add an entry"""
# json_data = request.get_json()
title = str(request.data.get('title', '')).strip()
description = str(request.data.get('description', ''))
# check empty title
if not title:
response = {"message": "Please input title", "status": 401}
return ... | 5,288,388 |
def check_java_home_set():
"""Check if the java home set"""
# check if environ variable is set
if "JAVA_HOME" not in os.environ:
Log.error("JAVA_HOME not set")
return False
# check if the value set is correct
java_path = get_java_path()
if os.path.isfile(java_path) and os.access(java_path, os.X_OK)... | 5,288,389 |
def error_403(error):
"""
Página de erro customizada: Erro 403
Args:
error: error class
Returns:
Template renderizado: errors/403.html
"""
return render_template('errors/403.html', legend='Erro 403'), 403 | 5,288,390 |
def post_sqs_message(queue, payload, delay=0):
"""
Send a new SQS message for backend processing
:param queue: Boto3 SQS Queue object
:param payload: Json Serializable Python object
:param delay: Delay in second. How much time to delay before message becomes active
:return: Nothing
"""
t... | 5,288,391 |
def print_banner(filename: str, template: str = DEFAULT_BANNER_TEMPLATE) -> None:
"""
Print text file to output.
:param filename: Which file to print.
:param template: Format string which specified banner arrangement.
:return: Does not return anything
"""
if not os.path.isfile(filename):
... | 5,288,392 |
def get_test_data_folder(schemaroot='schema', which=''):
"""
"""
import privapi.tests.data
folder = os.path.dirname(os.path.abspath(privapi.tests.data.__file__))
folder = os.path.join(os.path.join(folder, schemaroot), which)
return folder | 5,288,393 |
def fill_nan(array: np.ndarray) -> np.ndarray:
"""Replace NaNs with values interpolated from their neighbors
Replace NaNs with values interpolated from their neighbors using a 2D Gaussian
kernel, see: https://docs.astropy.org/en/stable/convolution/#using-astropy-s-convolution-to-replace-bad-data
"""
... | 5,288,394 |
def backup_remote():
"""Does a remote database dump and scps the file. Returns the filename."""
remote_filename = get_backup_filename(hostname=env.host_string)
print("Remote filename: " + remote_filename)
with cd('bookmarker'):
run('source env/bin/activate && ' + BACKUP_COMMAND + remote_filenam... | 5,288,395 |
def parse_args():
"""Parse command-line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('config', help='train config file path')
parser.add_argument('--n_data', default=None, dest='n_data', type=int,
help='size of dataset to generate (overrides config fi... | 5,288,396 |
def build_signature_def_from_tensors(inputs, outputs, method_name):
"""Builds signature def with inputs, outputs, and method_name."""
return tf.saved_model.signature_def_utils.build_signature_def(
inputs={
key: tf.saved_model.utils.build_tensor_info(tensor)
for key, tensor in inputs.items(... | 5,288,397 |
def splice_before(base, search, splice, post_splice="_"):
"""Splice in a string before a given substring.
Args:
base: String in which to splice.
search: Splice before this substring.
splice: Splice in this string; falls back to a "." if not found.
post_splice: String to add ... | 5,288,398 |
def _field_from_annotation(attr: str,
annotation,
array_type: FieldArrayType = FieldArrayType.scalar,
) -> FieldDesc:
"""
Create a SimpleField or a StruturedField, given annotation information.
Parameters
----------
at... | 5,288,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.