content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getAffinityIV(duration): # TODO: 와헌 어나더 바이트처럼 실시간 계산
"""
어피니티IV의 지속시간은 5000ms
평균 리차지 주기에 따라 5000ms 사이에 n회, n+1회 공격할 확률을 각각 구한 다음
리차지가 5000ms동안 전부 실패할 확률을 계산해 가동률을 구합니다.
"""
count = 5000 // duration
timeDiv = 5000 - duration * count
prob = timeDiv / duration
ratio = (1 - prob) * (... | 04256163b33f536a5e1bf5780c79be06660632e2 | 69,400 |
import PyOpenColorIO as ocio
import logging
def create_builtin_transform(style):
"""
Creates an *OpenColorIO* builtin transform for given style.
If the style does not exist, a placeholder transform is used in place
of the builtin transform.
Parameters
----------
style : unicode
*... | c56031d9f737ebbd7ead7c438b942845cab3a229 | 69,401 |
def generate_rcmap_table(kmerlen, kmers):
"""make a lookup table for reverse complement k-mer ids for speed
Arguments:
kmerlen -- integer, length of k-mer
kmers -- list, a full set of k-mers generated by generate_kmers
Return:
a dictionary containing the mapping table
"""
revcomp_func = revcomp
kmer_id_dic... | acaf4e07e3c8b0847b4341708e0e5a48a756c1d0 | 69,402 |
import re
def _get_pcode_ids(pcode):
"""
Pull out the function and variable names from the given p-code
disassembly.
pcode - (str) The p-code disassembly.
return - (set) The set of function and variable names.
"""
# Look at each line of the disassembly.
ids = set()
in_id_section... | 84223a944a1f20b4e324748349fdf1d83d1ebc77 | 69,403 |
def add_motif_consensus_sequence(metadata_file, pwm_dict, out_file, model_col=2):
"""Add consensus motif
"""
with open(out_file, 'w') as out:
with open(metadata_file, 'r') as fp:
for line in fp:
if "ensembl" in line:
# write out header
... | 1ebedb16f717084d8a0199d63aea67ed5d7b48bd | 69,404 |
from typing import Sequence
from typing import Iterable
def _remove_decorators(
decorators: Sequence, module_aliases: Iterable[str], method_aliases: Iterable[str]
) -> Sequence:
"""Removes decorators specified as a `blqs.DecoratorSpec` from the decorator node list.
This performs a best effort to remove t... | 2d57a093b9371b02699436915f876cc69dd03033 | 69,405 |
from pathlib import Path
def strings_to_paths(strings: list[str]) -> list[Path]:
"""Converts a list of filenames in string form into a list of paths"""
return [Path(string) for string in strings] | 660e5f0fe72f32a4c4f2b218386e4c640c038846 | 69,406 |
import argparse
def get_training_args():
"""Initialize command line arguments for train.py"""
parser = argparse.ArgumentParser(
description = 'Training Image Classifier',
)
parser.add_argument('data_dir', action='store')
parser.add_argument('--save_dir',
action='sto... | 04dd1c9c78773fe8214dbff73dd758d16a9fd317 | 69,407 |
def hybrid_encrypt(lang: str, pub_keyset: bytes) -> _primitives.HybridEncrypt:
"""Returns a HybridEncrypt primitive, implemented in lang."""
global _ts
return _primitives.HybridEncrypt(lang, _ts.hybrid_stub(lang), pub_keyset) | 4d728185729e2be4a8a132fde4ef06f3971fdee1 | 69,408 |
from typing import Dict
from typing import Any
import requests
import os
import json
def get_metadata(url: str) -> Dict[str, Any]:
"""Return dictionary from JSON file at given path."""
ret_val: Dict[str, Any]
scheme = urlparse(url).scheme
if scheme == "http" or scheme == "https":
response = re... | 77c66412021806c6d75e82a0355e6e9f27d058e5 | 69,409 |
from colorama import Cursor
def async_alert_str(*, terminal_columns: int, prompt: str, line: str, cursor_offset: int, alert_msg: str) -> str:
"""Calculate the desired string, including ANSI escape codes, for displaying an asynchronous alert message.
:param terminal_columns: terminal width (number of columns)... | 9db90846a75378f13a38a97a215e2965785c01b8 | 69,410 |
def text2tfidf(dataset:Dataset, min_df=3, sublinear_tf=True, inplace=False, **kwargs):
"""
Transforms a Dataset of textual instances into a Dataset of tfidf weighted sparse vectors
:param dataset: a Dataset where the instances are lists of str
:param min_df: minimum number of occurrences for a word to b... | 8e3a2f8c1eab792268fca7dddaeb7f6289b27231 | 69,411 |
def three_sum_closest(nums, target):
"""
Return total closest to target
Worst case: O(n^2)
"""
nums.sort() # sort nums to perform two pointers
result = sum(nums[:3]) # initial sum
for i, _ in enumerate(nums):
left = i + 1
right = len(nums) - 1
while left < right:
... | 8114a5b1ccd8fec0782f1757c69c183411ba1966 | 69,412 |
def min_required_char(text: str) -> int:
"""
NAIVE VERSION!
Find minimum number of characters required to make a String Palindromic
NOTE:The only operation allowed is to insert characters in the beginning
of the string. Return the number of characters that are needed to be
inserted to make the s... | 7c2b90c9f0bfebb0de96737eac1c84729172123e | 69,413 |
def process_station_list(stationlist,id_col="id",agency_id_col="agency_id",
param_col=None,param=None,
subloc_col=None,subloc_lookup=None,subloc="default",
station_lookup=None,param_lookup=None,source = 'cdec'):
"""Process a csv list of stat... | c15b8a30ea673c7381a6ddb71abc99c1edd6921e | 69,414 |
def convert_data_escaped_string(data: tuple):
"""
Converts data from tuple form to a string statement
to a SQL string statement
data: tuple
return: a SQL formatted string
rtype: str
"""
_processed_data = list()
for i in data:
if isinstance(i, str):
b = i.replace(... | 7f245abb157bce84b2bb134e910087d735bfc814 | 69,415 |
def build_argparser():
"""
Parse command line arguments.
:return: command line arguments
"""
parser = ArgumentParser()
parser.add_argument("-m", "--model", required=True, type=str,
help="Model path")
parser.add_argument("-l", "--label", required=True, type=str,
... | 582bf197b72bf5c7dd52a63122cadbf61fe6a77a | 69,416 |
def contains_invalid_mxid_characters(localpart: str) -> bool:
"""Check for characters not allowed in an mxid or groupid localpart
Args:
localpart: the localpart to be checked
Returns:
True if there are any naughty characters
"""
return any(c not in mxid_localpart_allowed_characters... | f5be39becb8c39f87462b32e51acc9ad084b124a | 69,417 |
def images_crop(arFrames, nHeightTarget, nWidthTarget):
"""
Crop array of frames to specified size, choose centered image
Keyword arguments:
arFrames -- np.array representing list of images, shape : (nSamples, nHeight, nWidth, nDepth)
nHeightTarget -- height of target image
nWidthTarget -- widt... | 29be05ce06a29d2a69c1b850dd2949252d64bd63 | 69,418 |
def track_to_mask(track: Track, idx: np.ndarray = None) -> Mask:
"""
Gives Track with parent values filled in by closest neighbor
Args:
- track
- idx: locations of parent values to fill in
"""
if idx is None: idx = track < 0
ind = ndi.distance_transform_edt(idx,
... | 4bf71e22e77971da5e8119b1a4663748e8ee80b3 | 69,419 |
def Rotation_fromRotX(*args):
"""Rotation_fromRotX(float const pRotX) -> Rotation"""
return _almathswig.Rotation_fromRotX(*args) | 22ed7a23b4207f463077751c00975cd2dd6626dc | 69,420 |
def get_reddit_stream(reddit):
"""Returns the comment and submission stream.
Streams need to be restarted/re-obtained when they throw exception.
:param reddit: The reddit account instance
:return: The comment and subreddit stream
"""
comment_stream = reddit.subreddit(config.SUBREDDIT).stream.co... | 7e1f62b9f68796c08fc3af7bd1f874f991d46c55 | 69,421 |
import re
def find_between(a, b, string):
"""Returns a list of substrings between a and b in the given string."""
p = "%s(.*?)%s" % (a, b)
p = re.compile(p, re.DOTALL | re.I)
return [m for m in p.findall(string)] | b522cfd698d8a304e7964d9a1ff25556963ce36b | 69,422 |
def predict(params, inputs):
"""A functional interface to the trained Module."""
return QuickDrawModule().apply({'params': params}, inputs) | d20aca173b4b08c81735a890e1fba3bdfb5d1587 | 69,423 |
def meta(str1, str2, ratios, weights):
"""A meta ratio function. Returns a weighted meta ratio.
The Wiesendahl ratio is a meta ratio which combines a weighted
ratio of given ratio functions.
Args:
str1 (str): first string
str2 (str): second string
ratios (list(function(str... | b694216cce7b78e15065788497985416537ea95c | 69,424 |
def make_channel_layer(
name, layer_size, channel_width, color_RGB, z_position=0.0, parent=None
):
"""Create a 3D print channel layer.
Args:
name (str): Name to give the object.
layer_size (3-element tuple or list of floats or ints): x,y,z size
channel_width (float or int): Width of... | 719b074fd336f1604d92d489a77f860ffe424af1 | 69,425 |
import requests
def cbsodatav3_to_gbq(id, third_party=False, schema="cbs", credentials=None, GCP=None):
"""Load CBS odata v3 into Google BigQuery.
For given dataset id, following tables are uploaded into schema (taking `cbs` as default and `83583NED` as example):
- cbs.83583NED_DataProperties: descripti... | 68f316fa60fe588fdced23842482e5744189cb94 | 69,426 |
from typing import Dict
def infer_data(data: Dict[str, np.ndarray], infer_request: InferRequest, cw_l: int = 0, cw_r: int = 0) -> np.ndarray:
"""Do a synchronous matrix inference"""
frames_to_infer = {}
result = {}
batch_size = infer_request.get_input_tensor(0).shape[0]
num_of_frames = next(iter(... | 6dae3b3cb240dc6ee2f118742b9fa3576d035eb4 | 69,427 |
def infer_metadata(
featureset: FeatureSet,
source,
entity_columns=None,
timestamp_key=None,
namespace=None,
options: InferOptions = None,
) -> pd.DataFrame:
"""Infer features schema and stats from a local DataFrame
example::
quotes_set = FeatureSet("stock-quotes", entities=[En... | 6f183bc097b5f91e9a94c8b5bffb8c0eb974f13c | 69,428 |
def tjoin(leftkey, leftseq, rightkey, rightseq, left_default=no_default, right_default=no_default):
"""
>>> tjoin(identity, [1, 2, 3], identity, [2, 3, 4],
... left_default=None, right_default=None)
((2, 2), (3, 3), (None, 4), (1, None))
"""
return tuple(join(leftkey, leftseq, rightkey, ri... | c3e00ea628abe6f5fb2b04c0d20c5b6d81861c9b | 69,429 |
import warnings
def get_unique_schema_name(components, name, counter=0):
"""Function to generate a unique name based on the provided name and names
already in the spec. Will append a number to the name to make it unique if
the name is already in the spec.
:param Components components: instance of th... | 68086fc7a8e523322f5a1745996b6dc8056833a1 | 69,430 |
def snakeuppercase(var): # SOME_VARIABLE
"""
Snake uppercase convention. Include '_' between each element and transform in uppercase.
:param var: Variable to transform
:type var: :py:class:`list`
:returns: **transformed**: (:py:class:`str`) - Transformed input in ``SNAKE_UPPERCASE`` conve... | 60f93e7b3c3c3e2a4e6667c4786cad1c1dbe4acc | 69,431 |
import io
import select
from operator import and_
def read_task_timing(proc_url, task_name, tag):
""" Reads timing info for a given timing tag """
if io.is_db_url(proc_url):
metadata = io.open_db_metadata(proc_url)
timing_log = metadata.tables["timing_log"]
columns = list(timing_log.c... | 0025d50eb7a860b3d35453e77145d2c64f05a917 | 69,432 |
def df_aidxf_macro_cbb():
"""Example df_aidxf of a macrocycle with a fragment combination of type cbb. This tests that redundant intermediary rings are filtered out."""
mol = Chem.MolFromSmiles('C1CC2CC(CCC3CC(CCO3)CCCCC3CCC(CC3)CCCCCC2)N1')
return pd.DataFrame([
['macro_cbb', 'XXX'... | 7f7d92956d55bbc5ee6da2b55aa52258ad53efc4 | 69,433 |
def map(function, *collections):
"""does 3 separate things, hence this enormous docstring.
1. if function is None, return a list of tuples, each with one
item from each collection. If the collections have different
lengths, shorter ones are padded with None.
2. if function i... | 8b5eb71ec70ce18b7030e3c01dabc84f8f293e48 | 69,434 |
import six
import re
import keyword
def is_valid_varname(varname):
""" Checks syntax and validity of a variable name """
if not isinstance(varname, six.string_types):
return False
match_obj = re.match(varname_regex, varname)
valid_syntax = match_obj is not None
valid_name = not keyword.isk... | 4746ccb19d43dbe10ff2579184c5b925a030c6fc | 69,435 |
import os
import glob
import darshan
def discover_subcommands():
"""
Enable experimental features such as aggregation methods for reports.
Args:
verbose (bool): Display log of enabled features. (Default: True)
"""
subcommands = []
paths = glob.glob(darshan.__path__[0] + "/cli/*.py"... | 46981a44a5072d50113347d850441fe5d605539e | 69,436 |
def split_train_variableInput(sequence, minSamplesTrain, numOutputs, numJumps):
""" Returns sets to train a model with variable input length
i.e. X[0] = sequence[0], ..., sequence[minSamplesTrain]
y[0] = sequence[0], ..., sequence[minSamplesTrain+numOutputs]
...
X[k] =... | 7f8a03da19d21b4c29145cfeab7c2b20eb25ef25 | 69,437 |
import torch
def Ncontrast(x_dis, adj_label, tau=1):
"""
compute the Ncontrast loss
"""
x_dis = torch.exp(tau * x_dis)
x_dis_sum = torch.sum(x_dis, 1)
x_dis_sum_pos = torch.sum(x_dis * adj_label, 1)
loss = -torch.log(x_dis_sum_pos * (x_dis_sum**(-1))).mean()
return loss | dbec91553c38249f0aca5c7e11d6272f8f147879 | 69,438 |
def read_str_num(string, sep=None):
"""Returns a list of floats pulled from a string.
Delimiter is optional; if not specified, uses whitespace.
Parameters
----------
string : str
String to be parsed.
sep : str, optional
Delimiter (default is None, which means consecutive whites... | 87851e73fc8e81559d890abafc91cef8fc5f8a0a | 69,439 |
def _numeric_summary(arg, exact_nunique=False, prefix=None):
"""
Compute a set of summary metrics from the input numeric value expression
Parameters
----------
arg : numeric value expression
exact_nunique : boolean, default False
prefix : string, default None
String prefix for metric ... | cd2b14acaaa907aa5345e689125f45e8ad31aea1 | 69,440 |
def get(isamAppliance, name, check_mode=False, force=False):
"""
Retrieve a specific mapping rule
"""
ret_obj = search(isamAppliance, name=name)
id = ret_obj['data']
if id == {}:
return isamAppliance.create_return_object()
else:
return _get(isamAppliance, id) | 8d05f1aca64e86400a8ddb57de8b76dd4b2ecfff | 69,441 |
def assert_http_server(test, host, port,
path=b"", expected_response=b"hi"):
"""
Assert that a HTTP serving a response with body ``b"hi"`` is running
at given host and port.
This can be coupled with code that only conditionally starts up
the HTTP server via Flocker in order t... | 2c2eec1317ca584d5f1dc21c534101b39cc68eca | 69,442 |
import re
def to_bare_command_name(seq):
"""
Strips register and count data from @seq.
"""
# Special case.
if seq == '0':
return seq
new_seq = re.sub(r'^(?:".)?(?:[1-9]+)?', '', seq)
# Account for d2d and similar sequences.
new_seq = list(KeySequenceTokenizer(new_seq).iter_tok... | 70879c5f60fba5709f3c00c12d805e5de3309f1b | 69,443 |
def model_from_config(config: ml_collections.ConfigDict):
"""Builds a text classification model from a config."""
model = models.TextClassifier(
embedding_size=config.embedding_size,
hidden_size=config.hidden_size,
vocab_size=config.vocab_size,
output_size=config.output_size,
dropout_r... | 77a188b0b4c584f53a4fc001b193334da1def8a4 | 69,444 |
import os
def calc_load_sequence(filenames, toplevel_dir):
"""Given a list of starting javascript files, figure out all the Module
objects that need to be loaded to satisfiy their dependencies.
The javascript files shoud specify their dependencies in a format that is
textually equivalent to base.js' require ... | f193aba6875f8ada7ea53dee809a5c91b6f6834e | 69,445 |
import os
def dirname(hdfs_path):
"""
Return the directory component of ``hdfs_path``.
"""
return os.path.dirname(hdfs_path) | 7b1a8798d915feeb95f00692de6d7e6884cfc656 | 69,446 |
import os
def change_ext(path_src, ext_dst):
""" path_src の拡張子を ext_dst に変更する。
ext_dst の先頭は '.' を想定。
"""
assert(ext_dst[0] == '.')
fn_dir, fn_fn = os.path.split(path_src)
fn_base, fn_ext = os.path.splitext(fn_fn)
path_dst = os.path.join(fn_dir, '%s%s' % (fn_base, ext_dst))
return ... | 8ccf470f2ae02192782ebd9b339e73ffe3d28813 | 69,447 |
def _nobarrier(ts_dct):
""" Determine if reaction is barrierless
"""
print('cla', ts_dct['class'])
rad_rad = bool('radical radical' in ts_dct['class'])
low_spin = bool('low' in ts_dct['class'])
return rad_rad and low_spin | 393831d8b0af5085f8ff0f42d54bf8d14faca680 | 69,448 |
def resid_vs_pred_plot(y_true, y_pred, target):
"""Return plot containing residuals versus predictions."""
# -------------------------------------------------------------------------
# Setup
# -------------------------------------------------------------------------
# Define constants
MARKER = '... | 88933ce01fd4a43b4b8693d7d7964bedf03b8b4f | 69,449 |
def load_tfcsv_dataset(config, batch_size, augmentation=False, exclude=[], ann_dir=None, ann_file=None, img_dir=None):
""" Load the hardhat dataset
"""
ann_dir = config.data.ann_dir if ann_dir is None else ann_dir
ann_file = config.data.ann_file if ann_file is None else ann_file
img_dir = config.dat... | 1be2d697a6d123d64a0350aef7b500c8c33adf18 | 69,450 |
def identity_block(input_tensor,
kernel_size,
filters,
stage,
block,
weight_decay=1e-4,
batch_norm_decay=0.9,
batch_norm_epsilon=1e-5):
"""The identity block is the block that has no co... | 10c3dc77ed051ec93ea5af31dc3837c87ed7aadc | 69,451 |
def make_empty_df():
""" Make an empty dataframe as a placeholder. """
df = pd.DataFrame(data=None, dtype=int, columns=SEG_INFO_COLUMNS)
return df.set_index(cn.seg_id) | 7a6226fad2636cd5e21b6ef56fed0842716e6468 | 69,452 |
def create_args_string(num):
"""
生成占位符
返回 '?,?,?,?'
"""
L = []
for n in range(num):
L.append("?")
return ", ".join(L) | f9d52affe17c9dfb138338a3258d2d21dbd12c6e | 69,453 |
def escape_html(text):
"""
escape text for html file e.g. comment file
"""
text = multiple_str_sub(ESCAPE_HTML_CHAR_MAP_REGEX, ESCAPE_HTML_CHAR_MAP, text)
return text | ace05f9824a827ffd74af61c6e906d3f8690ad69 | 69,454 |
import slicer, fnmatch
def getNodes(pattern = "", scene=None):
"""Return a dictionary of nodes where the name or id matches the 'pattern'.
Providing an empty 'pattern' string will return all nodes.
"""
nodes = {}
if scene is None:
scene = slicer.mrmlScene
count = scene.GetNumberOfNodes()... | f1a3d15a9a416c2312e82c43f03443e6ff6f9f21 | 69,455 |
import os
def deepmind_atari(data_path, env_name, split, loss_to_use, batch_size,
noise_type, rgb_frames):
"""
Create TF Dataset object from DM-style atari frames (84, 84, 1)
:param data_path: location of root data dir.
:param env_name: environment name.
:param split: {'train', ... | 2bba1f289a883aadb734d7ec7583d231767ba073 | 69,456 |
def get_preferred_sparse_format():
"""Get the preferred sparse matrix format supported by the backend.
Different backends have their preferred backend. This info is useful when
constructing a sparse matrix.
"""
return "csr" | 266a0af45f274a28597a89bcaac38d9713addd11 | 69,457 |
def roll2(arr, xy):
"""Translates an array by the shift xy, wrapping at the edges."""
if (xy == 0).all():
return arr
return np.roll(np.roll(arr, xy[0], -1), xy[1], -2) | e1030e54a4b8f9ef5469ff8bbc4e9273a059f9bb | 69,458 |
import logging
import sys
def validate_taxonomy_field_values(config, field_definitions, csv_data):
"""Loop through all fields in field_definitions, and if a field
is a taxonomy reference field, validate all values in the CSV
data in that field against term IDs in the taxonomies referenced
by ... | b953c3adcf9f41739179c2a04e170f8b45e3035d | 69,459 |
import torch
def pad_collate_func(batch):
"""
This should be used as the collate_fn=pad_collate_func for a pytorch DataLoader object in order to pad out files in a batch to the length of the longest item in the batch.
"""
vecs = [x[0] for x in batch]
labels = [x[1] for x in batch]
x = torch.n... | 89d4f2c2adb7295457afe7f6a3235bbc4d9c8155 | 69,460 |
def get_regex(resolver_or_pattern):
# type: (Union[URLPattern, URLResolver]) -> Pattern[str]
"""Utility method for django's deprecated resolver.regex"""
try:
regex = resolver_or_pattern.regex
except AttributeError:
regex = resolver_or_pattern.pattern.regex
return regex | 1ade237453800f9995e31f43a61e6507010b388b | 69,461 |
import sys
def no_variant_found(gts, svtype, chrom, start, end, debug):
"""
skips variants with no non-ref samples
"""
if not any(sum(x) > 0 for x in gts if None not in x):
if debug:
print(
"Skipping {} at {}:{}-{}, no samples have non-ref genotypes".format(
... | 27c2b57bc70e634c5de92245bad437de5ffc5ca6 | 69,462 |
def get_type_from_default(default_var, vm):
"""Get the type of an attribute from its default value."""
if default_var.data == [vm.convert.none]:
# A default of None doesn't give us any information about the actual type.
return vm.convert.unsolvable
typ = vm.convert.merge_classes(default_var.data)
if typ... | 244720a5d0956a2ea300357e4134f04a491f810e | 69,463 |
def create_model_table(Enrollments_dict,segments):
"""
Generate the models recarray and the phone number hashtable
Parameters
----------
Enrollments_dict : dict
Dictionnary created by create_enrollments_dict()
segments : recarray
array containing informations all the segments
... | cd378d26fe510b31c4a54ddfdc787c9b965a268a | 69,464 |
def get_results(df, model, label_translation):
"""
get prediction results from a model 'model'
and a dataframe 'df'
:param df: data to predict
:type df: pd.DataFrame
:param model: classification model
:type model: any model from the module 'models'
:return: results
:rtype: pd.DataFr... | c550000b8586136af6b25d1e30cfa637e285fa35 | 69,465 |
def _FilterForUnsignedImageArchives(artifacts):
"""Return only instances of UnsignedImageArchive from a list of artifacts."""
return [x for x in artifacts if gspaths.IsUnsignedImageArchive(x)] | 17c2194fd9da459f0248265902f99c992cdcf72b | 69,466 |
def transpile_query(input_query, sketch_id):
"""Entry point function for cypher transpilation. Given a Cypher query,
this function parses it, inserts constraints (in match clauses, pattern
expressions and pattern comprehensions) to restrict the query to only
nodes and edges with given sketch_id property... | ce9a26e4f32dcf8afea31dfdb489dbae59019e55 | 69,467 |
def random_saturation(img, annotation, saturation=0.5):
""" Change the saturation randomly. """
coef = np.array([[[0.299, 0.587, 0.114]]])
alpha = np.random.uniform(-saturation, saturation)
gray = img * coef
gray = np.sum(gray, axis=2, keepdims=True)
img = alpha * img + (1.0 - alpha) * gray
... | 7405315987cb35e2db7c0beff5a1eca2cf48db89 | 69,468 |
def naively_call_mutation_directly(
alt_pos, cov_pos, p, min_alt_pos=2, only_call_if_rare=False
):
"""The guts of naively_call_mutation().
Abstracted to a separate function so that I can call this from other
contexts besides ordinary pileup -- e.g. for calling codons as p-mutated.
"""
if p > 50... | ec5b06fee1707ebd50bde8fbb880dfee005076b1 | 69,469 |
def cdlunique3river(opn, high, low, close):
"""Unique 3 River:
The unique three river is a candlestick chart pattern that predicts a bullish reversal,
although there is some evidence that it could act as a bearish continuation pattern. The
unique three river pattern is composed of three price candles. ... | b5f118066d1f4b0ccdc29f0f108863b1ed40e54e | 69,470 |
def PGaus(inImage, Beam):
"""
Create an ObitFArray containing a unit area Gaussian in the center
returns Python FArray object with normalized Gaussian
* inImage = Obit Image with geometry
* Beam = [maj, min, PA] defining eliptical Gaussian
size in image cell units or pixels if none... | 526aa7db3a238328d3e9c271ae91a82ab036a407 | 69,471 |
import re
def splitMySQLcode(string):
"""
MySQL code can only be executed one command at a time, and fails if it has any empty slots
So as a convenience wrapper, I'm just splitting it and returning an array.
"""
try:
output = ['%s;\n' % query for query in string.split(';') if re.search(r"\... | 43bf3f9209ced9c3c19c0ad4476b06a4d68f6e0c | 69,472 |
import os
def train_input_fn(features,labels,batch_size,user_negative,num_neg):
"""
features: 训练特征数据集
label: 对应训练集的正确分类标签,1维数组
batch_size: 切分数据集用于训练的批次大小
user_negative: 用户的负分类集合
num_neg: 负分类集合的大小
"""
data_path = os.path.join(DATA_PATH, 'train_data.npy')
if not o... | b0efb06e6780d1a4c6fe9173d128ab1ec35deab2 | 69,473 |
from typing import Optional
def get_article_by_id(article_id: int, annotate: bool = False) -> Optional[Article]:
"""Return article by the article's id"""
try:
article = get_all_articles(annotate).get(id=article_id)
except ObjectDoesNotExist:
raise Http404()
return article | 905e55538824cd378bc3e73c3ec919c200c7fd34 | 69,474 |
from typing import Callable
def three_body_mc_force_en(env1: AtomicEnvironment, env2: AtomicEnvironment,
d1: int, hyps: 'ndarray', cutoffs: 'ndarray',
cutoff_func: Callable = cf.quadratic_cutoff) \
-> float:
"""3-body multi-element k... | 306b690f0a4e769a0a70e44af5e221c656c126a6 | 69,475 |
from pathlib import Path
import subprocess
def patch_search_command(monkeypatch, grim_config, trainer_config):
"""Patches all external methods used by SearchCommand objects."""
def mock_load_grim_config(file_path: Path):
return grim_config
def mock_load_trainer_configuration(file_path: Path):
... | 97cd4d5a4ac52581c032f0df0bf8c1a48b4a3724 | 69,476 |
import re
def parse_value(line,key_word):
"""finds value in line by parsing keyword"""
value = re.sub(key_word,'',line,1)
return value.strip() | eb093da1577f10f9f7a271985b62b35ff3bf906e | 69,477 |
def calc_pr(positive, proposal, ground):
"""
Calculate precision and recall
:param positive: number of positive proposals
:param proposal: number of all proposals
:param ground: number of ground truths
:return:
"""
if not proposal or not ground:
return 0, 0
return positive / ... | 277456d2c7c5d4352b925931342030663f1a541b | 69,478 |
def user_has_view_permission(user, page=None):
"""
This code largely duplicates Page.has_view_permission(). We do this because
the source method requires a request object, which isn't appropriate in
this case. Fortunately, the source method (and its dependencies) use the
request object only to get t... | 146b72878d023f8c76781eac855a000ff3f141ad | 69,479 |
def broadcast_shape(shape, comm=MPI.COMM_WORLD, root=0):
""" Broadcast shape to all processes
Parameters
----------
shape : int, tuple of int
Shape representation of numpy.ndarray object
comm : MPI Communicator, optional
MPI process communication object. If none specified
d... | 504624db0b8fb7e70e912262ef95d274c8d2f607 | 69,480 |
def noz3d(P, Y, y, m, c, o, plm):
"""
This is equivalent to Draper-Stoneman, as when there is no Z
Y remains unchanged.
"""
Mr = P @ plm.X[y][m][c][o]
return Mr, Y | b239bd250b79eee5c64eb10c0cff06ebf7ace458 | 69,481 |
import torch
from typing import Union
import math
import warnings
def get_kwta_threshold(tensor: torch.Tensor,
sparsity: Union[float, SparsityPredictor]):
"""
Returns the threshold for kWTA activation function as if input tensor is a linear (batch x embedding_dim).
:param tensor: (... | 8c32fde3bf655dd7e1af57b1b36fa0c81a18866f | 69,482 |
def merge_list(this, other, cb, comp=lambda o: type(o)):
"""
Merge two lists by their children's type,
for each given list, their children must be unique in type.
:param this:
:param other:
:param cb:
:param comp: a function to get children's type, defaults to type()
:return:
"""
... | e6d5a5c8082a7b622eb2b025b10788a49cf512ae | 69,483 |
import re
import gettext
def mix_vimeo(vimeo_id):
#TODO: validate given id
"""
Fetch related content from Vimeo based on single video ID
"""
video_list = []
vids = VIMEO.get(("/videos/{}/videos?filter=related&per_page=20").format(
vimeo_id), params={"fields": "name, pictures.uri, d... | e0df6153b698e021bc72121062791ce1a580afcf | 69,484 |
def parse(d, model):
"""
Parse a dictionary of JSON types into their Kubernetes types.
"""
parsed = {}
for field, type_ in model.openapi_types.items():
if field not in d and field in model.attribute_map:
# node_affinity -> nodeAffinity
field = model.attribute_map[fie... | 6faade9cf8e4e7a5d06200a9a363a67b870eaf07 | 69,485 |
def _preprocess_for_cut(x):
"""
handles preprocessing for cut where we convert passed
input to array, strip the index information and store it
seperately
"""
x_is_series = isinstance(x, Series)
series_index = None
name = None
if x_is_series:
series_index = x.index
na... | dfbb61122693e6e84a1280a16395b1df76782bfe | 69,486 |
def fetch_splice_motif_code(chrom, start_pos, end_pos, strand, genome):
""" Use Pyfasta to extract the splice motif sequence based on the start
and end of the splice junction. Then, convert this sequence motif
to a numeric code. """
start_motif = get_splice_seq(chrom, start_pos, 0, genome)
... | 4abe9c9f4c28573302426185337cd9fcfbe7e9cf | 69,487 |
import json
def read_template(client, template):
"""Read the template from a file or the stack object"""
if template.endswith(tuple(['.yaml', '.yml', '.json'])):
validate_template(client, template)
tmpl = read_file(template)
if template.endswith('.json'):
tmpl = json.dumps(... | 2e1db6ed135a9e7f5e5b470dcb5207d8289249f1 | 69,488 |
import os
def test_overlay(dfs_index, how):
"""
Basic overlay test with small dummy example dataframes (from docs).
Results obtained using QGIS 2.16 (Vector -> Geoprocessing Tools ->
Intersection / Union / ...), saved to GeoJSON
"""
df1, df2 = dfs_index
result = overlay(df1, df2, how=how)
... | 91a3c88baad0d897977a3a4e8229c95e614c34d4 | 69,489 |
def largest_product(series: str, size: int) -> int:
"""Largest Series Product from strings
:param series: str: takes a series of digits
:param size: int: size of slices / groups / chunks
:returns: int: the largest product within groups of n size
"""
series_slices = slices(series, size)
ret... | 25055736741075d718eb78dfd75df3c6f564b233 | 69,490 |
import requests
def netbox_is_responsive(url):
"""Chack if the HTTP service is up and responsive."""
try:
response = requests.get(url)
if response.status_code == 200:
return True
except (
ConnectionError,
ConnectionResetError,
requests.exceptions.Connect... | cd71140a40f01c536b315790c4c1d581c67891e8 | 69,491 |
from typing import Any
import random
def getKeyByWeights(array: dict, item: int = 0) -> Any:
"""
Returns a weighted random key from array
:param array: dict[Any: int | float]
:param item: int
:return:
- key - Any
"""
return random.choices(list(array.keys()), weights=list(array.valu... | 8f1d474c97466407ff643abce1ea0b12b3ebd951 | 69,492 |
def get_partner_theme_list():
"""
grabbing MFI Partner and Loan Theme
"""
themes = Theme.query.filter_by(active=True).all()
partners = Partner.query.filter_by(active=True).all()
data = {'themes':[x.loan_theme for x in themes], 'partners':[x.partner_name for x in partners]}
return create_... | 921cf800040ee180974fce50096d99b381d7e30f | 69,493 |
def get_ymal_data(data):
"""Get metadata and validate them
:param data: metadata in yaml format
"""
try:
format_data = yaml.load(data)
except yaml.YAMLError, e:
msg = "Yaml format error: {}".format(
unicode(str(e), "utf-8")
)
logging.error(msg)
sy... | fbd11985090c77bb24f0434a10325548d235b161 | 69,494 |
def convert_base(arg, from_base, to_base):
"""
Convert number (as integer or string) from one base to another
Parameters
----------
arg : string or integer
from_base : integer
to_base : integer
Returns
-------
converted : string
"""
return _ops.BaseConvert(arg, from_bas... | 0a765a83734fa7e0574059eb961f357542de499b | 69,495 |
def sinhm(A):
"""
Compute the hyperbolic matrix sine.
This routine uses expm to compute the matrix exponentials.
Parameters
----------
A : (N, N) array_like
Input array.
Returns
-------
sinhm : (N, N) ndarray
Hyperbolic matrix sine of `A`
Examples
--------... | c4ccf9fcfab5982b9bd1bb41984b5763ce3adb22 | 69,496 |
import logging
def init_altimeter(configuration: Configuration):
"""Initialize the sensor for pressure, temperature, and altitude"""
try:
logging.info("Initializing altimeter")
assignments = configuration.get_pin_assignments("bmp3xx")
if not assignments:
return None
... | 004eb7c41bf133cd8b0e74c2f53218510f98829c | 69,497 |
import sys
def should_run_single_process():
"""determines whether to run in normal or distributed mode"""
if '-distributed' not in sys.argv:
return True
else:
rank = get_integer_arg(sys.argv, '-rank')
if rank is not None and rank != -1:
return True
return False | 128eb7dbc98b716b89ee92bb263b6a411134a6e2 | 69,498 |
def create_learning_rate(hparams, global_step):
"""Creates a learning rate Tensor.
Args:
hparams: ConfigDict containing the learning rate configuration.
global_step: The global step Tensor.
Returns:
A learning rate Tensor.
"""
if hparams.get("learning_rate_decay_factor"):
learning_rate = tf.... | d12fbfd5f13be8a9c8479a791bfd6b4cd2e1d712 | 69,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.