content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _get_inner_text(html_node):
"""Returns the plaintext of an HTML node.
This turns out to do exactly what we want:
- strips out <br>s and other markup
- replace <a> tags with just their text
- converts HTML entities like and smart quotes into their
unicode equivalents... | 36697baa3ad4bb8b2f33d37109dfbe8513517c13 | 3,635,600 |
from typing import Iterable
from typing import Type
import pkgutil
from typing import cast
from typing import Any
import os
import importlib
def get_all_commands() -> Iterable[Type[Cog]]:
"""
List all applications.
"""
loader = pkgutil.get_loader('figtag.apps')
filename = cast(Any, loader).get_fil... | caeed4994d739194eb87c7f97ed881dd936da417 | 3,635,601 |
def zern_normalisation(nmodes=30):
"""
Calculate normalisation vector.
This function calculates a **nmodes** element vector with normalisation constants for Zernike modes that have not already been normalised.
@param [in] nmodes Size of normalisation vector.
@see <http://research.opt.indiana.edu/Library/VSIA/VSI... | badd1d6f7ec185edcac42e4ec0cc8be748557fdf | 3,635,602 |
def sample_without_replacement(n, N, dtype=np.int64):
"""Returns uniform samples in [0, N-1] without replacement. It will use
Knuth sampling or rejection sampling depending on the parameters n and N.
.. note::
the values 0.6 and 100 are based on empirical tests of the
functions and would n... | d044e09a910f543adb754a6dacd661e985e5bf0f | 3,635,603 |
def bustypes(bus, gen):
"""Builds index lists of each type of bus (C{REF}, C{PV}, C{PQ}).
Generators with "out-of-service" status are treated as L{PQ} buses with
zero generation (regardless of C{Pg}/C{Qg} values in gen). Expects C{bus}
and C{gen} have been converted to use internal consecutive bus numb... | 41f3fd23c217e113f6395475a7920f27199d6dd9 | 3,635,604 |
from typing import Union
from typing import Mapping
from typing import Iterable
from typing import Tuple
from typing import Any
def update_and_return_dict(
dict_to_update: dict, update_values: Union[Mapping, Iterable[Tuple[Any, Any]]]
) -> dict:
"""Update a dictionary and return the ref to the dictionary that... | 8622f96a9d183c8ce5c7f260e97a4cb4420aecc7 | 3,635,605 |
def get_max_value_key(dic):
"""Gets the key for the maximum value in a dict."""
v = np.array(list(dic.values()))
k = np.array(list(dic.keys()))
maxima = np.where(v == np.max(v))[0]
if len(maxima) == 1:
return k[maxima[0]]
# In order to be consistent, always selects the minimum key
... | 56e9c6d54547b16a881bdb110187f36b9812c178 | 3,635,606 |
def main(event, context):
"""一个对时间序列进行线性插值的函数, 并且计算线性意义上的可信度。
"""
timeAxis = event["timeAxis"]
valueAxis = event["valueAxis"]
timeAxisNew = event["timeAxisNew"]
reliable_distance = event["reliable_distance"]
timeAxis = [totimestamp(parser.parse(i)) for i in timeAxis]
timeAxisNew = [... | a5c67afd9f7c9b197c4847394869c27ae145f0bf | 3,635,607 |
import xbmcaddon
def Addon_Info(id='',addon_id=''):
"""
Retrieve details about an add-on, lots of built-in values are available
such as path, version, name etc.
CODE: Addon_Setting(id, [addon_id])
AVAILABLE PARAMS:
(*) id - This is the name of the id you want to retrieve.
The list of buil... | 2fbdca3e5b4486c7fd702db3673433fe17dab4fe | 3,635,608 |
import hashlib
def _hash_string_to_color(string):
"""
Hash a string to color (using hashlib and not the built-in hash for consistency
between runs)
"""
return COLOR_ARRAY[
int(hashlib.sha1(string.encode("utf-8")).hexdigest(), 16) % len(COLOR_ARRAY)
] | 5539fba65f5d4c3cf245faea678f33d05c164aac | 3,635,609 |
def get_build(id):
"""Show metadata for a single build.
**Example request**
.. code-block:: http
GET /builds/1 HTTP/1.1
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 367
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:2... | 3903188dad4236ec3675de893c1c7444fe8322a9 | 3,635,610 |
def get_unity_snapshotschedule_parameters():
"""This method provide parameters required for the ansible snapshot
schedule module on Unity"""
return dict(
name=dict(type='str'),
id=dict(type='str'),
type=dict(type='str', choices=['every_n_hours', 'every_day',
... | a25cb6c62a0a69f2586135677802309e033d86bc | 3,635,611 |
import io
import zipfile
import os
def create_bootloader_win(interpreter_zip, executable, argv):
"""
Prepares executable for execution on target machine. Appends client code to `interpreter_zip` archive. Embeds new
archive into `executable`.
:param interpreter_zip: Zip file containing python runtime, ... | 5c72deb7022682b63fbc9304910b0b8c34eaa124 | 3,635,612 |
def gaussian_kernel(X, kernel_type="gaussian", sigma=3.0, k=5):
"""gaussian_kernel: Build an adjacency matrix for data using a Gaussian kernel
Args:
X (N x d np.ndarray): Input data
kernel_type: "gaussian" or "adaptive". Controls bandwidth
sigma (float): Scalar kernel bandwidth
k... | 6d541e5d1faa12d3b61aa1eb5dba416efb303253 | 3,635,613 |
def get_all_camera_shapes(full_path=True):
"""
Returns all cameras shapes available in the current scene
:param full_path: bool, Whether tor return full path to camera nodes or short ones
:return: list(str)
"""
return maya.cmds.ls(type='camera', long=full_path) or list() | 513207a51bce4ec74ff6bbb08357a0b0b975fffd | 3,635,614 |
def CreateVGGishNetwork(hop_size=0.96): # Hop size is in seconds.
"""Define VGGish model, load the checkpoint, and return a dictionary that points
to the different tensors defined by the model.
"""
vggish_slim.define_vggish_slim()
checkpoint_path = 'vggish_model.ckpt'
vggish_params.EXAMPLE_HOP_SECONDS = h... | dc7725524ede7b02fc9afdf63f8aeecde5c9c092 | 3,635,615 |
def estimate_mpk_parms_1d(
pk_pos_0, x, f,
pktype='pvoigt', bgtype='linear',
fwhm_guess=0.07, center_bnd=0.02
):
"""
Generate function-specific estimate for multi-peak parameters.
Parameters
----------
pk_pos_0 : TYPE
DESCRIPTION.
x : TYPE
DESCRIP... | d1d92548e4d3125bb1df9cea7f5037a262a5594c | 3,635,616 |
from typing import Tuple
from typing import Optional
import json
async def _parse_collection_from_search(
request: Request,
) -> Tuple[Optional[str], Optional[str]]:
"""
Parse the collection id from a search request.
The search endpoint is a bit of a special case. If it's a GET, the collection
an... | 52d392e13dce549905e357dc7a09b592e45d6c9e | 3,635,617 |
import itertools
def make_cnf_clauses_by_group(N_, board_group, varboard_group):
"""
:param board_group: e.g. a row of sudoku board, of shape (M...)
:param varboard_group: e.g. a row of sudoku variable id,
of shape (M..., N_)
"""
cclauses_local = []
board_group = board_group.reshape... | e3dc103a5a1674141780aed4d9af1e1d3eea0927 | 3,635,618 |
from typing import Tuple
def get_operations(
archive_action: str, archive_type: str, compression_type: str
) -> Tuple[Operation]:
"""
A function to fetch relevant operations based on type of archive
and compression if any.
"""
operations = {
"archive_ops": {
"zip": {
... | 39e03759f565a2969a3c50cbe5d314a131d498b4 | 3,635,619 |
import os
def import_spyview_dat(data_dir, filename):
"""
Returns a np.array in the same shape as the raw .dat file
"""
with open(os.path.join(data_dir, filename)) as f:
dat = np.loadtxt(f)
return dat | 2fe12eba01c2fa4f779366bb5232c4ef8b8065c8 | 3,635,620 |
def Norm(norm, *args, **kwargs):
"""
Return an arbitrary `~matplotlib.colors.Normalize` instance. Used to
interpret the `norm` and `norm_kw` arguments when passed to any plotting
method wrapped by `~proplot.axes.cmap_changer`. See
`this tutorial \
<https://matplotlib.org/tutorials/colors/colormapnor... | e3018d77dbd629a367c8cdfb10d13318e388ddd3 | 3,635,621 |
def run_trajectory(
model, time_stop, time_step, initial_state,
seed, n_points=500, docker=None):
"""
Run one trajectory using the given model and initial state
Parameters
----------
model: str
smoldyn model description
time_stop: float
Simulation duration
ti... | 38f497f93fdeb978de420d85fc910cd674c0faf4 | 3,635,622 |
from pathlib import Path
def get_project_root_dir() -> Path:
"""
Gets the Root path of Project
Returns:
Path: of Root project
"""
root_path = _get_script_file()
return root_path.parent | 30de0b9a91770e201cf921a56bb512a67e0dd486 | 3,635,623 |
from typing import Dict
def get_deployment_statuses() -> Dict[str, DeploymentStatusInfo]:
"""Returns a dictionary of deployment statuses.
A deployment's status is one of {UPDATING, UNHEALTHY, and HEALTHY}.
Example:
>>> from ray.serve.api import get_deployment_statuses
>>> statuses = get_deployme... | 00fc586f36256b2a73d1b78dff8d5af79b3f5e8e | 3,635,624 |
def dumps_tikz(g, scale='0.5em'):
"""Return TikZ code as `str` for `networkx` graph `g`."""
s = []
s.append(padding_remove(r"""
\begin{{tikzpicture}}[
signal flow,
pin distance=1pt,
label distance=-2pt,
x={scale}, y={scale},
baseline=(current bounding box.center),
]""").format(scale=scale))
... | 7bca58ded761992d455029055b167568414ef759 | 3,635,625 |
def drawModel(ax, model):
"""
将模型的分离超平面可视化
"""
x1 = np.linspace(ax.get_xlim()[0], ax.get_xlim()[1], 100)
x2 = np.linspace(ax.get_ylim()[0], ax.get_ylim()[1], 100)
X1, X2 = np.meshgrid(x1, x2)
Y = model.predict_proba(np.c_[X1.ravel(), X2.ravel()])[:, 1]
Y = Y.reshape(X1.shape)
ax.cont... | 4e4e464682c970ed90e0db8a06696891af51280a | 3,635,626 |
import sys
def keyboard_interrupt(func):
"""Decorator to be used on a method to check if there was a keyboard interrupt error that was raised."""
def wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except KeyboardInterrupt:
self.close() # this will... | 1914924986c278bb919274b746ce13fb718268e8 | 3,635,627 |
import warnings
def correct_mpl(obj):
"""
This procedure corrects MPL data:
1.) Throw out data before laser firing (heights < 0).
2.) Remove background signal.
3.) Afterpulse Correction - Subtraction of (afterpulse-darkcount).
NOTE: Currently the Darkcount in VAPS is being calculated as
... | 4d1da14d35e26dcd5ebc56fc333969e593ca02f8 | 3,635,628 |
def cutoff_depth(d: int):
"""A cutoff function that searches to depth d."""
return lambda game, state, depth: depth > d | af7396a92f1cd234263e8448a6d1d22b56f4a12c | 3,635,629 |
from typing import Dict
def create_contributor_node(d: Dict, label: str = "Contributor") -> Node:
""" Using the k, v pairs in `d`, create a Node object with those properties.
Takes k, as-is except for 'uuid', which is cast to int.
Args:
d (dict): property k, v pairs
label (str): The py2neo... | bbb83ec8a8c76678c91ea8b009c9e137c03f025b | 3,635,630 |
def extractLipsHaarCascade(haarDetector, frame):
"""Function to extract lips from a frame"""
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
roi_gray = 0
faces = haarDetector.detectMultiScale(gray, 1.3, 5)
if len(faces) == 0:
roi_gray = cv2.resize(gray, (150, 100))
return roi_gray
... | f1d220df5af2dc2d6905aba05344ca04a96de8d5 | 3,635,631 |
import sys
def we_are_frozen():
"""Returns whether we are frozen via py2exe.
This will affect how we find out where we are located."""
return hasattr(sys, "frozen") | 98d9a5b8e304a4e615ab0ffe2548a8e10a348783 | 3,635,632 |
def rgb_to_hex(red, green, blue):
"""Return color as #rrggbb for the given RGB color values."""
return '#%02x%02x%02x' % (int(red), int(green), int(blue)) | 7523bcb4b7a033655c9f5059fcf8d0ed656502c8 | 3,635,633 |
from typing import Callable
def rescue(
function: Callable[
[_SecondType],
KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType],
],
) -> Kinded[Callable[
[KindN[_RescuableKind, _FirstType, _SecondType, _ThirdType]],
KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType],
]]... | c5474129e260729c61f5ecc80e3c1bb714195b25 | 3,635,634 |
def try_get_resource(_xmlroot, parent_node: str, child_node: str, _lang: str):
""" Получить ресурс (решение / условия) """
for tutorial in _xmlroot.find(parent_node).iter(child_node):
lang = tutorial.attrib['language']
_type = tutorial.attrib['type']
if lang == _lang and _type == 'applic... | 7cb362ec0c1e8fb7926b67b3790b8c5bc9539a67 | 3,635,635 |
import os
def download_song(file_name, content):
""" Download the audio file from YouTube. """
_, extension = os.path.splitext(file_name)
if extension in ('.webm', '.m4a'):
link = content.getbestaudio(preftype=extension[1:])
else:
log.debug('No audio streams available for {} type'.form... | df9fcf9b6fd1942aa616f5ebb261ba9a1d3f30d2 | 3,635,636 |
def load_distributed_dataset(split,
batch_size,
name,
drop_remainder,
use_bfloat16,
normalize=False,
with_info=False,
... | 6d2652fdae9acff9cbe3e134dfac6d0df5fbd048 | 3,635,637 |
def get_sample_media():
"""Gets the sample media.
Returns:
bytes
"""
path = request.args.get("path")
# `conditional`: support partial content
return send_file(path, conditional=True) | 9e3d98928096b4261bf3451564791384423524ef | 3,635,638 |
def _is_swiftmodule(path):
"""Predicate to identify Swift modules/interfaces."""
return path.endswith((".swiftmodule", ".swiftinterface")) | 085fa4f8735ce371927f606239d51c44bcca5acb | 3,635,639 |
import itertools
def _unpack_array(fmt, buff, offset, count):
"""Unpack an array of items.
:param fmt: The struct format string
:type fmt: str
:param buff: The buffer into which to unpack
:type buff: buffer
:param offset: The offset at which to start unpacking
:type offset: int
:param... | 4aad2b38a332a9c57e4bb412990b4ba8ffd282dd | 3,635,640 |
def _add_column_and_sort_table(sources, pointing_position):
"""Sort the table and add the column separation (offset from the source) and phi (position angle from the source)
Parameters
----------
sources : `~astropy.table.Table`
Table of excluded sources.
pointing_position : `~astropy.c... | 780fa4cd5ebed99b556cb283f41a52594921db39 | 3,635,641 |
from jsmin import jsmin as jsmin_processor
def jsmin(content):
""" Minify your JavaScript code.
Use `jsmin <https://pypi.python.org/pypi/jsmin>`_ to compress JavaScript.
You must manually install jsmin if you want to use this processor.
Args:
content: your JavaScript code
Returns:
... | 9ab9b29ed74cf798ec868e4fbdf8d5df697e3339 | 3,635,642 |
from typing import IO
import sys
import tempfile
def generate_server_config() -> IO[bytes]:
"""Returns a temporary generated file for use as the server config."""
boards = stm32f429i_detector.detect_boards()
if not boards:
_LOG.critical('No attached boards detected')
sys.exit(1)
config... | d61177fde609be4bfc4803cb5f0aaf92a1bdc040 | 3,635,643 |
import torch
def smooth_l1_loss_detectron2(input, target, beta: float, reduction: str = "none"):
"""
Smooth L1 loss defined in the Fast R-CNN paper as:
| 0.5 * x ** 2 / beta if abs(x) < beta
smoothl1(x) = |
| abs(x) - 0.5 * beta otherwise,
where x = input - targ... | d6e9264e8de9acf3fec59cb70207c1aa4075ece6 | 3,635,644 |
def png_to_jpg(png_path, jpg_path):
""" convert image format: png -> jpg, then save picture with jpg
Args:
png_path (str)
jpg_path (str)
Return:
True or False (bool)
"""
img = Image.open(png_path)
try:
if len(img.split()) == 4:
# prevent IOError: ... | 255f5ed67d8929c05cbf573fcc64c45ff019ece1 | 3,635,645 |
import warnings
import io
def split_lines_to_df(in_lines_trunc_df):
"""
For a column of strings that each represent the line of a CSV
(and each line may have a different number of separators),
read them into a DataFrame.
in_lines_trunc_df: Assumes that the relevant column is `0`
Returns: The ... | eec9624a88f0758d4db2ecafc6df3eaa9e3a3eb2 | 3,635,646 |
def generate_full_vast_beleg_ids_request_xml(form_data, th_fields=None, use_testmerker=False):
""" Generates the full xml for the Verfahren "ElsterDatenabholung" and the Datenart "ElsterVaStDaten",
including "Anfrage" field.
An example xml can be found in the Eric documentation under
common/... | 88dd6e5e374deec62ce1229525bc936e2fb2ac79 | 3,635,647 |
def get_q_vocab(ques, count_thr=0, insert_unk=False):
"""
Args:
ques: ques[qid] = {tokenized_question, ...}
count_thr: int (not included)
insert_unk: bool, insert_unk or not
Return:
vocab: list of vocab
"""
counts = {}
for qid, content in ques.iteritems():
... | 4926a595d2d4bff50db986ad012a21357fb9b8ec | 3,635,648 |
def get_desc_dist(descriptors1, descriptors2):
""" Given two lists of descriptors compute the descriptor distance
between each pair of feature. """
#desc_dists = 2 - 2 * (descriptors1 @ descriptors2.transpose())
desc_sims = - descriptors1 @ descriptors2.transpose()
# desc_sims = d... | 2baea3bfa01b77765ec3ce95fd9a6be742783420 | 3,635,649 |
def _parse_cells_icdar(xml_table):
"""
Gets the table cells from a table in ICDAR-XML format.
"""
cells = list()
xml_cells = xml_table.findall(".//cell")
cell_id = 0
for xml_cell in xml_cells:
text = get_text(xml_cell)
start_row = get_attribute(xml_cell, "start-row"... | fdfca5c77f1122ae14bc8b72a676ab5cafab6c63 | 3,635,650 |
from typing import Optional
from typing import BinaryIO
import requests
import time
def download(link: str,
method: str = "GET",
to_file: Optional[BinaryIO] = None,
headers: Optional[dict] = None,
allow_redirects: bool = True,
max_retries: int = 3) -> "... | e6f62914f89b0de314ce158a5e62c4a42af904f4 | 3,635,651 |
import os
def get_mem_usage():
"""returns percentage and vsz mem usage of this script"""
pid = os.getpid()
psout = os.popen( "ps -p %s u"%pid ).read()
parsed_psout = psout.split("\n")[1].split()
return float(parsed_psout[3]), int( parsed_psout[4] ) | 9d0060f435a1fb0d77a31ce946d7e46ffb7b4762 | 3,635,652 |
import os
import requests
def download_file(url, local_folder=None):
"""Downloads file pointed to by `url`.
If `local_folder` is not supplied, downloads to the current folder.
"""
filename = os.path.basename(url)
if local_folder:
filename = os.path.join(local_folder, filename)
# Downl... | 2229239b4c54c9ef7858b3013cb78d00e0ea2ae0 | 3,635,653 |
def gist_ncar(range, **traits):
""" Generator for the 'gist_ncar' colormap from GIST.
"""
_data = dict(
red = [(0.0, 0.0, 0.0),
(0.0050505050458014011, 0.0, 0.0),
(0.010101010091602802, 0.0, 0.0),
(0.015151515603065491, 0.0, 0.0),
(0.020202020183205605... | f4ade6627bdaba25ae873c76b5b0970f7a650a70 | 3,635,654 |
def main(request, username):
"""
User > Main
"""
namespace = CacheHelper.ns('user:views:main', username=username)
response_data = CacheHelper.io.get(namespace)
if response_data is None:
response_data, user = MainUserHelper.build_response(request, username)
if response_data['sta... | b605987f395b227a481012257c0c04add787cee5 | 3,635,655 |
import copy
def checksum2(path):
"""Calculate the checksum of a TSV.
The checksum of a TSV is calculated as the sum of the division between the
only two numbers in each row that evenly divide each other.
Arguments
---------
path : str
Path to a TSV file.
Returns
-------
... | 01ccbfbd1a2c4258105d5bf9dd46395ebd50b080 | 3,635,656 |
import configparser
def load_config(config_file_path):
"""
Load the config ini, parse settings to WORC
Args:
config_file_path (String): path of the .ini config file
Returns:
settings_dict (dict): dict with the loaded settings
"""
settings = configparser.ConfigParser()
se... | 3f85f3ccd9e635cb9ce021d424ed97e98cbfb75c | 3,635,657 |
import pathlib
def find_toplevel() -> pathlib.Path:
"""Get the toplevel git directory."""
return pathlib.Path(cmd_output(["rev-parse", "--show-toplevel"]).strip()) | 3d2cc723aadcec69b0d86b879e5d720f15d2c5da | 3,635,658 |
def db20(value):
"""Convert voltage-like value to dB."""
return 20 * log10(np.abs(value)) | ef261696d5fd4b3a0f841411e03fc9897a9a9a93 | 3,635,659 |
from typing import Any
def construct_class_by_name(*args, class_name: str = None, **kwargs) -> Any:
"""Finds the python class with the given name and constructs it with the given arguments."""
return call_func_by_name(*args, func_name=class_name, **kwargs) | a666bf509513a8098b0c4deca58141a2957741fb | 3,635,660 |
import csv
def simple_file_scan(reader, bucket_name, region_name, file_name):
""" Does an initial scan of the file, figuring out the file row count and which rows are too long/short
Args:
reader: the csv reader
bucket_name: the bucket to pull from
region_name: the regi... | ccd1aad870124a9b48f05bbe0d7fe510ae36bc33 | 3,635,661 |
import typing
import torch
import copy
def random_plane(model: typing.Union[torch.nn.Module, ModelWrapper], metric: Metric, distance=1, steps=20,
normalization='filter', deepcopy_model=False) -> np.ndarray:
"""
Returns the computed value of the evaluation function applied to the model or agen... | 8c431268a56a1ac929e9b5f272b476cbda64ab70 | 3,635,662 |
def _solarize_impl(pil_img, level):
"""Applies PIL Solarize to `pil_img`.
Translate the image in the vertical direction by `level`
number of pixels.
Args:
pil_img: Image in PIL object.
level: Strength of the operation specified as an Integer from
[0, `PARAMETER_MAX`].
Returns:
A PIL Ima... | d07952a043f61e401cc2c6fc858d43947c68019d | 3,635,663 |
def detect_area(hsv_img,lower_color,upper_color,marker_id,min_size,draw=False):
"""Detects the contour of an object containing a marker based on color
It always returns the smallest contour which still contains the marker
The contour is detected using an image with hsv color space to be robust under di... | 3d6d86a285fd949c35025059c1b7cb4a6a644549 | 3,635,664 |
def payment_callback():
"""通用支付页面回调"""
data = request.params
sn = data['sn']
result = data['result']
is_success = result == 'SUCCESS'
handle = get_pay_notify_handle(TransactionType.PAYMENT, NotifyType.Pay.SYNC)
if handle:
# 是否成功,订单号,_数据
return handle(is_success, sn)
if ... | dc7c2dfaadf47c00fe355f1c82465c38e8bf7c7c | 3,635,665 |
import os
import sqlite3
def get_users_name(path):
"""
登録されているユーザ情報の回収
Parameters
----------
path : str
homeディレクトリまでのパス
Returns
-------
name_dict : dict
登録ユーザ情報の辞書
"""
path_db = os.path.join(path, 'data', 'list.db')
name_list = []
with sqlite3.connect(... | 4a71b52a4dfa1e40eab62134795944b43a774a73 | 3,635,666 |
def get_rest_parameter_state(parameter_parsing_states):
"""
Gets the rest parameter from the given content if there is any.
Parameters
----------
parameter_parsing_states `list` of ``ParameterParsingStateBase``
The created parameter parser state instances.
Returns
-------
p... | e90d1ee848af7666a72d9d0d4fb74e3fedf496fa | 3,635,667 |
def random_user_id() -> str:
"""Return random user id as string."""
return generate_random_id() | ee6a8299a81458bc20d4c0879a9ca4ab0741b790 | 3,635,668 |
import os
import imp
def import_plugin(name):
"""Tries to import given module"""
path = os.path.join(BASE_PATH, "backends", "plugins", name + ".py")
try:
with open(path, 'rb') as f:
try:
plugin = imp.load_module(
"p_" + name, f, name + '.py',
... | 2be34bd5138ac9e74544fcc335659fcfac02e860 | 3,635,669 |
from typing import List
def batch_answer_same_question(question: str, contexts: List[str]) -> List[str]:
"""Answers the question with the given contexts (local mode).
:param question: The question to answer.
:type question: str
:param contexts: The contexts to answer the question with.
:type cont... | 3e013b793cebbb172c90d054e90bb830fbb7009f | 3,635,670 |
def calculate_log_probs(conditioners, joint_dists):
"""
Calculates the marginal log probabilities of each feature's values and also the conditional
log probabilities for the predecessors given in the predecessor map.
"""
log_marginals = [
N.log(joint_dists[f,f])
for f in xrange(len(condi... | dd84cf8b76177aeeb90ca6205402e95b3686b421 | 3,635,671 |
import json
def validate_response_code(response, expected_res):
""" Function to validate work order response.
Input Parameters : response, check_result
Returns : err_cd"""
# check expected key of test case
check_result = {"error": {"code": 5}}
check_result_key = list(check_result.keys(... | caf687ecffbe5deb9d8b458efede71f4c2c0b3be | 3,635,672 |
from scipy.stats import gaussian_kde
def _calc_density(x: np.ndarray, y: np.ndarray):
"""\
Function to calculate the density of cells in an embedding.
"""
# Calculate the point density
xy = np.vstack([x, y])
z = gaussian_kde(xy)(xy)
min_z = np.min(z)
max_z = np.max(z)
# Scale be... | 64ea42d14c933137ffb0efaf3a74d3ca1b4927b0 | 3,635,673 |
from x2paddle.op_mapper.pytorch2paddle import prim2code
def gen_layer_code(graph, sub_layers, sub_layers_name, different_attrs=dict()):
""" 根据sub_layers生成对应的Module代码。
Args:
graph (x2paddle.core.program.PaddleGraph): 整个Paddle图。
sub_layers (dict): 子图的id和其对应layer组成的字典。
sub_layers_name (s... | b4aac353a525405a8eecb82c3b719c419f1e938b | 3,635,674 |
import torch
def test_CreativeProject_integration_ask_tell_one_loop_kwarg_response_works(covars, model_type, train_X, train_Y,
covars_proposed_iter, covars_sampled_iter,
response_sampled... | aba248b5102013ea91f81c380faa922c18449cd9 | 3,635,675 |
import io
def read_all_files(filenames):
"""Read all files into a StringIO buffer."""
return io.StringIO('\n'.join(open(f).read() for f in filenames)) | efb2e3e8f35b2def5f1861ecf06d6e4135797ccf | 3,635,676 |
from typing import Optional
def calculate_distance(geojson, unit: Unit = Unit.meters) -> Optional[float]:
"""
Calculate distance of LineString or MultiLineString GeoJSON.
Raises geojson_length.exc.GeojsonLengthException if input GeoJSON is invalid.
:param geojson: GeoJSON feature of type LineString or... | 5f019f6acf7ff49189ceab7531ffddeef5a15d03 | 3,635,677 |
def weighted_mse_loss(y_true, y_pred):
"""
apply weights on heatmap mse loss to only pick valid keypoint heatmap
since y_true would be gt_heatmap with shape
(batch_size, heatmap_size[0], heatmap_size[1], num_keypoints)
we sum up the heatmap for each keypoints and check. Sum for invalid
keypoint... | 2ad89db78ec78d571a727002d6e62fc6de624965 | 3,635,678 |
def p_marketprices(
i: pd.DatetimeIndex,
avg: float = 100,
year_amp: float = 0.30,
week_amp: float = 0.05,
peak_amp: float = 0.30,
has_unit: bool = True,
) -> pd.Series:
"""Create a more or less realistic-looking forward price curve timeseries.
Parameters
----------
i : pd.Datet... | db51ba10f6dda4f1df77833d29310a97411f0979 | 3,635,679 |
def read_flow(fn):
""" Read .flo file in Middlebury format"""
# Code adapted from:
# http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
# WARNING: this will work on little-endian architectures (eg Intel x86) only!
with open(fn, 'rb') as f:
... | e8b1d39a40b6650bdeb1ae8cf8b8ecd00b45c787 | 3,635,680 |
from typing import List
def sma(grp_df: pd.DataFrame, cols: List[str], windows: List[int]) -> pd.DataFrame:
"""
Calculate the simple moving average.
Parameters:
-------
grp_df: pd.DataFrame
The grouped dataframe.
col: str
window: list
List of windows to take simple moving ... | 12c80365255893330d1ced017019c318f3683587 | 3,635,681 |
def add_anchor_tag(anchor_id, header):
"""
Add anchor tag to header.
Input and output will look like below.
Input:
## Task 02 - Do something
Output:
## <a id="task02"></a> Task 02 - Do something [^](#toc)
"""
anchor = ANCHOR.format(anchor_id)
# Replace the first space w... | 1f58f985cc90d7cb8243a1d593eb89e329e7ccef | 3,635,682 |
from typing import Callable
def create_async_executor(query: Query) -> Callable:
"""Create async executor for query.
Arguments:
query: query for which executor should be created.
Returns:
Created async executor.
"""
executor = _OPERATION_TO_EXECUTOR[query.operation_type]
retu... | 0e13ae11e8096b807615c3cc8812dcd3e5acaed9 | 3,635,683 |
def batch_write_coverage(bed_fname, bam_fname, out_fname, by_count, processes):
"""Run coverage on one sample, write to file."""
cnarr = coverage.do_coverage(bed_fname, bam_fname, by_count, 0, processes)
tabio.write(cnarr, out_fname)
return out_fname | 7b29ed2422181f8a42574368a22da8814693f7f9 | 3,635,684 |
def splitTargets(targetStr):
""" break cmdargs into parts consisting of:
1) cmdargs are already stripped of their first arg
2) list of targets, including their number. Target examples:
* staff
* staff 2
* staff #2
* player
* player #3
"""
... | 4b53a7db8d8b871b21b2d5b9044f1889be462ace | 3,635,685 |
def get_model():
"""
Epoch 50/50
3530/3530 [==============================] - 10s - loss: 8.5420e-04 - acc: 1.0000 - val_loss: 0.3877 - val_acc: 0.9083
1471/1471 [==============================] - 1s
Train score: 0.00226768349974
Train accuracy: 1.0
"""
model=Sequential()... | d2a6baf0071c6d6e37cb9cf43e64e4ec2703b725 | 3,635,686 |
def path_inside_dir(path, directory):
"""
Returns True if the specified @path is inside @directory,
performing component-wide comparison. Otherwise returns False.
"""
return ((directory == "" and path != "")
or path.rstrip("/").startswith(directory.rstrip("/") + "/")) | 30ad431f9115addd2041e4b6c9c1c8c563b93fe9 | 3,635,687 |
import sympy
import os
def tfi_chain(qubits, boundary_condition="closed", data_dir=None):
"""1D Transverse field Ising-model quantum data set.
$$
H = - \sum_{i} \sigma_i^z \sigma_{i+1}^z - g\sigma_i^x
$$
Contains 81 circuit parameterizations corresponding to
the ground states of the 1D TFI c... | f3e352fb7451720575bca3c8eb574de474707fb5 | 3,635,688 |
def generate_sd_grid_mapping_traj(ipath_sd, n_top_grid, ipath_top_grid, ipath_grid_block_gps_range,
odir_sd, mapping_rate=1, mapping_bais=None):
"""generate the gird-mapping traj for SD
"""
def random_sampling(grid_range):
"""generate a sample point within a grid ra... | dbc70465e6a66cb967b697559f598d0e8c2ece90 | 3,635,689 |
import os
def get_2bit_path(db_opt):
"""Check if alias and return a path to 2bit file."""
if os.path.isfile(db_opt): # not an alias
return db_opt # there is nothing to do
aliased = two_bit_templ.format(db_opt)
# check that it's a file
die(f"Error! Cannot find {aliased} file", 1) if not o... | 4576b90df21e8996774e93ab8cf28023d025b85d | 3,635,690 |
def butterworth_type_filter(frequency, highcut_frequency, order=2):
"""
Butterworth low pass filter
Parameters
----------
highcut_frequency: float
high-cut frequency for the low pass filter
fs: float
sampling rate, 1./ dt, (default = 1MHz)
period:
period of the sign... | f8ff570d209560d65b4ccc9fdfd2d26ec8a12d35 | 3,635,691 |
import sys
def draw_mesh(
# Main input
edof,
coord,
dof,
element_type,
# Other parameters
scale = 0.02,
alpha = 1,
render_nodes = True,
color = 'yellow',
offset = [0, 0, 0],
# BC- & F-marking
bcPrescr = None,
bc = None,
bc_color = 'red',
fPrescr = None... | b4728316496221b8c9341dd8ae747f74eb08fbaf | 3,635,692 |
def mypad(x, pad, mode='constant', value=0):
""" Function to do numpy like padding on tensors. Only works for 2-D
padding.
Inputs:
x (tensor): tensor to pad
pad (tuple): tuple of (left, right, top, bottom) pad sizes
mode (str): 'symmetric', 'wrap', 'constant, 'reflect', 'replicate', ... | 48e435e1622a1d74bff0b44e159dc0562e12bb5e | 3,635,693 |
import operator
def molarity(compound, setting = None, moles = None, volume = None):
"""
Calculations involving the molarity of a compound. Returns a value based on the setting.
The compound must be the Compound class. The moles/volume setting will be gathered from the compound itself if defined.
**Volume... | 4fb477115f2c41c5729702b4037aa63abcfaf6f1 | 3,635,694 |
def set_initial_det(noa, nob):
""" Function
Set the initial wave function to RHF/ROHF determinant.
Author(s): Takashi Tsuchimochi
"""
# Note: r'~~' means that it is a regular expression.
# a: Number of Alpha spin electrons
# b: Number of Beta spin electrons
if noa >= nob:
# Here... | 53b34999014d0926f02308122ad32f88ea08a802 | 3,635,695 |
def face_detection(frame):
""" detect face using cv2
:param frame:
:return: (x,y), w, h: face position x,y coordinates, face width, face height
"""
if frame is None :
return 0,0,0,0
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gr... | 8a75ca46fd78d481fa2ec6d93d7d8123d7bf4463 | 3,635,696 |
def coro1():
"""定义一个简单的基于生成器的协程作为子生成器"""
word = yield 'hello'
yield word
return word # 注意这里协程可以返回值了,返回的值会被塞到 StopIteration value 属性 作为 yield from 表达式的返回值 | 1bfcfb150748c002638d2c6536299025864ac1f6 | 3,635,697 |
import itertools
import scipy
def plot_combinations_9array3x3_v2(coli_to_test, sorted_combinations, sorted_vals, comb_ind, renaming_fun):
"""Plot the nine best decompositions of a given set with variables
outside the matrix for a decomposition of 3 variables
Parameters
----------
coli_to_test... | d34684e12b2ffb8157dff33a461ae9ee4f45c818 | 3,635,698 |
from typing import Union
from typing import Tuple
def random_split(df: Union[DataFrame, Series], split_size: float,
shuffle: bool = True, random_state: int = None) -> Tuple[DataFrame]:
"""Shuffles a DataFrame and splits it into 2 partitions according to split_size.
Returns a tuple with the sp... | 2b69d97d69bebd3257201bf5629bb4e033134f82 | 3,635,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.