content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_indicators_mv(df_mv):
"""Compute indicators about missing values. Used for plotting figures."""
# 1: Statistics on the full database
n_rows, n_cols = df_mv.shape
n_values = n_rows*n_cols
df_mv1 = df_mv == 1
df_mv2 = df_mv == 2
df_mv_bool = df_mv != 0
# Number of missing values i... | 5,300,300 |
def fitness(pop):
""" Applies _fitness to every chromossome in the population."""
pop_size = pop.shape[0]
fitvec = np.zeros(pop_size, np.float64)
for i in range(pop_size):
fitvec[i] = _fitness(pop[i])
return fitvec | 5,300,301 |
def randomquote(user, channel, text):
"""Show a random quote"""
callback = partial(_single_quote_callback, channel)
run_query("SELECT rowid, quote FROM quote ORDER BY random() DESC\
LIMIT 1;", [], callback) | 5,300,302 |
def trim_t_results(
results: OdeResult,
t_span: Union[List, Tuple, Array],
t_eval: Optional[Union[List, Tuple, Array]] = None,
) -> OdeResult:
"""Trim ``OdeResult`` object based on value of ``t_span`` and ``t_eval``.
Args:
results: Result object, assumed to contain solution at time points
... | 5,300,303 |
def test_cifar100_to_mindrecord_directory(fixture_file):
"""
test transform cifar10 dataset to mindrecord
when destination path is directory.
"""
with pytest.raises(MRMOpenError,
match="MindRecord File could not open successfully"):
cifar100_transformer = Cifar100ToMR(... | 5,300,304 |
def itk_image_type(medipy_image):
""" Return the ITK image type corresponding to the given ``medipy.base.Image``
"""
if medipy_image.data_type == "scalar" :
itk_type = types.dtype_to_itk[medipy_image.dtype.type]
image_type = itk.Image[itk_type, medipy_image.ndim]
elif medipy_image.d... | 5,300,305 |
def analyze_cna_mrna(genes, cell_line):
"""Plot CNA vs mRNA reported by CCLE for given genes in a cell line."""
import matplotlib.pyplot as plt
cna = cbio_client.get_ccle_cna(genes, [cell_line])[cell_line]
mrna = cbio_client.get_ccle_mrna(genes, [cell_line])[cell_line]
plt.ion()
plt.figure()
... | 5,300,306 |
def load_gt_boxes(path):
"""
Don't care about what shit it is. whatever, this function
returns many ground truth boxes with the shape of [-1, 4].
xmin, ymin, xmax, ymax
"""
bbs = open(path).readlines()[1:]
roi = np.zeros([len(bbs), 4])
for iter_, bb in zip(range(len(bbs)), bbs):
... | 5,300,307 |
def pushbullet(ALERTID=None, TOKEN=None):
"""
Send a `link` notification to all devices on pushbullet with a link back to the alert's query.
If `TOKEN` is not passed, requires `PUSHBULLETTOKEN` defined, see https://www.pushbullet.com/#settings/account
"""
#if not PUSHBULLETURL:
#return ("PUS... | 5,300,308 |
def get_cost(outputs, targets):
"""Return the cost/error rate at the output."""
cost_per_sample = []
cost = []
if(np.array(outputs).ndim == 2):
for idx, outputs_per_epoch in enumerate(outputs):
cost_per_sample.append(list(np.array(outputs_per_epoch) - np.array(targets)))
... | 5,300,309 |
def calculate_truhlar_scaling_factors(zpe_dict, level_of_theory):
"""
Calculate the scaling factors using Truhlar's method:
FREQ: A PROGRAM FOR OPTIMIZING SCALE FACTORS (Version 1)
written by Haoyu S. Yu, Lucas J. Fiedler, I.M. Alecu, and Donald G. Truhlar
Department of Chemistry and Supercomputing... | 5,300,310 |
def pairwise_intersection(boxlist1, boxlist2):
"""Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx1x4 floatbox
boxlist2: NxDx4
Returns:
"""
x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=2) # NxDx1
x_min2, y_min2, x_max2, y_max2 = tf.split(boxl... | 5,300,311 |
def _parse_sha1_thumbprint_openssl(output):
# type: (str) -> str
"""Get SHA1 thumbprint from buffer
:param str buffer: buffer to parse
:rtype: str
:return: sha1 thumbprint of buffer
"""
# return just thumbprint (without colons) from the above openssl command
# in lowercase. Expected open... | 5,300,312 |
def people_preferences_get(search=None) -> ApiOptions: # noqa: E501
"""List of People Preference options
List of People Preference options # noqa: E501
:param search: search term applied
:type search: str
:rtype: ApiOptions
"""
try:
if search:
data = [tag for tag in P... | 5,300,313 |
def encode_name(name):
"""
Encode a unicode value as utf-8 and then URL encode that
string. Use for entity titles in URLs.
"""
return quote(name.encode('utf-8'), safe=".!~*'()") | 5,300,314 |
def reduce(braid, (p, q)):
"""
Applies one step of the alphabetical homomorphism on the given handle.
Returns a new reduced braid.
"""
new_handle = []
j = abs(braid.generators[p])
e = j/braid.generators[p]
for letter in braid.generators[p:q+1]:
exp = abs(letter)/letter
i... | 5,300,315 |
def test_hash():
"""Test Node Server hash."""
node = Node(
default_route_domain=2,
**cfg_test
)
node1 = Node(
default_route_domain=2,
**cfg_test
)
cfg_changed = copy(cfg_test)
cfg_changed['name'] = 'test'
node2 = Node(
default_route_domain=2,
... | 5,300,316 |
def service_init_hk_stock_table():
"""
Init database from a blank stock list.
"""
from libbasemodel.stock_manager import EventTradeDataManager
from libbasemodel.stock_model import StockList
from dev_global.path import CONF_FILE
url = read_url('url_hk_stock_list', CONF_FILE)
stock_list = ... | 5,300,317 |
def MAEMetric(key):
"""Create max absolute error metric on key."""
return DictMetric(key, MaximumAbsoluteError()) | 5,300,318 |
def nmap_handle(ip_address, nmap_type, output):
"""
This function handles nmap to run with a given nmap scan type. special is recommended!!
:param ip_address: ip address of the target
:param nmap_type: the chosen nmap scan type
:param output: the result path
:return:
"""
if nmap_type == ... | 5,300,319 |
def filter_measurements():
# * To Do *
"""
Create a list of "estimates", by using the predict and update methods of the kf class.
https://github.com/rlabbe/filterpy
""" | 5,300,320 |
def run():
"""Runs the main script"""
mobiles_ns = []
mobiles_sg = []
timetable_ns = 'https://www.n-somerset.gov.uk/my-services/leisure/libraries/bringing-the-library-to-you/mobile-library/'
timetable_sg = 'https://www.southglos.gov.uk/libraries/mobile-library-almondsbury-severn-beach-pilning/'
... | 5,300,321 |
def get_data(group: h5py.Group, name: str) -> np.ndarray:
"""
Gets data in array form. This is mostly so that I can change the way I get data later
# TODO: Maybe make this only get data that isn't marked as bad or something in the future?
Args:
group (): Group that data is in
name (): N... | 5,300,322 |
def generate_json_config(jsonnet_config_path, values):
"""Generate json config from jsonnet config and values.yaml.
Jsonnet code is used to load jsonnet config and merge it with values.
Args:
jsonnet_config_path (str): Path to jsonnet (libsonnet) config file.
values (dict): Values from val... | 5,300,323 |
def test_hbp_approximation_mnist_model():
"""Check correct usage of HBP approximations in MNIST model."""
aij = [True, False]
apj = [True, False]
# assert correct approximations in layers
linear_idx = [0, 2, 4, 6]
linear_idx = [item + 1 for item in linear_idx]
activation_idx = [1, 3, 5]
... | 5,300,324 |
def convert_to_scitype(obj, to_scitype, from_scitype=None, store=None):
"""Convert single-series or single-panel between mtypes.
Assumes input is conformant with one of the mtypes
for one of the scitypes Series, Panel, Hierarchical.
This method does not perform full mtype checks, use mtype or check... | 5,300,325 |
def main() -> int:
"""Script entry point."""
args = parse_args()
# Clear out any existing docs for the target.
if os.path.exists(args.sphinx_build_dir):
shutil.rmtree(args.sphinx_build_dir)
# TODO(pwbug/164): Printing the header causes unicode problems on Windows.
# Disabled for now; ... | 5,300,326 |
def add(config_or_file, default=False):
"""
Add an endpoint to the registry.
``config_or_file`` can be the path to a yaml definition file or a dictionary of arguments to pass to
``endpoints.api``. See also Google's documentation on `endpoints.api <https://cloud.google.com/appengine/docs/python/endpoint... | 5,300,327 |
def test_make_system_from_file(examplefile, comm):
"""
longtermgoal for confortable and secure use
Returns
-------
"""
# TODO: test this on npy and nc file
# Maybe it will be another Function or class
fn, res, data = examplefile
interaction = HardWall()
system = make_system(su... | 5,300,328 |
def find_dice_medial(dice):
"""Средний бросок кости в формате навроде 1d6, 2d6, 1d12.
"""
dice_list = dice.split('d')
medial_number = math.floor(int(dice_list[0]) * (int(dice_list[1]) / 2))
return medial_number | 5,300,329 |
def log(context, text):
"""
logs text in the js console
"""
script_text = 'console.log("%s")' % text
context.browser.execute_script(script_text) | 5,300,330 |
def remove_out_of_bounds_bins(df, chromosome_size):
# type: (pd.DataFrame, int) -> pd.DataFrame
"""Remove all reads that were shifted outside of the genome endpoints."""
# The dataframe is empty and contains no bins out of bounds
if "Bin" not in df:
return df
df = df.drop(df[df.Bin > chrom... | 5,300,331 |
async def afk_on_pm(sender):
""" Siz afk iken PM atanları afk olduğunuza dair bildirmeye yarayan fonksiyondur. """
global ISAFK
global USERS
global COUNT_MSG
if sender.is_private and sender.sender_id != 777000 and not (
await sender.get_sender()).bot:
if PM_AUTO_BAN:
... | 5,300,332 |
def inspect_container(container_name_or_id=''):
""" e.g. fab --host trinity10 inspect_container:container_name_or_id=... """
container_id = run("docker inspect --format '{{.Id}}' " + container_name_or_id)
container_name = run("docker inspect --format '{{.Name}}' " + container_name_or_id)
if container_na... | 5,300,333 |
def create_instance_configuration(details):
"""
Create an instance configuration
:param details: object details about the instance configuration
:param details["sessionId"] string id of a session
:param details["userId"] string id of a user
:param details["cameraHost"] string host of the camera
... | 5,300,334 |
def delete_order_condition(context: SagaContext) -> bool:
"""For testing purposes."""
return "b" in context | 5,300,335 |
def shorten_url(url_long) -> str:
"""Can be used to shorten a long url with tiny-url
:param url_long: The URL that shoul be shortened
:return: Shortened URL as string
"""
url = "http://tinyurl.com/api-create.php" + "?" \
+ parse.urlencode({"url": url_long})
res = get(url)
return res... | 5,300,336 |
def main():
"""
Module execution
:return:
"""
argument_spec = keycloak_argument_spec()
meta_args = dict(
state=dict(default='present', choices=['present', 'absent']),
id=dict(type='str'),
realm=dict(type='str'),
access_code_lifespan=dict(type='int', aliases=['a... | 5,300,337 |
def build_parser(args):
""" This method allows us to test the args.
>>> args = build_parser(['--verbose'])
>>> print(args.verbose)
True
"""
parser = argparse.ArgumentParser(usage='$ python parser.py',
description='Parse the MTA alert feed, ret... | 5,300,338 |
def save_cas_user_attributes(user, attributes, **kwargs):
"""Save attributes for user that authenticated from CAS"""
full_name = attributes.get('nama', '').split()
user.first_name = full_name[0]
user.last_name = full_name[-1]
user.profile.name = attributes.get('nama', '')
if (attributes.get('peran_user') ... | 5,300,339 |
def dep_pin(ctx, package, version, checks=None, upgrade=False, quiet=False):
"""Pin a dependency for all checks that require it. Setting the version
to `none` will remove the package. `pip-compile` must be in PATH.
Example invocations:
inv pin cryptography 2.2.2
inv pin --upgrade requests 2... | 5,300,340 |
def encode_string_list(x):
"""
:Summary: Take a list of strings x and encode its values to a list of integers.
:param x: list of strings
:return y: list of integers that are codes for x. x is sorted before being encoded.
:Example:
x = ['cat', 'dog', 'book', 'pencil', 'dog', 'book']
... | 5,300,341 |
def dummy_latrd_data(path_factory):
"""
Construct a temporary directory containing dummy LATRD data.
The data are spread across several files, in the manner of a LATRD data
collection, with each file having an entry for each of the LATRD data keys.
Args:
path_factory: The Pytest tmp_path_... | 5,300,342 |
def initial_split(writepath, readpath, verbose=True):
"""
Reads the gzip and splits the data into multiple sorted buckets
:param writepath: Directory to write the data
:param readpath: gZip File
:param verbose: Verbose boolean
"""
print("\n\nReading Maps CSV and splitting into multiple sorte... | 5,300,343 |
def mean_specobj(dat, inds=slice(None), *args, **kwargs):
"""
A specobj constructor, that returns an average over the *inds*.
See also:
ind_specobj
"""
a = ind_specobj(dat, inds, *args, **kwargs)
out = a.mean()
del a
return out | 5,300,344 |
def test_create_lessBand(landsat_get_mtl, monkeypatch):
"""Shoult raise an error on wrong band indexes."""
monkeypatch.setattr(l8_full, "LANDSAT_BUCKET", landsat_bucket)
landsat_get_mtl.return_value = landsat_meta
bands = [5, 4]
with pytest.raises(Exception):
l8_full.create(landsat_scene_c1,... | 5,300,345 |
def program(connection, args):
"""Download program sources command wrapper"""
checkout_program(connection, args.name) | 5,300,346 |
def two_traits(uni):
"""Get two table traitlets."""
if not hasattr(uni, "atom_two"):
raise AttributeError("for the catcher")
if "frame" not in uni.atom_two.columns:
uni.atom_two['frame'] = uni.atom_two['atom0'].map(uni.atom['frame'])
lbls = uni.atom.get_atom_labels()
df = uni.atom_tw... | 5,300,347 |
def unzip(zip_tar_rar_path, specified_dfs, dst_path):
"""
Function: open_source or vendor下.nupkg .zip .jar文件所在的文件夹路径
Args:
zip_tar_rar_path (str): open_source or vendor下.nupkg .zip .jar文件
specified_dfs (list): 指定zip中的文件列表
dst_path (str): 目的文件
Returns:
... | 5,300,348 |
def fill_sat_properties(sat_ext, href):
"""Fills the properties for SAR.
Based on the sat Extension.py
Args:
sat_ext (pystac.extensions.sat.SatExtension): The extension to be populated.
href (str): The HREF to the scene, this is expected to be an netCDF4 file.
Returns:
pystac.Ass... | 5,300,349 |
def cleanup(fmd):
"""
Cleanup ftp_mirror instance
"""
# print("I'm in "+sys._getframe().f_code.co_name)
#logging.info("I am in "+sys._getframe().f_code.co_name)
#sys.stdout.write("...\n")
sys.stdout.flush()
fmd = None
logging.info('[%s] - *** D O N E ***', now()) | 5,300,350 |
def randomforest_feature_importance(X_train, y_train, classification):
"""
Trains a RandomForestRegressor on the data and analyzes which features were weighed as more important
Returns an eli5 weights option
"""
import eli5
from sklearn.model_selection import train_test_split
train_X, val_X,... | 5,300,351 |
def wmt_zhen_tokens(model_hparams, wrong_vocab_size):
"""Chinese to English translation benchmark."""
p = default_problem_hparams()
# This vocab file must be present within the data directory.
if model_hparams.shared_embedding_and_softmax_weights == 1:
model_hparams.shared_embedding_and_softmax_weights = 0
... | 5,300,352 |
def _alter_pipe(alter: schemas.PipeAlter, name: str, version: Union[str, int], db: Session):
"""
The implementation of the update_pipe route with logic here so other functions can call it
:param alter: The pipe to alter
:param name: The pipe name
:param version: The version to alter
:param db: T... | 5,300,353 |
def get_docker_container_image(docker_client):
"""
Returns a dictionary containing the image each existing container.
"""
containers = docker_client.containers(all=True)
images = dict()
for container in containers:
names = container['Names']
image = container['Image']
f... | 5,300,354 |
def path_leaf(path):
"""
:param path:
:return:
"""
"""
Extract path and filename
:param path: Entire filepath
:return: Return a tuple that contains the (path, filename)
"""
head, tail = _split(path)
return (head, tail or _basename(head)) | 5,300,355 |
def writeXML(ofile, polylist, withHeader=False):
"""
Write a readable representation of the Polygons in polylist to a XML file.
A simple header can be added to make the file parsable.
:Arguments:
- ofile: see above
- polylist: sequence of Polygons
- optional withHeader: bool
... | 5,300,356 |
def Calc_Cold_Pixels_Veg(NDVI,NDVI_max,NDVI_std,QC_Map,ts_dem,Image_Type, Cold_Pixel_Constant):
"""
Function to calculates the the cold pixels based on vegetation
"""
cold_pixels_vegetation = np.copy(ts_dem)
cold_pixels_vegetation[np.logical_and(NDVI <= (NDVI_max-0.1*NDVI_std),QC_Map != 0.0)] = 0... | 5,300,357 |
def coverage_print(var, region, use_ascii=True):
"""
Prints coverage only
"""
my_seq = var.ref_range.sequence
prev = -1
did_dots = False
p_vert = chr(0x2502)
for pos, cov in enumerate(var.coverage[:-1]):
if cov != prev:
print(u"{:<12}:{:>12} {:2} {:.1}{}".format(reg... | 5,300,358 |
async def post(service, workspace_id, utterance, sem):
""" Single post restrained by semaphore
"""
counter = 0
async with sem:
while True:
try:
res = await message(service, workspace_id, utterance)
return res
except Exception as e:
... | 5,300,359 |
def largest_number(seq_seq):
"""
Returns the largest number in the subsequences of the given
sequence of sequences. Returns None if there are NO numbers
in the subsequences.
For example, if the given argument is:
[(3, 1, 4),
(13, 10, 11, 7, 10),
[1, 2, 3, 4]]
then thi... | 5,300,360 |
def test_issue_54755(tmp_path, state_tree, modules):
"""
Verify github issue 54755 is resolved. This only fails when there is no
pip module in the python environment. Since the test suite normally has
a pip module this test will pass and is here for posterity. See also
unit.states.test_pip_state.Pi... | 5,300,361 |
def ScanSingleParameter(script_name, parameter_name, values):
"""
Generic function to run a MOTMaster script (script_name - note you don't need the path or .cs suffix)
repeatedly, whilst scanning a single parameter (parameter_name) over a list of values. Can be used
directly or with one of convenience functions d... | 5,300,362 |
def merge_line_list(mod_text, vanilla_text, gen_text):
"""Merges sequences of lines.
Params:
mod_text
The lines of the mod file being added to the merge.
vanilla_text
The lines of the corresponding vanilla file.
gen_text
The lines of the previously me... | 5,300,363 |
def get(key=None):
"""
Returns the value of a configuration key.
:param str key: Configuration key. If key
is None, then returns entire dictionary.
:return value:
:Raises KeyError: Key not present
"""
if os.path.isfile(cn.CONFIG_FILE_PATH):
with open(cn.CONFIG_FILE_PATH, 'r') as fd:
yaml_dic... | 5,300,364 |
def covid_deconvolve(Cdiff, Fdiff, kp, t = None, mode='C', alpha=1, BS=1000, TSPAN=200, data_poisson=True, kernel_syst=True):
"""
COVID time-series deconvolution.
Args:
Cdiff: observed daily cases array
Fdiff: observed daily fatalities array
kp: kernel... | 5,300,365 |
def get_usc_release_text(
release_vers, short_title, section_number
) -> USCSectionContentList: # noqa: E501
"""Your GET endpoint
Get the text for a specific section # noqa: E501
:param release_vers:
:type release_vers: str
:param short_tile:
:type short_tile: str
:param section_numbe... | 5,300,366 |
def approximate_parabola(args):
"""
Args:
args: verified arguments from arparser
"""
parab_range = 1 # one-sided range of parabola function
deepspline_params = {
'mode': 'fc',
'size': args.spline_size,
'range_': args.spline_range,
'init': args.spline_init,
... | 5,300,367 |
def get_work_history_file(cfolder, filename, nyears):
"""
Generates a vector of works found in a lattes CV.
Args:
cfolder: folder containing the researcher Lattes CV file.
filename: name of the file containing the Lattes CV.
nyears: number of years to be considered in the vecto... | 5,300,368 |
def _parse_args(cmdl):
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"--inbam",
"-i",
help="input BAM (/dev/stdin)",
type=argparse.FileType("r"... | 5,300,369 |
def jacobi_iteration(A, b, tol=1e-9, Max_iter=5000):
""" Solve linear equations by Jacobi iteration method.
Args:
A: ndarray, coefficients matrix
b: ndarray, constant vector
tol: double, iteration accuracy
Max_iter: int, maximum iteration number
Returns:
y: ndarray,... | 5,300,370 |
def load_3dlut_3dl_format(filename):
"""
3DL形式の3DLUTデータをファイルから読み込む。
Parameters
----------
filename : str
file name.
Returns
-------
lut : array_like
3DLUT data with 3dl format.
grid_num : int
grid number.
title : str
title of the 3dlut.
"""
... | 5,300,371 |
def split_model(model, xi_kern=None):
"""
Take a model where the output has multiple columns (channels) and split it
so that each model only deals with a single column.
:param model:
:return: (list of models)
"""
yt = model.Y.value.copy().T
print("Split model ({} channels)...".format(yt.... | 5,300,372 |
def betaPDF(mean, var, centers, eps=1e-6):
"""
Calculate beta PDF
:param mean: mean
:type mean: float
:param var: variance
:type var: float
:param centers: bin centers
:type centers: array
:param eps: smallness threshold
:type eps: float
:return: pdf
:rtype: array
""... | 5,300,373 |
def connect(receiver, signal=All, sender=Any, weak=True):
"""Connect ``receiver`` to ``sender`` for ``signal``.
- ``receiver``: A callable Python object which is to receive
messages/signals/events. Receivers must be hashable objects.
If weak is ``True``, then receiver must be weak-referencable (m... | 5,300,374 |
def classify(parameters, data):
""" tests the algorithm """
global count
x_data, y_data = parameters
data = from_data_to_haar(data)
distances = ((x_data-data)**2).sum(axis=1)
# nearest = sorted(zip(distances, y_data), key=itemgetter(0))[:K_CONSTANT]
item_indexes = np.argsort(distances)[:K_CO... | 5,300,375 |
def format_list_to_dataframe(json_string: str) -> Optional[str]:
"""
:param json_string: Takes in input json in form of a string value
:return: Formatted tabular output of the json sent
"""
val = ast.literal_eval(json_string)
val1 = json.loads(json.dumps(val))
pd.set_option("colheader_justif... | 5,300,376 |
def _es_marker(request, client):
"""Clear out all indices and index templates before and after
tests marked with ``es``.
"""
marker = request.node.get_closest_marker("es")
if marker:
def teardown_es():
client.indices.delete(index="*")
client.indices.delete_template("... | 5,300,377 |
def __unwrap_nonsense_request(request):
"""
Unwrap the given "estimate nonsense" request into a string.
Args:
request: A JSON-like dict describing an "estimate nonsense" request
(as described on https://clusterdocs.azurewebsites.net/)
Returns: A string that represents the sentence of w... | 5,300,378 |
def modify_LP2_1dx_calib(calib_path, LP3_1dx, OPT_ELEM='G140L', CENWAVE=1280, verbose=True):
""" Modify WCA and PSA definitions in the 1dx calibration file
of LP2 according to the values in the file for LP3
Only necessary for CALCOS v2
Step 3b of the procedure
Parameters
----------
calib_... | 5,300,379 |
def available_agents() -> List[str]:
"""Returns a list of all available agent names.
Returns:
A list of strings indicating the agents that are available.
"""
return list(_mapping.keys()) | 5,300,380 |
def visualise_days():
"""Visualise data by day of the week"""
# grab previously parsed data
data_file = p.parse(p.MY_FILE, ",")
# create variable 'counter', counts each match for the string "Day of Week"
counter = Counter(item["DayOfWeek"] for item in data_file)
# Separate out the counter to... | 5,300,381 |
def default_remove_obj(obj, world) :
"""Effectively removes an object from play by making it have no
positional location."""
world.remove_relation(Contains(Z, obj))
world.remove_relation(Supports(Z, obj))
world.remove_relation(Has(Z, obj))
world.remove_relation(PartOf(obj, Z))
world.remove_r... | 5,300,382 |
def parseDefault(eInfo):
"""Return None for each element; use as a catch-all
"""
assert (isinstance(eInfo, pd.Series))
eInfo.loc[:] = None
return eInfo | 5,300,383 |
def test_bad_input():
"""fails on bad input"""
bad = random_filename()
rv1, out1 = getstatusoutput('{} -k foo {}'.format(prg, bad))
assert rv1 > 0
assert out1 == '"{}" is not a file'.format(bad)
rv2, out2 = getstatusoutput('{} {}'.format(prg, 'swiss.txt'))
assert rv2 > 0
assert re.se... | 5,300,384 |
def wait_for_cluster(api, expected_nodes, timeout=1800):
"""
Wait up to half an hour for cluster to form correctly
api: datera sdk object used to interface with the cluster
expected_nodes (list of str): IPs of nodes that should be in the cluster
timeout (int): number of seconds to wait for cluster ... | 5,300,385 |
def set_reverse(flag):
"""Action to reverse color palette colors"""
return {"kind": SET_PALETTE, "payload": {"reverse": flag}} | 5,300,386 |
def test_bound_methods_hash():
""" Make sure that calling the same method on two different instances
of the same class does resolve to the same hashes.
"""
a = Klass()
b = Klass()
assert (hash(filter_args(a.f, [], (1, ))) ==
hash(filter_args(b.f, [], (1, )))) | 5,300,387 |
def _clean(target_str: str, is_cellref: bool = False) -> str:
"""Rids a string of its most common problems: spacing, capitalisation,etc."""
try:
output_str = target_str.lstrip().rstrip()
except AttributeError:
raise AttributeError("Cannot clean value other than a string here.")
if is_cel... | 5,300,388 |
def stop(c):
"""Stop local slacm process"""
c.run("pkill -SIGTERM -f slacm_run") | 5,300,389 |
def _gen_testcase_with_post(testcase_method, epilogues):
"""
Attach an epilogue to a testcase method
:param testcase_method: a testcase method
:param epilogue: a callable with a compatible signature
:return: testcase with epilogue attached
"""
@wraps(testcase_method)
def testcase_with_... | 5,300,390 |
def read_peaks(path, arr=False):
"""
read peak list in the form of
prot peaks selected cmplx name
output hash cmplx name prot => peaks selected
"""
header = []
HoA = makehash()
temp = {}
for line in open(path, "r"):
line = line.rstrip("\n")
if line.startswith("MB\tID... | 5,300,391 |
def get_values(record, tag):
"""Gets values that matches |tag| from |record|."""
keys = [key for key in record.keys() if key[0] == tag]
return [record[k] for k in sorted(keys)] | 5,300,392 |
def relabel_nodes(tree_file, pickle_file, output_file):
"""
Relabel nodes on tree according to mapping saved in pickle file
Input:
tree_file <str> -- path to input tree file (Newick)
pickle_file <str> -- path to pickle containing new->old mapping
output_file <str> -- path to ... | 5,300,393 |
def email(subject="", body_text="", body_html=""):
"""Send email with subject and body provided.
:param subject: Subject line of email. (optional)
(If left blank default subject line will be used)
:param body_text: Body of email which will be embedded as plain text.
... | 5,300,394 |
def expected_value(values: List[float]) -> float:
"""Return the expected value of the input list
>>> expected_value([1, 2, 3])
2.0
"""
return sum(values) / len(values) | 5,300,395 |
def has_partition(collection_name, partition_name, using="default"):
"""
Checks if a specified partition exists in a collection.
:param collection_name: The collection name of partition to check
:type collection_name: str
:param partition_name: The name of partition to check.
:type partition... | 5,300,396 |
def import_file(full_name: str, path: str) -> Any:
"""Import a python module from a path"""
spec = importlib.util.spec_from_file_location(full_name, path)
mod = importlib.util.module_from_spec(spec)
# We assume this is not None and has an exec_module() method.
# See https://docs.python.org/3/refer... | 5,300,397 |
def iterate_task_executions(client, node_execution_identifier, limit=None, filters=None):
"""
This returns a generator for task executions, given a node execution identifier
:param flytekit.clients.friendly.SynchronousFlyteClient client:
:param flytekit.models.core.identifier.NodeExecutionIdentifier nod... | 5,300,398 |
def calculate_stats(num_observations, time_list):
"""Calculate mean and standard deviation of a list"""
time_array = np.array(time_list)
median = np.median(time_array)
mean = np.mean(time_array)
std_dev = np.std(time_array)
max_time = np.amax(time_array)
min_time = np.amin(time_array)
q... | 5,300,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.