content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def plt_img(img_numpy):
"""
:param img_numpy:
:return:
"""
plt.imshow(img_numpy)
plt.show() | 62,600 |
def hdu_records(hdu_list: fits.BinTableHDU) -> fits.FITS_rec:
"""
Generator function to yield each record in hdu_list
:param hdu_list: HDUList object (containing data)
:return: List of HDU records
"""
return hdu_list.data | 62,601 |
def import_image(action):
"""
Controller to import a report
"""
if action == "map" or action == "image":
doc_table = s3db.doc_image
else:
doc_table = s3db.doc_document
sgtable = s3db.stats_group
sgt_table = s3db.stats_group_type
di_file = doc_table.file
file = req... | 62,602 |
def format_italic(value):
"""
Wrap the input value in the ANSI escape sequence for italic.
"""
return _format_code(value, 3) | 62,603 |
def publish_jsonl_to_s3(key, row, target_bucket, max_retries=5, validate_payload_checksum=False):
"""
Publishes individual rows to S3 as minified JSON. This assumes that the
entire 'row' element is written as a single JSON object to the target file.
'data_type' is the plugin-name or otherwise descriptor... | 62,604 |
def inTransaction(transactionCreator, operation, label="jobqueue.inTransaction", **kwargs):
"""
Perform the given operation in a transaction, committing or aborting as
required.
@param transactionCreator: a 0-arg callable that returns an
L{IAsyncTransaction}
@param operation: a 1-arg calla... | 62,605 |
def generate_target_points(subject_paths) -> \
Union[np.ndarray, list[np.ndarray]]:
"""
This function generates the coordinates for a
target point or list of target points.
It calls upon a GUI implemented in `gui.targetSelection`
"""
target_points = gui.targetSelection.main(subject_path... | 62,606 |
def roc_auc(y_true, y_score):
"""
Returns are under the ROC curve
"""
notnull = ~np.isnan(y_true)
fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true[notnull], y_score[notnull])
return sklearn.metrics.auc(fpr, tpr) | 62,607 |
def checkForApp():
""" Check for the app, download if not existing """
data_path = getAddonDataPath()
if not os.path.exists(os.path.join(data_path, 'Puppet Fever Companion')):
log(language(50013))
dialog.ok(language(50012), language(50013))
params = {"url": "https://storage.googlea... | 62,608 |
def extract_cassette_exon(denovo_dir, tophat_dir, pAplus_dir, output_dir,
rpkm_flag):
"""
1. Check each exon and fetch PSI
2. Calculate RPKM if needed
Modified from Han et al., Nature, 2013, 498:241-245.
"""
print('Start to parse circular RNA exons...')
exons = {}
... | 62,609 |
def run(logdir, run_name, filter_weights):
"""Connectome nodal values."""
tf.reset_default_graph()
input_ = tf.placeholder(tf.float32)
summary_op = roi_summary.op("roi_stuff", input_)
writer = tf.summary.FileWriter(os.path.join(logdir, run_name))
sess = tf.Session()
summary = sess.run(summary_op, fe... | 62,610 |
def config_stp_vlan_param(dut, cfgdictionary={}):
"""
config spanning_tree vlan <enable/disable> <vlanid>
cfgdictionary={'' : ['enable', 'vlanid']}
cfgdictionary={'' : ['disable', 'vlanid']}
config spanning_tree vlan forward_delay <vlanid> <forward_delay>
cfgdictionary={'forward_delay' : ['vid'... | 62,611 |
def Events_detail(request, query):
"""
Retrieve, update or delete a serie.
"""
try:
map_columns=names_to_representation(Cleanevent)
map_columns={i[1]:i[0] for i in map_columns}
parameters=query.split("-")
dict_params={}
for i in parameters:
spli... | 62,612 |
def splice_in_preproc_name(base_env_name, preproc_name):
"""Splice the name of a preprocessor into a magical benchmark name. e.g.
you might start with "MoveToCorner-Demo-v0" and insert "LoResStack" to end
up with "MoveToCorner-Demo-LoResStack-v0". Will do a sanity check to ensure
that the preprocessor a... | 62,613 |
def load(thing=None, working_directory=None):
"""
Loads site files (customization files) from various locations.
Without an argument, loads all default site customization options.
With a specific argument, load that argument as a customization file (real file or URL).
"""
if thing is None:
... | 62,614 |
def invert_node_predicate(node_predicate):
"""Build a node predicate that is the inverse of the given node predicate.
:param node_predicate: An edge predicate
:type node_predicate: (pybel.BELGraph, BaseEntity) -> bool
:rtype: (pybel.BELGraph, BaseEntity) -> bool
"""
def inverse_predicate(graph... | 62,615 |
def from_protos_v2(
proto_list: List[fra.ForwardRateAgreement],
config: "ForwardRateAgreementConfig" = None
) -> Dict[str, Any]:
"""Creates a dictionary of preprocessed swap data."""
prepare_fras = {}
for fra_proto in proto_list:
short_position = fra_proto.short_position
h, currency, rate_term... | 62,616 |
def query(q):
"""Run query exacly as provided."""
con = get_db()
c = con.cursor()
c.execute(q)
con.commit()
return c.fetchall() | 62,617 |
def main():
"""
Main Chili-Pepper command line interface handler
"""
cli = CLI()
parser = argparse.ArgumentParser(description="Serverless asynchronous tasks")
parser.add_argument("--app", "-A", type=str, help="The Chili-Pepper application location")
# TODO add verbose and quiet args
su... | 62,618 |
def adjacent_moves(self):
"""Returns all moves for adjacent tiles."""
moves = []
if world.tile_exists(self.x + 1, self.y):
moves.append(actions.MoveEast())
if world.tile_exists(self.x - 1, self.y):
moves.append(actions.MoveWest())
if world.tile_exists(self.x, self.y - 1):
mov... | 62,619 |
def get_number_by_pro(number_list, pro_list):
"""
:param number_list:数字列表
:param pro_list:数字对应的概率列表
:return:按概率从数字列表中抽取的数字
"""
# 用均匀分布中的样本值来模拟概率
x = random.uniform(0, 1)
# 累积概率
cum_pro = 0.0
# 将可迭代对象打包成元组列表
for number, number_pro in zip(number_list, pro_list):
cum_pro... | 62,620 |
def _pauli2circuit(pauli_ansatz):
"""Transform a pauli ansatz to parameterized quantum circuit."""
circuit = Circuit()
for k, v in pauli_ansatz.items():
circuit += decompose_single_term_time_evolution(k, v)
return circuit | 62,621 |
def is_valid_source_state(value):
"""This function makes exeptions for special source states.
E.g. It explicitly allows '*' (for any state)
and `None` (as this is default value for sqlalchemy colums)
"""
return (value == '*') or (value is None) or is_valid_fsm_state(value) | 62,622 |
def test_construct_img_tag(attributes):
"""Test for validating whether the img tag is constructed correctly or not.
"""
image = Img(**attributes)
assert image.construct() == img.render(attributes) | 62,623 |
def configure_logging(args):
"""
Creates logging configuration and sets logging level based on cli argument
Args:
args: all arguments parsed from cli
Returns:
logging: logging configuration
"""
if args.debug:
logging.basicConfig(stream=sys.stdout,
... | 62,624 |
def is_valid_ip_whitelist_name(name):
"""True if string looks like a valid IP whitelist name."""
return bool(IP_WHITELIST_NAME_RE.match(name)) | 62,625 |
def gcd_fast(a: int, b: int) -> tuple:
"""
GCD using Euler's Extended Algorithm generalized for all integers of the
set Z. Including negative values.
:param a: The first number.
:param b: The second number.
:return: gcd,x,y. Where x and y are bezout's coeffecients.
"""
gcd=0
x=0
y=0
x=0
"""
if a < 0:
s... | 62,626 |
def get_option_name(flags):
"""
Function to get option names from the user defined arguments.
Parameters
----------
flags : list
List of user defined arguments
Returns
-------
flags : list
List of option names
"""
for individualFla... | 62,627 |
def write_ros_handshake_header(sock, header):
"""
Write ROS handshake header header to socket sock
@param sock: socket to write to (must be in blocking mode)
@type sock: socket.socket
@param header: header field keys/values
@type header: {str : str}
@return: Number of bytes sent (for stati... | 62,628 |
def run_epylint(argv: Sequence[str] | None = None) -> NoReturn:
"""Run epylint.
argv can be a list of strings normally supplied as arguments on the command line
"""
from pylint.epylint import Run as EpylintRun
EpylintRun(argv) | 62,629 |
def generate_sampled_data():
"""전체 CSV 파일에서 일부만 임의추출하여 작은 CSV 파일 만들기"""
with open(CSV_FILE_WHOLE, 'r') as whole:
with open(CSV_FILE_SAMPLED, 'w') as sampled:
sampled.write(whole.readline())
sampled.writelines(
l for l in whole if random.random() <= SAMPLE_RATE
... | 62,630 |
def _rrv_add_ ( s , o ) :
"""Addition of RooRealVar and ``number''
>>> var = ...
>>> num = ...
>>> res = var + num
"""
if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve ()
elif hasattr ( o , 'getVal' ) : o = o.getVal ()
#
v = s.ge... | 62,631 |
def manage_interfaces(device, data):
"""Manage interfaces."""
primary_address = None
lag_interfaces = get_lag_interfaces(data)
for interface in data[device]:
if data[device][interface]["type"] in ["virtual", "port-channel", "mlag"]:
continue
device_a = utils.nb.dcim.device... | 62,632 |
def find_lib_path(name):
"""
Find full path of a shared library.
Parameter
---------
name : str
Link name of library, e.g., cublas for libcublas.so.*.
Returns
-------
path : str
Full path to library.
Notes
-----
Code adapted from ctyles.util module.
""... | 62,633 |
def teardown_function():
"""Check if there are no children processes started by the test after it ended.
Be sure to call `capture_processes` in the test.
"""
global pool_processes
global pools
assert len(pool_processes), "No processes where tracked - did the test call capture_processes?"
po... | 62,634 |
def NarrowToOctaveBand(freq, dat, n):
"""
Convert dat from narrowband freq to 1/n octave band
"""
df = np.mean(np.diff(freq))
lowf = 1000 # Start at 1000 Hz
prevf = lowf*(2**(1.0/n))
while (prevf-lowf)>df:
prevf = lowf
lowf = lowf/(2**(1.0/n))
# Calculate center freque... | 62,635 |
def test_ACN10():
"""When the same footnote is associated more than once with the same
additional code then there may be no overlap in their association
periods."""
assert False | 62,636 |
def acq_max(f_acq, gp, y_max, bounds, space, num_warmup, num_starting_points):
"""
A function to find the maximum of the acquisition function
It uses a combination of random sampling (cheap) and the 'L-BFGS-B'
optimization method. First by sampling ``num_warmup`` points at random,
and then running ... | 62,637 |
def create_article_html_renditions(sender, instance, created, **kwargs):
""" Cria os documentos HTML para cada idioma do artigo.
"""
if created:
celery.current_app.send_task(
'journalmanager.tasks.create_article_html_renditions',
args=[instance.pk]) | 62,638 |
def openthread_suppress_error_flags():
"""Suppress errors for openthread"""
return [
'-Wno-error=embedded-directive',
'-Wno-error=gnu-zero-variadic-macro-arguments',
'-Wno-error=overlength-strings', '-Wno-error=c++11-long-long',
'-Wno-error=c++11-extensions', '-Wno-error=variadic... | 62,639 |
def _get_object_detector_cache_filenames(cache_dir,
image_dir,
annotations_dir,
annotations_list,
num_shards,
cache... | 62,640 |
def signal_rshift(shift: int) -> Callable[[int], int]:
"""A circuit element performing a fixed RSHIFT on a signal."""
return lambda x: limit_signal(x >> shift) | 62,641 |
def es_indices(prefix="", conn=None):
""" es_indices gets a potentially filtered list of index names.
:type prefix: str
:param prefix: the prefix to filter for
:type conn: Elasticsearch
:param conn: an ES connection object
:return: _all or list of index names
"""
if prefix is not "":
... | 62,642 |
def test_youyoun():
"""
Run `python -m pytest ./day-05/part-1/youyoun.py` to test the submission.
"""
assert (
YouyounSubmission().run(
"""
""".strip()
)
== None
) | 62,643 |
def daemonize():
"""
daemonize:
Purpose:
Detach from stdin/stdout/stderr, return control of the term to the user.
Returns:
Nothing.
"""
if os.name == "nt" or os.name == "ce":
# No way to fork or daemonize on windows. Just do nothing for now?
return
if not os.fork():
# get o... | 62,644 |
def build_production_ini_from_global_application_configuration():
""" This function makes a request to secrets manager for the identity passed to the container.
See documentation on API in dcicutils.
"""
identity = assume_identity()
# build production.ini
with override_environ(**identity):
... | 62,645 |
def wakeup():
"""Determine whether the afflicted should wake up."""
return random.randint(0, 99) < WAKEUP_RATE | 62,646 |
def addon_keymap_register(keymap_data):
"""
Register a set of keymaps for addons using a list of keymaps.
See 'blender_defaults.py' for examples of the format this takes.
"""
import bpy
wm = bpy.context.window_manager
from bl_keymap_utils.io import keymap_init_from_data
kconf = wm.key... | 62,647 |
def check_raster_file(src_path: str) -> ValidationInfo: # pragma: no cover
"""
Implementation from
https://github.com/cogeotiff/rio-cogeo/blob/0f00a6ee1eff602014fbc88178a069bd9f4a10da/rio_cogeo/cogeo.py
This function is the rasterio equivalent of
https://svn.osgeo.org/gdal/trunk/gdal/swig/python/s... | 62,648 |
def validate(val_loader, model, p_model, criterion):
"""
Run evaluation
"""
losses = AverageMeter()
top1 = AverageMeter()
# switch to evaluate mode
_set_fix_method_eval_ori(model)
model.eval()
with torch.no_grad():
for i, (input, target) in enumerate(val_loader):
... | 62,649 |
def detect_bullet_asteroid_collisions(bullet_class, asteroid_class):
"""Detect collisions between bullets and asteroids.
For each asteroid, search through bullets for a collision. If there
is, delete both the asteroid and the bullet."""
asteroid_destroy_list = []
for asteroid in asteroid_class.ast... | 62,650 |
def test_percentage_of_peaks_found():
"""This function tests the operation of the
percentage_of_peaks_found function in peakidentify.py"""
#First, generate good data.
shoyu_data_dict = pickle.load(open('raman_spectra/shoyu_data_dict.p', 'rb'))
compound_1 = shoyu_data_dict['WATER']
compound_2 = s... | 62,651 |
def ServiceRequest(opener, host, method, request_dict):
"""Makes service request to '/service/' + "method" API method."""
req = _MakeRequest(host, '/service/%s' % method, request_dict)
return _HandleResponse(method, opener.open(req)) | 62,652 |
def test_catch_failure():
"""Test case for when the function called with catch raises an exception."""
def f_fail():
return 1 / 0
assert catch(f_fail) is None | 62,653 |
def get_content_node_args(node_data):
"""
Returns (source_id, title, license) from node_data dictionary.
"""
node_data = copy.deepcopy(node_data)
source_id = node_data.pop('source_id')
title = node_data.pop('title')
license = node_data.pop('license')
return source_id, title, license | 62,654 |
def get_alt(ref, var_size, var_type):
"""
Generate alternative allele from SNV and INS but not DEL.
:param var_type: SNV or INS
:return: A string of nucleotides
"""
if var_type == 'SNV':
nucleotides = [x for x in dna if x != ref]
return choice(nucleotides)
elif var_type == '... | 62,655 |
def minify_js(
js_files,
root,
js_comments,
js_encoding,
git_repo,
verbose,
quiet,
test_run,
continue_on_error,
compilation_errors,
file_map,
):
"""sass compilation."""
changed_files = False
for input_str, output_str in js_files.items():
input_path = root... | 62,656 |
def interpolate_volume(ref, resize):
"""Intperolate a 3D volume
"""
assert len(ref.shape) == 3, "3D data only"
(sx, sy, sz) = ref.shape
assert sx == sy, "Only cubic data allowed"
assert sx == sz, "Only cubic data allowed"
# 2D interpolation along first two axes
twodintp = np.zeros((sx, ... | 62,657 |
def mock_run_controller(decoy: Decoy) -> RunController:
"""Get a fake RunController dependency."""
return decoy.mock(cls=RunController) | 62,658 |
def detectorEff(E):
"""Function to describe the detector efficiency. It is based on a fit of
Serpent2 results.
Parameters
----------
E : float or list
Energy in MeV
Returns
-------
Eps : float or list
Detector efficiency at energy/energies E
"""
E=E*100... | 62,659 |
def getenv():
"""Get a mapping of current options."""
global _env
if not _env:
raise EnvError("No environment exists")
else:
log.debug("Got a copy of environment %r options", _env)
return _env.options.copy() | 62,660 |
def hilbert(x, N=None, axis=-1):
"""
Compute the analytic signal, using the Hilbert transform.
The transformation is done along the last axis by default.
Parameters
----------
x : array_like
Signal data. Must be real.
N : int, optional
Number of Fourier components. Defaul... | 62,661 |
def setup_logging(logger=None, console=False, console_level='INFO', filename=None,
file_level='DEBUG', queue=None, file_kwargs=None):
"""Setup logging for console and/or file logging. Returns a scribe thread object.
Defaults to no logging."""
if queue is None:
queue = Queue()
i... | 62,662 |
def retrieve_monthly_average_scores(database_connection: mysql.connector.connect
) -> Dict:
"""Retrieve average panelist scores grouped by month
for every available year"""
cursor = database_connection.cursor(dictionary=True)
query = ("SELECT YEAR(s.showdate) AS year,... | 62,663 |
def ejecutar_cuantas_peliculas_18_mas(p1: dict, p2: dict, p3: dict, p4: dict, p5: dict) -> None:
"""Ejecuta la opcion de consultar cuantas peliculas de la agenda tienen clasificacion
18+.
Parametros:
p1 (dict): Diccionario que contiene la informacion de la pelicula 1.
p2 (dict): Diccionario ... | 62,664 |
def Float(*args, **kwargs):
"""Create a validator that checks that the value is a valid float
according to the `spec`
:param spec: The specification to check the float against.
Can be either
None
Anything that is a float passes. e.g. 1.2 and "1.2" ar... | 62,665 |
def CV_IS_SEQ_POLYGON(*args):
"""CV_IS_SEQ_POLYGON(CvSeq seq) -> int"""
return _cv.CV_IS_SEQ_POLYGON(*args) | 62,666 |
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Setup sensors from a config entry created in the integrations UI."""
config = hass.data[DOMAIN][config_entry.entry_id]
devices = await async_get_devices(config, hass)
as... | 62,667 |
def eval_instance_segmentation_coco(
pred_masks, pred_labels, pred_scores,
gt_masks, gt_labels, gt_areas=None, gt_crowdeds=None):
"""Evaluate instance segmentations based on evaluation code of MS COCO.
This function evaluates predicted instance segmentations obtained from
a dataset by using... | 62,668 |
def fetch_fork_result_list(pipe_ids):
"""
Read the output pipe of the children, used after forking to perform work
and after forking to entry.writeStats()
@type pipe_ids: dict
@param pipe_ids: Dictinary of pipe and pid
@rtype: dict
@return: Dictionary of fork_results
"""
out = {}
... | 62,669 |
def is_drf_friendly_errors_dict(val) -> bool:
"""Check if val is in format drf-friendly-errors."""
try:
return (
isinstance(val, Mapping)
and val.get('code', None) is not None
and is_integer_value(val.get('code'))
and 0 <= int(val.get('code')) < 10000
... | 62,670 |
def test_pass():
"""
true forever
"""
assert True | 62,671 |
def start():
"""
This function is run once every time the start button is pressed
"""
# If we use a global variable in our function, we must list it at
# the beginning of our function like this
global counter
# The start function is a great place to give initial values to global variables
... | 62,672 |
def home():
"""Will render React once compiled."""
return render_template("index.html") | 62,673 |
def del_flowspec_local(flowspec_family, route_dist, rules):
"""Deletes/withdraws Flow Specification route from VRF identified
by *route_dist*.
"""
try:
tm = CORE_MANAGER.get_core_service().table_manager
tm.update_flowspec_vrf_table(
flowspec_family=flowspec_family, rou... | 62,674 |
def import_data(species_name: str, dataset_name: str, dataset_file: str):
"""
Import dataset
Parameters
----------
:param species_name: species name
:param dataset_name: dataset names (e.g. name of the corresponding publication)
:param dataset_file: input file path
"""
df = pd.read_... | 62,675 |
def logical_slice_assign_op(x, update, slice_tup_list: Sequence[Tuple[int, int, int]]):
"""Update a slice of tensor `x`(in-place). Like `x[start:stop:step] = update`.
Args:
x: A `Tensor`, whose slice will be updated.
update: A `Tensor`, indicate the update content.
slice_tup_list: A li... | 62,676 |
def standardize(X, scale_dict = None, reverse = False):
"""Facilitates standardizing data by subtracting the mean and dividing by
the standard deviation. Set reverse to True to perform the inverse
operation.
Parameters
----------
X : numpy ndarray, or pandas.DataFrame
Data for whic... | 62,677 |
def draw_landmarks_edges(image,
keypoint_locs,
keypoint_edges,
edge_colors,
keypoint_color=(0, 255, 0)):
"""Draw landmarks and edges on the input image and return it."""
for landmark in keypoint_locs:
landmark_x ... | 62,678 |
def psnr(img_batch, ref_batch, batched=False, factor=1.0):
"""Standard PSNR."""
def get_psnr(img_in, img_ref):
mse = ((img_in - img_ref)**2).mean()
# if mse > 0 and torch.isfinite(mse):
# return (10 * torch.log10(factor**2 / mse))
# elif not torch.isfinite(mse):
# ... | 62,679 |
def current_loss(model_loss):
"""
Returns the minimum validation loss from the
trained model
"""
losses_list = []
[losses_list.append(x) for x in model_loss]
return np.min(np.array(losses_list)) | 62,680 |
def explicit_impute(
adata: AnnData,
replacement: (str | int) | (dict[str, str | int]),
impute_empty_strings: bool = True,
copy: bool = False,
) -> AnnData:
"""Replaces all missing values in all or the specified columns with the passed value
There are two scenarios to cover:
1. Replace all ... | 62,681 |
def get_nodes_and_edges(schema):
"""Creates lists of nodes and edges, through references and relations.
Parameters:
schema (dict): contains information on all nodes and edges in a schema.
Returns:
nodes (dict): dictionary of nodes
edges (list): list of edges
"""
nodes = {}
edges ... | 62,682 |
def jacobi_solver(L,dp_dx,mu,u_i,tol):
"""
simple jacobi solver for testing purposes
"""
Ny = np.size(u_i)
u_even = np.copy(u_i)
u_odd = np.copy(u_i)
h = L/(float(Ny) - 1.)
rhs = (h**2)*(1./mu)*dp_dx
maxIter = 1000000
KEEP_GOING = True
nIter = 0
exit_code = 0
wh... | 62,683 |
def default_for_unknown(word):
"""Provide a default definition for words that are not in the lexicon."""
proper_noun = ast.SentenceNode(word, ast.Var(word.lower()), ast.TYPE_ENTITY)
single_place = ast.SentenceNode(
word,
ast.Lambda("x", ast.Call(ast.Var(word.title()), ast.Var("x"))),
... | 62,684 |
def add_basic_head(model, blob_in, dim_in, pool_stride, out_spatial_dim,
suffix, lfb_infer_only, test_mode):
"""Add an output head for models predicting "clip-level outputs"."""
# -> (B, 2048, 1, 1, 1)
pooled = model.AveragePool(
blob_in, blob_in + '_pooled',
kernels=[pool_stri... | 62,685 |
def connect(app: Application) -> NetworkState:
"""
Estabilish a connection to the server.
"""
client = nm.get_client()
assert app.current_network_uuid is not None
nm.activate_connection(
client,
app.current_network_uuid,
partial(on_any_update_callback, app),
)
ret... | 62,686 |
def gen_malicious(num_per_dga=10000):
"""Generates num_per_dga of each DGA"""
domains = []
labels = []
# We use some arbitrary seeds to create domains with banjori
banjori_seeds = ['somestring', 'firetruck', 'bulldozer', 'airplane', 'racecar',
'apartment', 'laptop', 'laptopcomp... | 62,687 |
def rnd_date_array(size, start=date(1970, 1, 1), end=date.today()):
"""
Array or Matrix of random date generator.
"""
start = parser.parse_date(start)
end = parser.parse_date(end)
_assert_correct_start_end(start, end)
return _randn(size, _rnd_date, start, end) | 62,688 |
def main():
"""
Main function
"""
print(
"--------------------------------------------------------------------------------"
)
print("START READING DATA")
while True:
time.sleep(
sleep_time
) # we want to sleep for few seconds to let the sensors capture ... | 62,689 |
def createResolutionCallbackFromClosure(fn):
"""
Create a resolutionCallback by introspecting the function instead of
looking up the stack for the enclosing scope
"""
closure = get_closure(fn)
def env(key):
if key in closure:
return closure[key]
elif hasattr(builtins... | 62,690 |
def test_collector_sends_requests_to_plugins(collector_ref, test_actor):
"""
MetricsCollector sends StatsRequest messages to its plugin on any message
that is not a StatsResponse message.
GIVEN: We have a MetricCollector with 2 plugins configured.
WHEN: MetricsCollector receives a message.
THEN... | 62,691 |
def run(known_args, pipeline_args):
"""Main entry point; defines and runs the reconstruction pipeline."""
if known_args.testmode:
pipeline_args.append('--runner=DirectRunner')
else:
pipeline_args.append('--runner=DataflowRunner')
pipeline_args.extend([
'--project=wikidetox-viz',
'--staging_loca... | 62,692 |
def print_charac_table(x2, y2, y2label, headers, table_features=['Diagnosis:', 'Maternal Diagnosis:', 'Maternal-birthplace:', 'Maternal-marriageStatus:', 'Maternal-nationality:', 'Maternal-race:', 'Maternal-ethnicity:', 'Maternal-Language:', 'Vital:', 'Gender']):
"""
Computing and printing to standard output, a... | 62,693 |
def setup_self_factors(tree: Tree, observations: dict) -> None:
"""This function sets up the self-factors for each node and assigns
these values to tree.self_factors for each node.
Arguments:
tree {Tree} -- A Tree object.
observations {dict} -- A dict of observations where keys are n... | 62,694 |
def i3wm_window_resize(size, grow=True):
"""resizes the selected window by the specified number of key movements"""
actions.user.system_command('i3-msg mode "resize"')
if grow:
actions.key(f"right:{size}")
actions.key(f"down:{size}")
else:
actions.key(f"left:{size}")
acti... | 62,695 |
def move(locations):
"""
Provide an interface to the user facilitating their movement between
locations.
Arguments
---------
locations : list
A list of locations they can move to.
Returns
-------
str
The location the user enters to move to.
"""
move... | 62,696 |
def test_public_key_handler_store_not_der_public_key_format():
"""
Case: send transaction request to store certificate public key not in DER format.
Expect: invalid transaction error is raised with public key is already registered error message.
"""
not_der_format_public_key_to_store = b'h8ybuhtvrof... | 62,697 |
def run_wasm_tests(work_dir, target, desired_config, config_name, options):
"""Runs wasm via blaze/v8, or returns 0 if skipped."""
if desired_config is not None and desired_config != config_name:
return 0
args = [options.v8, "--no-liftoff", "--experimental-wasm-simd"]
# Otherwise v8 returns 0 even after com... | 62,698 |
def test_parse_raw_input_perturbations_F():
"""
`parse_raw_input_perturbations`
Feature F: raising exception for duplicate (modulo whitespace) node
states.
"""
raw_input_perturbations = {'A': {'1': '5', ' 1': '15'}}
node_names = ['A']
max_t = inf
# Test for {Simulate mode, Attrac... | 62,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.