content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _get_vcf_breakends(hydra_file, genome_2bit, options=None):
"""Parse BEDPE input, yielding VCF ready breakends.
"""
if options is None: options = {}
for features in group_hydra_breakends(hydra_parser(hydra_file, options)):
if len(features) == 1 and is_deletion(features[0], options):
... | 5,340,200 |
def get_line_pixels(start, end):
"""Bresenham's Line Algorithm
Produces a list of tuples from start and end
>>> points1 = get_line((0, 0), (3, 4))
>>> points2 = get_line((3, 4), (0, 0))
>>> assert(set(points1) == set(points2))
>>> debuginfo(points1)
[(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
... | 5,340,201 |
def extrema(x):
"""
Gets the local extrema points from a time series. This includes endpoints if necessary.
Note that the indices will start counting from 1 to match MatLab.
Args:
x: time series vector
Returns:
imin: indices of XMIN
"""
x = np.asarray(x)
imin = signal.a... | 5,340,202 |
def mv_single_gpu_test(model, data_loader, runstate, draw_contours=False, draw_target=True, out_dir=None):
"""Test with single GPU.
Args:
model (nn.Module): Model to be tested.
data_loader (nn.Dataloader): Pytorch data loader.
show (bool): Whether show results during infernece. Default:... | 5,340,203 |
def d2X_dt2_Vanderpol(X, t=0):
""" Return the Jacobian matrix evaluated in X. """
return array([[0, 1 ],
[-2*r*X[1]*X[0]-w**2 , r*(1-X[0]**2)]]) | 5,340,204 |
def multiply_scalar(s, q, qout):
"""Multiply scalar by quaternion s*q"""
qout[0] = s * q[0]
qout[1] = s * q[1]
qout[2] = s * q[2]
qout[3] = s * q[3] | 5,340,205 |
def list_used_variables(node, ARGS=None):
""" thanks Avi
https://software.ecmwf.int/wiki/pages/viewpage.action?pageId=53513079
"""
if ARGS is None:
ARGS = object()
ARGS.var_name = None
ARGS.not_value = None
# make a list of all nodes up the parent hierarchy
parent_hierar... | 5,340,206 |
def main():
"""Opened ports getting and their protocols recognizing."""
host, ports = argument_parse()
print("Analysing...")
ports_analysers = []
with ThreadPoolExecutor(max_workers=WORKERS_COUNT) as thread_pool:
for port in ports:
if 0 <= port <= 65535:
port_ana... | 5,340,207 |
def domain(domain):
"""Locate the given domain in our database and
render an info page for it.
"""
current_app.logger.info('domain [%s]' % domain)
g.domain = current_app.iwn.domain(domain)
if g.domain is None:
return Response('', 404)
else:
return render_template('domain.jinj... | 5,340,208 |
def gaussian_filter(img, kernel_size, sigma=0):
"""take value weighted by pixel distance in the neighbourhood of center pixel.
"""
return cv2.GaussianBlur(img, ksize=kernel_size, sigmaX=sigma, sigmaY=sigma) | 5,340,209 |
def extractBillAdoptedLinks(soup):
"""Extract list of links for Adopted Bill Texts (HTML & PDF Versions)
"""
tables = soup.find_all("table")
content_table = [t for t in tables if t.text.strip().startswith("View Available Bill Summaries")][-1]
adopted_links = {}
for row in content_table.find_all(... | 5,340,210 |
def do_flavor_access_list(cs, args):
"""Print access information about the given flavor."""
if args.flavor:
flavor = _find_flavor(cs, args.flavor)
if flavor.is_public:
raise exceptions.CommandError(_("Access list not available "
"for public... | 5,340,211 |
def copy_sheets_to_packages(sheets: Union[str,list[str]], template: str = None) -> None:
"""Copy designated sheets from template to all package Excel files.
This is intended to be used for updating the non-user-edited sheets
:param sheets: list of sheet names to copy, or a single name that will be listifie... | 5,340,212 |
def uniq(string):
"""Removes duplicate words from a string (only the second duplicates).
The sequence of the words will not be changed.
"""
words = string.split()
return ' '.join(sorted(set(words), key=words.index)) | 5,340,213 |
def git_repo_empty(tmpdir):
"""Create temporary empty git directory, meaning no commits/users/repository-url to extract (error)"""
cwd = str(tmpdir)
version = subprocess.check_output("git version", shell=True)
# decode "git version 2.28.0" to (2, 28, 0)
decoded_version = tuple(int(n) for n in versio... | 5,340,214 |
def l2_regularizer(
params: kfac_jax.utils.Params,
haiku_exclude_batch_norm: bool,
haiku_exclude_biases: bool,
) -> chex.Array:
"""Computes an L2 regularizer."""
if haiku_exclude_batch_norm:
params = hk.data_structures.filter(
lambda m, n, p: "batchnorm" not in m, params)
if haiku_exclude_... | 5,340,215 |
def _on_monitor_deleted(ref):
"""Remove the weakreference from the set
of active MONITORS. We no longer
care about keeping track of it
"""
MONITORS.remove(ref) | 5,340,216 |
def _normalize(log_weights):
"""Normalize log-weights into weights and return resulting weights and log-likelihood increment."""
n = log_weights.shape[0]
max_logw = jnp.max(log_weights)
w = jnp.exp(log_weights - max_logw)
w_mean = w.mean()
log_likelihood_increment = jnp.log(w_mean) + max_logw
... | 5,340,217 |
def schedule_notification(*, event, affected_object, extra_data):
"""
Schedule notifying users about a given event.
@returns right after scheduling the event. Notification delivery, retries and failures is handled separately
"""
# TODO: Currently only resolves email sending. Later on, weekly letter... | 5,340,218 |
def pq_compute_multi_core(matched_annotations_list,
gt_folder,
pred_folder,
categories,
file_client=None,
nproc=32):
"""Evaluate the metrics of Panoptic Segmentation with multithreading.... | 5,340,219 |
def logout():
"""
Function that handles logout of user
---
POST:
description: remove curent user in the session
responses:
200:
description:
Successfuly log out user from the session.
"""
logout_user() # flask logout library
return redirect("/... | 5,340,220 |
def edit_line(file_name: str, regex: str, replace: str, mode: str = 'status',
show_ok: bool = False):
"""
Edit line in file matching a regular expression.
:param file_name: Full path and name of file to write content to.
:param regex: Regular expression for matching line to edit.
... | 5,340,221 |
def header(data):
"""Create class based on decode of a PCI configuration space header from raw data."""
buf = ctypes.create_string_buffer(data, len(data))
addr = ctypes.addressof(buf)
field_list = header_field_list(addr)
return header_factory(field_list).from_buffer_copy(data) | 5,340,222 |
def downscale_fit(fitter, data, seed, Pool):
"""Do a fit for a given Fitter (for multiple locations)
"""
n_sample, is_print, n_thread = get_fit_parser()
pool = None
if n_thread is None:
pool = Pool()
else:
pool = Pool(n_thread)
fitter.fit(data, seed, n_sample, pool, is_print)... | 5,340,223 |
def FilterByKeyUsingSideInput(pcoll, lookup_entries, filter_key):
"""Filters a single collection by a single lookup collection, using a common key.
Given:
- a `PCollection` (lookup_entries) of `(V)`, as a lookup collection
- a `PCollection` (pcoll) of `(V)`, as values to be filtered
- a commo... | 5,340,224 |
def sw_maxent_irl(x, xtr, phi, phi_bar, max_path_length, nll_only=False):
"""Maximum Entropy IRL using our exact algorithm
Returns NLL and NLL gradient of the demonstration data under the proposed reward
parameters x.
N.b. the computed NLL here doesn't include the contribution from the MDP dynamics
... | 5,340,225 |
def __multiprocess_point_in_poly(df: pd.DataFrame,
x: str,
y: str,
poly: Polygon):
"""
Return rows in dataframe who's values for x and y are contained in some polygon coordinate shape
Parameters
---------... | 5,340,226 |
def print_runtime(func, create_global_dict=True):
"""
A timer decorator that creates a global dict for reporting times across multiple runs
"""
def function_timer(*args, **kwargs):
"""
A nested function for timing other functions
"""
import time
from collections i... | 5,340,227 |
def generate_astrometry(kop, time_list):
"""
Simulates observational data.
:param kop: Keplerian orbit parameters
:param time_list: List of observation times
:return: astrometry
"""
trajectory = generate_complete_trajectory(kop, time_list)
return {'t':time_list,
'x':traje... | 5,340,228 |
def _open_remote(file_ref):
"""Retrieve an open handle to a file.
"""
return io.StringIO(_run_gsutil(["cat", file_ref]).decode()) | 5,340,229 |
def fit(image, labels, featurizer="../model/saved_model/UNet_hpa_4c_mean_8.pth"):
"""Train a pixel classifier.
Parameters
----------
image: np.ndarray
Image data to be classified.
labels: np.ndarray
Sparse classification, where 0 pixels are ingored, and other integer
values ... | 5,340,230 |
def test_register_algorithm_with_missing_fields(
host: str,
token: str,
project: int) -> None:
""" Unit test for the ReigsterAlgorithm endpoint focused on missing request body fields
Request bodies are created with missing required fields and a workflow tries
to be registered with t... | 5,340,231 |
def overlay_data(
graph: BELGraph,
data: Mapping[BaseEntity, Any],
label: Optional[str] = None,
overwrite: bool = False,
) -> None:
"""Overlay tabular data on the network.
:param graph: A BEL Graph
:param data: A dictionary of {tuple node: data for that node}
:param label: The annotatio... | 5,340,232 |
def himydata_client(args):
"""Returns an instance of Himydata Client or DryRunClient"""
if args.dry_run:
return DryRunClient()
else:
with open(args.config) as input:
config = json.load(input)
if not config.get('disable_collection', True):
logger.info('Sending... | 5,340,233 |
def KeywordString():
"""Returns the specified Keyword String
@note: not used by most modules
"""
return ST_KEYWORDS[1] | 5,340,234 |
def coo_index_to_data(index):
"""
Converts data index (row, col) to 1-based pixel-centerd (x,y) coordinates of the center ot the pixel
index: (int, int) or int
(row,col) index of the pixel in dtatabel or single row or col index
"""
return (index[1] + 1.0, index[0] + 1.0) | 5,340,235 |
def prepare_output_well(df, plates, output, rawdata, identifier_features, location_features):
""" Prepare the output file with plate, row and column information
Calculate penetrance and p-value
Args:
df: Existing combined dictionary
plates: ... | 5,340,236 |
def main(input_file):
"""Solve puzzle and connect part 1 with part 2 if needed."""
inp = read_input(input_file)
p1, p2 = part_1_and_2(inp)
print(f"Solution to part 1: {p1}")
print(f"Solution to part 2: {p2}")
return p1, p2 | 5,340,237 |
def extract_fields():
"""Compiles all the fields within an object on a Tkinter Listbox"""
global object_name
object_name = select(entity, 0)
options = sf.query_all(
("SELECT ID, QualifiedAPIName from FieldDefinition "
"where EntityDefinitionId = '" + select(entity, 0)
+ "' orde... | 5,340,238 |
def generateListPermutations(elements, level=0):
"""Generate all possible permutations of the list 'elements'."""
#print(" " * level, "gP(", elements, ")")
if len(elements) == 0:
return [[]]
permutations = []
for e in elements:
reduced = elements[:]
reduced.remove(e)
... | 5,340,239 |
def save_config(config_dict, filename=None, update=False):
"""
Writes configuration to a file
"""
filename = filename or default_config_filename
config = configparser.RawConfigParser()
if update:
if os.path.exists(filename):
config.read(filename)
else:
b... | 5,340,240 |
def test_tree_with_one_node_root_exists(one_t):
"""Root of tree should exist if it has one node."""
assert one_t.root | 5,340,241 |
def main(provider: Provider, args: List[str]) -> None: # args not in use?
"""For use as the `main` in programs that wrap a custom Provider
implementation into a Pulumi-compatible gRPC server.
:param provider: an instance of a Provider subclass
:args: command line arguiments such as os.argv[1:]
"... | 5,340,242 |
def run_tfa(tfalclist_path, trendlisttfa_paths, datestfa_path, lcdirectory,
statsdir,
nworkers=16, do_bls_ls_killharm=True, npixexclude=10,
blsqmin=0.002, blsqmax=0.1, blsminper=0.2, blsmaxper=30.0,
blsnfreq=20000, blsnbins=1000, lsminp=0.1, lsmaxp=30.0,
lssub... | 5,340,243 |
def write_abundance(species_path, markers_path, species_abundance, markers_abundance):
""" Write species results to specified output file """
# Sort the species by median_coverage
output_order = sorted(species_abundance.keys(), key=lambda sid: species_abundance[sid]['median_coverage'], reverse=True)
wi... | 5,340,244 |
def has_security_updates(update_list):
"""
Returns true if there are security updates available.
"""
return filter_updates(update_list, 'category', lambda x: x == 'security') | 5,340,245 |
def lobby():
"""Return an unchecked place named lobby."""
return UncheckedPlace("Lobby") | 5,340,246 |
def get_random_sample_indices(
seq_len, num_samples=100, device=torch.device("cpu")):
"""
Args:
seq_len: int, the sampled indices will be in the range [0, seq_len-1]
num_samples: sample size
device: torch.device
Returns:
1D torch.LongTensor consisting of sorted sampl... | 5,340,247 |
def render_mesh_as_dot(mesh, template=DOT_TEMPLATE):
"""Renders the given mesh in the Graphviz dot format.
:param Mesh mesh: the mesh to be rendered
:param str template: alternative template to use
:returns: textual dot representation of the mesh
"""
custom_filters = {
'hash': lambda s... | 5,340,248 |
def snrest(noisy: np.ndarray, noise: np.ndarray, axis=None):
"""
Computes SNR [in dB] when you have:
"noisy" signal+noise time series
"noise": noise only without signal
"""
Psig = ssq(noisy, axis)
Pnoise = ssq(noise)
return 10 * np.log10(Psig / Pnoise) | 5,340,249 |
def test_sgp4(client):
""" test the sgp4 device interface """
tsince = np.linspace(0, 100, client.n, dtype=np.float64)
sgp4.sgp4(tsince, client.whichconst_array, client.satrec_array)
array = []
for ts in tsince:
r, v = prop.sgp4(client.Satrec(), ts, wgs72)
array.append([r[0], r[1], ... | 5,340,250 |
async def trace_bek(client: Client, message: Message):
""" Reverse Search Anime Clips/Photos """
x = await message.reply_text("Reverse searching the given media")
dls_loc = await media_to_image(client, message, x)
if dls_loc:
async with ClientSession() as session:
tracemoe = tr... | 5,340,251 |
def load(spect_path, spect_format=None):
"""load spectrogram and related arrays from a file,
return as an object that provides Python dictionary-like
access
Parameters
----------
spect_path : str, Path
to an array file.
spect_format : str
Valid formats are defined in vak.io.... | 5,340,252 |
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(views.blueprint, url_prefix='/api')
app.register_blueprint(pipeline.views.blueprint, url_prefix='/api')
app.register_blueprint(job.views.blueprint, url_prefix='/api')
app.register_blueprint(stage.views.blueprint, url_prefix=... | 5,340,253 |
def PSNR(a, b, max_val=255.0, name=None):
"""Returns the Peak Signal-to-Noise Ratio between a and b.
Arguments:
a: first set of images.
b: second set of images.
max_val: the dynamic range of the images (i.e., the difference between the
maximum the and minimum allowed values).
name: namespace ... | 5,340,254 |
def split_list(iterable: Iterable,
size: Optional[int] = 5) -> List[list]:
"""Takes an iterable and splits it into lists of its elements.
The size of each sub-list depends on the provided size argument."""
for i in range(0, len(iterable), size):
yield iterable[i:i + size] | 5,340,255 |
def command(f):
""" indicate it's a command of naviseccli
:param f: function that returns the command in list
:return: command execution result
"""
@functools.wraps(f)
def func_wrapper(self, *argv, **kwargs):
if 'ip' in kwargs:
ip = kwargs['ip']
del kwargs['ip']... | 5,340,256 |
def top():
"""
CPU和内存监测
CPU and memory monitoring
:return: None
"""
from . import dir_char
if dir_char == '\\':
from .SystemTools.Monitor import top
top()
else:
import sys
sys.argv = ['bpytop'] + sys.argv[2:]
from . import requirePackage
... | 5,340,257 |
def clean_data(file_name):
"""
file_name: file to be cleaned
This function converts the data types in the original dataframe into more suitable type.
The good news is that the orginal dataframe is already in good shape so there's less to do.
"""
df_input = pd.read_excel(file... | 5,340,258 |
def get_contact_pages(buffer, domain):
"""
Returns links to all possible contact pages found on the site index page
"""
usual_contact_titles = [u'Contact', u'Contacts', u'About', u'Контакты', u'Связаться с нами']
usual_contact_urls = ['/contact', '/contacts', '/info']
result = list()
html =... | 5,340,259 |
def _hydrate_active_votes(vote_csv):
"""Convert minimal CSV representation into steemd-style object."""
if not vote_csv:
return []
votes = []
for line in vote_csv.split("\n"):
voter, rshares, percent, reputation = line.split(',')
votes.append(dict(voter=voter,
... | 5,340,260 |
def skew(width, height, magnitude, mode='random'):
"""
Skew the ChArUco in 4 different modes.
:param width:
:param height:
:param magnitude:
:param mode: 0: top narrow, 1: bottom narrow, 2: left skew, 3 right skew
:return:
"""
# Randomize skew
if mode == 'random':
mode ... | 5,340,261 |
def reset_env(exit=True):
"""Reset the environment by cleaning out all temporary outputs."""
print('NOTE: Resetting the environment...')
wd.database.init()
wd.database.delete_temp()
wd.outputtools.delete_temp()
wd.database.close()
if exit:
print('NOTE: Exiting the program... Goodbye!... | 5,340,262 |
def aws_ec2_pricing():
"""---
get:
tags:
- aws
produces:
- application/json
description: &desc Get EC2 pricing per gibabyte in all regions and storage types
summary: *desc
responses:
200:
description: List of instance ty... | 5,340,263 |
def create_app():
"""
Create the application and return it to the user
:return: flask.Flask application
"""
app = Flask(__name__, static_folder=None)
app.url_map.strict_slashes = False
# Load config and logging
load_config(app)
logging.config.dictConfig(
app.config['SLACKBA... | 5,340,264 |
def before_feature(context, feature):
"""
HOOK: To be executed before each Feature.
"""
__logger__.info("Starting execution of feature")
__logger__.info("##############################")
__logger__.info("##############################") | 5,340,265 |
def _get_graph_cls(name):
"""Get scaffoldgraph class from name string."""
if name == 'network':
return ScaffoldNetwork
elif name == 'tree':
return ScaffoldTree
elif name == 'hiers':
return HierS
else:
msg = f'scaffold graph type: {name} not known'
raise ValueE... | 5,340,266 |
def benchmark_index(
indices_dict, gt_test, test_points, vectors_size_in_bytes, save_path=None, speed_dict=None, size_dict=None
):
"""
Compute recall curves for the indices.
"""
perfect_index_label = "perfect index"
if perfect_index_label not in indices_dict:
indices_dict[perfect_index... | 5,340,267 |
def getgrayim(ra, dec, size=240, output_size=None, filter="g", format="jpg"):
"""Get grayscale image at a sky position
ra, dec = position in degrees
size = extracted image size in pixels (0.25 arcsec/pixel)
output_size = output (display) image size in pixels (default = size).
output_... | 5,340,268 |
def get_logger(base_name, file_name=None):
"""
get a logger that write logs to both stdout and a file. Default logging level is info so remember to
:param base_name:
:param file_name:
:param logging_level:
:return:
"""
if (file_name is None):
file_name = base_name
logger = lo... | 5,340,269 |
def elastic_transform(x, alpha, sigma, mode="constant", cval=0, is_random=False):
"""Elastic transformation for image as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__.
Parameters
-----------
x : numpy.array
A greyscale image.
alpha : float
Alpha valu... | 5,340,270 |
def create_markdown(
escape=True,
renderer=None,
plugins=None,
acronyms=None,
bibliography="",
chapters=False,
toc=False,
):
"""Create a Markdown instance based on the given condition.
:param escape: Boolean. If using html renderer, escape html.
:param renderer: renderer instanc... | 5,340,271 |
def make_game_from_level(level: int, options: Optional[GameOptions] = None) -> textworld.Game:
""" Make a Cooking game of the desired difficulty level.
Arguments:
level: Difficulty level (see notes).
options:
For customizing the game generation (see
:py:class:`textworld.... | 5,340,272 |
def _split(num):
"""split the num to a list of every bits of it"""
# xxxx.xx => xxxxxx
num = num * 100
result = []
for i in range(16):
tmp = num // 10 ** i
if tmp == 0:
return result
result.append(tmp % 10)
return result | 5,340,273 |
def genGameMap():
"""This is an "abstract function" to hold this docstring and information.
A GameMap function defines Places and connects all the Places it defines in
a graph, but simpler graph than CommandGraph. It simply uses Place.nextnodes.
A GameMap function returns the starting location.""... | 5,340,274 |
def getHitmask(image):
"""returns a hitmask using an image's alpha."""
mask = []
for x in xrange(image.get_width()):
mask.append([])
for y in xrange(image.get_height()):
mask[x].append(bool(image.get_at((x,y))[3]))
return mask | 5,340,275 |
def get_args_kwargs_param_names(fparams) -> (str, str):
"""fparams is inspect.signature(f).parameters
for some function f.
Doctests:
>>> import inspect
>>> def f(): pass
>>> get_args_kwargs_param_names(inspect.signature(f).parameters)
(None, None)
>>> def f(*args): pass
>>> get_args... | 5,340,276 |
def clean_up_tokenization_spaces(out_string):
"""Converts an output string (de-BPE-ed) using de-tokenization algorithm from OpenAI GPT."""
out_string = out_string.replace('<unk>', '')
out_string = out_string.replace(' .', '.').replace(' ?', '?').replace(' !', '!').replace(' ,', ','
).replace(" '... | 5,340,277 |
def upload_pkg(go_workspace, pkg_file, service_url, tags, service_account):
"""Uploads existing *.cipd file to the storage and tags it.
Args:
go_workspace: path to 'infra/go' or 'infra_internal/go'.
pkg_file: path to *.cipd file to upload.
service_url: URL of a package repository service.
tags: a l... | 5,340,278 |
def train_world_model(env, data_dir, output_dir, hparams, epoch):
"""Train the world model on problem_name."""
train_steps = hparams.model_train_steps * (
epoch + hparams.inital_epoch_train_steps_multiplier)
model_hparams = trainer_lib.create_hparams(hparams.generative_model_params)
# Hardcoded for now. ... | 5,340,279 |
def make_rgg(n: int, kbar: float) -> ig.Graph:
"""Make Random Geometric Graph with given number of nodes
and average degree.
"""
radius = np.sqrt(kbar/(np.pi*(n-1)))
return ig.Graph.GRG(n, radius=radius, torus=True) | 5,340,280 |
def list_directory(bucket, prefix, s3=None, request_pays=False):
"""AWS s3 list directory."""
if not s3:
session = boto3_session(region_name=region)
s3 = session.client('s3')
pag = s3.get_paginator('list_objects_v2')
params = {
'Bucket': bucket,
'Prefix': prefix,
... | 5,340,281 |
def manual_overrides():
"""Read the overrides file.
Read the overrides from cache, if available. Otherwise, an attempt is made
to read the file as it currently stands on GitHub, and then only if that
fails is the included file used. The result is cached for one day.
"""
return _manual_overrides... | 5,340,282 |
def _ExtractCLPath(output_of_where):
"""Gets the path to cl.exe based on the output of calling the environment
setup batch file, followed by the equivalent of `where`."""
# Take the first line, as that's the first found in the PATH.
for line in output_of_where.strip().splitlines():
if line.startswith('... | 5,340,283 |
def preprocess_data_for_clustering(df):
"""Prepare data in order to apply a clustering algorithm
Parameters
----------
df : pandas.DataFrame
Input data, *i.e.* city-related timeseries, supposed to have
`station_id`, `ts` and `nb_bikes` columns
Returns
-------
pandas.DataFrame
... | 5,340,284 |
def chars(line):
"""Returns the chars in a TerminalBuffer line.
"""
return "".join(c for (c, _) in notVoids(line)) | 5,340,285 |
def map_is_finite(query_points: tf.Tensor, observations: tf.Tensor) -> Dataset:
"""
:param query_points: A tensor.
:param observations: A tensor.
:return: A :class:`~trieste.data.Dataset` containing all the rows in ``query_points``,
along with the tensor result of mapping the elements of ``obser... | 5,340,286 |
def docker_image_exists(args, image): # type: (EnvironmentConfig, str) -> bool
"""Return True if the image exists, otherwise False."""
try:
docker_command(args, ['image', 'inspect', image], capture=True)
except SubprocessError:
return False
return True | 5,340,287 |
def remove_local(path):
"""Remove a local file or directory.
Arguments:
path (str): Absolute path to the file or directory.
Returns:
Boolean indicating result.
"""
if os.path.isfile(path):
# Regular file
remover = os.remove
elif os.path.isdir(path):
# D... | 5,340,288 |
def get_g2_fit_general_two_steps(
g2,
taus,
function="simple_exponential",
second_fit_range=[0, 20],
sequential_fit=False,
*argv,
**kwargs,
):
"""
Fit g2 in two steps,
i) Using the "function" to fit whole g2 to get baseline and beta (contrast)
ii) Then using the obtained bas... | 5,340,289 |
def run_doctest(module, verbosity=None):
"""Run doctest on the given module. Return (#failures, #tests).
If optional argument verbosity is not specified (or is None), pass
test_support's belief about verbosity on to doctest. Else doctest's
usual behavior is used (it searches sys.argv for -v).
"""... | 5,340,290 |
def rate_matrix_arrhenius_time_segmented(energies, barriers, segment_temperatures, segment_start_times, t_range):
"""
Compute the rate matrix for each time ``t`` in ``t_range``, where the bath temperature is a piecewise constant
function of time.
The bath temperature function, by which the rate matrice... | 5,340,291 |
def div_tensor(tensor, coords=(x, y, z), h_vec=(1, 1, 1)):
"""
Divergence of a (second order) tensor
Parameters
----------
tensor : Matrix (3, 3)
Tensor function function to compute the divergence from.
coords : Tuple (3), optional
Coordinates for the new reference system. This ... | 5,340,292 |
def convert_path_to_repr_exp(path, with_end=False):
"""
Generate a representative expression for the given path
"""
exp = ""
#print("Path: {}".format(path))
for i in range(len(path)):
if with_end == False and \
((i == 0) or (i == len(path)-1)):
continue
... | 5,340,293 |
def test_unicast_ip_incorrect_eth_dst(do_test, ptfadapter, setup, tx_dut_ports, pkt_fields, eth_dst, ports_info):
"""
@summary: Create packets with multicast/broadcast ethernet dst.
"""
if "vlan" in tx_dut_ports[ports_info["dut_iface"]].lower():
pytest.skip("Test case is not supported on VLAN i... | 5,340,294 |
def cluster_create(context, values):
"""Create a cluster from the values dictionary."""
return IMPL.cluster_create(context, values) | 5,340,295 |
def compute_heading_error(est, gt):
"""
Args:
est: the estimated heading as sin, cos values
gt: the ground truth heading as sin, cos values
Returns:
MSE error and angle difference from dot product
"""
mse_error = np.mean((est-gt)**2)
dot_prod = np.sum(est * gt, axis=1)
... | 5,340,296 |
def _get_count_bid(soup: bs4.BeautifulSoup) -> int:
""" Return bidding count from `soup`.
Parameters
----------
soup : bs4.BeautifulSoup
Soup of a Yahoo Auction page.
Returns
-------
int
Count of total bidding.
"""
tags = soup.find_all('dt', text='... | 5,340,297 |
def _is_class(s):
"""Imports from a class/object like import DefaultJsonProtocol._"""
return s.startswith('import ') and len(s) > 7 and s[7].isupper() | 5,340,298 |
def evaluate(vsm, wordsim_dataset_path):
"""Extract Correlation, P-Value for specified vector space mapper."""
return evaluation.extract_correlation_coefficient(
score_data_path=wordsim_dataset_path, vsm=vsm
) | 5,340,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.