content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import _asyncio
def threaded_async(func: _typing.Callable):
"""
Helper decorator used to resolve future in a thread-safe manner.
"""
future: _typing.Coroutine = func()
def _call():
"""
Inner function used to resolve the future correctly.
"""
return _asyncio.run_cor... | 3da1397cb382066124fd121d7ab93a45471356a9 | 3,615,200 |
def barycenter(P, K, reference="debiased", **kwargs):
"""Compute OT barycenter."""
ndim = P.ndimension()
if ndim > 3 or ndim <= 1:
raise ValueError("Data dimension must be 2 for 1d distributions"
" or 3 for 2d distributions.")
if reference == "debiased":
if ndim ... | 14ac0b7764bebacdfa6afeede31a544d4c0fca41 | 3,615,201 |
def map_serial_number(facilities) -> str:
"""Map serial number."""
facility = facilities.get("body", {}).get("facilitiesList", [])[0]
return str(facility.get("serialNumber", None)) | 81491de02a2583d30ee31833a427b4ffdebe6a88 | 3,615,202 |
def get_shape_xyz(self):
"""Return the mode shape in cartesian coordinates.
Parameters
----------
self : Mode
a Mode object
Returns
-------
shape : ndarray
ndarray of the shape (Nnodes*Ndof)
"""
if self.shape_xyz is not None and self.shape_xyz.size != 0:
re... | dea33ea0dccc2196f2ee5676136f88436a22c603 | 3,615,203 |
def product_check(product_name):
"""
Check if product name already exists in the database
"""
if mongo.db.products.find_one({"name": product_name}):
# Display flash message
flash("Product " + product_name +
" already exists in the database", "warning")
product_check... | af7ac0716d92cd1f71bcba2e574c4ca0e0c37078 | 3,615,204 |
def login(body):
""" todoc
"""
try:
username = body["username"]
password = body["password"]
except:
return _get_bad_request()
user = User.query.filter(User.username == username).first()
if not user:
return {"code": "NOT_FOUND", "message": "Wrong username/password"... | 219be4fe3a8864d444961a44f203339d30b4993d | 3,615,205 |
import argparse
def get_arguments():
"""Read arguments for the program and returns the ArgumentParser"""
parser = argparse.ArgumentParser(description='''DroidLysis3 is a Python
script which processes Android samples. \n
1/ It extracts properties from the samples (e.g connects to Internet, roots the phone...... | 9aa7028ce478cbdcc7f6ba88fdbb7e6d811b2aec | 3,615,206 |
import hashlib
def get_atoms_id(atoms: Atoms) -> str:
"""
Returns a unique ID for the Atoms object. Note: The .info dict
and calculator is excluded from the hash generation.
Parameters
----------
atoms
.Atoms object
Returns
-------
md5hash
MD5 hash of the .Atoms o... | a37bc45d0638908cc782c75b0d87b233b7be58e7 | 3,615,207 |
def get_payees():
"""Loads the payees override file"""
return load_config_file("payees") | daead676fbb137528fbd55104096660e317a174c | 3,615,208 |
def _get_maxmem(profile_df):
"""
Get current peak memory
:param pandas.core.frame.DataFrame profile_df: a data frame representing the current profile.tsv for a sample
:return str: max memory
"""
return "{} GB".format(str(max(profile_df['mem']) if not profile_df['mem'].empty else 0)) | 2e628d48f7b4e0e3c1465f09da7aa795d2954a06 | 3,615,209 |
def read(file_ref, **kwargs):
"""Read a LAS file.
Note that only versions 1.2 and 2.0 of the LAS file specification
are currently supported.
Arguments:
file_ref (file-like object, str): either a filename, an open file
object, or a string containing the contents of a file.
Retu... | 8582381412814a42b73f3ca3551ea5c4843e47e0 | 3,615,210 |
def mk_sentence(_id, topic, category, title):
""" e.g. [테슬라-모빌리티] 👀 테슬라가 승차공유 서비스 Tesla Network를 출시합니다. https://snak.news/newsList/news/208?channel=slack&corp=pozalabs"""
link = SNAK_URL.format(_id=_id, corp=CORP)
return f"[{topic}-{category}] {title} {link}" | 665f97aa47f9a8d13a6b33de34524f8efb5177a8 | 3,615,211 |
from loopy.kernel.instruction import BarrierInstruction
def get_global_barrier_order(kernel):
"""Return a :class:`tuple` of the listing the ids of global barrier instructions
as they appear in order in the kernel.
See also :class:`loopy.instruction.BarrierInstruction`.
"""
barriers = []
visit... | 34faf08b5a1382928b5a9efce5a3242c71ac8488 | 3,615,212 |
import argparse
def str2bool(v):
"""
Helper to pass boolean arguements.
Extracted from: https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
Author: @Maxim
"""
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
re... | 1450c0ffe5441f5fe94a1d723361351dfde30d21 | 3,615,213 |
import torch
def MaskedNLL(target, probs, balance_weights=None):
# adapted from https://gist.github.com/jihunchoi/f1434a77df9db1bb337417854b398df1
"""
Args:
target: A Variable containing a LongTensor of size
(batch, ) which contains the index of the true
class for each corr... | 17132ad088b00ae096f16946f5026ed2133c8eeb | 3,615,214 |
def count_triangle(tbl_name, conn):
""" input is a matrix """
tol = 0.1
b = 'b'
lim = 10
cur = conn.cursor()
tn = tbl_name
print "create matrix..."
create_vector_or_matrix(b, conn)
print "Counting dimension..."
calc_dim_query = "select max(row), max(col) from %s" % (tn)
cur.e... | 3de7085dffebf052cb033207097c5f472f9a5979 | 3,615,215 |
async def process_headers(headers):
"""Filter out unwanted headers and return as a dictionary."""
headers = dict(headers)
header_keys = (
"user-agent",
"referer",
"accept-encoding",
"accept-language",
"x-real-ip",
"x-forwarded-for",
)
return {k: header... | 32feeb40c12c4b69d65da1c178e396e85fc9e557 | 3,615,216 |
def Bound_EXT(S, Ex, boundaries):
"""
This function computes the extension of a signal for
filtering purposes
:param S: The Input signal
:param Nf: The Size of the Kernel (must be an odd number!)
:param boundaries: The type of extension:
‘reflect’ (d c b a | a b c d | d c b a) The inpu... | 273d2e5d9999fc2b4ee452c8a8d6d064f567f403 | 3,615,217 |
from typing import Tuple
def infer_dtype_from_array(
arr, pandas_dtype: bool = False
) -> Tuple[DtypeObj, ArrayLike]:
"""
Infer the dtype from an array.
Parameters
----------
arr : array
pandas_dtype : bool, default False
whether to infer dtype including pandas extension types.
... | 0af3cebe46d10328faa3a9b6f469c0e1956f0cec | 3,615,218 |
def np(url):
"""
Transforms a reddit link into a no participation URL (which in some
subreddits hides voting arrows, to help prevent administrator shadowbans.
:param url: URL to transform
:return: A no participation (NP) link
"""
url = urlparse(url)
return "https://np.reddit.com{}".forma... | b4b3006b423f0b1f1a6abc7cb8e98c8564658c4d | 3,615,219 |
import torch
def sample(method, clf, x0, start, sampling_method, n_samples=[50_000, 100_000], prior=None,
inn_prods=None, theta_kern=None):
"""
Uses a density ratio estimator clf to sample from the posterior for x0
and prior.
Inputs:
- method: str, either "signature" or "gru-resnet" depending on which
... | dada3aa971f3c02b76520301d7a8813b64c9ed3a | 3,615,220 |
def get_authenticate_headers(request, error_type="invalid_token"):
# type: (Request, Str) -> Optional[HeadersType]
"""
Obtains all required headers by 401 responses based on executed :paramref:`request`.
:param request: request that was sent to attempt authentication or access which must respond with U... | 8c7b01fe864e7979bf92a573d8711870b24467fd | 3,615,221 |
from typing import Tuple
def get_current_and_head_revision(
database_url: str,
alembic_config_filename: str,
alembic_base_dir: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]:
"""
Returns a tuple of ``(current_revision, head_revision)``; see
... | ca9040343be556e831ff6c4220ca5d9451c2c556 | 3,615,222 |
def extract_root(pitch):
"""
Try to extract an integer root from a non-integral pitch
"""
if isinstance(pitch[0], Fraction):
pitch = pitch + 0
root = 1
while True:
d = 1
for coord in pitch:
if coord.denominator > 1:
d = ... | 8cda1bf8daef0b948512a720130a5cf28670e5f0 | 3,615,223 |
def get_kind(cm, kind, value):
"""
Return the value of the 'kind' argument
:param cm: a ClassManager object
:type cm: :class:`ClassManager`
:param kind: the type of the 'kind' argument
:type kind: int
:param value: the value of the 'kind' argument
:type value: int
:rtype: string
""... | f4e1d2333178d86492705a8ad5898f7229884b83 | 3,615,224 |
import os
from datetime import datetime
def _generate_global_config() -> str:
"""Generate a standard configuration file for the application in the
user's home folder ~/.aiscalator/config/aiscalator.conf from the
template file in aiscalator/config/template/aiscalator.conf
"""
logger = getLogger(__n... | a831533e566d6de404daf43f524236151db0abf5 | 3,615,225 |
import tempfile
import os
def temp_fetch(url):
"""Fetch a URL and save it in a temporary file, returning the filename."""
conn = urllib2.urlopen(url)
try:
fp = tempfile.NamedTemporaryFile(delete=False)
LOG.info("Saving %s to a temporary file" % truncate_url(url))
try:
... | fde722376ecc7877e36ff4ad2ba5e9bee5cd2090 | 3,615,226 |
import os
import csv
def load_video_infos_csv(file_path: str):
"""load the values of a .csv file
containing the info of all videos
in the directory
Args:
file_path (str): the file path to the file
debug_function (bool, optional): Defaults to None.
Returns:
(list(dict)): ... | a9cc287b8f4854bf0d944537be35fe7518eced25 | 3,615,227 |
def mean_abs_mismatch(slice0, slice1):
""" Mean absoute difference between images
"""
return np.mean(np.abs(slice0 - slice1)) | d8e66d3b4eea3bc921f8f5f47e75d9fcb7d34dc4 | 3,615,228 |
def loads(payload, **kwargs):
"""
Deserialize an object from a bytestring.
:param bytes payload: the bytestring to serialize
:param kwargs: keyword arguments passed to :class:`~.CBORDecoder`
:return: the deserialized object
"""
fp = uio.BytesIO(payload)
return CBORDecoder(fp, **kwargs).d... | 9a320636a6eccc43a5b0c7782300e24dde74bad7 | 3,615,229 |
def calc_acc(fn: float, fp: float, tp: float, tn: float) -> float:
"""
:param fn: false negative miss
:param fp: false positive or false alarm
:param tp: true positive or hit
:param tn: true negative or correct rejection
:return: accuracy
"""
return (tp + tn) / (tp + tn + fn + fp) | cd790df66fe1f1537ed700e2a453b383390fee3f | 3,615,230 |
import ray
def errors(all_jobs=False):
"""Get error messages from the cluster.
Args:
all_jobs: False if we should only include error messages for this
specific job, or True if we should include error messages for all
jobs.
Returns:
Error messages pushed from the c... | 1f79618dde4ad0f61d814f48c5b3f3388594df77 | 3,615,231 |
import os
import sys
def main(args):
"""
TODO: Populate docstring with --help readable information
"""
# TODO: Populate docstring
#/* ----------------------------------------------------------------------- */#
#/* Print usage
#/* -----------------------------------------------------... | 931fd03e229a25b2cc23bd0bfcca908f95546950 | 3,615,232 |
def _gen_test_tree_4():
"""
Not BST
5
3 9
2 10 6 8
"""
tree = BinaryNode(5)
tree.left = BinaryNode(3)
tree.left.left = BinaryNode(2)
tree.left.right = BinaryNode(10)
tree.right = BinaryNode(9)
tree.right.left = BinaryNode(6)
tree.right.right = BinaryNode(8)
r... | 0e9f67bbc85c71f67918fb47099ecbb635688d10 | 3,615,233 |
def by_circ(x, y):
"""
Sort circRNAs by the start and end position
"""
return x.end - y.end if x.start == y.start else x.start - y.start | 5d8205389960b92f10c450fdb6385678a279406b | 3,615,234 |
import yaml
def get_rest_of_manifest_values():
""" If an existing manifest is present then we do not want to overwrite any fields
the user may have filled out. So we want to read in everything but the resources:
section and use that when generating the file. """
stream = open('hardening_manifest/harde... | 03cc8afbcdf26a91596d189bafecce08c9cf2895 | 3,615,235 |
def ConvertJsonIntoDict(string):
"""Read a JSON string and convert its contents into a Python datatype."""
if len(string) == 0:
print >> sys.stderr, ('Error could not parse empty string')
raise Exception('JSON data missing')
try:
json = simplejson.loads(string)
except ValueError, e:
print >> sy... | 899e7613928848b334da014bcbb870787068d590 | 3,615,236 |
def process_html(body):
"""Transform a screen-optimized HTML body to a mail-optimized one.
Relies on :class:`premailer.Premailer` to include styles in HTML body
and optimize content.
Args:
body (str): The HTML string to process.
Returns:
:class:`str`: The processed HTML mail body.... | d281eed35ebd6e8f46a2f97ed2ab58c411492a7d | 3,615,237 |
def img_crop(img, length, cx=None, cy=None):
"""
Crop the image to square (length^2). If cx and cy are not specified, it will set to
where the max pixel count is.
I: plt.imread()
length: pixel sizes
cx, cy: center pixel of the image
"""
if not (cx and cy):
cy, cx = unravel_index(... | 7f94b7adc90b53d4bceee8ee880f54aad2bf86a4 | 3,615,238 |
import requests
import json
def post_special(url, param: dict = None):
"""
发送 post 请求,主要是参数中的ddjm等参数,可能用于防火墙拦截
:param url: url
:param param: param dict
:return: 返回json中的data域
"""
param_json = COMMON_PARAMS.copy()
param_json.update(param if param is not None else {})
response = requ... | 8afa3fb936fff574a2f43a81044857f40f0ac7c9 | 3,615,239 |
import sys
import gc
def nogc(func):
"""disable garbage collector
Python's garbage collector triggers a GC each time a certain number of
container objects (the number being defined by gc.get_threshold()) are
allocated even when marked not to be tracked by the collector. Tracking has
no effect on ... | cdc9a1f48608d84b8a3e568bb0b50a6f12ffa34a | 3,615,240 |
def evaluate_f1_update_confusion_matrix(df, new_rule, class_col_name, counts, min_max, classes):
"""
Computes the F1 score of the dataset for a given set of rules using leave-one-out cross-evaluation.
Assumes that the initial confusion matrix already exists, hence evaluate_f1_initialize_confusion_matrix() s... | 17c91fdd00ab6ed3af6419092f85a7f57452ecb3 | 3,615,241 |
import time
import torch
def forward(model, generator, return_input=False,
return_target=False):
"""Forward data to a model.
Args:
model: object
generator: object
return_input: bool
return_target: bool
Returns:
audio_name: (audios_num,)
clipwise_output: (aud... | f43724008956b7f0695ccd28ab41bab380ebaf4e | 3,615,242 |
def corrfun_mat(image_dict):
"""
A useful fixture containing the correction function evaluated over the range of the sky plane test image.
"""
ra = image_dict["ra"]
dec = image_dict["dec"]
# pre-multiply the image by the correction function
return spheroidal_gridding.corrfun_mat(np.fft.ffts... | 33a487037f1f7edb7eb5d924f5b1a40569dcf76e | 3,615,243 |
from typing import List
def get_nft_info_from_puzzle(nft_coin_info: NFTCoinInfo) -> NFTInfo:
"""
Extract NFT info from a full puzzle
:param nft_coin_info NFTCoinInfo in local database
:return: NFTInfo
"""
uncurried_nft: UncurriedNFT = UncurriedNFT.uncurry(nft_coin_info.full_puzzle)
data_ur... | 5f88a25b38308db1cc04beb5f84a0d960cc241cc | 3,615,244 |
import sys
def try_import(name, alternative=None, error_callback=None):
"""Attempt to import a module, with a fallback.
Attempt to import ``name``. If it fails, return ``alternative``. When
supporting multiple versions of Python or optional dependencies, it is
useful to be able to try to import a m... | 5c8733af99173caef74efdc9148266390581ac34 | 3,615,245 |
def fix_masks(masks, indices):
"""Remove from every mask any common pixels with another mask"""
new_masks = []
for ind in indices:
mask = masks[ind]
for ind1 in indices:
if ind != ind1:
mask = np.logical_and(mask, np.logical_and(masks[ind], np.logical_not(masks[in... | ca8b043274ace6376d9af03cb912e9195d36ca73 | 3,615,246 |
from typing import Sequence
def barnsley_fern(range_x: Sequence[float], range_y: Sequence[float],
steps: int = 20, samples: int = 20000
) -> tuple[np.ndarray, np.ndarray]:
"""Generates a Barnsley Fern
Args:
init_x: x coordinates of the starting points
init_... | e717d34f4b8f737325b53d62f1aac6c8cb6cfe03 | 3,615,247 |
def getoutput(cmd):
"""Return output (stdout or stderr) of executing cmd in a shell.
Like getstatusoutput(), except the exit status is ignored and the return
value is a string containing the command's output. Example:
>>> import subprocess
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'
... | 1654e0b8f25836652eaff84852099b4b207db5e8 | 3,615,248 |
import sys
import getopt
def takearg(argv):
""" Function which record arguments from the command line."""
# default values
masked = False # freq 0,1 and 1,0 masked if masked = 1
pts_l = None # Grids sizes for extrapolation
outputname = "mis_fs_2d_optlog"
model_list = ["PAN","PANG","PANGb","PA... | c4d6cef76b5cf634fc0fa7e95c21cd88870a7452 | 3,615,249 |
def handle_choice(uid):
"""
This function handles the choice of the user.
"""
print("Type 'Back' to go back.")
choice = input("Enter Code > ")
if choice.lower() == "back":
show_menu(uid)
else:
return search_for_choice(uid, choice) | 8f1c40d036c8322e33e93ded7f67515dc7004e7e | 3,615,250 |
from typing import Union
import torch
from typing import Optional
from typing import Tuple
def get_window(window_type: str,
window_size: int,
device: Union[str, torch.device],
periodic: Optional[bool] = True,
padding: Optional[Tuple[int, int]] = (0, 0)
... | f5c0a0ffb509da788fb75f9bd152997abcc2814a | 3,615,251 |
import base64
def process_log_token(logtoken):
"""
processLogToken retrieve username and password from a given login token
(!)Override this method to manage more complex and secure algorithms;
tester code uses the following encrypted string to store user
credentials:
username=<userna... | e4566b4242e172f2699010851760668a6ac18a6e | 3,615,252 |
def _normalize_longitude(lon: float) -> float:
"""Normalize longitudes between [-180, 180]"""
return ((lon + 180.0) % 360.0) - 180.0 | e50dc8fee9a0499a2e32f3ccf8b2e9a634581bba | 3,615,253 |
def get_objection_text():
"""
Client sends a list of objection ids, we respond
with a dictionary of id:text elements.
"""
objection_labels = request.form.getlist('objections[]')
result = []
for label in objection_labels:
objection_text = DATABASE.get_objection_text(label)
res... | 7d02712641162b5e596649a2cbf7e4a93cfca4b2 | 3,615,254 |
def test_fallback_max():
"""
Feature: JIT Fallback
Description: Test max() in graph mode.
Expectation: No exception.
"""
@ms_function
def foo():
x = max([1, 2, 3])
return x
assert foo() == 3 | ae79e6f910c63280cfaacc3f4795a22402cf679f | 3,615,255 |
def get_tf_tensor_shape(tensor):
"""Get tensor shape, if there is unkown tensor, set it as None"""
shape = []
try:
shape = tensor.get_shape().as_list()
if any(s is None for s in shape):
return None
return shape
except Exception: # pylint: disable=broad-except
shape = None
return shape | 33c7e17102ad2f7d407c1f86b13c7cdfa61ca677 | 3,615,256 |
def _update_selected_experiment_table_rows(
last_select_click, last_clear_click, experiment_table_indices
):
"""The callback to select or deselect all rows in the experiment table.
Triggered when the select all or clear all button is clicked.
"""
last_select_click = last_select_click if last_select... | 7a527272c780750ea9cbc076f0d947fe9b68a460 | 3,615,257 |
from typing import List
from typing import Counter
def get_answer_slow(input_data: List[str], steps: int) -> int:
"""
The iteration in process(template, rules) causes the program to run out of memory on large steps
Use get_answer instead
"""
template, rules = parse_input(input_data)
for i in ... | a1b0b9abbcf7c351388171598efbdfe8c80d13e7 | 3,615,258 |
from typing import List
def get_strategies() -> List[MaskingStrategy]:
"""Returns all supported masking strategies"""
return [e.value for e in SupportedMaskingStrategies] | 7223f8433fb22fea4a772838875b9aba29af608a | 3,615,259 |
def add2dict(dict, name, item):
"""
checks whether name is in dict before adding the item.
file is a string containing a file name,
"""
if debug and name in dict:
print("\nWarning: the key ", name, "already in dict will be overwritten")
print("old value=",dict[name])
print("n... | 28aa5668c083eabdb45ec8492e5f2043b6a95696 | 3,615,260 |
def rc4Decrypt(data, key):
"""RC4 algorithm"""
x = 0
box = list(range(256))
for i in range(256):
x = (x + int(box[i]) + int(key[i % len(key)])) % 256
box[i], box[x] = box[x], box[i]
x = y = 0
out = []
for char in data:
x = (x + 1) % 256
y = (y + box[x]) % 256
... | 91c959cf03410626378647ab6d85391e5b0970d2 | 3,615,261 |
def _move_tutor_version_groups(table):
"""Tutored moves are never the same between version groups, so the column
collapsing ignores tutors entirely. This means that we might end up
wanting to show several versions as having a tutor within a single column.
So that "E, FRLG" lines up with "FRLG", there h... | 5b9d43a11d5e5d92351ac5b93a7ada5b8d5daa36 | 3,615,262 |
def load_from_module(path=None, workspace=None):
"""Load opener interface from path or from python environment.
Opener can be defined as an Opener subclass or directly has a module.
Return an OpenerWrapper instance.
"""
interface = utils.load_interface_from_module(
'opener',
interf... | ad780aeeb518ef3d7b5a1d30eafb4b8c4c1ef802 | 3,615,263 |
import os
import sys
def setup(cli_arguments):
"""Perform BAF setup."""
log.info("Setup")
with log.indent():
input_file = get_input_file(cli_arguments)
dry_run = cli_arguments.dry
generate_text = cli_arguments.text
generate_html = cli_arguments.html
generate_csv = c... | 42c33e3d291ec969f8f21ce6290dcb1c78da60c5 | 3,615,264 |
import subprocess
def getTotalBalance(cli):
"""Wrapper function for the relevant RPC function call.
Args:
cli (str): Full path to cli binary associated with coin.
Returns:
String: String containing the command output.
"""
command = CLI_GET_BALANCE.format(cli)
... | 9de58dd3646c9e4aaf42a9493584eb9eee24816c | 3,615,265 |
import textwrap
def make_code_format(light_theme: bool = False) -> str:
"""Create code format template for rich."""
theme = "light" if light_theme else "dark"
code_format = textwrap.dedent(
f"""\
<div class="terminal-container">
<div class="terminal {theme}-terminal">
... | deb5d97f3bce85c1ef91d4c9e88b68474d70c173 | 3,615,266 |
import anyio
def mqtt_connected(func):
"""
MQTTClient coroutines decorator which will wait until connection before calling the decorated method.
:param func: coroutine to be called once connected
:return: coroutine result
"""
@wraps(func)
async def wrapper(self, *args, **kwargs... | 54af1ef8b33aa336fb5703d9d2d2b668fbbec8fe | 3,615,267 |
def to_canonical(fn, self, arg, orig_t):
"""Check and convert an argument to the canonical representation.
Arguments:
arg: The argument to convert.
orig_t: The type of the argument as returned by to_abstract.
Returns:
A version of the argument where classes/dicts become tuples
... | d87d9ef2e4f1f6be8d356a8ef22959d5fba690ae | 3,615,268 |
def copy_dsa(data: dsa.PolyData) -> dsa.PolyData:
"""Deep copy a PolyData"""
res = dsa.WrapDataObject(vtk.vtkPolyData())
res.VTKObject.DeepCopy(data.VTKObject)
return res | 0bb0e6fb5160f730c59db7a5692f7de560f408f7 | 3,615,269 |
import subprocess
def run_get_output(cmd, chk_err=True, log_cmd=True):
"""
Wrapper for subprocess.check_output.
Execute 'cmd'. Returns return code and STDOUT, trapping expected exceptions.
Reports exceptions to Error if chk_err parameter is True
"""
if log_cmd:
logger.verbose(u"run cm... | eb046c7b304215da3f6439871d32db603585ed36 | 3,615,270 |
def modify_network_interfaces(
self,
if_info: list,
) -> bool:
"""Modify interface information on appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - networkInterfaces
- POST
- /networkInterfaces
:pa... | dcf22de0d88927d1c217f08d744ea18a426c7633 | 3,615,271 |
def _wrapped_value_and_num(value):
"""Returns a list containing value plus the list's length."""
if isinstance(value, (list, tuple)):
return value, len(value)
else:
return [value], 1 | 811521a18dffd9ee046751c74d4d8a097662c8cd | 3,615,272 |
def perform_fit(cfmclient, fabric_uuid, name, description):
"""
Request a full fit across managed Composable Fabrics.
:param cfmclient: CFM Client object
:param fabric_uuid: Valid Fabric UUID of an existing fabric
:param name: Simple name of the fit
:param description: Longer Description of the ... | 66d6462c97b1354ef11b6378b82912030ed40a94 | 3,615,273 |
def __get_host_vol_dict(k8s_conf):
"""
Returns a dict of configured host volumes where the key is the name and
the value is the size
:param k8s_conf: the k8s configuration used to deploy the cluster
:return: dict
:raises Exception
"""
out = dict()
host_vols = config_utils.get_host_vo... | 2ecef222fa183821e8d4092bd3d648e7b0a363de | 3,615,274 |
def normalize(value, *normalizers, **options):
"""
normalizes the given value.
:param str value: value to be normalized.
:param str normalizers: normalizer names to be used.
they will be used in the order of their appearance.
if not provided, all... | 04ce63808264784fee26263fb903468d7d39c3a5 | 3,615,275 |
def rescale(image):
"""
If the input video is other than network size, it will resize the input video
:param image: a frame form input video
:return: scaled down frame
"""
scale_side = max(image.shape)
# image width and height are equal to 192
scale_value = config["input_width"] / scale_... | 0033043752e0d1d5cd58b07734655f61954a44b4 | 3,615,276 |
def remove_noise(frame):
""" Remove noise using morphological operation: erode, then diate."""
### Morphology: Opening ###
kernel = np.ones((3,3),np.uint8)
frame = cv2.morphologyEx(frame, cv2.MORPH_OPEN, kernel, iterations=1)
return frame | 8dc4af1fd93e8b652f665c98f968b16b92f3922b | 3,615,277 |
import shlex
import subprocess
def get_password_from_vault():
"""Call pass and return the output."""
pass_path = find_pass()
command_line = f'{pass_path} {VAULT_NAME}'
command_args = shlex.split(command_line)
process = subprocess.Popen(
command_args,
stdin=subprocess.PIPE,
... | f3cb1d9d518f6b1362ba849b6f6ac1a10e550754 | 3,615,278 |
import os
def get_specific_host(service, container):
"""Return the hostname/address of a specific container/instance of the
given service."""
try:
return os.environ['{}_{}_HOST'.format(_to_env_var_name(service),
_to_env_var_name(container))]
except... | e56fefbb2b64598b916a1ad273822fd60dd9a722 | 3,615,279 |
def get_instrument_names() -> np.ndarray:
"""Return the names of each instrument in the metadata cache."""
image_metadata = preprocessing.image_meta.read_metadata()
return np.unique(image_metadata["Instrument"]) | af187f618d2300cacc1b7ef80937ee32edc65c76 | 3,615,280 |
import tempfile
def get_reads_with_subseq(subseq: str, run: Fast5run, outfile=None, revcompl=False):
"""
Get all reads containing specific subsequence
:param subseq: sequence to be looked for
:param run: Fast5run object, where to search
:param outfile: file, where the selected reads should be wri... | 458ed02ac0bc76a85c8b629f5feb85f39451222b | 3,615,281 |
def qnt_jogadores():
"""
-> Irá ler o arquivo de configurações e analisar o parâmetro "qnt_jogadores"
:return: retornará o valor do parâmetro
"""
try:
linha = ler_linha(linha=2, inicio_linha_index=15)
return int(linha)
except:
raise FileNotFoundError("Arquivo não encontra... | ac51b1c5cce84d0bf20faac8c989ab6864553ada | 3,615,282 |
def connected_amp_protocol():
"""
:return: ``AMP`` hooked up to transport.
"""
p = AMP()
p.makeConnection(StringTransport())
return p | 2128d7bdfea66f8bef70ec34ef5236bb90be12dd | 3,615,283 |
def check_converge(pf, abs_tol=1e-4):
"""
Return Y/N, converged pf/ raw pf, relative changes
"""
is_converge = isConverge(pf, abs_tol)
if len(pf) >= 2:
abs_err = abs(pf[-2]-pf[-1])
else:
abs_err = None
if is_converge:
res = (True, pf[-1], abs_err)
else:
... | 9f29034d682ba280c4da576e02680b7c5b1a313f | 3,615,284 |
def extract_trajectories(n_true, n_tot, idxs, threshold):
"""Extract frequency trajectories for different positions on the genome.
See the documentation of `extract_trajectory`"""
times = sorted(list(n_tot.keys()))
trajs = {}
for idx in idxs:
trajs[idx] = extract_trajectory(n_true, n_tot, id... | 58d4e9f493cda9f27bf3f5ae77255c1987071406 | 3,615,285 |
import logging
import pickle
def load_file(file_adress: str):
"""
load data from file of type pickle, intended to be used with
the method save_file, check if the file exist before open.
args:
file_adress: full adress to the file to be open
returns: if the file exist returns the content,
... | 91c4cbe19a8c39cf17d7cce20cce06c973ca0d1e | 3,615,286 |
import torch
def straight_through_estimator(input: torch.Tensor) -> torch.Tensor:
""" straight through estimator
>>> straight_through_estimator(torch.randn(3, 3))
tensor([[0., 1., 0.],
[0., 1., 1.],
[0., 0., 1.]])
"""
return _STE.apply(input) | f07588cb723819e7003780552b06ab04e4ab0e76 | 3,615,287 |
def bbox_transform_inv(boxes, deltas, mean=None, std=None):
"""Adjust boxes based on deltas
Args
boxes : collection of box in the format (x1, y1, x2, y2)
deltas : amount of shifting needed to be done to each box
mean : fixed distance to shift in each direction
std : degree... | f240cf7832aac3522c2c20a996acff26af3e1576 | 3,615,288 |
import shutil
def os_zipfolder(
dir_tozip="/zdisks3/output", zipname="/zdisk3/output.zip", dir_prefix=True, iscompress=True
):
"""
shutil.make_archive('/zdisks3/results/output', 'zip',
root_dir=/zdisks3/results/',
base_dir='output')
os_zipfolder('zdisk/test/aapackag... | a8baabf165c957a2d23a40842259432724b40b91 | 3,615,289 |
def make_task_hashable(task):
"""
Makes a task dict hashable.
Parameters
----------
task : dict
task that shall be made hashable.
Returns
-------
TYPE
hashable task.
"""
if isinstance(task, (tuple, list)):
return tuple((make_task_hashable(e) for e in task)... | 4e27fe4c27c4ae220ed8b15ce701f2d87796b715 | 3,615,290 |
def select_roi(image, title):
""" Select a region of interest with PyQtGraph """
global app # created when loading the module
X = image.shape[0]
Y = image.shape[1]
disp_shape = (max(800, X + 100), max(800, Y + 100))
w = pg.GraphicsWindow(size=disp_shape, border=True)
w.setWindowTitle('Selec... | 2a6100134619990cc62705825deb8bb2264f8025 | 3,615,291 |
def read_collections_config(request):
"""Load settings for a minor repo with shared tree collections"""
conf = get_conf_object(request)
collections_repo_parent = conf.get("apis","collections_repo_parent")
collections_repo_remote = conf.get("apis", "collections_repo_remote")
try:
git_ssh ... | 0fcd22362040de8d46bfb168d7aa512228ad466c | 3,615,292 |
from pathlib import Path
def parent(path: str):
"""Returns the parent `Path` of the given path."""
return Path(path).parent.resolve() | d86b37bc8310b024eb0a78c1b1de404cf6c2c85a | 3,615,293 |
def train_step(
env: gym.Env,
env_step: TFStep,
initial_state: tf.Tensor,
actor: tf.keras.Model,
critic: tf.keras.Model,
actor_optimizer: tf.keras.optimizers.Optimizer,
critic_optimizer: tf.keras.optimizers.Optimizer,
gamma: float,
max_steps_per_ep... | 5a552021682067c3e969623ecc2eb0fda92698d7 | 3,615,294 |
def get_class_means_between_and_within_covs(samples, classids, bias=True):
""" Return class means and the between and shread within class covariance matrix.
Args:
samples (np.array): input data
classids (np.array): identification of classes
bias (bool): type of normalization, see np.cov... | 3466a93fc0f91357c1a22a7f7e358c7b5a0b6d04 | 3,615,295 |
def get_phone_number(phone_number):
"""
Following suggested RFC 3966 protocol by open id
expect: +111-1111-111111 format
"""
if '-' in phone_number:
phone_split = phone_number.split('-')
if len(phone_split) > 2:
#if had country code
return phone_split[2]
... | 287d3dde0cabc3c7730ac48bf94b2c4fc809f123 | 3,615,296 |
def isGroup(obj):
"""Returns true if the object is a group, false if not
@return: If the object is a group
@rtype: bool"""
# isinstance is needed here due to NestedGroup's inheritance
# pylint: disable=unidiomatic-typecheck
return (
type(obj) == opencue.wrappers.group.Group or
(... | 9072bc3e2d585bb28403c5f4fc5f1ccd92a70cf8 | 3,615,297 |
def AppTypeInsert(json_data):
""" Insert AppType objects into DB """
result = []
for r in json_data:
apptype = AppType(id=int(r['id']), desc=r['desc'])
print("[-] apptype: Insert %s ..." % r)
db.merge(apptype)
result.append(apptype)
db.commit()
return result | 5c00241fa96f3951301fdba99873ed3855deaa5f | 3,615,298 |
from typing import Optional
from typing import Dict
def get_selections(
selection: Selection,
*,
typename: Optional[str] = None,
) -> Dict[str, SelectedField]:
"""Resolve subselections considering fragments.
Args:
selection:
The selection to retrieve subselections from
... | 5bca9c6f6647713a425d13acba3c7d1f0451341d | 3,615,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.