content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def percentiles(a, pcts, axis=None):
"""Like scoreatpercentile but can take and return array of percentiles.
Parameters
----------
a : array
data
pcts : sequence of percentile values
percentile or percentiles to find score at
axis : int or None
if not None, computes scor... | 0e7217ec3e36a361a6747729543cd694912a2874 | 3,657,400 |
import json
def single_request(gh,kname='CVE exploit',page=1,per_page=50):
"""
解析单页仓库数据,获取CVE和exp标记
:return cve_list:list, cve id in each page by searching github.com
"""
cve=dict()
url="https://api.github.com/search/repositories?q={key_name}&sort=updated&order=desc&page={page}&per_page={per_p... | 5fdd3fe28f0e973fb9d854e20b8ce77ed109d3c6 | 3,657,401 |
def ownerOf(tokenId: bytes) -> UInt160:
"""
Get the owner of the specified token.
The parameter tokenId SHOULD be a valid NFT. If not, this method SHOULD throw an exception.
:param tokenId: the token for which to check the ownership
:type tokenId: ByteString
:return: the owner of the specified... | 68f164a377f59614f6c1287b97a53ca14937800f | 3,657,402 |
def stuff_context(sites, rup, dists):
"""
Function to fill a rupture context with the contents of all of the
other contexts.
Args:
sites (SiteCollection): A SiteCollection object.
rup (RuptureContext): A RuptureContext object.
dists (DistanceContext): A DistanceContext object.... | 9c197a41414a875942a6df22c03899c3e936967f | 3,657,403 |
def number_to_float(value):
"""The INDI spec allows a number of different number formats, given any, this returns a float
:param value: A number string of a float, integer or sexagesimal
:type value: String
:return: The number as a float
:rtype: Float
"""
# negative is True, if the value i... | 8b754a32848b3e697e0f82dbee4a1c35c560f1be | 3,657,404 |
def spg_line_search_step_length(current_step_length, delta, f_old, f_new,
sigma_one=0.1, sigma_two=0.9):
"""Return next step length for line search."""
step_length_tmp = (-0.5 * current_step_length ** 2 * delta /
(f_new - f_old - current_step_length * delt... | 844cccdfe1ec3f9c2c287384284ceb2ac3530e8e | 3,657,405 |
def group_by_iter(metrics_dict):
"""
Restructure our metrics dictionary to have the last list store all the trials' values \
for a given iteration, instead of all the iterations' values for a given trial.
:param metrics_dict: data for an experiment (output of parse_party_data)
:type metrics_dict: `... | 469fb0df4d7acb63a982c0aab629031dbb345be6 | 3,657,406 |
def calc_pv_invest(area, kw_to_area=0.125, method='EuPD'):
"""
Calculate PV investment cost in Euro
Parameters
----------
area : float
Photovoltaic area
kw_to_area : float , optional
Ratio of peak power to area (default: 0.125)
For instance, 0.125 means 0.125 kWp / m2 ar... | 2de9ee05580bc9d41522272a06cd97aaf3f5bc55 | 3,657,407 |
def procrustes_2d(x, y, n_restart=10, scale=True):
"""Align two sets of coordinates using an affine transformation.
Attempts to find the affine transformation (composed of a rotation
matrix `r` and a transformation vector `t`) for `y` such that
`y_affine` closely matches `x`. Closeness is measures usin... | f315f475af58419ac95896e8ce25f68f7197294d | 3,657,408 |
def samps2ms(samples: float, sr: int) -> float:
"""samples to milliseconds given a sampling rate"""
return (samples / sr) * 1000.0 | 49e07ee02984bf0e9a0a54715ef6b6e5a3c87798 | 3,657,409 |
def nice_year(dt, lang=None, bc=False):
"""Format a datetime to a pronounceable year.
For example, generate 'nineteen-hundred and eighty-four' for year 1984
Args:
dt (datetime): date to format (assumes already in local timezone)
lang (string): the language to use, use Mycroft default langua... | 641195195023ecca030f6cd8d12ff9a3fc9c989c | 3,657,410 |
def get_results(job_id):
"""
Get the result of the job based on its id
"""
try:
job = Job.fetch(job_id, connection=conn)
if job.is_finished:
return jsonify({
"status": "finished",
"data": job.result
}), 200
elif job.is_f... | ada9042cd4d7961415ec274a68631f6e9af81fad | 3,657,411 |
def get_clean_dict(obj: HikaruBase) -> dict:
"""
Turns an instance of a HikaruBase into a dict without values of None
This function returns a Python dict object that represents the hierarchy
of objects starting at ``obj`` and recusing into any nested objects.
The returned dict **does not** include ... | 3daca47b6d8c42fca8856221f39b635791eb0fce | 3,657,412 |
def generate_html_frieze(type, value):
"""
Gets the data to be able to generate the frieze.
Calls the function to actually generate HTML.
Input:
- Type (session or dataset) of the second input
- A SQLAlchemy DB session or a dataset (list of mappings)
Output:
- The HTML to be... | ddf914d9d710e60af48a6dc687a9e3961ab0cf94 | 3,657,413 |
import os
def get_folder_name(path, prefix=''):
"""
Look at the current path and change the name of the experiment
if it is repeated
Args:
path (string): folder path
prefix (string): prefix to add
Returns:
string: unique path to save the experiment
"""
if prefix == '... | 126648fbe460581272eedafc8599a3af1ded07e4 | 3,657,414 |
from typing import Optional
import re
def instantiate_model(model_to_train: str,
dataset_directory: str,
performance_directory: str,
gpu: Optional[bool] = None):
"""
A function to create the instance of the imported Class,
Classifier.
Ar... | 8053053b5e77f1c74404826e7335b05bece8b99f | 3,657,415 |
def generate_hmac_key():
"""
Generates a key for use in the :func:`~securitylib.advanced_crypto.hmac` function.
:returns: :class:`str` -- The generated key, in byte string.
"""
return generate_secret_key(HMAC_KEY_MINIMUM_LENGTH) | 877cf9fbe56b6715f1744839ce83ac1abf9d7da8 | 3,657,416 |
import argparse
def get_args():
"""! Command line parser for Utterance level classification Leave
one speaker out schema pipeline -- Find Best Models"""
parser = argparse.ArgumentParser(
description='Utterance level classification Leave one '
'speaker out schema pipeline -- Fin... | 4a349da4fe3b570dae359937ed80494075bf26ea | 3,657,417 |
def uscensus(location, **kwargs):
"""US Census Provider
Params
------
:param location: Your search location you want geocoded.
:param benchmark: (default=4) Use the following:
> Public_AR_Current or 4
> Public_AR_ACSYYYY or 8
> Public_AR_Census2010 or 9
:param vintage: (... | bd73acb87f27e3f14d0b1e22ebd06b91fcec9d85 | 3,657,418 |
def getAllItemsWithName(name, cataloglist):
"""Searches the catalogs in a list for all items matching a given name.
Returns:
list of pkginfo items; sorted with newest version first. No precedence
is given to catalog order.
"""
def compare_item_versions(a, b):
"""Internal comparison ... | 0babcd8363918d15d835fb67a37600b960adb942 | 3,657,419 |
def reco_source_position_sky(cog_x, cog_y, disp_dx, disp_dy, focal_length, pointing_alt, pointing_az):
"""
Compute the reconstructed source position in the sky
Parameters
----------
cog_x: `astropy.units.Quantity`
cog_y: `astropy.units.Quantity`
disp: DispContainer
focal_length: `astrop... | 14b7fee325bc8a571a13d257f046cd0e7bf838db | 3,657,420 |
def segment_annotations(table, num, length, step=None):
""" Generate a segmented annotation table by stepping across the audio files, using a fixed
step size (step) and fixed selection window size (length).
Args:
table: pandas DataFrame
Annotation table.
... | 4b1bb8298113b43716fcd5f7d2a27b244f63829c | 3,657,421 |
def get_vdw_style(vdw_styles, cut_styles, cutoffs):
"""Get the VDW_Style section of the input file
Parameters
----------
vdw_styles : list
list of vdw_style for each box, one entry per box
cut_styles : list
list of cutoff_style for each box, one entry per box. For a
box with... | 5cd0825d73e11c4fcb8ecce0526493414842697c | 3,657,422 |
import subprocess
def load_yaml_file(file):
"""
Loads a yaml file from file system.
@param file Path to file to be loaded.
"""
try:
with open(file, 'r') as yaml:
kwargs=ruamel.yaml.round_trip_load(yaml, preserve_quotes=True)
return kwargs
except subprocess.CalledPro... | 7fe74fefcb5dd7068bc0040528670c68e926eaf5 | 3,657,423 |
def freduce(x, axis=None):
"""
Reduces a spectrum to positive frequencies only
Works on the last dimension (contiguous in c-stored array)
:param x: numpy.ndarray
:param axis: axis along which to perform reduction (last axis by default)
:return: numpy.ndarray
"""
if axis is None:
... | 8d13e66a18ef950422af49a68012605cf0d03947 | 3,657,424 |
import os
def init_pretraining_params(exe,
pretraining_params_path,
main_program):
"""load params of pretrained model, NOT including moment, learning_rate"""
assert os.path.exists(pretraining_params_path
), "[%s] cann't be found... | 16d9a3fc2c73613047348f5b6234f5150ca9ef6c | 3,657,425 |
import json
def sort_shipping_methods(request):
"""Sorts shipping methods after drag 'n drop.
"""
shipping_methods = request.POST.get("objs", "").split('&')
assert (isinstance(shipping_methods, list))
if len(shipping_methods) > 0:
priority = 10
for sm_str in shipping_methods:
... | 307ecef020ac296982a7006ce1392cb807461546 | 3,657,426 |
def appendRecordData(record_df, record):
"""
Args:
record_df (pd.DataFrame):
record (vcf.model._Record):
Returns:
(pd.DataFrame): record_df with an additional row of record (SNP) data.
"""
# Alternate allele bases
if len(record.ALT) == 0:
alt0, alt1 = n... | 0904b317e1925743ed9449e1fcb53aaafa2ffc81 | 3,657,427 |
def get_removed_channels_from_file(fn):
"""
Load a list of removed channels from a file.
Raises
------
* NotImplementedError if the file format isn't supported.
Parameters
----------
fn : str
Filename
Returns
-------
to_remove : list of str
List of channels... | ac3cbeb83c7f1305adf343ce26be3f70f8ae48e8 | 3,657,428 |
def invertHomogeneous(M, range_space_homogeneous=False, A_property=None):
""" Return the inverse transformation of a homogeneous matrix.
A homogenous matrix :math:`M` represents the transformation :math:`y = A x + b`
in homogeneous coordinates. More precisely,
..math:
M \tilde{x} = \left[ \begi... | ea9039c935c82686291145652f762eb79404e417 | 3,657,429 |
import string
import os
def rename(level_folder: str) -> int:
"""Rename a custom level folder to the correct name."""
prefix = load_info(level_folder)[PREFIX].strip()
suffix = load_info(level_folder)[SUFFIX].strip()
prefix = prefix.translate(str.maketrans('', '', string.punctuation))
suffix = suff... | 0a35edefd9e27fdbdf1d758142d3cfe8b8907bd4 | 3,657,430 |
import requests
def show_department(department_id):
"""
Returns rendered template to show department with its employees.
:param department_id: department id
:return: rendered template to show department with its employees
"""
url = f'{HOST}api/department/{department_id}'
department = reque... | 170318ea40a4f7355fab77f2aeaaad682b9fab2f | 3,657,431 |
def archive_scan():
"""
Returns converted to a dictionary of functions to apply to parameters of archive_scan.py
"""
# Dictionary of default values setter, type converters and other applied functions
d_applied_functions = {
'favor': [bool_converter, favor_default],
'cnn': [bool_conve... | 71aa3d2c17e880a152529de09b0614dfd619e7da | 3,657,432 |
def esOperador(o):
""""retorna true si 'o' es un operador"""
return o == "+" or o == "-" or o == "/" or o == "*" | 7e1088b641dee7cad2594159c4a34cf979362458 | 3,657,433 |
def valid_identity(identity):
"""Determines whether or not the provided identity is a valid value."""
valid = (identity == "homer") or (identity == "sherlock")
return valid | 9865d19802b596d1d5fdce6ff8d236678da29ee6 | 3,657,434 |
def is_align_flow(*args):
"""
is_align_flow(ea) -> bool
"""
return _ida_nalt.is_align_flow(*args) | 40aa1fb7d86083bc3ace94c6913eb9b4b5ab200e | 3,657,435 |
import time
def avro_rdd(ctx, sqlContext, hdir, date=None, verbose=None):
"""
Parse avro-snappy files on HDFS
:returns: a Spark RDD object
"""
if date == None:
date = time.strftime("year=%Y/month=%-m/day=%-d", time.gmtime(time.time()-60*60*24))
path = '%s/%s' % (hdir, date)
e... | caa923e4b6186e106a59764cbb61f908858acd70 | 3,657,436 |
import random
def generate_gesture_trace(position):
"""
生成手势验证码轨迹
:param position:
:return:
"""
x = []
y = []
for i in position:
x.append(int(i.split(',')[0]))
y.append(int(i.split(',')[1]))
trace_x = []
trace_y = []
for _ in range(0, 2):
tepx = [x[... | 3281cf9e99175190e2855ac98593f67473703c77 | 3,657,437 |
import argparse
def parse_arguments():
"""parse_arguments"""
parser = argparse.ArgumentParser(description="MindSpore Tensorflow weight transfer")
parser.add_argument("--pretrained", default=None, type=str)
parser.add_argument("--name", default="imagenet22k", choices=["imagenet22k",])
args = parser... | 08b57fffe7f95a96f19e35839ca137f9382573ba | 3,657,438 |
def mad_daub_noise_est(x, c=0.6744):
""" Estimate the statistical dispersion of the noise with Median Absolute
Deviation on the first order detail coefficients of the 1d-Daubechies
wavelets transform.
"""
try:
_, cD = pywt.wavedec(x, pywt.Wavelet('db3'), level=1)
except ValueError:
... | 3811d490e344cd4029e5b7f018823ad02c27e3dd | 3,657,439 |
import unicodedata
import re
def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase. Also strip leading and trailing whitespace.
From Django's ... | 3fc85ffec7faa3b4df2d1556dfd7b1d7c3e9920e | 3,657,440 |
import json
def get_categories() -> dict:
""" :return: dictionary with a hirachy of all categories """
with open("../src/categories.json", "r", encoding="utf-8") as f:
return json.load(f) | 90a442840550f3251137b2f9ff8fb5581d8d49e5 | 3,657,441 |
import os
def check_file_integrity(indir, outdir):
""" Parse file in dir and check integrity """
dic_files={}
dic_param={}
dic_integ={}
for f in os.listdir(indir):
path= os.path.join(indir, f)
#if os.path.isdir(path)==True:
# print (str(f) + "is a dir" )
#el... | 48a8bf3d506925b1b41408c3305002365b38413d | 3,657,442 |
def get_ax(rows=1, cols=1, size=16):
"""Return a Matplotlib Axes array to be used in
all visualizations in the notebook. Provide a
central point to control graph sizes.
Adjust the size attribute to control how big to render images
"""
_, ax = plt.subplots(rows, cols, figsize=(size*cols, siz... | 97acc81878076c030287840a0bbacccbde0e50a8 | 3,657,443 |
import argparse
def build_arg_parser():
"""
Builds an argparse object to handle command-line arguments passed in.
"""
parser = argparse.ArgumentParser(description="Loads an ontology file in " +
"OBO file format into a Neo4j graph database.")
parser.add_argument('-i', '-... | 8b9da4a060138b5487f346452c9e3ca85e55b801 | 3,657,444 |
def createSynthModel():
"""Return the modeling mesh, the porosity distribution and the
parametric mesh for inversion.
"""
# Create the synthetic model
world = mt.createCircle(boundaryMarker=-1, segments=64)
tri = mt.createPolygon([[-0.8, -0], [-0.5, -0.7], [0.7, 0.5]],
... | aa63ce6c8b633530efb17add4d902da30c62689c | 3,657,445 |
def edits_dir():
"""
Return the directory for the editable files (used by the
website).
"""
return _mkifnotexists("") | eb882c04e3269496a610103908453a73e4a7ae5f | 3,657,446 |
def get_expected(stage, test_block_config, sessions):
"""Get expected responses for each type of request
Though only 1 request can be made, it can cause multiple responses.
Because we need to subcribe to MQTT topics, which might be formatted from
keys from included files, the 'expected'/'response' nee... | 67c6704b8a70f7eac1301ebcd3caa2bb60e69dba | 3,657,447 |
def convolve_hrf(X, onsets, durations, n_vol, tr, ops=100):
"""
Convolve each X's column iteratively with HRF and align with the timeline of BOLD signal
parameters:
----------
X[array]: [n_event, n_sample]
onsets[array_like]: in sec. size = n_event
durations[array_like]: in sec. size = n_ev... | d035b47ffafe0ac3d7e1446d4d36dc2f707363bd | 3,657,448 |
def flatten(x, params):
"""
Plain ol' 2D flatten
:param x: input tensor
:param params: {dict} hyperparams (sub-selection)
:return: output tensor
"""
return layers.Flatten()(x) | 6db829641681ab48f75b23894f9a4a3250250cec | 3,657,449 |
def xml_unescape(text):
""" Do the inverse of `xml_escape`.
Parameters
----------
text: str
The text to be escaped.
Returns
-------
escaped_text: str
"""
return unescape(text, xml_unescape_table) | 2e53d8bc617ad70fd22bb5dd82cd34db366b80a4 | 3,657,450 |
def tseb_pt(T_air, T_rad, u, p, z, Rs_1, Rs24, vza, zs,
aleafv, aleafn, aleafl, adeadv, adeadn, adeadl,
albedo, ndvi, lai, clump, hc, time, t_rise, t_end,
leaf_width, a_PT_in=1.32, iterations=35):
"""Priestley-Taylor TSEB
Calculates the Priestley Taylor TSEB fluxes using a s... | 6851b00f27b1819e79ce7ed625074c37ac35298f | 3,657,451 |
def GetPrivateIpv6GoogleAccessTypeMapper(messages, hidden=False):
"""Returns a mapper from text options to the PrivateIpv6GoogleAccess enum.
Args:
messages: The message module.
hidden: Whether the flag should be hidden in the choice_arg
"""
help_text = """
Sets the type of private access to Google ser... | 9aa87977be9d0888d572c70d07535c9ec0b9d8f4 | 3,657,452 |
def calc_director(moi):
""" Calculate the director from a moment of inertia.
The director is the dominant eigenvector of the MOI tensor
Parameters:
-----------
moi : list
3x3 array; MOItensor
Returns:
--------
director : list
3 element list of director vector
"""
... | 28f8b3446f83759704d426653dc8f7812e71e900 | 3,657,453 |
def _solve_upper_triangular(A, b):
""" Solves Ax=b when A is upper triangular. """
return solve_triangular(A, b, lower=False) | 5c33d5d10922172a133a478bdfdcb8cf7cd83120 | 3,657,454 |
def check_create_account_key(key):
"""
Returns the user_id if the reset key is valid (matches a user_id and that
user does not already have an account). Otherwise returns None.
"""
query = sqlalchemy.text("""
SELECT user_id
FROM members
WHERE create_account_key = :k
AND user_id NOT IN (SELEC... | b02a710d443410b5b60c31a030d056f3282a5747 | 3,657,455 |
import os
def find_gaia_files_hp(nside, pixlist, neighbors=True):
"""Find full paths to Gaia healpix files in a set of HEALPixels.
Parameters
----------
nside : :class:`int`
(NESTED) HEALPixel nside.
pixlist : :class:`list` or `int`
A set of HEALPixels at `nside`.
neighbors : ... | fec2bc3b73df17617802ef88d586a6b895d2af32 | 3,657,456 |
def _crc16(data, start = _CRC16_START) :
"""Compute CRC16 for bytes/bytearray/memoryview data"""
crc = start
for b in data :
crc ^= b << 8
for _ in range(8) :
crc = ((crc << 1) & 0xFFFF) ^ _CRC16_POLY if crc & 0x8000 else (crc << 1)
return crc | e6e33471601d3126ac7873b61e23f843349e8e90 | 3,657,457 |
import json
def load_json():
"""Load the translation dictionary."""
try:
with open(JSON_FILENAME, "r", encoding="utf8") as file:
known_names = json.load(file)
if "version" in known_names:
if known_names.get("version") < JSON_VERSION:
print("U... | d263411d0c0aae7bba30f92c5af22dd7ff596542 | 3,657,458 |
def get_username() -> str:
"""
Prompts the user to enter a username and then returns it
:return: The username entered by the user
"""
while True:
print("Please enter your username (without spaces)")
username = input().strip()
if ' ' not in username:
return usernam... | 1a18a229908b86c32a0822c068b5b9081cc9fdc3 | 3,657,459 |
def condition(f):
"""
Decorator for conditions
"""
@wraps(f)
def try_execute(*args, **kwargs):
try:
res, m = f(*args, **kwargs)
m.conditions_results.append(res)
return m
except Exception as e:
raise ConditionError(e)
return try_ex... | fb05645861c7aa234f894cc8eee3689e1f1293c9 | 3,657,460 |
def get_spatial_anomalies(
coarse_obs_path, fine_obs_rechunked_path, variable, connection_string
) -> xr.Dataset:
"""Calculate the seasonal cycle (12 timesteps) spatial anomaly associated
with aggregating the fine_obs to a given coarsened scale and then reinterpolating
it back to the original spatial re... | 54dc830e9eb6b7440abf5857141ab369d8d45358 | 3,657,461 |
def get_pip_package_name(provider_package_id: str) -> str:
"""
Returns PIP package name for the package id.
:param provider_package_id: id of the package
:return: the name of pip package
"""
return "apache-airflow-providers-" + provider_package_id.replace(".", "-") | e7aafbdfb0e296e60fedfcf7e4970d750e4f3ffa | 3,657,462 |
import numpy
def func_asymmetry_f_b(z, flag_z: bool = False):
"""Function F_b(z) for asymmetry factor.
"""
f_a , dder_f_a = func_asymmetry_f_a(z, flag_z=flag_z)
res = 2*(2*numpy.square(z)-3)*f_a
dder = {}
if flag_z:
dder["z"] = 8 * z * f_a + 2*(2*numpy.square(z)-3)*dder_f_a["z"]
re... | 5fc157856c379267c12137551f0eb5e6c4ddd3aa | 3,657,463 |
def parse_args():
"""Command-line argument parser for generating scenes."""
# New parser
parser = ArgumentParser(description='Monte Carlo rendering generator')
# Rendering parameters
parser.add_argument('-t', '--tungsten', help='tungsten renderer full path', default='tungsten', type=str)
parse... | 4fad89d60f5446f9dbd66f4624a43b9436ee97a5 | 3,657,464 |
def unique_id(token_id):
"""Return a unique ID for a token.
The returned value is useful as the primary key of a database table,
memcache store, or other lookup table.
:returns: Given a PKI token, returns it's hashed value. Otherwise, returns
the passed-in value (such as a UUID token ID ... | 9526e483f617728b4a9307bd10097c78ec361ad0 | 3,657,465 |
def encode_aval_types(df_param: pd.DataFrame, df_ret: pd.DataFrame, df_var: pd.DataFrame,
df_aval_types: pd.DataFrame):
"""
It encodes the type of parameters and return according to visible type hints
"""
types = df_aval_types['Types'].tolist()
def trans_aval_type(x):
... | a68ff812f69c264534daf16935d88f528ba35464 | 3,657,466 |
def first(iterable, default=None):
"""
Returns the first item or a default value
>>> first(x for x in [1, 2, 3] if x % 2 == 0)
2
>>> first((x for x in [1, 2, 3] if x > 42), -1)
-1
"""
return next(iter(iterable), default) | 6907e63934967c332eea9cedb5e0ee767a88fe8f | 3,657,467 |
def generate_uuid_from_wf_data(wf_data: np.ndarray, decimals: int = 12) -> str:
"""
Creates a unique identifier from the waveform data, using a hash. Identical arrays
yield identical strings within the same process.
Parameters
----------
wf_data:
The data to generate the unique id for.
... | e12a6a8807d68181f0e04bf7446cf5e381cab3f9 | 3,657,468 |
def aggregate(table, key, aggregation=None, value=None, presorted=False,
buffersize=None, tempdir=None, cache=True):
"""Group rows under the given key then apply aggregation functions.
E.g.::
>>> import petl as etl
>>>
>>> table1 = [['foo', 'bar', 'baz'],
... ... | 22d857001d0dcadaed82a197101125e5ca922e07 | 3,657,469 |
def show_mpls_bypass_lsp_name_extensive_rpc(self, show_lsp_input_info=None, api_timeout=''):
"""
This is an auto-generated method for the PySwitchLib.
**Supported Versions**:
* SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02
**Child Instance Keyword Argument Tuple(s)**:
:type show_lsp_input_inf... | 4819c0f1f9cdd4eb46440cd51656cce5a93b3005 | 3,657,470 |
def most_similar(sen, voting_dict):
"""
Input: the last name of a senator, and a dictionary mapping senator names
to lists representing their voting records.
Output: the last name of the senator whose political mindset is most
like the input senator (excluding, of course, the input se... | 6889d08af21d4007fa01dbe4946748aef0d9e3e6 | 3,657,471 |
def fixed_ro_bci_edge(ascentlat, lat_fixed_ro_ann,
zero_bounds_guess_range=np.arange(0.1, 90, 5)):
"""Numerically solve fixed-Ro, 2-layer BCI model of HC edge."""
def _solver(lat_a, lat_h):
# Reasonable to start guess at the average of the two given latitudes.
init_guess = ... | 544c1747450cac52d161aa267a6332d4902798d1 | 3,657,472 |
def fresh_jwt_required(fn):
"""
A decorator to protect a Flask endpoint.
If you decorate an endpoint with this, it will ensure that the requester
has a valid and fresh access token before allowing the endpoint to be
called.
See also: :func:`~flask_jwt_extended.jwt_required`
"""
@wraps(... | e5f30192c68018a419bb086522217ce86b27e6f6 | 3,657,473 |
import random
def random_small_number():
"""
随机生成一个小数
:return: 返回小数
"""
return random.random() | 45143c2c78dc72e21cbbe0a9c10babd00100be77 | 3,657,474 |
def get_sample(df, col_name, n=100, seed=42):
"""Get a sample from a column of a dataframe.
It drops any numpy.nan entries before sampling. The sampling
is performed without replacement.
Example of numpydoc for those who haven't seen yet.
Parameters
----------
df : pandas.Data... | a4fb8e1bbc7c11026b54b2ec341b85310596de13 | 3,657,475 |
def gen_mail_content(content, addr_from):
"""
根据邮件体生成添加了dkim的新邮件
@param content: string 邮件体内容
@return str_mail: 加上dkim的新邮件
"""
try:
domain = addr_from.split('@')[-1]
dkim_info = get_dkim_info(domain)
if dkim_info:
content = repalce_mail(content, addr_from)
... | 90ad569f8f69b7fa39edab799b41522fddc3ce97 | 3,657,476 |
import warnings
def autocov(ary, axis=-1):
"""Compute autocovariance estimates for every lag for the input array.
Parameters
----------
ary : Numpy array
An array containing MCMC samples
Returns
-------
acov: Numpy array same size as the input array
"""
axis = axis if axi... | e17dcfcbdee37022a5ab98561287f891acfefaf6 | 3,657,477 |
import argparse
def get_args(argv=None):
"""Parses given arguments and returns argparse.Namespace object."""
prsr = argparse.ArgumentParser(
description="Perform a conformational search on given molecules."
)
group = prsr.add_mutually_exclusive_group(required=True)
group.add_argument(
... | 424ac2f714a30e31bce79a31b950e4ade06c8eab | 3,657,478 |
def _optimize_rule_mip(
set_opt_model_func,
profile,
committeesize,
resolute,
max_num_of_committees,
solver_id,
name="None",
committeescorefct=None,
):
"""Compute rules, which are given in the form of an optimization problem, using Python MIP.
Parameters
----------
set_o... | 41c3ace270be4dcb4321e4eeedb23d125e6766c3 | 3,657,479 |
import itertools
def Zuo_fig_3_18(verbose=True):
"""
Input for Figure 3.18 in Zuo and Spence \"Advanced TEM\", 2017
This input acts as an example as well as a reference
Returns:
dictionary: tags is the dictionary of all input and output paramter needed to reproduce that figure.
"""
... | 560272c4c28c8e0628403573dd76c0573ae9d937 | 3,657,480 |
def subscribe_feed(feed_link: str, title: str, parser: str, conn: Conn) -> str:
"""Return the feed_id if nothing wrong."""
feed_id = new_feed_id(conn)
conn.execute(
stmt.Insert_feed,
dict(
id=feed_id,
feed_link=feed_link,
website="",
title=titl... | 88a49ebaa4f766bfb228dc3ba271e8c98d50da99 | 3,657,481 |
import os
def run(fname):
"""
Create a new C file and H file corresponding to the filename "fname",
and add them to the corresponding include.am.
This function operates on paths relative to the top-level tor directory.
"""
# Make sure we're in the top-level tor directory,
# which contain... | c20130f6f46b4f47996d9a817f93099484b284fd | 3,657,482 |
def process_grid(procstatus, dscfg, radar_list=None):
"""
Puts the radar data in a regular grid
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
2 post-processing
dscfg : dictionary of dictionaries
data set configuration. Acc... | b414fb327d3658cc6f9ba1296ec1226b5d2a7ff6 | 3,657,483 |
def float_to_16(value):
""" convert float value into fixed exponent (8) number
returns 16 bit integer, as value * 256
"""
value = int(round(value*0x100,0))
return value & 0xffff | 0a587e4505c9c19b0cbdd2f94c8a964f2a5a3ccd | 3,657,484 |
def create_keras_one_layer_dense_model(*,
input_size,
output_size,
verbose=False,
**kwargs
):
"""
Notes:
https://www.tensorflow.org/tutorials/keras/save_and_load
"""
# ...................................................
# Create model
model = Seq... | d7d34d9981aac318bca5838c42ed7f844c27cfda | 3,657,485 |
def API_encrypt(key, in_text, formatting:str = "Base64", nonce_type:str = "Hybrid"):
""" Returns: Input Text 147 Encrypted with Input Key. """
try:
# Ensure an Appropriate Encoding Argument is Provided.
try: encoding = FORMATS[formatting]
except: raise ValueError("Invalid Encoding Argume... | d7336197ba1d32d89c8dc0c098bfbc20c795168d | 3,657,486 |
def convert_log_dict_to_np(logs):
"""
Take in logs and return params
"""
# Init params
n_samples_after_warmup = len(logs)
n_grid = logs[0]['u'].shape[-1]
u = np.zeros((n_samples_after_warmup, n_grid))
Y = np.zeros((n_samples_after_warmup, n_grid))
k = np.zeros((n_samples_after_warmu... | 1962fa563ee5d741f7f1ec6453b7fd5693efeca2 | 3,657,487 |
import os
def get_parent_dir():
"""Returns the root directory of the project."""
return os.path.abspath(os.path.join(os.getcwd(), os.pardir)) | f6c0a43cf2a38f507736f09429b7ca7012739559 | 3,657,488 |
from pathlib import Path
from typing import Callable
def map_links_in_markdownfile(
filepath: Path,
func: Callable[[Link], None]
) -> bool:
"""Dosyadaki tüm linkler için verilen fonksiyonu uygular
Arguments:
filepath {Path} -- Dosya yolu objesi
func {Callable[[Link], None]} -- Link al... | 4f6aa7ee5ecb7aed1df8551a69161305601d0489 | 3,657,489 |
def half_cell_t_2d_triangular_precursor(p, t):
"""Creates a precursor to horizontal transmissibility for prism grids (see notes).
arguments:
p (numpy float array of shape (N, 2 or 3)): the xy(&z) locations of cell vertices
t (numpy int array of shape (M, 3)): the triangulation of p for which the ... | 555f8b260f7c5b3f2e215378655710533ee344d5 | 3,657,490 |
def count_datavolume(sim_dict):
"""
Extract from the given input the amount of time and the memory you need to
process each simulation through the JWST pipeline
:param dict sim_dict: Each key represent a set of simulations (a CAR activity for instance)
each value is a list of ... | dabe86d64be0342486d1680ee8e5a1cb72162550 | 3,657,491 |
import inspect
import sys
def get_exception_class_by_code(code):
"""Gets exception with the corresponding error code,
otherwise returns UnknownError
:param code: error code
:type code: int
:return: Return Exception class associated with the specified API error.
"""
code = int(code)
mo... | 36d42291737a7a18f7ffea07c1d5ffc71a82e8b1 | 3,657,492 |
def context():
"""Return an instance of the JIRA tool context."""
return dict() | e24e859add22eef279b650f28dce4f6732c346b8 | 3,657,493 |
def dist_to_group(idx: int, group_type: str, lst):
"""
A version of group_count that allows for sorting with solo agents
Sometimes entities don't have immediately adjacent neighbors.
In that case, the value represents the distance to any neighbor, e.g
-1 means that an entity one to the left or righ... | 74ae510de4145f097fbf9daf406a6156933bae20 | 3,657,494 |
from typing import AnyStr
from typing import List
from typing import Dict
def get_nodes_rating(start: AnyStr,
end: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
Get the rating by node.
:start (AnyStr) A timestamp, as... | b75d35fc195b8317ed8b84ab42ce07339f2f1bf3 | 3,657,495 |
def f(OPL,R):
""" Restoration function calculated from optical path length (OPL)
and from rational function parameter (R). The rational is multiplied
along all optical path.
"""
x = 1
for ii in range(len(OPL)):
x = x * (OPL[ii] + R[ii][2]) / (R[ii][0] * OPL[ii] + R[ii][1])
return x | 5b64b232646768d2068b114d112a8da749c84706 | 3,657,496 |
def _str_conv(number, rounded=False):
"""
Convenience tool to convert a number, either float or int into a string.
If the int or float is None, returns empty string.
>>> print(_str_conv(12.3))
12.3
>>> print(_str_conv(12.34546, rounded=1))
12.3
>>> print(_str_conv(None))
<BLANKLINE... | d352e8f0956b821a25513bf4a4eecfae5a6a7dcd | 3,657,497 |
def build_eval_graph(input_fn, model_fn, hparams):
"""Build the evaluation computation graph."""
dataset = input_fn(None)
batch = dataset.make_one_shot_iterator().get_next()
batch_holder = {
"transform":
tf.placeholder(
tf.float32,
[1, 1, hparams.n_parts, hparams.n_d... | 3f3d1425d08e964de68e99ea0c6cb4397975427a | 3,657,498 |
def _encodeLength(length):
"""
Encode length as a hex string.
Args:
length: write your description
"""
assert length >= 0
if length < hex160:
return chr(length)
s = ("%x" % length).encode()
if len(s) % 2:
s = "0" + s
s = BinaryAscii.binaryFromHex(s)
le... | fd85d5faf85da6920e4a0704118e41901f327d9c | 3,657,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.