content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def hashed_class_mix_score256(cycle_hash: bytes, identifier: bytes, ip: str, ip_bytes: bytearray) -> int:
"""
Nyzo Score computation from hash of IP start + end of last IP byte to effectively reorder the various c-class and their gaps.
Then complete the score with first half latest IP byte.
That last IP... | 22,800 |
def test_configuration_files(SystemInfo, File):
"""
Test if configuration settings added
"""
config_file_path = ''
if SystemInfo.distribution == 'ubuntu':
config_file_path = '/opt/mongodb/mms/conf/conf-mms.properties'
config_file = File(config_file_path)
assert config_file.contain... | 22,801 |
def test_pickle():
"""This test refers to PR #4 which adds pickle support."""
original_table = Table({'a': [1, 2, 3], 'b': [4, 5, 6]})
serialized_table = pickle.dumps(original_table)
deserialized_table = pickle.loads(serialized_table)
assert original_table.keys == deserialized_table.keys
asser... | 22,802 |
def processShowListFile(suppliedFile):
"""Search for each show entry in file line by line."""
with open(suppliedFile) as f:
for line in f:
lineContents = line.split()
if len(lineContents) < 3:
try:
print "%s entry is incorrectly fo... | 22,803 |
def distance_vinchey(f, a, start, end):
"""
Uses Vincenty formula for distance between two Latitude/Longitude points
(latitude,longitude) tuples, in numeric degrees. f,a are ellipsoidal parameters
Returns the distance (m) between two geographic points on the ellipsoid and the
... | 22,804 |
def plotCTbs(bcount, idx):
"""
Plots data points, individual, and mean curve of both control and treatment group for a bootstrapping sample
:param bcount: index of bootstrapping sample
:param idx: index of the selection
"""
fdgrp0tme_arr = np.array(fulldataS[bcount][fulldat... | 22,805 |
def py_cpu_nms(dets, thresh):
"""Pure Python NMS baseline."""
# x1、y1、x2、y2、以及score赋值
dets = np.array(dets)
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
#每一个检测框的面积
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
#按照score置信度降序排序
order = score... | 22,806 |
def _romanize(word: str) -> str:
"""
:param str word: Thai word to be romanized, should have already been tokenized.
:return: Spells out how the Thai word should be pronounced.
"""
if not isinstance(word, str) or not word:
return ""
word = _replace_vowels(_normalize(word))
res = _RE... | 22,807 |
def lookup_beatmap(beatmaps: list, **lookup):
""" Finds and returns the first beatmap with the lookup specified.
Beatmaps is a list of beatmap dicts and could be used with beatmap_lookup().
Lookup is any key stored in a beatmap from beatmap_lookup().
"""
if not beatmaps:
return None
fo... | 22,808 |
def scott(
x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None
) -> float:
"""Scott similarity
Scott, W. A. (1955).
Reliability of content analysis: The case of nominal scale coding.
Public opinion quarterly, 321-325.
Args:
x (BinaryFeatureVector): binary f... | 22,809 |
def write_coverage_file(coverage_file_path: Path, exit_code: int, coverage_content):
"""Write the formatted coverage to file."""
with open(coverage_file_path, "w", encoding="utf-8") as f:
if exit_code == 0:
f.write("## Coverage passed ✅\n\n")
else:
f.write("## Coverage fa... | 22,810 |
def test_genesis_hash(genesis_fixture):
"""
py current: 7e2c3861f556686d7bc3ce4e93fa0011020868dc769838aca66bcc82010a2c60
fixtures 15.10.:f68067286ddb7245c2203b18135456de1fc4ed6a24a2d9014195faa7900025bf
py poc6: 08436a4d33c77e6acf013e586a3333ad152f25d31df8b68749d85046810e1f4b
fixtures 19.9... | 22,811 |
def mainmenu_choice(message):
"""Выбор пункта главного меню"""
choice = message.text
if choice == 'Скрин':
take_screenshot(message)
else:
BOT.send_message(message.chat.id, 'Неизвестная команда')
mainmenu(message) | 22,812 |
def get_test_runner():
"""
Returns a test runner instance for unittest.main. This object captures
the test output and saves it as an xml file.
"""
try:
import xmlrunner
path = get_test_dir()
runner = xmlrunner.XMLTestRunner(output=path)
return runner
except Excep... | 22,813 |
def _construct_capsule(geom, pos, rot):
"""Converts a cylinder geometry to a collider."""
radius = float(geom.get('radius'))
length = float(geom.get('length'))
length = length + 2 * radius
return config_pb2.Collider(
capsule=config_pb2.Collider.Capsule(radius=radius, length=length),
rotation=_vec... | 22,814 |
def test_locked_final(tmpdir):
"""The auto-patch workflow is interrupted by a persistent lock,
auto-patch eventually gives up waiting.
"""
with tmpdir.as_cwd():
caller = AutoPatchCaller.get_caller("locked_final", config=no_wait)
caller.run()
caller.check_report() | 22,815 |
def file_root_dir(tmpdir_factory):
"""Prepares the testing dirs for file tests"""
root_dir = tmpdir_factory.mktemp('complex_file_dir')
for file_path in ['file1.yml',
'arg/name/file2',
'defaults/arg/name/file.yml',
'defaults/arg/name/file2',
... | 22,816 |
def path_nucleotide_length(g: BifrostDiGraph, path: Iterable[Kmer]) -> int:
"""Compute the length of a path in nucleotides."""
if not path:
return 0
node_iter = iter(path)
start = next(node_iter)
k = g.graph['k']
length = g.nodes[start]['length'] + k - 1
prev = start
for n in... | 22,817 |
def extract_static_links(page_content):
"""Deliver the static asset links from a page source."""
soup = bs(page_content, "html.parser")
static_js = [
link.get("src")
for link in soup.findAll("script")
if link.get("src") and "static" in link.get("src")
]
static_images = [
... | 22,818 |
def zero_inflated_nb(n, p, phi=0, size=None):
"""Models a zero-inflated negative binomial
Something about hte negative binomail model here...
This basically just wraps the numpy negative binomial generator,
where the probability of a zero is additionally inflated by
some probability, psi...
P... | 22,819 |
def test_missing_properties():
# pylint: disable=line-too-long
"""Test that ValueError is raised if an embedded representation does not have properties attribute.
1. Create an embedded representation marshaler for an object without properties attribute.
2. Try to call marshal_properties method.
3. ... | 22,820 |
async def get_bot_queue(
request: Request,
state: enums.BotState = enums.BotState.pending,
verifier: int = None,
worker_session = Depends(worker_session)
):
"""Admin API to get the bot queue"""
db = worker_session.postgres
if verifier:
bots = await db.fetch("SELECT bot_id, prefix,... | 22,821 |
def ask_for_rating():
"""Ask the user for a rating"""
heading = '{} {}'.format(common.get_local_string(30019),
common.get_local_string(30022))
try:
return int(xbmcgui.Dialog().numeric(heading=heading, type=0,
defaultt=''))
... | 22,822 |
def exec_file(filename, globals=None, locals=None):
"""Execute the specified file, optionaly setup its context by using globals and locals."""
if globals is None:
globals = {}
if locals is None:
locals = globals
locals['__file__'] = filename
from py import path
from _pytest impor... | 22,823 |
def isthai(text,check_all=False):
"""
สำหรับเช็คว่าเป็นตัวอักษรภาษาไทยหรือไม่
isthai(text,check_all=False)
text คือ ข้อความหรือ list ตัวอักษร
check_all สำหรับส่งคืนค่า True หรือ False เช็คทุกตัวอักษร
การส่งคืนค่า
{'thai':% อักษรภาษาไทย,'check_all':tuple โดยจะเป็น (ตัวอักษร,True หรือ False)}
"""
listext=list(t... | 22,824 |
def _convert_object_array(
content: List[Scalar], dtype: Optional[DtypeObj] = None
) -> List[Scalar]:
"""
Internal function ot convert object array.
Parameters
----------
content: list of processed data records
dtype: np.dtype, default is None
Returns
-------
arrays: casted con... | 22,825 |
def update_room_time(conn, room_name: str, req_time: int) -> int:
"""部屋のロックを取りタイムスタンプを更新する
トランザクション開始後この関数を呼ぶ前にクエリを投げると、
そのトランザクション中の通常のSELECTクエリが返す結果がロック取得前の
状態になることに注意 (keyword: MVCC, repeatable read).
"""
cur = conn.cursor()
# See page 13 and 17 in https://www.slideshare.net/ichirin2501... | 22,826 |
def search_db_via_query(query):
"""Function that checks database for matching entries with user input.
The function takes the user input and adds it to the used sql command to search for matching entries in the provided database
if there are matching entries these will be printed in the python console
... | 22,827 |
def get_layer_coverage(cat, store, store_obj):
"""Get correct layer coverage from a store."""
coverages = cat.mosaic_coverages(store_obj)
# Find the correct coverage
coverage = None
for cov in coverages["coverages"]["coverage"]:
if store == cov['name']:
coverage = cov
... | 22,828 |
def test_bsplines(tmp_path, testnum):
"""Test idempotency of B-Splines interpolation + approximation."""
targetshape = (10, 12, 9)
# Generate an oblique affine matrix for the target - it will be a common case.
targetaff = nb.affines.from_matvec(
nb.eulerangles.euler2mat(x=0.9, y=0.001, z=0.001)... | 22,829 |
def retarget(songs, duration, music_labels=None, out_labels=None,
out_penalty=None, volume=None, volume_breakpoints=None,
springs=None, constraints=None,
min_beats=None, max_beats=None,
fade_in_len=3.0, fade_out_len=5.0,
**kwargs):
"""Retarget a song ... | 22,830 |
def st_get_ipfs_cache_path(user_did):
"""
Get the root dir of the IPFS cache files.
:param user_did: The user DID
:return: Path: the path of the cache root.
"""
return _st_get_vault_path(user_did) / 'ipfs_cache' | 22,831 |
def create_img_caption_int_data(filepath):
""" function to load captions from text file and convert them to integer
format
:return: dictionary with image ids and associated captions in int format
"""
print("\nLoading caption data : started")
# load caption data
img_caption_dict = load... | 22,832 |
def process_submission(submission_id, chain=True):
"""
Handles the uploading of a submission.
"""
assert Submission.objects.filter(id=submission_id).count() > 0, "Submission {} does not exist!".format(submission_id)
assert SubmissionState.objects.filter(submission_id=submission_id).count() > 0, "Sub... | 22,833 |
def eigenvector_2d_symmetric(a, b, d, eig, eps=1e-8):
"""Returns normalized eigenvector corresponding to the provided eigenvalue.
Note that this a special case of a 2x2 symmetric matrix where every element of the matrix is passed as an image.
This allows the evaluation of eigenvalues to be vectorized over ... | 22,834 |
def write_func_tsvs(file_dataframe):
"""
Given a complete dataframe of files, writes appropriate tsvs for func files.
Parameters
----------
file_dataframe : DataFrame
DataFrame created by organize_files() containing metadata about each file
"""
for subject in file_dataframe:
... | 22,835 |
def update_atoms_from_calc(atoms, calc=None, calc_prefix=''):
"""Update information in atoms from results in a calculator
Args:
atoms (ase.atoms.Atoms): Atoms object, modified in place
calc (ase.calculators.Calculator, optional): calculator to take results from.
Defaults to :attr:`a... | 22,836 |
def get_protection_path_name(protection: Optional[RouteProtection]) -> str:
"""Get the protection's path name."""
if protection is None:
return DEFAULT_PROTECTION_NAME
return protection | 22,837 |
def _get_object_description(target):
"""Return a string describing the *target*"""
if isinstance(target, list):
data = "<list, length {}>".format(len(target))
elif isinstance(target, dict):
data = "<dict, length {}>".format(len(target))
else:
data = target
return data | 22,838 |
def build_tf_xlnet_to_pytorch_map(model, config, tf_weights=None):
""" A map of modules from TF to PyTorch.
I use a map to keep the PyTorch model as
identical to the original PyTorch model as possible.
"""
tf_to_pt_map = {}
if hasattr(model, "transformer"):
if hasattr(model, "l... | 22,839 |
def dynamicviewset(viewset):
"""
The activate route only makes sense if
user activation is required, remove the
route if activation is turned off
"""
if not settings['REQUIRE_ACTIVATION'] and hasattr(viewset, 'activate'):
delattr(viewset, 'activate')
return viewset | 22,840 |
def generate_arabic_place_name(min_length=0):
"""Return a randomly generated, potentially multi-word fake Arabic place name"""
make_name = lambda n_words: ' '.join(random.sample(place_names, n_words))
n_words = 3
name = make_name(n_words)
while len(name) < min_length:
n_words += 1
n... | 22,841 |
def main():
"""
Run each of the functions and store the results to be reported on in a
results file
"""
system_info = {}
args = handle_arguments()
system_info['profile'] = get_os_info(args.verbose)
system_info['compatability'] = check_system_type(
system_info.get('profile').get('... | 22,842 |
def find_cutoffs(x,y,crdist,deltas):
"""function for identifying locations of cutoffs along a centerline
and the indices of the segments that will become part of the oxbows
from MeanderPy
x,y - coordinates of centerline
crdist - critical cutoff distance
deltas - distance between neighboring poin... | 22,843 |
def task_gist_submodule():
"""load gist as submodules from api data"""
import sqlite_utils, sqlite3, json
db = sqlite_utils.Database(sqlite3.connect(SETTINGS.db))
table = db["gist"]
for row in table.rows:
if not row["public"]:
continue
if not row["description"]:
... | 22,844 |
def test_show_navbar_depth(sphinx_build_factory):
"""Test with different levels of show_navbar_depth."""
sphinx_build = sphinx_build_factory(
"base",
confoverrides={"html_theme_options.show_navbar_depth": 2},
).build(
assert_pass=True
) # type: SphinxBuild
sidebar = sphinx_b... | 22,845 |
def log_stdout() -> logging.Logger:
"""
Returns stdout logging object
"""
log_level = logging.INFO
log = logging.getLogger("stdout_logger")
if not log.handlers:
log.setLevel(log_level)
sh = logging.StreamHandler(sys.stdout)
sh.setFormatter(formatter)
log.addHandle... | 22,846 |
def training_set_multiplication(training_set, mult_queue):
"""
Multiply the training set by all methods listed in mult_queue.
Parameters
----------
training_set :
set of all recordings that will be used for training
mult_queue :
list of all algorithms that will take one recordin... | 22,847 |
def addDictionaryFromWeb(url, params=None, **kwargs):
"""
指定した URL にあるページに含まれる辞書メタデータ(JSON-LD)を取得し、
メタデータに記載されている URL から地名解析辞書(CSVファイル)を取得し、
データベースに登録します。
既に同じ identifier を持つ辞書データがデータベースに登録されている場合、
削除してから新しい辞書データを登録します。
登録した辞書を利用可能にするには、 ``setActivateDictionaries()``
または ``activateDict... | 22,848 |
def test_nested_blocks(pprint):
"""
Expected result:
procedure test(x, y: Integer);
begin
x:=1;
y:=200;
for z:= 1 to 100 do
begin
x := x + z;
end;
y:=x;
end;
"""
def brk(offset=0):
"force a new line and indent by given offset"
return T.BREAK(blankSpace... | 22,849 |
async def read(
sensors: Sequence[Sensor], msg: str = "", retry_single: bool = False
) -> bool:
"""Read from the Modbus interface."""
global READ_ERRORS # pylint:disable=global-statement
try:
try:
await SUNSYNK.read(sensors)
READ_ERRORS = 0
return True
... | 22,850 |
def initindex():
"""Delete all information from the elastic search Index."""
click.echo('Loading data into Elastic Search')
from app import data_loader
data_loader = data_loader.DataLoader()
data_loader.build_index() | 22,851 |
def boxlist_iou_guide_nms(boxlist, nms_thresh, max_proposals=-1, score_field="scores"):
"""
Performs non-maximum suppression on a boxlist, with scores specified
in a boxlist field via score_field.
Arguments:
boxlist(BoxList)
nms_thresh (float)
max_proposals (int): if > 0, then o... | 22,852 |
def parse(tokens:list):
"""Transforme la liste des tokens en un arbre d'instructions ou de valeurs"""
ouverts=Pile(newnode(tokens[0]))
for token in tokens:
if token[0]=="balise":
if token[1][0]=="/":
if ouverts.top.REPR.lower()[:len(token[1])-1]!=token[1][1:]:
print(f"A tag has been opened({ouve... | 22,853 |
def get_payload_bin(payload, seconds):
"""
Since we can't run the ysoserial.exe file in ubuntu (at least not
easily with mono) we build the different payloads in windows and
save them to the PAYLOADS map above.
:param payload: The payload name
:param seconds: The seconds to wait
:return: Th... | 22,854 |
def srange(start, step, length, dtype=None):
"""
Like np.arange() but you give the start, the step, and the number
of steps. Saves having to compute the end point yourself.
"""
stop = start + (step * length)
return np.arange(start, stop, step, dtype) | 22,855 |
def get_tool_by_id(tool_id):
"""
returns the tool given the id
"""
tool = ToolType.objects.get(pk=tool_id)
return tool | 22,856 |
def domainr(text):
"""<domain> - uses domain.nr's API to search for a domain, and similar domains
:type text: str
"""
try:
data = http.get_json('http://domai.nr/api/json/search?q=' + text)
except (http.URLError, http.HTTPError):
return "Unable to get data for some reason. Try again l... | 22,857 |
def manage_blog():
""" 博文管理页面路由 """
if 'adminname' in session:
if request.method == 'POST':
del_result = manage_del_blog(db, Post, Comment, request.form.get('edit_id'))
return del_result
else:
blog_list = Post.query.order_by(Post.post_time.desc()).all()
... | 22,858 |
def split(nodes, index, axis=0):
"""
Split a array of nodes into two separate, non-overlapping arrays.
Parameters
----------
nodes : numpy.ndarray
An N x M array of individual node coordinates (i.e., the
x-coords or the y-coords only)
index : int
The leading edge of wher... | 22,859 |
def smart_oracle(oracle, text, code, block_len, max_rand):
"""Call oracle normally, or repeatedly call oracle in case of random prefix.
Returns "clean" oracle ouptut regardless of whether the oracle adds a
random prefix.
"""
if not max_rand:
return oracle(text, code) if code else oracle(text... | 22,860 |
def initializeMotorController(mc: BaseMotorController):
"""
Initializes a motor controller to an "initial state" (applies common settings).
: param mc : A VictorSPX or TalonSRX to initialize.
"""
if not wpilib.RobotBase.isSimulation():
mc.configFactoryDefault()
mc.configFactoryDefault(timeout)
mc... | 22,861 |
def start_active_span_from_edu(
edu_content,
operation_name,
references=[],
tags=None,
start_time=None,
ignore_active_span=False,
finish_on_close=True,
):
"""
Extracts a span context from an edu and uses it to start a new active span
Args:
edu_content (dict): and edu_con... | 22,862 |
async def setup():
"""
Create a clean test database every time the tests are run.
"""
async with db.with_bind(DB_URL):
alembic_config = Config('./alembic.ini')
command.upgrade(alembic_config, 'head')
yield | 22,863 |
def inference_video_feed(request, project_id):
"""inference_video_feed
"""
return Response({
"status": "ok",
"url": "http://" + inference_module_url() + "/video_feed?inference=1",
}) | 22,864 |
def extract_start_timestamp() -> datetime:
"""Define extraction start timestamp.
Returns:
Extraction start timestamp used for testing.
"""
timestamp = datetime(2019, 8, 6, tzinfo=timezone.utc)
return timestamp | 22,865 |
def phi_pdf(X, corr=None):
"""
Standard normal PDF/Multivariate pdf.
**Input:**
* **X** (`float`)
Argument.
* **corr** (`ndarray`)
Correlation matrix.
**Output**
Standard normal PDF of X.
"""
norm_pdf = None
if isinstance(X, int) or isinstance(X, float):
... | 22,866 |
def computeStatistic( benchmarks, field, func ):
"""
Return the result of func applied to the values of field in benchmarks.
Arguments:
benchmarks: The list of benchmarks to gather data from.
field: The field to gather from the benchmarks.
func: The function to apply to the data... | 22,867 |
def bus_update_request(payload):
"""Parser for `bus_update_request` tracepoint"""
try:
match = re.match(bus_update_request_pattern, payload)
if match:
match_group_dict = match.groupdict()
return BusUpdateRequest(**match_group_dict)
except Exception as e:
raise... | 22,868 |
def update_employee(request,id):
"""
Updating the employee profile.
"""
try:
obj = User.objects.get(id=id)
total_cl = obj.no_of_cl
total_sl = obj.no_of_sl
total_wh = obj.no_of_wh
attendance_cl = Attendance.objects.filter(id=id,leave_type='... | 22,869 |
def func(TI, S0, alpha, T1):
""" exponential function for T1-fitting.
Args
----
x (numpy.ndarray): Inversion times (TI) in the T1-mapping sequence as input for the signal model fit.
Returns
-------
a, b, T1 (numpy.ndarray): signal model fitted parameters.
"""
mz = 1 - alp... | 22,870 |
def validate(spec):
"""Decorator to validate a REST endpoint input.
Uses the schema defined in the openapi.yml file
to validate.
"""
def validate_decorator(func):
@functools.wraps(func)
def wrapper_validate(*args, **kwargs):
try:
data = request.get_json(... | 22,871 |
def make_random_coordinate():
""" Make a random coordinate dictionary"""
return make_coordinate(randint(0, 100), randint(0, 100)) | 22,872 |
def smiles_to_antechamber(
smiles_string,
gaff_mol2_filename,
frcmod_filename,
residue_name="MOL",
strictStereo=False,
):
"""Build a molecule from a smiles string and run antechamber,
generating GAFF mol2 and frcmod files from a smiles string. Charges
will be generated using the OpenEye... | 22,873 |
def analyze():
""" kicks bottle to separate from other things """
output = bottle_finder.detect_bottle()
if output:
print("Bottle found")
belt_controller.write(b'b')
print('kicked')
return
print("Bottle not detected")
belt_controller.write(b'n') | 22,874 |
def inv_qft_core(qubits):
"""
Generates a quil programm that performs
inverse quantum fourier transform on given qubits
without swaping qubits at the end.
:param qubits: A list of qubit indexes.
:return: A Quil program to compute the invese QFT of the given qubits without swapping.
""... | 22,875 |
def analysis_precheck(_id, feature_table, rep_seqs, taxonomy, metadata):
"""
Do prechecks as to decrease the chance of job failing.
Input:
- feature_table: QIIME2 artifact of type FeatureTable[Frequency]
- rep_seqs: QIIME2 artifact of type FeatureData[Sequence]
"""
feature_table_path = save_uploaded_file(_id,... | 22,876 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Deluge from a config entry."""
host = entry.data[CONF_HOST]
port = entry.data[CONF_PORT]
username = entry.data[CONF_USERNAME]
password = entry.data[CONF_PASSWORD]
api = await hass.async_add_executor_job(
... | 22,877 |
def powerFactor(n):
"""Function to compute power factor given a complex power value
Will this work if we're exporting power? I think so...
"""
# Real divided by apparent
pf = n.real.__abs__() / n.__abs__()
# Determine lagging vs leading (negative).
# NOTE: cmath.phase returns counter-clockwi... | 22,878 |
def send_request(url, raise_errors):
"""
Sends a request to a URL and parses the response with lxml.
"""
try:
response = requests.get(url, headers={'Accept-Language': '*'}, verify=_PEM_PATH)
response.raise_for_status()
doc = html.fromstring(response.text)
return doc
... | 22,879 |
def test_telluric_import():
"""Can we import the module?"""
skymodel = TelluricModel()
assert isinstance(skymodel, torch.nn.Module) | 22,880 |
def _static_idx(idx, size):
"""Helper function to compute the static slice start/limit/stride values."""
assert isinstance(idx, slice)
start, stop, step = idx.indices(size)
if (step < 0 and stop >= start) or (step > 0 and start >= stop):
return 0, 0, 1, False # sliced to size zero
if step > 0:
retur... | 22,881 |
def crop_array(input_array, ylength, xlength=None, orgn=(0,0)):
"""Crops an image in numpy array format. Pads crops outside
of input image with zeros if necessary. If no y dimension
is specified, outputs a square image.
"""
if xlength == None:
xlength = ylength
ylength = int(ylength)
... | 22,882 |
def get_service_defaults(servicename, version, **_):
"""
Load the default configuration for a given service version
Variables:
servicename => Name of the service to get the info
version => Version of the service to get
Data Block:
None
Result example:
{'accepts': '... | 22,883 |
def read_nnet3_model(model_path: str) -> nnet3.Nnet:
"""Read in a nnet3 model in raw format.
Actually if this model is not a raw format it will still work, but this is
not an official feature; it was due to some kaldi internal code.
Args:
model_path: Path to a raw nnet3 model, e.g., "data/fina... | 22,884 |
def flat_list_of_lists(l):
"""flatten a list of lists [[1,2], [3,4]] to [1,2,3,4]"""
return [item for sublist in l for item in sublist] | 22,885 |
def cancel(api, order_ids=None):
"""
DELETE all orders by api["symbol"] (or) by symbol and order_id:
"""
if DETAIL:
print(cancel.__doc__, "symbol", api['symbol'], "order_ids", order_ids)
if order_ids is None:
order_ids = [] # must be a list
# format remote procedure call to excha... | 22,886 |
def prev_next_group(project, group):
"""Return adjacent group objects or None for the given project and group.
The previous and next group objects are relative to sort order of the
project's groups with respect to the passed in group.
"""
# TODO: Profile and optimize this query if necessary
gr... | 22,887 |
def decrypt(mess, key):
"""Decrypt the cypher text using AES decrypt"""
if len(key) % 16 != 0:
a = 16 - len(key) % 16
key = key.ljust(len(key) + a)
cipher = AES.new(key)
plain_txt = cipher.decrypt(mess)
return plain_txt | 22,888 |
def multiVecMat( vector, matrix ):
"""
Pronásobí matici vektorem zprava.
Parametry:
----------
vector: list
Vektor
matrix: list
Pronásobená matice. Její dimenze se musí shodovat s dimenzí
vektoru.
Vrací:
list
Pole velikosti ve... | 22,889 |
def handleEvent(eventKey):
"""Process an incoming Kaku Event.
Retrieve the event data from the key given and call the appropriate handler.
Valid Event Types are mention, post, gather
For gather events, only the data item will be found
For mention and post, action and data will be found
Valid... | 22,890 |
def verify_state(
state_prec_gdf,
state_abbreviation,
source,
year,
county_level_results_df,
office,
d_col=None,
r_col=None,
path=None,
):
"""
returns a complete (StateReport) object and a ((CountyReport) list) for the state.
:state_prec_gdf: (GeoDataFrame) containing pr... | 22,891 |
def remove_profile(serial, profile_id):
"""hubcli doesn't remove profiles so we have to do this server-side."""
r = requests.post(
url=f"https://{ AIRWATCH_DOMAIN }/API/mdm/profiles/{ profile_id }/remove",
json={"SerialNumber": serial},
headers={
"aw-tenant-code": AIRWATCH_KE... | 22,892 |
def ProgressBar(Title, Percent, InProgress=None):
"""Displays a progress bar.
Title - Title of the progress bar. Three periods are automatically added to the end.
Percent - A number 1-100 indicating what percent of the task is done.
Optional:
InProgress - What part of the task is currently bei... | 22,893 |
def skin_detect_percentage(image_dir=None):
"""Skin detection from image."""
result = skin_detect(image_dir)
filename = os.path.join(PROCESSED_DIR, image_dir.split('/')[-1])
if not os.path.exists(PROCESSED_DIR):
os.makedirs(PROCESSED_DIR)
cv2.imwrite(filename, result)
# take pixel ... | 22,894 |
def KELCH(df, n):
"""
Keltner Channel
"""
temp = (df['High'] + df['Low'] + df['Close']) / 3
KelChM = pd.Series(temp.rolling(n).mean(), name='KelChM_' + str(n))
temp = (4 * df['High'] - 2 * df['Low'] + df['Close']) / 3
KelChU = pd.Series(temp.rolling(n).mean(), name='KelChU_' + str(n))
te... | 22,895 |
def find_isotopes(ms, peptides_in_bin, tolerance=0.01):
"""
Find the isotopes between mass shifts using mass difference of C13 and C12, information of amino acids statistics as well.
Paramenters
-----------
ms : Series
Series with mass in str format as index and values float mass shift.
... | 22,896 |
def wait_until_complete(jobs):
"""wait jobs finish"""
return [j.get() for j in jobs] | 22,897 |
def torquery(url):
"""
Uses pycurl to fetch a site using the proxy on the SOCKS_PORT.
"""
output = io.BytesIO()
query = pycurl.Curl()
query.setopt(pycurl.URL, url)
query.setopt(pycurl.PROXY, 'localhost')
query.setopt(pycurl.PROXYPORT, SOCKS_PORT)
query.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS... | 22,898 |
def check_for_negative_residual(vel, data, errors, best_fit_list, dct,
signal_ranges=None, signal_mask=None,
force_accept=False, get_count=False,
get_idx=False, noise_spike_mask=None):
"""Check for negative residual feat... | 22,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.