content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import urllib
import json
def fetch_object(object_id: int, url: str):
"""
Fetch a single object from a feature layer. We have to fetch objects one by one, because they
can get pretty big. Big enough, that if you ask for more than one at a time, you're likely to
encounter 500 errors.
object_id: ob... | d193d9368eec79028beeb545a3fe411fa0c131bc | 14,000 |
def density_forecast_param(Yp, sigma, _, rankmatrix, errordist_normed, dof):
"""creates a density forecast for Yp with Schaake Schuffle
Parameters
----------
Yp: numpy.array
24-dimensional array with point-predictions of day ahead prices
sigma: nump... | 809458a7d3de0ae2997f392e52f91a9b4c02e181 | 14,001 |
def gaussian_blur(img: np.ndarray, kernel_size: int) -> np.ndarray:
"""Applies a Gaussian Noise kernel"""
if not is_valid_kernel_size(kernel_size):
raise ValueError(
"kernel_size must either be 0 or a positive, odd integer")
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) | 6bedc6b15848c18ed52c8348f3bec1b4181f74d7 | 14,002 |
def get_controls_snapshots_count(selenium, src_obj):
"""Return dictionary with controls snapshots actual count and count taken
from tab title."""
controls_ui_service = webui_service.ControlsService(selenium)
return {
"controls_tab_count": controls_ui_service.get_count_objs_from_tab(
src_obj=src_... | 5e6a11a2a94093850f810e0ec6c93037a9f40bca | 14,003 |
import random
import math
def fast_gnp_random_graph(n, p, seed=None, directed=False):
"""Returns a `G_{n,p}` random graph, also known as an Erdős-Rényi graph or
a binomial graph.
Parameters
----------
n : int
The number of nodes.
p : float
Probability for edge creation.
se... | f84c577a4f575186913980c8d9a5dcc16d771291 | 14,004 |
import math
def round_to(f: float, p: int = 0) -> float:
"""Round to the specified precision using "half up" rounding."""
# Do no rounding, just return a float with full precision
if p == -1:
return float(f)
# Integer rounding
elif p == 0:
return round_half_up(f)
# Round to ... | ad464bced2e2b1b87208f61e7ca73b42d5e31fa5 | 14,005 |
def get_interface_type(interface):
"""Gets the type of interface
"""
if interface.upper().startswith('GI'):
return 'GigabitEthernet'
elif interface.upper().startswith('TE'):
return 'TenGigabitEthernet'
elif interface.upper().startswith('FA'):
return 'FastEthernet'
elif i... | 8a898f75e0e05715e0ced7258b8e8d4bf9905377 | 14,006 |
def __get_global_options(cmd_line_options, conf_file_options=None):
""" Get all global options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: ... | 3c9880616ae274f4254cdd29558f1022fdfc6ff4 | 14,007 |
def download_file(service, drive_file):
"""Download a file's content.
Args:
service: Drive API service instance.
drive_file: Drive File instance.
Returns:
File's content if successful, None otherwise.
"""
download_url = drive_file.get('downloadUrl')
if download_url:
resp, content = service... | fa8ad859e47dbaec0cb9a4eea0be5497239e359e | 14,008 |
def get_include_file_end_before(block: Block) -> str:
"""
>>> # test end-before set to 'end-marker'
>>> block = lib_test.get_test_block_ok()
>>> get_include_file_end_before(block)
'# end-marker'
>>> assert block.include_file_end_before == '# end-marker'
>>> # test end-before not set
>>>... | c8ae330fb24a2a7e5304d8a5e5c5438bf9346c63 | 14,009 |
import torch
import random
def add_random_circles(tensor: torch.Tensor, n_circles: int, equalize_overlaps: bool = True):
"""Adds n_circles random circles onto the image."""
height, width = tensor.shape
circle_img = torch.zeros_like(tensor)
for _ in range(n_circles):
circle_img = add_circle(cir... | 17e0cf8d53cf0f8b3c542f0fd0f49151c6842ba9 | 14,010 |
def sample_quadric_surface(quadric, center, samples):
"""Samples the algebraic distance to the input quadric at sparse locations.
Args:
quadric: Tensor with shape [..., 4, 4]. Contains the matrix of the quadric
surface.
center: Tensor with shape [..., 3]. Contains the [x,y,z] coordinates of the
... | e4448be0058f4a8010a72eaf9506e95695b1b35e | 14,011 |
def mol2df(mols: Mols[pd.DataFrame], multiindex=False) -> pd.DataFrame:
"""
flattens a mol into a dataframe with the columns containing the start, stop and price
:param mols: mols to transform
:return:
"""
if multiindex:
flat = {
((start, stop), price): series
for... | 63b16fa99a9c76a29cbef8755cf29928f05637f6 | 14,012 |
from typing import Tuple
def load_sequence_classifier_configs(args) -> Tuple[WrapperConfig, pet.TrainConfig, pet.EvalConfig]:
"""
Load the model, training and evaluation configs for a regular sequence classifier from the given command line
arguments. This classifier can either be used as a standalone mode... | 8729851faae06ed7c0331960db4f933283e7278e | 14,013 |
def gender(word):
""" Returns the gender for the given word, either:
MALE, FEMALE, (MALE, FEMALE), (MALE, PLURAL) or (FEMALE, PLURAL).
"""
w = word.lower()
# Adjectives ending in -e: cruciale, difficile, ...
if w.endswith(("ale", "ile", "ese", "nte")):
return (MALE, FEMALE)
# Mos... | 7a8384d778b9aec9fcc5eb32f26c282805cdfa0b | 14,014 |
from typing import Counter
def fcmp(d,r):
"""
Compares two files, d and r, cell by cell. Float comparisons
are made to 4 decimal places. Extending this function could
be a project in and of itself.
"""
# we need to compare the files
dh=open(d,'rb')
rh=open(r,'rb')
dlines = dh... | 9f6f24314316fbef26ce0fb404a88d34c3049b2b | 14,015 |
def is_vector_equal(vec1, vec2, tolerance=1e-10):
"""Compare if two vectors are equal (L1-norm) according to a tolerance"""
return np.all(np.abs(vec1 - vec2) <= tolerance) | 9bb42fa3bc2cbb25edd6eabeddb2aa2d8d93e5c8 | 14,016 |
def partition_pair(bif_point):
"""Calculate the partition pairs at a bifurcation point.
The number of nodes in each child tree is counted. The partition
pairs is the number of bifurcations in the two child subtrees
at each branch point.
"""
n = float(sum(1 for _ in bif_point.children[0].ipreord... | 7889eb95a0ac3b2a7d1138061a4651b1e79427c0 | 14,017 |
def readPyCorrFit(file):
"""
Read header and data of .csv PyCorrFit output file
========== ===============================================================
Input Meaning
---------- ---------------------------------------------------------------
file String with path to .csv file
... | 0dcaa26c0ef2f8270748241cbd03bc6aaa750672 | 14,018 |
def end_of_time(t):
""" Return the next hour of the passed time. e.g, 18:25:36 --> 19:00:00 """
return t + timedelta(minutes=60) - timedelta(minutes=t.minute) - timedelta(seconds=t.second) | dce1f0cde67c834580edb349e0dfbcdee0b4d171 | 14,019 |
def modf(x):
"""modf(x)
Return the fractional and integer parts of x. Both results carry the sign
of x.
"""
signx = sign(x)
absx = Abs(x)
return (signx * Mod(absx, 1), signx * floor(absx)) | 18f4e9aca22591f2960bb6ddf28fcf677bedee65 | 14,020 |
from typing import Tuple
def get_user_from_request(request, available_query_params: list()) -> Tuple[User, GeneralApiResponse]:
"""
Entra com o request da view e uma lista de query params do user que podem ser consultados
Retorna um user caso seja si mesmo, ou tenha permissão de acesso a outros usuários
... | b9d0274ac5ea8e0cbc210b1f4f5e8d46398e8e6d | 14,021 |
def longest_CD(values):
"""
Return the sequence range for the longest continuous
disorder (CDl) subsequence.
"""
# Filter residues with score equal or greater than 0.5
# and store its position index
dis_res = [index for index, res in enumerate(values)
if float(res) >= 0.5]
... | f07b74b9553c156d2d4b62e17ea02b466a16fe74 | 14,022 |
def get_read_length(filename):
""" Return the first read length of fastq file.
:param str filename: fastq file.
"""
with FastqReader(filename) as filin:
read_len = len(next(iter(filin)))
return read_len | 961af7ff12c422c68349dabee064acd465a1a090 | 14,023 |
def no_outliers_estimator(base_estimator, x, alpha=0.01):
""" Calculate base_estimator function after removal of extreme quantiles
from the sample
"""
x = np.array(x)
if len(x.shape) < 3:
x = np.expand_dims(x, -1)
low_value = np.quantile(x, alpha, axis=(0, 1))
high_value = np.quantil... | 3c23f9cacc1108d6ecb24b690ff731e3a3554b44 | 14,024 |
from server.forms import FormNotCompleteError, FormValidationError
from typing import cast
from typing import Tuple
def error_state_to_dict(err: ErrorState) -> ErrorDict:
"""Return an ErrorDict based on the exception, string or tuple in the ErrorState.
Args:
err: ErrorState from a api error state
... | 79cf9a971886241c8760bf0091af0c91a4d80ade | 14,025 |
from typing import Set
def english_words() -> Set[str]:
"""Return a set of english words from the nltk corpus "words".
Returns:
Set of english words.
"""
nltk_resource("corpora/words")
return set(nltk.corpus.words.words()) | 2cda38fb0026805c7792bcf45727492b09b38a89 | 14,026 |
def bipartite_matching_wrapper(a, b, score_func, symmetric=False):
"""A wrapper to `bipartite_matching()` that returns `(matches, unmatched_in_a, unmatched_in_b)`
The list of `matches` contains tuples of `(score, a_element, b_element)`. The two unmatched
lists are elements from each of the respective input... | 702c290b6874b595fb0249c865c5723c84d485ba | 14,027 |
import itertools
def gen_seldicts(
da,
dims=None,
check_empty=True,
unstack=True
):
"""
TODO: improve documentation
generates a list of dictionaries to be passed into dataarray selection
functions.
Parameters
----------
da : xr.DataArray
datarray to... | 2bd46bcf9d94ab64593d889bbae89f4e07d689b2 | 14,028 |
def get_interface_type(interface):
"""Gets the type of interface
Args:
interface (str): full name of interface, i.e. Ethernet1/1, loopback10,
port-channel20, vlan20
Returns:
type of interface: ethernet, svi, loopback, management, portchannel,
or unknown
"""
if in... | 8196bfa37ef25f0fa1c08577d215329ecc977c4a | 14,029 |
def create_int_feature_list(name, key, prefix="", module_dict=None):
"""Creates accessor functions for bytes feature lists.
The provided functions are has_${NAME}, get_${NAME}_size, get_${NAME}_at,
clear_${NAME}, and add_${NAME}.
example = tensorflow.train.SequenceExample()
add_image_timestamp(1000000, exam... | 58b08f518050a67db72f0572a78f7dab5a68d468 | 14,030 |
def ROC(y_pred, y_true, positive_column = 0,draw = True):
"""
ROC
"""
y_pred = y_pred[:,0]
y_true = y_true[:,0]
# sort by y_pred
sort_index = np.argsort(-y_pred)
y_pred = y_pred[sort_index]
y_true = y_true[sort_index]
tprs = []
fprs = []
positive_num = (y_tru... | efeefbd570988c83f912345794cbd19e15ec67a2 | 14,031 |
def ignore_check(self, channel: discord.TextChannel, ignore_dm: bool = False, from_main: bool = False):
"""
A function that checks whether or not that channel allows command.
Args:
self: instance of the class this command calls or this can be commands.Bot
channel (discord.TextChannel): the ... | 284ba6432d792a3382383cf9b53a5932897b5e53 | 14,032 |
def network_count_allocated_ips(context, network_id):
"""Return the number of allocated non-reserved ips in the network."""
return IMPL.network_count_allocated_ips(context, network_id) | 33f7ce340d222c3843962e6e64a06440e5dfd526 | 14,033 |
def _parse_transform_spec( transform_spec ):
"""
Parses a transform specification into its name and parameters dictionary.
Raises ValueError if the specification is invalid, it represents an unknown
transform, or if the encoded parameters do not match the transform's expected
types.
Takes 1 ar... | b914d96d9ad1e8da3deb10f1c6500c2ee58b4928 | 14,034 |
from typing import Union
from typing import List
def parse_text_multiline(data: Union[str, List[str]]) -> str:
"""Parse the text in multiline mode."""
if isinstance(data, str):
return data
elif isinstance(data, list) and all(map(is_str, data)):
return '\n'.join(data)
else:
ra... | ba8e50422a89de14a464d4917138c5faa051124d | 14,035 |
def get_latest_episode_release(series, downloaded=True, season=None):
"""
:param series series: SQLAlchemy session
:param downloaded: find only downloaded releases
:param season: season to find newest release for
:return: Instance of Episode or None if not found.
"""
session = Session.object... | bcf01b5f3af00bb9bc8ddfb0609be771c9350a79 | 14,036 |
def _set_user_permissions_for_volumes(users, volumes):
"""
Returns the section of the user data script to create a Linux
user group and grant the group permission to access the mounted
volumes on the EC2 instance.
"""
group_name = 'volumes'
user_data_script_section = f"""
groupadd {group_n... | 2d262a52cfa2f3e142da3dd7767dcc6cff14c929 | 14,037 |
def cached_examples():
"""This view should be cached for 60 sec"""
examples = ExampleModel.query()
return render_template('list_examples_cached.html', examples=examples) | f598589967f82daaf3c7e9cb88f7679786e5bf18 | 14,038 |
def corona_surface_integral(solution, E, candidate_attach_pts, corona_elem, phys_param, debug_flag=False):
"""
Surface integral around the points that are marked as possible attachment candidates
"""
pcg_idx_vec = np.zeros((len(candidate_attach_pts.keys())), dtype=np.int64)
Q_vec = np.zeros((le... | 72f16e1f9afbd35f6f877263abe1af9d0ebbf6d0 | 14,039 |
from typing import Callable
import datasets
def librispeech_adversarial(
split_type: str = "adversarial",
epochs: int = 1,
batch_size: int = 1,
dataset_dir: str = None,
preprocessing_fn: Callable = None,
cache_dataset: bool = True,
framework: str = "numpy",
clean_key: str = "clean",
... | 2ab2da4f56194dada3cd361371ef32b1f2fd6194 | 14,040 |
def search4letters(phrase, letters='aeiou'):
"""
->return a set of the 'letters' found in 'phrase'.
:param phrase: phrase where the search will be made
:param letters:set of letters that will be searched for in the sentence
:return returns a set ()
"""
return set(letters).intersection(set(ph... | e58d0863aa090ac3644cd7bf26e783efe2956d35 | 14,041 |
import argparse
def handle_cmdline_args():
"""
Return an object with attributes 'infile' and
'outfile', after handling the command line arguments
"""
parser = argparse.ArgumentParser(
description='Generate synthetic data from a specification in a json '
'file using the... | 434316ca9333182b370e4863b6cda5fe2fb37b25 | 14,042 |
import gc
def merge_flights(prev_flights_filename, next_flights_filename, ids_df, log):
"""
Gets the next days flights that are the continuation of the previous days
flights and merges them with the previous days flights.
It writes the new next days and previous days flights to files prepended
wi... | 6d0cec2c8cc66d04facdde01e24ce0b3aa57dc55 | 14,043 |
def findClusters( peaks, thresh ):
"""Since the peaks are in sequence, this method follows a very simplistic
approach. For each peak it checks its distance from the previous peak. If
it is less than threshold, it clusters that peak with the previous one.
Note that in each of the clusters, input ord... | f74e504557e7c7e796d29290dccabe043ac70dc0 | 14,044 |
import os
def docker_compose_file(pytestconfig):
"""Get docker compose file"""
return os.path.join(str(pytestconfig.rootdir), "docker-compose.yml") | 8f723f0a6144bf687567c6e998ae54495dcd936d | 14,045 |
import os
def sample():
"""
Returns the path to the sample of the given name.
"""
def inner(name):
return os.path.join(
os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'samples'
), name
)
return inner | e042b6da15ee85d818ac830e6cfd74a1f11745a2 | 14,046 |
def acq_max_single_seed(ac, gp, y_max, bounds):
"""
A function to find the maximum of the acquisition function using
the 'L-BFGS-B' method.
Input Parameters
----------
ac: The acquisition function object that return its point-wise value.
gp: A gaussian process fitted to the relevant data.
... | 5a705e15e41be8063f476a40b1cfae9385b98af7 | 14,047 |
def futures_pig_rank(symbol: str = "外三元") -> pd.DataFrame:
"""
价格排行榜
https://zhujia.zhuwang.cc/lists.shtml
:param symbol: choice of {"外三元", "内三元", "土杂猪", "玉米", "豆粕"}
:type symbol: str
:return: 价格排行榜
:rtype: pandas.DataFrame
"""
if symbol == "外三元":
temp_df = pd.read_html("http... | 9afc155021afc2b8ffbef4a0e778f1ab6360219f | 14,048 |
import math
def psubl_T(T):
"""
EQ 6 / Sublimation Pressure
"""
T_star = 273.16
p_star = 611.657E-6
a = (-0.212144006E2, 0.273203819E2, -0.610598130E1)
b = ( 0.333333333E-2, 0.120666667E1, 0.170333333E1)
theta = T / T_star
sum = 0
for i in range(0, 3):
sum += a[i] * t... | 0e3f875fc2d249c78a5db6268dcc0df31213a7ff | 14,049 |
def map_key_values(f, dct):
"""
Like map_with_obj but expects a key value pair returned from f and uses it to form a new dict
:param f: Called with a key and value
:param dct:
:return:
"""
return from_pairs(values(map_with_obj(f, dct))) | 0918ff4ff9ab994b10fe2543dce305f99b7278fb | 14,050 |
def plot_ppc(
ax,
length_plotters,
rows,
cols,
figsize,
animated,
obs_plotters,
pp_plotters,
posterior_predictive,
pp_sample_ix,
kind,
alpha,
linewidth,
mean,
xt_labelsize,
ax_labelsize,
jitter,
total_pp_samples,
legend,
markersize,
ani... | 83d01e6b9f9f170b9e8dc2ff3cf95916106196c5 | 14,051 |
import importlib
def load_module(name):
"""Load the named module without registering it in ``sys.modules``.
Parameters
----------
name : string
Module name
Returns
-------
mod : module
Loaded module
"""
spec = importlib.util.find_spec(name)
mod = importlib.util.mod... | 762c99efcc17f9f1d1659cdae52989c9cfa9423a | 14,052 |
def make_no_graph_input_fn(graph_data, args, treatments, outcomes, filter_test=False):
"""
A dataset w/ all the label processing, but no graph structure.
Used at evaluation and prediction time
"""
def input_fn():
vertex_dataset = tf.data.Dataset.from_tensor_slices(
({'vertex_in... | 8526a64b55608f986ef4b000b2cb75a99160e1a0 | 14,053 |
import torch
def compute_gradient_penalty(D, real_samples, fake_samples):
"""Calculates the gradient penalty loss for WGAN GP"""
# Random weight term for interpolation between real and fake samples
alpha = torch.tensor(np.random.random((real_samples.size(0), 1, 1, 1,1)), dtype = real_samples.dtype, device... | 110e4854284be694c0813fd5fc71d2ff51d3b6d8 | 14,054 |
import copy
import json
def _perform_aggregation(resource, pipeline, options):
"""
.. versionadded:: 0.7
"""
# TODO move most of this down to the Mongo layer?
# TODO experiment with cursor.batch_size as alternative pagination
# implementation
def parse_aggregation_stage(d, key, value):
... | f0c8bbd35dbc8f40c1dcd2a7851fa18585387e5f | 14,055 |
def tab(num):
"""
Get tab indentation.
Parameters
----------
num : int
indentation depth
"""
return num * 4 * " " | 39311a9f28aa70f105271432916745dddeb0b46a | 14,056 |
def merge_sort(lst):
"""Sorts the input list into ascending order."""
if len(lst) < 2:
return lst
half = len(lst) // 2
# This variant of merge sort uses O(N * log N) memory, since list slicing in Python 3 creates a copy.
return merge(merge_sort(lst[:half]), merge_sort(lst[half:])) | e8cada6428fde5aa430497c3c562dc4361c11c1e | 14,057 |
from typing import Optional
def get_top_experts_per_item_dispatcher(gates: Array, name: str,
num_selected_experts: int,
batch_priority: bool,
capacity: Optional[int] = None,
... | 94e090bc3de59fd03903151fa2e34b2daca50198 | 14,058 |
import subprocess
def nix_prefetch_url(url, algo='sha256'):
"""Prefetches the content of the given URL."""
print(f'nix-prefetch-url {url}')
out = subprocess.check_output(['nix-prefetch-url', '--type', algo, url])
return out.decode('utf-8').rstrip() | 9aed687bed1a015a4da03836ce6438b0cf9b55ec | 14,059 |
def find_files_list(*args, **kwargs):
""" Returns a list of find_files generator"""
return list(find_files(*args, **kwargs)) | b51595dbc75308c583b75c3151c41ea84aafaeaf | 14,060 |
def bool_from_string(subject, strict=False, default=False):
"""Interpret a subject as a boolean.
A subject can be a boolean, a string or an integer. Boolean type value
will be returned directly, otherwise the subject will be converted to
a string. A case-insensitive match is performed such that strings... | b3f7728eb5fdd4c660144279200daabd25034bf3 | 14,061 |
from typing import Optional
from typing import Tuple
def scan_quality_check(label: str,
pivots: list,
energies: list,
scan_res: float = rotor_scan_resolution,
used_methods: Optional[list] = None,
log_fil... | 3b14e0d576d06c03c34a0e800e9fb0449d3a1428 | 14,062 |
import logging
def get_msg_timeout(options):
"""Reads the configured sbd message timeout from each device.
Key arguments:
options -- options dictionary
Return Value:
msg_timeout (integer, seconds)
"""
# get the defined msg_timeout
msg_timeout = -1 # default sbd msg timeout
cmd ... | 4b2df955ac796da38b5b9fa176477fec3c0470a2 | 14,063 |
import requests
import logging
def odata_getone(url, headers):
"""
Get a single object from Odata
"""
r = requests.get(url, headers=headers)
if not r.ok:
logging.warning(f"Fetch url {url} hit {r.status_code}")
return None
rjson = r.json()
if 'error' in rjson:
loggin... | 5d6c668845132d821f175a2e8c1a924492a9eb2f | 14,064 |
import json
def _tokenizer_from_json(json_string):
"""Parses a JSON tokenizer configuration file and returns a
tokenizer instance.
# Arguments
json_string: JSON string encoding a tokenizer configuration.
# Returns
A Keras Tokenizer instance
"""
tokenizer_config = json.loads(jso... | 665485d9faad1352927879e81c381dd81b77b5c5 | 14,065 |
from typing import List
from pathlib import Path
def get_all_pip_requirements_files() -> List[Path]:
"""
If the root level hi-ml directory is available (e.g. it has been installed as a submodule or
downloaded directly into a parent repo) then we must add it's pip requirements to any environment
defini... | 7ce5a327af6961ad23555ba5334246b75d8bd782 | 14,066 |
def load_data(dataset_name: str, split: str) -> object:
"""
Load the data from datasets library and convert to dataframe
Parameters
----------
dataset_name : str
name of the dataset to be downloaded.
split : str
type of split (train or test).
Returns
-------
object
... | f6dc374d8c12fa74b9f390a1766af369791bc3b2 | 14,067 |
def horizontal_south_link_neighbor(shape, horizontal_ids, bad_index_value=-1):
"""ID of south horizontal link neighbor.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
horizontal_ids : array of int
Array of all horizontal link ids *must be of len(horizontal_links)... | 413fdd5a4af8a0e77b0c3ab191bac60f2ba2cc26 | 14,068 |
def _get_output(algorithm, iport=0, iconnection=0, oport=0, active_scalar=None,
active_scalar_field='point'):
"""A helper to get the algorithm's output and copy input's vtki meta info"""
ido = algorithm.GetInputDataObject(iport, iconnection)
data = wrap(algorithm.GetOutputDataObject(oport))
... | dd70cbb1ee6c2d6ed085fc589c24e88fc62a17ab | 14,069 |
def read_cesar_out(cesar_line):
"""Return ref and query sequence."""
cesar_content = cesar_line.split("\n")
# del cesar_content[0]
fractions = parts(cesar_content, 4)
cesar_fractions = []
for fraction in fractions:
if len(fraction) == 1:
continue
ref_seq = fraction[1]... | fb1a1a66647fb6d3e6fec1b27d26836067c6b023 | 14,070 |
def aa_i2c_slave_write_stats (aardvark):
"""usage: int return = aa_i2c_slave_write_stats(Aardvark aardvark)"""
if not AA_LIBRARY_LOADED: return AA_INCOMPATIBLE_LIBRARY
# Call API function
return api.py_aa_i2c_slave_write_stats(aardvark) | 87e64465b1bc79c7ab48e39274e39cab17f74755 | 14,071 |
import json
def get_aliases_user(request):
"""
Returns all the Aliases
API_ENDPOINT:api/v1/aliases
----------
payload
{
"email":"a@a.com"
}
"""
alias_array = []
payload = {}
print("came to get_aliases_user()")
data_received = json.loads(request.body)
email = dat... | 2501fa15bafc2214585bd1e7d568a9a685725020 | 14,072 |
def _sorted_attributes(features, attrs, attribute):
"""
When the list of attributes is a dictionary, use the
sort key parameter to order the feature attributes.
evaluate it as a function and return it. If it's not
in the right format, attrs isn't a dict then returns
None.
"""
sort_key =... | 473c3d30c4fde5f00932adfb50c4d34c08324d54 | 14,073 |
import subprocess
import time
import random
def get_gpus(num_gpu=1, worker_index=-1, format=AS_STRING):
"""Get list of free GPUs according to nvidia-smi.
This will retry for ``MAX_RETRIES`` times until the requested number of GPUs are available.
Args:
:num_gpu: number of GPUs desired.
:worker_index: i... | 97956eaffa16514e34737d0733a69a1b176f7067 | 14,074 |
def ldensity_laplace_uniform_dist(prob_laplace, location, scale, low, high,
val):
"""
A mixture of a Laplace and a uniform distribution
"""
return np.log((prob_laplace * np.exp(-np.abs(val - location) / scale) / (2 * scale))
+ ((1 - prob_laplace) / (hi... | b069b2de4c2da3c69245b6a5507b61e918d5bb76 | 14,075 |
def readConfirmInput():
"""asks user for confirmation
Returns:
bool: True if user confirms, False if doesn't
"""
try:
result = readUserInput("(y/n): ") # UnrecognisedSelectionException
return 'y' in result[0].lower() # IndexError
except (UnrecognisedSelectionExcept... | 007fe5e0002711db7cd0bcb1869dcbef9c667213 | 14,076 |
def linkElectron(inLep, inLepIdx, lepCollection, genPartCollection):
"""process input Electron, find lineage within gen particles
pass "find" as inLepIdx of particle to trigger finding within the method"""
linkChain = []
lepIdx = -1
if inLepIdx == "find":
for Idx, lep in enumerate(lepCollec... | 87747414f5e086f16a455dbc732f86ddcb0db630 | 14,077 |
def status():
"""Determines whether or not if CrowdStrike Falcon is loaded.
:return: A Boolean on whether or not crowdstrike is loaded.
:rtype: bool
.. code-block:: bash
salt '*' crowdstrike.status
"""
if not __salt__['crowdstrike.system_extension']():
# if we should be using... | e9bdbce3e290967b95d58ddf75c2054e06542043 | 14,078 |
def sparse_search(arr, s):
""" 10.5 Sparse Search: Given a sorted array of strings that is interspersed
with empty strings, write a method to find the location of a given string.
EXAMPLE:
Input: find "ball" in {"at", "", "", "" , "ball", "", "", "car", "" , "" , "dad", ""}
Output: 4
"""
def ... | 605a56c518539117a83382c9e73d37d5e56b535f | 14,079 |
import uuid
def uuid_pk():
"""
Generate uuid1 and cut it to 12.
UUID default size is 32 chars.
"""
return uuid.uuid1().hex[:12] | 9efb12a6e72b02adcd4a64ca721ceab8c688055a | 14,080 |
def infected_symptomatic_00x80():
"""
Real Name: b'Infected symptomatic 00x80'
Original Eqn: b'Infected symptomatic 00+Infected symptomatic 80'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
return infected_symptomatic_00() + infected_symptomatic_80() | 0a3500659fad466c92fcd3d073003094c56efe9d | 14,081 |
def stencilCompare(firstElem, secondElem):
"""
stencilCompare(const std::pair< int, FP_PRECISION > &firstElem, const std::pair< int,
FP_PRECISION > &secondElem) -> bool
Comparitor for sorting k-nearest stencil std::pair objects
"""
return _openmoc.stencilCompare(firstElem, secondElem) | 3eda1a57e521134e77ba55ae38771f151699fdfd | 14,082 |
import random
def bisect_profiles_wrapper(decider, good, bad, perform_check=True):
"""Wrapper for recursive profile bisection."""
# Validate good and bad profiles are such, otherwise bisection reports noise
# Note that while decider is a random mock, these assertions may fail.
if perform_check:
if decide... | 8fbe2f018c7dfb7fdeb71dd5080993a9773a41d7 | 14,083 |
import typing
def rolling_median_with_nan_forward_fill(vector: typing.List[float], window_length: int) -> typing.List[float]:
"""Computes a rolling median of a vector of floats and returns the results. NaNs will be forward filled."""
forward_fill(vector)
return rolling_median_no_nan(vector, window_length) | 708cd1f6371846ea3b7acb4d7b59a7a61f85de7c | 14,084 |
def build_class_docstring(class_to_doc: ClassToDocument, formatter: Formatter) -> str:
"""A function to build the docstring of a class
Parameters
----------
class_to_doc : ClassToDocument
The class to document
formatter : Formatter
The formatter to use
Returns
-------
docstring : str
The docstring for... | ab9c487cd0c3059675e476fbab541f95fb912d2b | 14,085 |
from typing import Optional
from typing import Dict
def Subprocess(
identifier: Optional[str] = None, variables: Optional[Dict] = None,
env: Optional[Dict] = None, volume: Optional[str] = None
) -> Dict:
"""Get base configuration for a subprocess worker with the given optional
arguments.
Paramete... | 97a90179c91ec862c6008e12ae6c12368ec301c5 | 14,086 |
def get_var(name):
"""
Returns the value of a settings variable.
The full name is CONTROLLED_VOCABULARY_ + name.
First look into django settings.
If not found there, use the value defined in this file.
"""
full_name = "CONTROLLED_VOCABULARY_" + name
ret = globals().get(full_name, None)
... | 3c7b5507a387917b9639510023948571160b5973 | 14,087 |
def get_schema_from_dataset_url_carbon(dataset_url,
key=None,
secret=None,
endpoint=None,
proxy=None,
proxy_port=None,
... | 2c562e39232dfbe1ac7359d0c88bd2a1efa5a334 | 14,088 |
import time
def get_all_metrics(model, epoch, val_x, val_y, start_time, loss_fn):
"""每个epoch结束后在发展集上预测,得到一些指标
:param model: tf.keras.Model, epoch训练后的模型
:param epoch: int, 轮数
:param val_x: tf.data.Dataset, 发展集的输入, 和val_y一样的sample_size
:param val_y: tf.data.Dataset, 发展集的标签
:param start_time: ti... | 24025cbdcc702ca32c5887f1ec2ccf424d492e69 | 14,089 |
def get_labels(decode_steps: DecodeSteps) -> LabelsDict:
"""Returns labels dict given DecodeSteps."""
return {
"target_action_types": decode_steps.action_types,
"target_action_ids": decode_steps.action_ids,
} | 66047e41b3d173e53b676a60e48647e3862aac16 | 14,090 |
def get_body_barycentric_posvel(body, time, ephemeris=None):
"""Calculate the barycentric position and velocity of a solar system body.
Parameters
----------
body : str or other
The solar system body for which to calculate positions. Can also be a
kernel specifier (list of 2-tuples) if... | 41be03294a5cd21163afae9650f556fc64257110 | 14,091 |
def recurDraw(num, data):
"""
Purpose: to draw polygons
Parameters: num - indicator of what layer the program is on, data - instance
of the Data class
Returns: data - instance of the data class
Calls: recurDraw - itself, Data - data processing class, toDraw - drawing
intermediary function
... | d94d2f250396b6acfcf02306fd78b180f070aa92 | 14,092 |
def cont4():
"""
Two clusters, namely <cont1> (5 contours) and <cont3> 4 contours).
The enclosing contours of the clusters have a different value.
Contains 3 minima.
"""
cont_min = [
cncc(5, (6.00, 3.00), 0.2, (1, 1)),
cncc(2, (7.00, 4.00), 0.1, (4, 1), rmin=0.15),
cncc(2... | c83cb48c3bc257dcf1ead50312d186464acdd57d | 14,093 |
def predict(test_data, qrnn, add_noise = False):
"""
predict the posterior mean and median
"""
if add_noise:
x_noise = test_data.add_noise(test_data.x, test_data.index)
x = (x_noise - test_data.mean)/test_data.std
y_prior = x_noise
y = test_data.y_noise
y... | d45e843d529babb99baa160ad976c0c9753da42d | 14,094 |
def handle_login_GET():
"""
Displays the index (the login page).
"""
if request.args.get('next'):
url_kwargs = dict(next=request.args.get('next'))
else:
url_kwargs = {}
try:
weblab_api.api.check_user_session()
except SessionNotFoundError:
pass # Expected beha... | f496519518b5d3b8a71ff4a8e60be2a2fe2110f3 | 14,095 |
import copy
def get_role_actions():
"""Returns the possible role to actions items in the application.
Returns:
dict(str, list(str)). A dict presenting key as role and values as list
of actions corresponding to the given role.
"""
return copy.deepcopy(_ROLE_ACTIONS) | 79b53e4003b1dc9264d9210f03395ce32d737c1e | 14,096 |
import json
def jsons_str_tuple_to_jsons_tuple(ctx, param, value):
"""
Converts json str into python map
"""
if value is None:
return []
else:
return [json.loads(a) for a in value] | 8b6f03650d566d74b0400868f12b59c2fa37bc3e | 14,097 |
def get_webelements_in_active_area(xpath, **kwargs):
"""Find element under another element.
If ${ACTIVE_AREA_FUNC} returns an element then the xpath is searched from
that element. Otherwise the element is searched under body element.
Parameters
----------
xpath : str
Xpath expression w... | 91579a7195c865734b4119e33d0668a4951eb3f4 | 14,098 |
import sys
def create_double_group():
"""
Returns: Create two simple control for all object under selected
"""
selections = cm.ls(selection=True)
if len(selections) < 1:
return om.MGlobal.displayError("This function need at lest two object to work with")
for selection in selection... | a240c5f7220e4e9270db1b6e84204ebf399e77b0 | 14,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.