content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calculate_boot_stats(sample, rep, n="auto", level=0.95, estimator="mean", random_seed=None, pass_dist=False):
"""Calculates a bootstrapped confidence interval for a sample.
A bootstrapped confidence interval for the desired estimator for
the provided sample is calculated for a confidence level `level`.... | 5,294,300 |
def _merge_a_into_b(a, b):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
if type(a) is not edict:
return
for k, v in a.items():
# a must specify keys that are in b
if k not in b.keys():
... | 5,294,301 |
def get_camera_params():
"""
Return a default camera parameter matrix
"""
pickle_in = open("config.pickle", "rb")
data_dict = pickle.load(pickle_in)
return data_dict['mtx']
# return np.array([[800, 0, 320], [0, 800, 240], [0, 0, 1]]) | 5,294,302 |
def setup_module(module):
"""
Create necessary files.
"""
if not os.path.exists("temp_sqlutils"):
os.mkdir("temp_sqlutils")
os.chdir("temp_sqlutils")
if os.path.exists("bbarchivist.db"):
os.remove("bbarchivist.db") | 5,294,303 |
def _distributed_edge_access(g, edges, issue_remote_req, local_access):
"""A routine that fetches local edges from distributed graph.
The source and destination nodes of local edges are stored in the local
machine and others are stored on remote machines. This code will issue
remote access requests fir... | 5,294,304 |
def queue_drain(orig_pre_list, orig_post_list, pre_line_changes, post_line_changes):
"""
Function to drain the remaining data
:param orig_pre_list:
:param orig_post_list:
:param pre_line_changes:
:param post_line_changes:
:return:
A List
pre_queue
post_queue
"""
... | 5,294,305 |
def graph_entropy(DAG, forward_entropy=False):
"""
Parameters
----------
DAG: NetworkX Graph
Directed Acyclic Graph
forward_entropy: Bool, default: False
if True, calculates entropy from maximal nodes (k_in = 0) nodes to others.
Otherwise calculates using paths from the botto... | 5,294,306 |
def check_letters():
"""
Check if all letters from input is in other string
"""
word = input("Give me a word: ").lower()
letters = input("Give letters to check for in word: ")
for l in letters:
if l not in word:
print("No match")
return 0
print("Match") | 5,294,307 |
def case_json(ses):
""" returns a list of JSON fomratted output for case object """
return _get_case_json(ses, '/case') | 5,294,308 |
def test_pos_outside_uc(get_model, models_equal):
"""Check that positions outside the UC are mapped back inside."""
model1 = get_model(0.1, 0.2, pos=((0.0, 0.0, 0.0), (-0.5, -0.5, 0.0)))
model2 = get_model(0.1, 0.2)
models_equal(model1, model2) | 5,294,309 |
def bernoulli_action_log_prob(logit, action):
"""Calculate the log p of an action with respect to a Bernoulli
distribution. Use logit rather than prob for numerical stability."""
if action == 0:
return F.logsigmoid(-logit)
else:
return F.logsigmoid(logit) | 5,294,310 |
def get_1d_coords(p, i, j):
"""
Finds index of site in 1d chain from 2d lattics based on snake
decomposition, ie 1d coords on 2d lattice look like:
0, 1, 2, 3,
7, 6, 5, 4,
8, 8, 10, 11
Args:
p - dictionary that contains the relevant system parameters
i - row index... | 5,294,311 |
def unpack_offset(msr_response):
"""
Extract the offset component of the response and unpack to voltage.
>>> from undervolt import unpack_offset
>>> unpack_offset(0x0)
0.0
>>> unpack_offset(0x40000000000)
0.0
>>> unpack_offset(0x100f3400000)
-99.609375
"""
plane_index = int(m... | 5,294,312 |
def gen_chapter(pg, meta, tmpl_env, epubdir, srcdir, htmldir, dropcaps=False,
asterism=False, **kwargs):
"""
Generates HTML chapter file from md source.
"""
# lines with `break_re` in the raw HTML output will be styled as in-page
# section breaks
break_re = [r'<<<\s*>... | 5,294,313 |
def check_early_stop(
perf_history,
minimum_length=20,
short_history=3,
long_history=5,
fail_function=np.less_equal):
"""
Determine whether to stop early. Using deepgaze criteria:
We determine this point by comparing the performance from
the last three epochs to ... | 5,294,314 |
def set_float(opt, k, v):
"""Set an option to a float value."""
try:
v = float(v)
except:
opt.opts.err('Invalid value: ' + str(v))
opt.set(v) | 5,294,315 |
def getAngle(v1,v2,prec=1E-6):
"""
Helper function to get angle between two vectors
inputs
--------
v1,v2 (list,list): two vectors
outputs
--------
angle (float, radians): angle between v1,v2
"""
return(math.acos((np.dot(v1,v2))/np.linalg.norm(v1)... | 5,294,316 |
def p_types_string(p):
"""types : STRING"""
p[0] = p[1]
global_tree.append(('type', p[1])) | 5,294,317 |
def test_alt_post(test_flask_client):
"""Tests the POST method"""
# Test arg parsing
data = {}
resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
assert resp.status_code == HTTPStatus.BAD_REQUEST
callsign = "X"
data = {utils.CALLSIGN_LABEL: callsign}
resp = test_flask_client.pos... | 5,294,318 |
def evaluate_cdr_hit(query, target, result={}, same_length=False):
"""
Compare query and target sequence positions in CDR3 and framework regions, return number of matches and % identity
If previous 'result' is provided, return (None, None) if an improvement has not been found.
"""
if same_lengt... | 5,294,319 |
def test_clang_tidy_tool_plugin_scan_calledprocesserror(mock_subprocess_check_output):
"""
Test what happens when a CalledProcessError is raised (usually means clang-tidy hit an error).
Expected result: issues is None
"""
mock_subprocess_check_output.side_effect = subprocess.CalledProcessError(2, '... | 5,294,320 |
def make_burst_emitter(
center_xy: Point,
filenames_and_textures: Sequence[FilenameOrTexture],
particle_count: int,
particle_speed: float,
particle_lifetime_min: float,
particle_lifetime_max: float,
particle_scale: float = 1.0,
fade_particles: bool = True)... | 5,294,321 |
def noop(*args, **kwargs):
"""
Do nothing.
"""
return | 5,294,322 |
def download_ccd(idx, ccd, base_url, ccd_image_dir, auth):
"""Faz o Download de um CCD do serviço do DES.
Args:
idx (int): Posição do registro no array de ccds a serem baixados
ccd (dict): Um dicionario que representa uma instancia do Model des/Ccd
base_url (str): referece ao valor da s... | 5,294,323 |
def cusolverDnSsyevd_bufferSize(handle, jobz, uplo, n, a, lda, w):
"""
Calculate size of work buffer used by culsolverDnSsyevd.
References
----------
`cusolverDn<t>gebrd <http://docs.nvidia.com/cuda/cusolver/index.html#cuds-eigensolver-reference>`_
"""
lwork = ctypes.c_int()
status = _... | 5,294,324 |
def get_github_repo_url(project_urls: Dict[str, str]) -> [str, None]:
"""
Get repo url for github.
:param project_urls: project urls to get github repo url from
:return: repo url if one is available, else None
"""
source_code_url = get_attribute(project_urls, ["Source Code"])
if source_code... | 5,294,325 |
def to_nii(img, dest_path, scale=None, affine_transform=None):
# TODO: see if we want also real units scale
"""
Write the brain volume to disk as nifty image.
:param img: A nifty image object or numpy array brain
:param str dest_path: The path where to save the brain.
:param tuple scale: A tup... | 5,294,326 |
def abrir_freq(file):
"""
Abre o ficheiro json com o dicionário das frequências das regras.
:param file: ficheiro json
:return: dicionário com as frequências das regras no corpus.
"""
with open(file) as f:
freq_svo_dict = json.load(f)
return freq_svo_dict | 5,294,327 |
def update_user_phone():
"""
用户修改电话号码
"""
userid = g.userinfo.get("id")
requstsData = request.get_json()
phone = requstsData.get("phone")
code = requstsData.get("code")
if phone and code:
dbres = db.query("select id,code from tb_sms_log where phone = '{}' and status = '0' and c... | 5,294,328 |
def update(
expanded_dir: str = ".",
cookiecutter_input: bool = False,
skip_apply_ask: bool = False,
skip_update: bool = False,
) -> bool:
"""Update specified project's cruft to the latest and greatest release."""
expanded_dir_path = Path(expanded_dir)
pyproject_file = expanded_dir_path / "p... | 5,294,329 |
def file_update_complete_response( volume, reply ):
"""
Sign a protobuf ms_reply structure, using Syndicate's private key
"""
import common.api as api
# sign each directory entry in the reply with the Syndicate key,
# so the MS attests to its index information
for ent_pb in reply.listing.entrie... | 5,294,330 |
def destructure_decorated_lambda(tree):
"""Get the AST nodes for ([f, g, h], lambda) in f(g(h(lambda ...: ...)))
Input must be a tree for which ``is_decorated_lambda`` returns ``True``.
This returns **the original AST nodes**, to allow in-place transformations.
"""
def get(tree, lst):
if t... | 5,294,331 |
def get_data_type(v):
"""
Infers type from value. Returns tuple of (type, value)
"""
if isinstance(v, datetime.datetime):
return ("date", msecs_since_epoch(v))
elif isinstance(v, bool):
return ("boolean", str(v).lower())
elif isinstance(v, float):
return ("double", v)
... | 5,294,332 |
def replace_around(i, l, r, f_nones=True):
"""Replace the three elements centered at i with r."""
if f_nones:
r = filter_nones(r)
return l[: max(i - 1, 0)] + r + l[i + 2 :] | 5,294,333 |
def debug_processing_loop(input_queue, output_queue):
"""A simple printer to help with debugging.
This function is used with the debug option to disable Spark
processing and simply print the requests for predictions.
"""
import time
output_queue.put('ready')
while True:
req = input_... | 5,294,334 |
def dictionariesToDataframe():
"""converts dictionaries on CSPP holdings to dataframes
return:
- [holdingsECB, holdingsECBDates]"""
matrixData = [] # 2D array with row per ISIN and columns for different data
for ISIN, dataInDictionary in dictionaryBondsECB.items():
item = [ISIN] + dat... | 5,294,335 |
def runAndCheckCommandComplete(cmd):
"""
This function will run a Command and return False if ssh was too busy.
It will return True if the command completed, successfully or not,
if ssh wasn't busy.
"""
retValue = True
cmd.run(validateAfter = False)
if sshBusy(cmd) == True:
... | 5,294,336 |
def get_model_parameters(model):
"""Extract model arguments that were used during training"""
params = ModelParameters()
names = [layer.name for layer in model.layers]
params.num_codes = model.get_layer(name='embedding').input_dim-1
params.emb_weights = model.get_layer(name='embedding').get_weights... | 5,294,337 |
def transpone(l):
"""transpones a list of multiple lists
if the entrys do not have the same length, an empty string will be put in their place"""
nestedlist=[]
length=[]
transponedlist=[]
for i in range(len(l)):
length.append(len(l[i]))
for i in range(max(length)):
... | 5,294,338 |
def to_df(records_tree, event_name, instrument_name):
"""
Converts a `get_records_tree()[event][instrument]` to a pandas DataFrame
"""
# get instrument records
records = records_tree[event_name][instrument_name]
# build dataframe rows from records
acc = []
for s, entries in records.item... | 5,294,339 |
def restore(ctx, snapshot_path):
"""Restore an existing snapshot"""
config_map = ctx.obj["config_map"]
if admin.restore_snapshot(config_map, snapshot_path):
print("Restore successful")
else:
print("Restore failed") | 5,294,340 |
def train_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
# Import any additional modules needed (to register custom classes)
for package_name in args.include_package:
import_submodules(package_name)
train_model_from... | 5,294,341 |
def compare(value1, value2, comparison):
"""
Compare 2 values
"""
if isnum(value1) and isnum(value2):
comparison = comparison.lower()
if comparison == 'equals':
return value1 == value2
elif comparison == 'not equal':
return value1 != value2
elif co... | 5,294,342 |
def get_minsep_range(minseps, cap=None):
"""
Create ranged minseps from an ensemble of minsep entries
Args:
minseps (list): A list of minsep dictionaries
cap (tuple): Minimum-maximum caps
Returns:
minsep (dict): A minsep where values are minimum and maximum values
"""
... | 5,294,343 |
def ga_exp(B, verbose = False):
"""
This is an expansion of the exponential of a general rotation and translation
Presented by R. Wareham (Applications of CGA)
B must be a general rotation object on the format $ \phi*P + t n_{\inf}} $
$P$ is a 2 blade in real space.
$$\phi \in \mathcal{... | 5,294,344 |
def size_mass():
"""Show sizes and masses of known GMCs"""
t = Table.read('../data/gmc.txt', format='cds')
rmin = 12
outer = t['Rgal']>rmin
plt.close()
plt.figure(figsize=(6,5))
plt.plot(t['Mf'], t['Rf'], 'o', color='0.5', label='All')
plt.plot(t['Mf'][outer], t['Rf']... | 5,294,345 |
def get_progress_bar(percentage, increment):
"""Get a progress bar string given a percentage."""
initial = percentage
total = 100
bar_format = generateProgressbar(
percentage) + "\n" + "{percentage:04.1f}%" + f"[{increment:+03.1f}]"
with tqdm(initial=initial, total=total, bar_format=bar_for... | 5,294,346 |
def parse_args(**kwargs):
""" Parse arguments """
course = kwargs.pop("course", "Computational Motor Control")
lab = kwargs.pop("lab", "Lab")
comp = kwargs.pop("compatibility", "Python2 and Python3 compatible")
parser = argparse.ArgumentParser(
description="{} - {} ({})".format(course, lab, ... | 5,294,347 |
async def test_min_sensor(opp):
"""Test the min sensor."""
config = {
"sensor": {
"platform": "min_max",
"name": "test_min",
"type": "min",
"entity_ids": ["sensor.test_1", "sensor.test_2", "sensor.test_3"],
}
}
assert await async_setup_com... | 5,294,348 |
def get_permutation(permuted_array, permuted_array_len, permutation_index):
"""
Fills a single array with a particular permutation
:param permuted_array:
The array that is being permuted
:param permuted_array_len:
The length of the permuted_array
:param permutation_index:
The index of th... | 5,294,349 |
def elsym(edgelen, order=1):
"""
Elementary symmetric polynomial of a given order
"""
l = len(edgelen)
if order == 0:
return 1
r = 0
for v in combinations(range(l), order):
r += np.product([edgelen[vv] for vv in v])
return r | 5,294,350 |
def _main(argv=None):
"""Bidsify runtime."""
options = _get_parser().parse_args(argv)
kwargs = vars(options)
bidsify_workflow(**kwargs) | 5,294,351 |
def parse_args():
"""Command line argument parsing."""
global flag_breakdown
try:
optlist, _ = getopt.getopt(sys.argv[1:], "db")
except getopt.GetoptError as err:
# unrecognized option
usage(str(err))
for opt, _ in optlist:
if opt == "-d":
u.increment_verbosity()
elif opt == "-b":
... | 5,294,352 |
def shorturl(request, key):
"""
Redirect the client.
"""
return redirect(get_object_or_404(ShortURL, pk=key).url) | 5,294,353 |
def test_mean_shift():
""" Test MeanShift algorithm
"""
bandwidth = 1.2
bandwidth_ = estimate_bandwidth(X, n_samples=300)
assert_true(0.9 <= bandwidth_ <= 1.5)
ms = MeanShift(bandwidth=bandwidth)
labels = ms.fit(X).labels_
cluster_centers = ms.cluster_centers_
labels_unique = np.un... | 5,294,354 |
def group_by_day(list_all_objects):
"""
Recebe uma lista de objetos onde cada um deles possui um atributo tipo date e logo ordena eles por dia.
:param: list_all_objects: Register.objects.all(): django.db.models.query.QuerySet
:return: objects_day_ordered: [[objetos_do_dia_1][objetos_do_dia_2][objetos_do... | 5,294,355 |
def get_dirtree(directory):
"""
Get the directory tree of the `directory`.
:param directory: The root directory from where to generate the directory tree.
:return: The list of paths with appropriate indenting
"""
element_list = []
ignore_patterns = []
file_link = fg("├── ", 241) # u'\u... | 5,294,356 |
def get_root_model(models):
""" Get a root model class from an iterator over `obj_tables.Model` classes
The root model is obtained by name, rather than from `core.Model`, because `models` may have
been obtained from `obj_tables` migration, which loads other versions of `wc_lang.core` in
private imports... | 5,294,357 |
def datetime_to_iso(date, only_date=True):
""" Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param ... | 5,294,358 |
def _copy_agave_agave(src_uri, dest_uri, agave):
"""
Copy Agave data using AgavePy Wrapper.
Args:
src_uri: Source URI parsed into dict with URIParser.
dest_uri: Destination URI parsed into dict with URIParser.
agave: dict that contains:
agave_wrapper: Agave wrapper objec... | 5,294,359 |
async def ping(ctx):
"""sends bot's ping"""
#above is an description of the command
#sends the ping
await ctx.send(f'My ping is {round(bot.latency * 1000)}ms') | 5,294,360 |
def test_ap_hs20_sim_oom(dev, apdev):
"""Hotspot 2.0 with simulated SIM and EAP-SIM - OOM"""
hlr_auc_gw_available()
bssid = apdev[0]['bssid']
params = hs20_ap_params()
params['hessid'] = bssid
params['anqp_3gpp_cell_net'] = "555,444"
params['domain_name'] = "wlan.mnc444.mcc555.3gppnetwork.or... | 5,294,361 |
def test_get_plot_key_name():
"""Tests getting a plot key"""
# pylint: disable=import-outside-toplevel
import plotclip as pc
data_file_name = os.path.realpath(os.path.join(TESTING_JSON_FILE_PATH, 'get_plot_key_name.json'))
assert os.path.exists(data_file_name)
with open(data_file_name, 'r', en... | 5,294,362 |
def cli_call(context, arg_list, expect_success=True):
"""Executes a CLI command in a subprocess and return the results.
@param context: the behave context
@param arg_list: a list command arguments
@param expect_success: use False to return even if an error occurred when executing the command
@retur... | 5,294,363 |
def load(path_or_strm, container, **opts):
"""
:param path_or_strm: input config file path or file/file-like object
:param container: callble to make a container object
:param opts: keyword options passed to :class:`configobj.ConfigObj`
"""
return container(configobj.ConfigObj(path_or_strm, **op... | 5,294,364 |
def default_unexpected(x):
"""Define unexpected values."""
large = 1.e3
small = -numpy.float('inf')
return (x is None) or x > large or x < small or numpy.isnan(x) | 5,294,365 |
def create_wrapper(args, isolate_index, isolated_index):
"""Creates a wrapper .isolate that add dynamic libs.
The original .isolate is not modified.
"""
cwd = os.getcwd()
isolate = args[isolate_index]
# The code assumes the .isolate file is always specified path-less in cwd. Fix
# if this assumption does... | 5,294,366 |
def predict_hot_pxl(sqr, model):
"""takes a numpy array (colour image) size 64x64 and a ML model,
returnes float number between 0 - 1 for hot pixel detection,
for 0 no hot pixel detected, 1 hot pixel detected"""
predict = model.predict(sqr.reshape(1,64,64,3))
y_pred = [i[0] for i in predict]
ret... | 5,294,367 |
def write_to_file(file_name, dir_path, content):
"""
Rewrite or create and write to file.
Parameters:
file_name (string): file name
dir_path (string): root path which file contains
content (string): content to be written
Returns:
... | 5,294,368 |
def _build_meta_block(
payload_spec: PayloadSpec,
) -> Tuple[Optional[Block], Block, Dict]:
"""
Performs validations in the meta specification and returns o
Args:
payload_spec (dict): Payload specifications.
Returns:
version_block (Block): A block to encode the version if
... | 5,294,369 |
def _unit_state_progress(uid, current, target):
"""
This method will ensure a unit state progression in sync with the state
model defined above. It will return a tuple: [new_state, passed_states]
where 'new_state' is either 'target' or 'current', depending which comes
later in the state model, and ... | 5,294,370 |
def search(
bounds: List[float],
min_cloud: float = 0,
max_cloud: float = 100,
min_date='2013-01-01',
max_date=datetime.today(),
period: str = None,
period_qty: int = 1,
stac_collection_limit: int = 500,
stac_url: str = "https://sat-api.development... | 5,294,371 |
def postprocess_report_by(config: Config, key: str) -> None:
"""For --report-by=region, select all sections."""
assert key == 'report.by'
if config.get(key) == 'region':
config.put('section.select-all', True), | 5,294,372 |
def get_label_object_attributes(dataset, progress_callback=None):
"""Compute shape attributes of integer-labeled objects in a dataset. Returns
an ITK shape label map. An optional progress_callback function can be passed
in. This callback is expected to take one argument, a floating-point number
in the r... | 5,294,373 |
def generate_structure():
"""Return a ``StructureData`` representing either bulk silicon or a water molecule."""
def _generate_structure(structure_id="Si"):
"""Return a ``StructureData`` representing bulk silicon or a snapshot of a single water molecule dynamics.
:param structure_id: identifie... | 5,294,374 |
def get_lat_bin(lat, nbins=NBINS):
""" get latitude bin """
if lat < LATLIM[0]:
return 0
if lat > LATLIM[1]:
return nbins
return int((lat-LATLIM[0]) * nbins / (LATLIM[1]-LATLIM[0])) | 5,294,375 |
def get_aff_trafo(xy0=None, xy1=None, theta=0, por=(0, 0), ax=None, patch=None):
"""
:param xy0: current position of the object, if not provided patch.get_xy() is used
:param xy1: desired position of the object
:param theta: rotation in degrees
:param por: point of rotation relative to the objects ... | 5,294,376 |
def get_sig_alg(sig: key.Signature) -> Dict[str, Any]:
"""
Create `SignedDigestAlgorithm` structure.
"""
if sig.meta.algorithm == key.AsymmetricAlgorithm.RSA:
return get_sig_alg_rsa(cast(rsa.RsaSignature, sig))
if sig.meta.algorithm == key.AsymmetricAlgorithm.ECDSA:
return get_sig_a... | 5,294,377 |
def read_manifest_file():
"""Reads the manifest file"""
manifest_file = os.path.join(settings.STATIC_ROOT, "mix-manifest.json")
with(open(manifest_file)) as manifest:
return json.load(manifest) | 5,294,378 |
def descendants(node, lst=None):
"""Return a list of all the descendants beneath a node"""
if lst is None:
lst = []
for child in node.children:
lst.append(child)
descendants(child, lst=lst)
return lst | 5,294,379 |
def read(path, onlyHeader=False):
"""reads any Type 1 font file, returns raw data"""
_, ext = os.path.splitext(path)
ext = ext.lower()
creator, typ = getMacCreatorAndType(path)
if typ == 'LWFN':
return readLWFN(path, onlyHeader), 'LWFN'
if ext == '.pfb':
return readPFB(path, onlyHeader), 'PFB'
else:
return... | 5,294,380 |
def test_html_inside_heading(ext_markdown):
"""Assert that headings don't double-escape HTML."""
output = ext_markdown.convert("::: tests.fixtures.builtin")
assert "=<" in output
assert "&" not in output | 5,294,381 |
def read_uncompressed_dataset(file):
""" Get a file path and return the uncompressed dataset"""
try:
return pd.read_pickle(file)
except:
try:
return pd.read_csv(file)
except:
print("%s cannot be read" % file)
return | 5,294,382 |
def _run_reformulator_eval(questions, annotations, reformulator_instance,
environment_fn, batch_size):
"""Runs eval with just the reformulator, using greedy decoding."""
f1s = []
for (questions_batch, annotations_batch) in batch(questions, annotations,
... | 5,294,383 |
def _get_single_node_name_from_collection(meta_graph_def, collection_key):
"""Obtain a node name that is the single element of a collection."""
if collection_key not in meta_graph_def.collection_def:
return None
collection = meta_graph_def.collection_def[collection_key]
if not collection.node_list.value:
... | 5,294,384 |
def test_run_failing_test():
"""Failing tests should be reported with a non-zero exit status unless the
`--no-fail-on-unexpected` option has been specified."""
if is_port_8000_in_use():
pytest.skip("port 8000 already in use")
failing_test = "/infrastructure/expected-fail/failing-test.html"
... | 5,294,385 |
def test_create_plots_create_matrix_deletion_raw_count():
"""
"""
#ref_seq, total_dels, total_ins, cov = crispr_count_indels._count_indels("15_dels_ladder_for_matrix.fasta")
ref_seq, ref_seq_id = count_indels._get_ref_seq("15_dels_ladder_for_matrix.fasta")
cov = count_indels._get_coverage("15_d... | 5,294,386 |
def wire_mutual_inductance(wire_i, wire_j, ref):
# di0: float, dj0: float, dij: float, rw0: float):
"""Inductance between wire i and wire j, with reference wire 0.
Uses widely separated assumption, di0/rw > 4
"""
if type(ref) == Wire:
rw0 = ref.radius
di0 = wire_i.distance_to(ref)
... | 5,294,387 |
def rescan_if_missed_blocks(store):
"""
Due to a bug, some blocks may have been loaded but not placed in
a chain. If so, reset all datadir offsets to 0 to force a rescan.
"""
(bad,) = store.selectrow("""
SELECT COUNT(1)
FROM block
LEFT JOIN chain_candidate USING (block_i... | 5,294,388 |
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('jsonFile',
help='detections json file')
parser.add_argument('-o', dest='resFile', type=str,
default='dummpy.npy',
... | 5,294,389 |
def extract_sapcar_file(sapcar_exe, sar_file, **kwargs):
"""
Execute SAPCAR command to decompress a SAP CAR or SAR archive files.
If user and password are provided it will be executed with this user.
Args:
sapcar_exe(str): Path to the SAPCAR executable
sar_file (str): Path to the sar fi... | 5,294,390 |
def add_equivalences(relations):
"""Based on a list of relations, append equivalences to equivalences.csv"""
hgnc_fam_ids = sorted(list(set(int(r[5]) for r in relations)))
equivs = []
for fid in hgnc_fam_ids:
equivs.append(('HGNC_GROUP', str(fid),
get_famplex_id(families[s... | 5,294,391 |
def parl_to_kaldi_test_pairs(request: Any) -> Tuple[str, str]:
"""Return an embedded statement from the above list using given index."""
index: int = request.param
return parl_to_kaldi_pairs[index] | 5,294,392 |
def global_pairwise_align_protein(seq1, seq2, gap_open_penalty=11,
gap_extend_penalty=1,
substitution_matrix=None,
penalize_terminal_gaps=False):
"""Globally align pair of protein seqs or alignments with Needleman-... | 5,294,393 |
def plot_confusion_matrix(cm, classes,
normalise=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalise=True`.
"""
i... | 5,294,394 |
def client(api_client):
"""Returns HttpClient instance with retrying feature skipped."""
api_client = api_client(disable_retry_status_list={503, 404})
# This won't work with Httpx but will save us about 10 mins for this test alone
api_client.session = requests.Session()
return api_client | 5,294,395 |
def create_elem_dict(row):
"""
Create new element dictionary from row with metadata common to all
nodes/ways/relations.
"""
elem = {
'id': row.id,
'version': row.version,
'userId': row.user_id,
'userName': row.user_name,
'timestamp': row.timestamp,
'ta... | 5,294,396 |
def source_ip_and_reverse_dns(
message: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]:
"""
Extract the source IP and reverse DNS information from a canary request.
"""
reverse_dns, source_ip = (None, None)
if 'SourceIP' in message:
source_ip = message['SourceIP']
# `Rev... | 5,294,397 |
def spark_flatMap(func: typing.Callable[[pyspark.rdd.RDD], pyspark.rdd.RDD]=default_function(1)):
"""Spark's flatMap
:param Callable func: The function to apply.
:input RDD data: The RDD to convert.
:output RDD result: The resulting RDD.
"""
def inner(data: pyspark.rdd.RDD) -> ReturnType[pyspar... | 5,294,398 |
def fCO2_to_CO2(fCO2, Ks):
"""
Calculate CO2 from fCO2
"""
return fCO2 * Ks.K0 | 5,294,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.