content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def show_nicks(handles):
""" return terminal sequence for /users result. """
from x84.bbs import getterminal
term = getterminal()
return u''.join((
time.strftime('%H:%M'), u' ',
term.blue('-'), u'!', term.blue('-'),
u' ', term.bold_cyan('%d' % (len(handles))), u' ',
u'use... | 5,337,400 |
def cvCmp(*args):
"""cvCmp(CvArr src1, CvArr src2, CvArr dst, int cmp_op)"""
return _cv.cvCmp(*args) | 5,337,401 |
def convert_to_dtype(data, dtype):
"""
A utility function converting xarray, pandas, or NumPy data to a given dtype.
Parameters
----------
data: xarray.Dataset, xarray.DataArray, pandas.Series, pandas.DataFrame,
or numpy.ndarray
dtype: str or numpy.dtype
A string denoting a... | 5,337,402 |
def process_files(data_path, output_path):
"""Returns a pipeline which rebalances data shards.
Args:
data_path: File(s) to read.
output_path: Path to which output CSVs are written, if necessary.
"""
def csv_pipeline(root):
_ = (
root
| beam.io.ReadFromText(data_path)
| bea... | 5,337,403 |
def delete_tasklog_cached(dc_id, user_id=None):
"""
Remove tasklog cache entry.
"""
if user_id:
key = _cache_log_key(user_id, dc_id)
else:
key = _cache_log_key(settings.TASK_LOG_STAFF_ID, dc_id)
return cache.delete(key) | 5,337,404 |
def strip_headers(data):
""" Strips headers from data #depreciate"""
try:
return data['items']
except (TypeError, KeyError) as e:
print(e)
return data | 5,337,405 |
def sns_plot(chart_type: str, df):
""" return seaborn plots """
fig, ax = plt.subplots()
if chart_type == "Scatter":
with st.echo():
sns.scatterplot(
data=df,
x="bill_depth_mm",
y="bill_length_mm",
hue="species",
... | 5,337,406 |
def decode_fields(source_str: str, resp_type):
""" This is the lower level decode of fields, no automatic guess of type is performed."""
field_decoding = FIELD_MAPPING[resp_type]
unpacked_fields = {}
for field_name, field_type, field_subtype in field_decoding:
search_term = f"{field_name}:".e... | 5,337,407 |
def make_egg(a=-1.25, b=7):
"""
Return x, y points that resemble an egg.
Egg equation is:
r = cos(2θ) + a * cos(θ) + b
@param a: Number.
@param b: Number.
"""
theta = np.linspace(0, 2 * np.pi, 100)
r = np.cos(2 * theta) + a * np.cos(theta) + b
y = r * np.cos(theta)
x =... | 5,337,408 |
def test_styling_object_which_implements_str_proto():
"""
Test styling an object which implements the str protocol
"""
class Dummy(object):
def __str__(self):
return 'I am a dummy object'
colorful = core.Colorful(colormode=terminal.ANSI_8_COLORS)
assert str(colorful.black(Du... | 5,337,409 |
def determine_auto_approval(financial_aid, tier_program):
"""
Takes income and country code and returns a boolean if auto-approved. Logs an error if the country of
financial_aid does not exist in CountryIncomeThreshold.
Args:
financial_aid (FinancialAid): the financial aid object to determine au... | 5,337,410 |
def crustal_model_files(alt = [200, 1000], anomaly = 'Global', lim = [0., 360. -90., 90.], binsize = 0.1):
""""
Reads the .bin IDL files of the crustal magnetic field model (Langlais) for a range of altitudes and creates a function based on a linear interpolation.
Parameters:
alt: 2-elemen... | 5,337,411 |
def write_gain_expressions_for_table():
"""Write expressions for google tables into file"""
seism_NRL = load_seism_NRL()
digi_NRL, _ = load_digi_NRL()
nrl = NRL()
for v in digi_NRL.values():
if v:
v[-1] = v[-1].format(sr=100)
# get sensitivities
digi_sens = {k: nrl.get_da... | 5,337,412 |
def f1(y_true, y_pred):
"""
Function for computing the unweighted f1 score using tensors. The Function
handles only the binary case and compute the unweighted f1 score
for the positive class only.
Args:
- y_true: keras tensor, ground truth labels
- y_pred: keras tensord, labels esti... | 5,337,413 |
def get_selector_score(key, selector, use_median, best_based_on_final):
"""
:param key: Thing to measure (e.g. Average Returns, Loss, etc.)
:param selector: Selector instance
:param use_median: Use the median? Else use the mean
:param best_based_on_final: Only look at the final value? Else use all
... | 5,337,414 |
def str_to_timezone(tz):
"""
从字符串构建时区
"""
return pytz.timezone(tz) if tz else pytz.utc | 5,337,415 |
def _get_previous_index_search_col(
m, col, nested_list, trans_function=None, transformation=False
):
"""Return previous index of a a key, from a sorted nested list where a key is being seached in the col number.Returns -1 if value is not found.
Args:
m (comparable): comparable being searched
... | 5,337,416 |
def guest_import(hypervisor, host):
"""
Import a new guest
::
POST /:hypervisor/:host/guests
"""
response.content_type = "application/json"
manager = create_manager(hypervisor, host)
guest = manager.guest_import(
request.environ['wsgi.input'],
request.content_length
... | 5,337,417 |
def get_doc_count(
group_by: List[str] = ["year", "country"],
sort_by: List[metadata.SortOn] = [
metadata.SortOn(field="year", order=metadata.SortOrder.desc),
metadata.SortOn(field="count", order=metadata.SortOrder.desc)],
limit: int = 10):
"""This endpoint provides a... | 5,337,418 |
def get_author_list(text):
"""function to extract authors from some text that will also include
associations
example input:
`J. C. Jan†, F. Y. Lin, Y. L. Chu, C. Y. Kuo, C. C. Chang, J. C. Huang and C. S. Hwang,
National Synchrotron Radiation Research Center, Hsinchu, Taiwan, R.O.C`
or
`M.B.... | 5,337,419 |
def start_transfer(protocol, chunk_size, ip, port, file, stop_and_wait):
""" Benchmark client """
client_class = cls_client[protocol]
client = client_class(ip=ip, port=port, stop_and_wait=stop_and_wait)
print('[CLIENT] Started client {}, chunk size {} for server {}:{} ... '.format(protocol, chunk_size,... | 5,337,420 |
def find_matching_format_function(word_with_formatting, format_functions):
""" Finds the formatter function from a list of formatter functions which transforms a word into itself.
Returns an identity function if none exists """
for formatter in format_functions:
formatted_word = formatter(word_with... | 5,337,421 |
def mean (inlist:List(float))->float:
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum/float(len(inlist)) | 5,337,422 |
def save_model(model_file_name, model):
"""
save_model(model_file_name, model) -> None
Save a LIBLINEAR model to the file model_file_name.
"""
liblinear.save_model(model_file_name.encode(), model) | 5,337,423 |
def print_files(files_from_disk, comparison_info):
"""Print both lists of files.
"""
print("Files in both database and on disk:\n")
for fn in list(files_from_disk.keys()):
if fn not in comparison_info['dbonly'] and fn not in comparison_info['diskonly']:
print(" %s" % (fn))
pr... | 5,337,424 |
def create_file_download_url(file_path: str) -> str:
"""
Creates Telegram URL for downloading of file.
- contains secret information (bot token)!
:param file_path: `file_path` property of `File` object.
"""
token = environ["TELEGRAM_API_BOT_TOKEN"]
return create_url(
"https://api.... | 5,337,425 |
def event_post():
"""this sample is to post not only one event"""
event_post_request = EventPostRequest.builder().set_event_identifier('Error') \
.add_value("power", 124) \
.add_values(SampleHelper.EVENTS_VALUE) \
.build()
event_post_response = client.publish(event_post_request)
... | 5,337,426 |
def convert_to_csv(items):
"""
Args:
items: all arns in a region from the DynamoDB query as a list
returns:
csv_body: body of the csv file to write out
"""
fieldnames = ["Package", "Package Version", "Status", "Expiry Date", "Arn"]
# sort by package, and then created date (oldest t... | 5,337,427 |
def _check_resample_inputs(x, f, direction, shift):
"""Checks the inputs to _downsample() and _upsample()."""
if len(x.shape) != 3:
raise ValueError('Expected `x` to have rank 3, but is of size {}'.format(
x.shape))
if len(f.shape) != 1:
raise ValueError('Expected `f` to have rank 1, but is of siz... | 5,337,428 |
async def test_todo_api(app, test_cli):
"""
testing todo api
"""
# GET
resp = await test_cli.get('/api/todo')
assert resp.status == 200
resp_json = await resp.json()
assert len(resp_json['todo_list']) == 0
# POST
resp = await test_cli.post(
'/api/todo',
data=jso... | 5,337,429 |
def manhattan(train_X, val_X):
"""
:param train_X: one record from the training set
(type series or dataframe including target (survived))
:param val_X: one record from the validation set
series or dataframe include target (survived)
:return: the Manhattan distanc... | 5,337,430 |
def generate_input(start, stop, step):
"""
Create input arguments for the function to be timed.
"""
for n in range(start, stop, step):
l = [random.randint(0, n) for _ in range(n)]
yield (l, ), n | 5,337,431 |
def author_idea_list(request, registrant_id):
"""
Returns author ideas
"""
registrant = get_object_or_404(Registrant, pk=registrant_id)
ideas = Idea.objects.filter(author=registrant)
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK) | 5,337,432 |
def compare_distilled(dir):
"""Compare all the distilled contents from the original pages with those from the mhtml archives
Args:
dir (str): directory containing all the extracted features
"""
files = [os.path.join(dir, f) for f in os.listdir(dir)]
mdfeatures = [f for f in files if os.path.isfile(f) an... | 5,337,433 |
def match(text: str, pattern: str) -> bool:
"""
Match a text against a given regular expression.
:param text: string to examine.
:param pattern: regular expression.
:returns: ``True`` if pattern matches the string.
"""
return re.match(pattern, text) is not None | 5,337,434 |
def find_marker(log):
"""Function: find_marker
Description: Locates the file marker.
Arguments:
(input) log -> LogFile class instance
"""
if log.marker:
log.find_marker(update=True) | 5,337,435 |
async def pp_(message: discord.Message, beatmap_url: str, *options):
""" Calculate and return the would be pp using `rosu-pp`.
Options are a parsed set of command-line arguments: /
`([acc]% | [num_100s]x100 [num_50s]x50) +[mods] [combo]x [misses]m hp[hp] ar[ar] od[od] cs[cs] [clock_rate]*`
**Addition... | 5,337,436 |
def _compute_hash_check(input_strings: tf.Tensor, field_size: int, seed: int,
dtype: tf.dtypes.DType) -> tf.Tensor:
"""Returns the hash_check for input_strings modulo field_size."""
hash_check_salt = _get_hash_check_salt(seed)
salted_input = tf.strings.join([hash_check_salt, input_strings]... | 5,337,437 |
def _trademark(request):
"""
access to the produt database is available here, making a request to save/check the data
for storage inside the database
"""
# site data from scrap program
websitename = WebsiteClassName().getProducts( WebsiteClassName().getCategoryLinks() )
# access the data structure we need to ... | 5,337,438 |
def calc_extinction(radius:float, mosaicity:float, model:str,
a:float, b:float, c:float, alpha:float, beta:float, gamma:float,
h:float, k:float, l:float,
f_sq:float, wavelength:float, flag_derivative_f_sq=False):
"""
Isotropical extinction coorection ... | 5,337,439 |
def package_software(pack_type, name_idx, version, debug):
"""
打包压缩软件
@param pack_type: 打包类型,update全量还是patch增量
@param name_idx: 名称索引
@param version: 版本
@param debug: 调试使能
@return:
"""
for item in pack_proc:
if item.option == name_idx:
item.proc(pack_type, item.name, v... | 5,337,440 |
def smape(y_true: Yannotation, y_pred: Yannotation):
"""
Calculate the symmetric mean absolute percentage error between `y_true`and `y_pred`.
Parameters
----------
y_true : array, `dataframe`, list or `tensor`
Ground truth values. shape = `[batch_size, d0, .. dN]`.
y_pred : array, `data... | 5,337,441 |
def acosh(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None):
"""
The ACosH operation
The arguments for this function are as follows:
:param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string
:param extent_type: one of "First... | 5,337,442 |
def load_does(
filepath: PathType, defaults: Optional[Dict[str, bool]] = None
) -> Tuple[Any, Any]:
"""Load_does from file."""
does = {}
defaults = defaults or {"do_permutation": True, "settings": {}}
data = OmegaConf.load(filepath)
data = OmegaConf.to_container(data)
mask = data.pop("mask")... | 5,337,443 |
def causal_segment_mask(segment_ids: JTensor,
dtype: jnp.dtype = jnp.float32) -> JTensor:
"""Computes the masks which combines causal masking and segment masks.
Args:
segment_ids: a JTensor of shape [B, T], the segment that each token belongs
to.
dtype: data type of the input.... | 5,337,444 |
def __docs__(self):
"""THIS is a libray used for creating all required filrs for making liabrary also for creating normal files"""
pass | 5,337,445 |
def remove_outliers(peaks: np.ndarray, **kwargs):
"""
https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.LocalOutlierFactor.html#sklearn.neighbors.LocalOutlierFactor
https://scikit-learn.org/stable/modules/outlier_detection.html
Parameters
----------
peaks
kwargs
Retur... | 5,337,446 |
def powerset(iterable):
""" Calcualtes the powerset, copied from https://docs.python.org/3/library/itertools.html#itertools-recipes """
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) | 5,337,447 |
def get_rotational_vector(skew_symmetric):
"""Get the rotational vector from a skew symmetric matrix.
Parameters
----------
skew_symmetric: numpy.ndarray
the skew symmetric matrix.
Returns
-------
rotational_vector:
the rotational vector.
"""
# make sure that the ... | 5,337,448 |
def diaperchange_lifetimes(changes):
"""
Create a graph showing how long diapers last (time between changes).
:param changes: a QuerySet of Diaper Change instances.
:returns: a tuple of the the graph's html and javascript.
"""
changes = changes.order_by("time")
durations = []
last_change... | 5,337,449 |
def batch_norm_conv(x, n_out, phase_train, scope='bn'):
"""
Batch normalization on convolutional maps.
Args:
x: Tensor, 4D BHWD input maps
n_out: integer, depth of input maps
phase_train: boolean tf.Varialbe, true indicates training phase
scope: string, ... | 5,337,450 |
def strip_variants(address):
"""Return a copy of the given address with the variants (if any) stripped from the name.
:rtype: :class:`pants.build_graph.address.Address`
"""
address, _ = parse_variants(address)
return address | 5,337,451 |
def list_rse_usage_history(rse, issuer, source=None, vo='def'):
"""
List RSE usage history information.
:param rse: The RSE name.
:param issuer: The issuer account.
:param source: The source of the usage information (srm, rucio).
:param vo: The VO to act on.
:returns: A list of historic RS... | 5,337,452 |
def assure_dir(outd):
"""Create directory 'outd' if it does not exist"""
if not os.path.exists(outd):
os.makedirs(outd) | 5,337,453 |
def deleteIdentifiedStock(bot, update):
"""Deletes the user's selected stock.
If the user's selected stock is valid, proceed to delete it.
Returns:
Return MENU state with normal keyboard.
"""
if update.message.chat.username is None:
# User has no username
update.mess... | 5,337,454 |
def z_inc_down(grid):
"""Return True if z increases downwards in the coordinate reference system used by the grid geometry
:meta common:
"""
if grid.crs is None:
assert grid.crs_uuid is not None
grid.crs = rqc.Crs(grid.model, uuid = grid.crs_uuid)
return grid.crs.z_inc_down | 5,337,455 |
def update_display_caption():
"""set the window title"""
pygame.display.set_caption("SoundRTS %s %s %s" % (VERSION, res.mods, res.soundpacks)) | 5,337,456 |
def load_coord_var(prob_data_type):
"""
Loads a coordinate variable from the source data and returns it.
:param prob_data_type:
:return:
"""
fpath = "{}/source_others/a1b_tas_jja_EAW_1961-1990.dat".format(BASEDIR)
with open(fpath, 'rb') as reader:
data = cPickle.load(read... | 5,337,457 |
def get_os():
"""Get the current operating system.
:returns: The OS platform (str).
"""
return platform.system() | 5,337,458 |
async def test_pipe_operator():
"""Overload the ``__or__`` operator to make piping streams look cool."""
logging.debug('+++++++++++++++++++++>> BEGIN TEST_PIPE_OPERATOR')
# Spool some commands
read_file = reel.Spool(f'cat {__file__}')
remove_grep = reel.Spool(f'grep -v grep')
find_cat = reel.Sp... | 5,337,459 |
def get_config():
"""This function retrieves API keys, access tokens, and other key data from the config file."""
global LOG_NAME, TARGET, URL_NUMBER, WHERE, BOT
print("Building OAuth header...")
if 'XKCD_APPNAME' in os.environ: # Running on a cloud server
key = [os.environ.get('API_KEY', None)... | 5,337,460 |
def count_hits(space, positions, pi_plus_4_vecs_lab, pi_null_4_vecs_lab, r):
"""returns a list of hit counts for z values in space"""
return [count_double_hits(positions, pi_plus_4_vecs_lab, pi_null_4_vecs_lab, r=r, z_detector=z) for z in space] | 5,337,461 |
def time_since(since, m_padding=2, s_padding=2):
"""Elapsed time since last record point."""
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
return '{}m:{}s'.format(str(int(m)).zfill(m_padding),
str(int(s)).zfill(s_padding)) | 5,337,462 |
def run_cmd(cmd, encoding=DEFAULT_ENCODING):
"""
Run a command as a subprocess.
# Arguments
* `cmd` (list<str>): The command to run.
* `encoding` (str): The encoding to use for communicating with the
subprocess.
# Returns
A named tuple with the following fields:
- returnc... | 5,337,463 |
def setconfig_list(ui, section, items):
"""
Alternative form of setting many configuration items with one call.
Here items are given as list of key,value pairs. Contrary to
setconfig_dict, this guarantees ordering.
>>> import mercurial.ui; ui = mercurial.ui.ui()
>>> setconfig_list(ui, "sect1",
... | 5,337,464 |
def record_check(record):
"""
record dict check
--- a dictionary is required as the input ---
"""
assert isinstance(
record, dict), 'record should be dict, while the input is {}'.format(type(record))
cnn_json_struct = JsonFormatSetting.CNN_JSON_STRUCTURE
record_struct = cnn_json_stru... | 5,337,465 |
def encrypt_chunk(chunk, password=None):
"""Encrypts the given chunk of data and returns the encrypted chunk.
If password is None then saq.ENCRYPTION_PASSWORD is used instead.
password must be a byte string 32 bytes in length."""
if password is None:
password = saq.ENCRYPTION_PASSWORD
... | 5,337,466 |
def freeze_graph(checkpoints_path, output_graph):
"""
:param checkpoints_path: ckpt文件路径
:param output_graph: pb模型保存路径
:return:
"""
with tf.Graph().as_default():
image = tf.placeholder(shape=[None, 608, 608, 3], dtype=tf.float32, name='inputs')
# 指定输出的节点名称,该节点名称必须是原模型中存在的节点
... | 5,337,467 |
def convert_to_pj_lop_plus(lops):
"""
Converts the list of PlayerStates to an LOP+
:param lops: The PlayerStates to be converted
:type lops: [PlayerState, ...]
:return: The LOP+
:rtype: PyJSON
"""
return [convert_to_pj_player_plus(ps) for ps in lops] | 5,337,468 |
def euler_to_quaternion(roll: float = 0, pitch: float = 0, yaw: float = 0) -> Tuple[float, float, float, float]:
"""
Convert Euler to Quaternion
Args:
roll (float): roll angle in radian (x-axis)
pitch (float): pitch angle in radian (y-axis)
yaw (float): yaw angle in radian (z-axis)
... | 5,337,469 |
def supervisorctl_url():
"""This parses supervisord.conf which contains the URL of supervisorctl."""
parsed_config = _get_parsed_configuration()
# For example 'http://localhost:9001'
control_url = _clean_config_value(parsed_config['supervisorctl']['serverurl'])
logging.debug("control_url=%s" % co... | 5,337,470 |
def create_generic_constant(type_spec, scalar_value):
"""Creates constant for a combination of federated, tuple and tensor types.
Args:
type_spec: Instance of `computation_types.Type` containing only federated,
tuple or tensor types for which we wish to construct a generic constant.
May also be som... | 5,337,471 |
def has_openid(request):
"""
Given a HttpRequest determine whether the OpenID on it is associated thus
allowing caller to know whether OpenID is good to depend on.
"""
from django_openid.models import UserOpenidAssociation
for association in UserOpenidAssociation.objects.filter(user=request.user... | 5,337,472 |
def get_wordcloud():
"""
Generates the wordcloud and sends it to the front end as a png file.
:return: generated tag_cloud.png file
"""
update_tagcloud(path_to_save='storage/tmp', solr_service=solr)
return send_from_directory("storage/tmp", "tag_cloud.png", as_attachment=True) | 5,337,473 |
def rtc_runner(rtc):
"""
:type rtc: pbcommand.models.ResolvedToolContract
:return:
"""
return gather_run_main(chunk_json=rtc.task.input_files[0],
chunk_key=Constants.CHUNK_KEY,
gathered_fn=rtc.task.output_files[0],
ln_n... | 5,337,474 |
def get_matching_axis(shape: Tuple, length: int) -> int:
"""
Infers the correct axis to use
:param shape: the shape of the input
:param length: the desired length of the axis
:return: the correct axis. If multiple axes match, then it returns the last
one.
"""
# noinspectio... | 5,337,475 |
def is_paths(maybe_paths, marker='*'):
"""
Does given object `maybe_paths` consist of path or path pattern strings?
"""
return ((is_path(maybe_paths) and marker in maybe_paths) or # Path str
(is_path_obj(maybe_paths) and marker in maybe_paths.as_posix()) or
(is_iterable(maybe_pa... | 5,337,476 |
def output_numpy_or_asa(obj, data, *, output_type=None, labels=None):
"""This function returns a numpy ndarray or nelpy.AnalogSignalArray
Parameters
----------
obj : numpy.ndarray or a nelpy object
data : numpy.ndarray, with shape (n_samples, n_signals)
Data is either passed through as the ... | 5,337,477 |
def embed_oar(features: Array, action: Array, reward: Array,
num_actions: int) -> Array:
"""Embed each of the (observation, action, reward) inputs & concatenate."""
chex.assert_rank([features, action, reward], [2, 1, 1])
action = jax.nn.one_hot(action, num_classes=num_actions) # [B, A]
reward = ... | 5,337,478 |
async def kibana(es, params):
"""
Simulates Kibana msearch dashboard queries.
It expects the parameter hash to contain the following keys:
"body" - msearch request body representing the Kibana dashboard in the form of an array of dicts.
"params" - msearch request parameters.
... | 5,337,479 |
def aggregations_terms(query=None):
"""Get page for aggregations."""
if query is None:
# Default query
query = "state,config.instance_type"
# Remove all white spaces from the str
query = query.replace(" ", "")
data = {"query": query}
end_point = "aggregations/terms"
url = S... | 5,337,480 |
def validate_base(model,
args,
loader,
loadername,
train=True):
"""
The validation function. Validates the ELBO + MIL, ELBO, and the accuracy
of the given [training, validation or test] loader.
Returns
-------
loss: list
... | 5,337,481 |
def parse_person(person):
"""
https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field-optional
A "person" is an object with an optional "name" or "email" field.
A person can be in the form:
"author": "Isaac Z. Schlueter <i@izs.me>"
For example:
>>> p = parse_person('Bar... | 5,337,482 |
def flag_dict_to_args(flag_map):
"""Convert a dict of values into process call parameters.
This method is used to convert a dictionary into a sequence of parameters
for a binary that parses arguments using this module.
Args:
flag_map: dict, a mapping where the keys are flag names (strings).
values... | 5,337,483 |
def build_snpeff(ref_genome):
"""Setup the SnpEff database for ref_genome.
This function does the following:
* Sets up the directory structure for SnpEff-related files.
* Writes a possibly modified Genbank to the location that SnpEff
expects to find it. A few cleanups are necessar... | 5,337,484 |
def _glasstone_surface_cf(y):
"""Correction factor provided by TEoNW for contact surface bursts (p. 335)."""
return np.interp(y, [1.0, 50.0, 100.0, 300.0, 700.0, 2000.0, 5000.0, 5000.0], [0.6666666666666666, 0.6666666666666666, 1.0, 1.25, 1.5, 2.0, 3.0, 3.0]) | 5,337,485 |
def create_eval_fn(task_id, calculate_gradient=False):
"""Creates an evaluation function for a given task. Returns an evaluation
function that takes in a model, dataloader, and device, and evaluates the
model on the data from the dataloader. Returns a dictionary with mean
"loss" and "accuracy". If calcu... | 5,337,486 |
def get_dashboard_oauth_client_id():
"""Gets the client ID used to authenticate with Identity-Aware Proxy
from the environment variable DASHBOARD_OAUTH_CLIENT_ID."""
return os.environ.get('DASHBOARD_OAUTH_CLIENT_ID') | 5,337,487 |
def naming_style(f):
"""Decorator for name utility functions.
Wraps a name utility function in a function that takes one or more names,
splits them into a list of words, and passes the list to the utility function.
"""
def inner(name_or_names):
names = name_or_names if isinstance(name_or_na... | 5,337,488 |
def parse_args(argv, app_name):
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description=app_name)
parser.add_argument(
"-c",
"--config",
dest="config",
type=str,
default="config.yaml",
help="Set config.yaml file",
)
parser.add... | 5,337,489 |
def has_newer_fw( current_fw, bundled_fw ):
"""
:param current_fw: current FW version of a device
:param bundled_fw: bundled FW version of the same device
:return: True if the bundled version is newer than the current one
"""
current_fw_digits = current_fw.split( '.' )
bundled_fw_digits = bu... | 5,337,490 |
def is_idaq(*args):
"""
is_idaq() -> bool
Returns True or False depending if IDAPython is hosted by IDAQ
"""
return _ida_kernwin.is_idaq(*args) | 5,337,491 |
def print_grid(grid):
"""
Print the given grid in a readable form
:param grid: input grid/world to be printed
"""
print('[')
for row in grid:
print('\t', row, ',')
print(']') | 5,337,492 |
def get_stats_yaml():
"""grab national stats yaml from scorecard repo"""
nat_dict = {}
try:
nat_yaml = requests.get(COLLEGE_CHOICE_NATIONAL_DATA_URL)
if nat_yaml.ok and nat_yaml.text:
nat_dict = yaml.safe_load(nat_yaml.text)
except AttributeError: # If response.text has no v... | 5,337,493 |
def signal_interpolate(x_values, y_values, desired_length, method="quadratic"):
"""Interpolate a signal.
Interpolate (fills the values between data points) a signal using different methods.
Parameters
----------
x_values : list, array or Series
The samples corresponding to the values to be... | 5,337,494 |
def check_module(feature):
"""
Checks if a module is available.
:param feature: The module to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the module is not defined in this version of Pillow.
"""
if not (feature in modules):
raise ... | 5,337,495 |
def get_original(N: int = 64) -> np.ndarray:
"""radontea logo base image"""
x = np.linspace(-N / 2, N / 2, N, endpoint=False)
X = x.reshape(1, -1)
Y = x.reshape(-1, 1)
z = logo(X, Y, N)
return np.array((z) * 255, dtype=np.uint16) | 5,337,496 |
def rebuild_ft_billing_for_day(service_id, day):
"""
Rebuild the data in ft_billing for the given service_id and date
"""
def rebuild_ft_data(process_day, service):
deleted_rows = delete_billing_data_for_service_for_day(process_day, service)
current_app.logger.info("deleted {} existing ... | 5,337,497 |
def get_sql_update_by_ids(table: str, columns: List[str], ids_length: int):
"""
获取添加数据的字符串
:param table:
:param columns:
:param ids_length:
:return:
"""
# 校验数据
if not table:
raise ParamError(f"table 参数错误:table={table}")
if not columns or not isinstance(columns, List):
... | 5,337,498 |
def extract_roi(
input_img,
masks_location,
mask_pattern,
cropped_input,
roi_list,
uncrop_output,
):
"""Extracts regions of interest defined by masks
This function extracts regions of interest from preprocessed nifti images.
The regions are defined using binary masks that must be loc... | 5,337,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.