content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
async def test_month_wordcloud(app: App, mocker: MockerFixture, message_record: None):
"""测试本月词云"""
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from nonebot_plugin_wordcloud import wordcloud_cmd
mocked_datetime_now = mocker.patch(
"nonebot_plugin_wordcloud.get_datetime_now_... | 5,301,700 |
def hash_files(paths: List[str]):
"""
MD5 checksum a list of file paths
"""
return map(hash_file, paths) | 5,301,701 |
def get_version(*file_paths):
"""Retrieves the version from django_toosimple_q/__init__.py"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
... | 5,301,702 |
def _probability_of_improvement(mu, sigma, y_max, xi):
"""
Calculates the probability of improvement at the point 'x', for which:
mu = mean(x)
sigma = std(x)
TODO: should be in log-domain?
Parameters
----------
mu : array_like, shape (n,)
Mean.
sigma : a... | 5,301,703 |
def length_of_year(year):
""" the length of a day
:param year: The year you wuld like to know the length.
:returns: exact days. a day is longer then 365 days.
"""
return float(365.2564) if is_leap_year(year) else float(364.2564) | 5,301,704 |
def activate_environment_variables():
"""Method to activate the current environment variables
activate_environment_variables
==============================
This method is used to activate the environments in the current active environment
"""
import subprocess as sp
from argparse import Na... | 5,301,705 |
def test_failure_response_from_bitcoin_abuse(requests_mock):
"""
Given:
- bitcoin address report.
When:
- Trying to report the address to Bitcoin Abuse Api, and receiving a failure response from Bitcoin Abuse service.
Then:
- Ensure the command throws an error.
... | 5,301,706 |
def remove_hydrogens(mol):
"""Removes any hydrogens from the graph of a molecule.
This is a wrapper around rdkit.Chem.rdmolops.RemoveHs.
Parameters
----------
mol: rdkit.Chem.Mol
The molecule to be modified.
Returns
-------
mol: rdkit.Chem.Mol
A new molecule with the h... | 5,301,707 |
def pixel_to_meter(sample, line, geotransform, shift=False):
"""provide point in map projection coordinates.
Parameters
==========
sample, line: <integer> Sample and line of an image in pixel coords
Geotransform in format as given by GDAL datasets.GetGeoTransform()
Returns
=======
tupl... | 5,301,708 |
def get_status(api_key=None, request_id=None, proxies=None, auth=None):
"""
Получить состояние активации:
http://sms-activate.ru/stubs/handler_api.php?api_key=$api_key&action=getStatus&id=$id
:param api_key: ключ API авторизации на сервисе
:param request_id: id активации
:param proxies: адрес пр... | 5,301,709 |
def wait_for_task_complete (task_name: str, task_href: str):
"""
Summary:
polls a task state and returns when the task is complete
Parameters:
task_name (str): the name of the task
task_href (str): the href for the task
Returns:
None
"""
#logging
msg = f"wa... | 5,301,710 |
def match_event(event_type):
"""Return event type matcher."""
def matcher(func):
"""Add decorated function to list for event matching."""
func = add_skill_attributes(func)
func.matchers.append(
{"event_type": {
"type": event_type}})
return func
ret... | 5,301,711 |
def fetch_data_for_date(record_date, site_id, data_dir):
"""
Download radar data for a given date and siteId from public S3 bucket
"""
files = []
bucket = S3.Bucket('noaa-nexrad-level2')
data_site_prefix = '{record_date}/{site_id}'.format(record_date=record_date, site_id=site_id)
for s3_obje... | 5,301,712 |
def update_item_from_dict(table_name, key, dictionary, client):
"""
Update the item identified by `key` in the DynamoDB `table` by adding
all of the attributes in the `dictionary`.
Args:
table_name (str):
key (dict):
dictionary (dict):
client:
Returns:
dict
... | 5,301,713 |
def indirect_bp_names():
"""Return a list of valid Indirect Branch Predictor names."""
return _indirect_bp_classes.keys() | 5,301,714 |
def safely_generate(ds: tf.data.Dataset, progress: bool = True):
"""Yields examples from dataset, catching and logging exceptions."""
# Unsafe generating:
# for example in ds:
# yield example
ds_iter = iter(ds)
i = 0
wall_t0 = time.time()
done = False
while not done:
t... | 5,301,715 |
def conv2tif_handler(config_file):
"""
Convert interferograms to geotiff.
"""
config_file = os.path.abspath(config_file)
params = cf.get_config_params(config_file, step=CONV2TIF)
conv2tif.main(params) | 5,301,716 |
def device_action(device):
"""
Generates an actionable text for a :class:`~two_factor.plugins.phonenumber.models.PhoneDevice`.
Examples:
* Send text message to `+31 * ******58`
* Call number `+31 * ******58`
"""
assert device.__class__.__name__ == 'PhoneDevice'
number = mask_phone_numb... | 5,301,717 |
def main_app_url(module_scoped_container_getter):
""" Wait for the api from fastapi_main_app_main to become responsive """
return h.get_app_url(module_scoped_container_getter, "fastapi_main_app_main") | 5,301,718 |
def help_discover():
"""
Discover the world
"""
s = ' ' * 2
# Discover the world
usage = '\n'
usage += s + grey(u'\u266A' + ' Discover the world \n')
usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
'You can try ' + light_green('trend US') + ' or ... | 5,301,719 |
def _get_sign_array_1d(i: int, nsyms: int) -> Array:
"""Calculate array of nsyms signs that alternate every 2**i entries."""
sym_ints = jnp.arange(nsyms)
# The exponent below is simply a clever way to get the value of the i_spin-th bit
# of each integer in the sym_int array, to give us signs which alte... | 5,301,720 |
def test_write_append_df(sample_dataframe, first_chunk, second_chunk, tmp_path_factory):
"""Write the dataframe in two pieces, read it again and check identity"""
tempdir = tmp_path_factory.mktemp("test_write_append_df")
# Write first chunk
backend = dframeio.ParquetBackend(str(tempdir))
backend.wr... | 5,301,721 |
def solve(lines):
"""Solve the problem."""
mem = dict()
mask = "X" * 36
for line in lines:
if line.startswith("mem"):
m = MEM_RE.match(line)
loc, val = [int(v) for v in m.groups()]
mem[loc] = apply_val_mask(mask, val)
elif line.startswith("mask"):
... | 5,301,722 |
def _squash_unicode_in_bestrefs(bestrefs, localrefs):
"""Given bestrefs dictionariesy `bestrefs` and `localrefs`, make sure
there are no unicode strings anywhere in the keys or complex
values.
"""
refs = {}
for filetype, refname in bestrefs.items():
if isinstance(refname, tuple):
... | 5,301,723 |
def enum(**enums):
"""Enable use of enums by utilizing types"""
return type('Enum', (), enums) | 5,301,724 |
def create_arithmetictrainer_from_files(*files) -> Arithmetictrainer:
"""
Create a Arithmetictrainer from a configuration file.
"""
config_files = configparser.ConfigParser()
config_files.read(*files)
if len(config_files.sections()) == 0:
raise ValueError("Could not find a valid config i... | 5,301,725 |
def shrink(epsilon, x):
"""The shrinkage operator.
This implementation is intentionally slow but transparent as
to the mathematics.
Args:
epsilon: the shrinkage parameter (either a scalar or a vector)
x: the vector to shrink on
Returns:
The shrunk vector
"""
# try e... | 5,301,726 |
def profiler_dtype_func(dtype, null=False):
"""
Return a function that check if a value match a datatype
:param dtype:
:param null:
:return:
"""
def _float(value):
if null is True:
return fastnumbers.isfloat(value, allow_nan=True) is True and fastnumbers.isint(value) is ... | 5,301,727 |
def stop(job_id, event, action, resource, _count):
"""App stop event type"""
job_name = '{}:event={}:action={}'.format(
resource, event, action
)
func_kwargs = dict(
job_id=job_id,
app_name=resource,
)
return job_name, func_kwargs | 5,301,728 |
def kurt(im):
"""Return kurtosis = mean((image-mode)/2)^4). """
mode = stats.mode(im, axis = None)[0][0]
z_score = (im-mode)/2
z_score = z_score**4
k = float(z_score.mean().values)
return k | 5,301,729 |
def _format(str_lst, concise):
"""Format a string for printing.
Parameters
----------
str_lst : list of str
List containing all elements for the string, each element representing a line.
concise : bool, optional, default: False
Whether to print the report in a concise mode, or not.
... | 5,301,730 |
def vector_add(v, w):
"""adds corresponding elements"""
return [v_i + w_i
for v_i, w_i in zip(v, w)] | 5,301,731 |
def test_distribution_parameter_support(setup):
"""
* multinomial: test_distribution_parameter_support -- make sure all
supports are (0.0, 1.0)...
"""
multinomp = setup['multinomp']
for p in multinomp:
assert multinomp.distribution_parameter_support[p] == (0.0, 1.0) | 5,301,732 |
def get_chebi_role_to_children() -> Mapping[str, Set[Tuple[str, str]]]:
"""Get the ChEBI role to children mapping."""
df = get_filtered_relations_df('chebi', relation=has_role)
return multisetdict(
(role_id, ('chebi', chemical_id))
for chemical_id, _, role_id in df.values
) | 5,301,733 |
def resample_solar_flux(solar_flux_file, sensor_waves, sensor_fwhms):
""" Resample solar flux to sensor wavelengths.
Arguments:
solar_flux_file: str
Solar flux filename.
sensor_waves: array
Sensor wavelengths.
sensor_fwhms: array
Sensor FWHMs.
Retu... | 5,301,734 |
def get_arguments():
"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="NAS Search")
parser.add_argument("--dataset_type", type=str, default='celebA',
help="dataset type to be traine... | 5,301,735 |
def nexthop_is_local(next_hop):
"""
Check if next-hop points to the local interface.
Will be True for Connected and Local route strings on Cisco devices.
"""
interface_types = (
'Eth', 'Fast', 'Gig', 'Ten', 'Port',
'Serial', 'Vlan', 'Tunn', 'Loop', 'Null'
)
for type in interf... | 5,301,736 |
def mouse_body_geometry(beta,gamma,s,theta,phi):
"""
This function calculates the configuration of the mouse body
In this configureation, it has four free parameters: azimuth and elevation of the nose/hip
Returns the points, which define the model: center-points and radii
theta el is elevation of th... | 5,301,737 |
def _set_mul(x, y): # noqa:F811
"""
Multiplications in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
# TODO: some intervals containing 0 and oo will fail as 0*oo returns nan.
comvals = (
(x.start * y.start, bool(x.left_open or y.left_open)),
(x.start *... | 5,301,738 |
def calculate_expval(xcoords, wfuncs):
"""
Calculates the expected values :math:`<x>` for the x-coordinate by
numerically calculating the integral
.. math::
\\int_{x_{min}}^{x_{max}} | \\psi (x) |^2 x dx
Args:
xcoords (1darray): Array containing the x-coordinates
wfuncs (nd... | 5,301,739 |
def generate_bbox(cls_map, reg, scale, threshold):
"""
得到对应原图的box坐标,分类分数,box偏移量
"""
# pnet大致将图像size缩小2倍
stride = 2
cellsize = 12
# 将置信度高的留下
t_index = np.where(cls_map > threshold)
# 没有人脸
if t_index[0].size == 0:
return np.array([])
# 偏移量
dx1, dy1, dx2, dy2 = [... | 5,301,740 |
def logistic_expval(mu, tau):
"""
Expected value of logistic distribution.
"""
return mu | 5,301,741 |
def is_(var):
"""intuitive handling of variable truth value also for `numpy` arrays.
Return `True` for any non-empty container, otherwise the truth value of the
scalar `var`.
Caveat of the most unintuitive case: [0] evaluates to True, like [0, 0].
>>> import numpy as np
>>> from cma.utilities... | 5,301,742 |
def test_biblary_upload_entry_get_with_storage(get_bibliography, client):
"""Test the :class:`biblary.views:BiblaryUploadFileView` view ``GET`` method with configured file storage."""
with get_bibliography():
url = reverse('upload-entry')
response = client.get(url)
assert response.status... | 5,301,743 |
def abs_load_diff(ilp_vars, x, y, vnfs, vims, dec_vars, types=['cpu', 'ram']):
"""
Calculating the actual load difference between two vims x and y.
"""
load_x = 0.0
load_y = 0.0
for res_type in types:
if res_type == 'cpu':
type_used = 'core_used'
type_tot = 'cor... | 5,301,744 |
def facebook_auth_settings(request):
"""
Facebook Auth client side ID.
"""
context = {}
context['FACEBOOK_AUTH_ID'] = getattr(settings, 'SOCIAL_AUTH_FACEBOOK_KEY', '')
return context | 5,301,745 |
def keras_model_fn(hyperparameters):
"""keras_model_fn receives hyperparameters from the training job and returns a compiled keras model.
The model will be transformed into a TensorFlow Estimator before training and it will be saved in a
TensorFlow Serving SavedModel at the end of training.
Args:
... | 5,301,746 |
def test_filter_entities_with_exclude_rename():
"""
filters entity results using given schema which has exclude and rename attributes.
"""
exclude = ['id']
rename = dict(grade='new_grade', id='new_id')
schema = ResultSchema(exclude=exclude, rename=rename, depth=4)
kwargs = dict(id=1, age=2... | 5,301,747 |
def _check_open_tarball(testcase, response):
"""
Check http-response headers and open tar ball from content.
"""
testcase.assertTrue(re.search(r'attachment;\s*filename="[^"]*.tar.gz"',
response['Content-Disposition']))
testcase.assertEqual(response['Content-Type'], ... | 5,301,748 |
def test_mscs_pre_assoc(dev, apdev):
"""MSCS configuration pre-association"""
try:
run_mscs_pre_assoc(dev, apdev)
finally:
dev[0].request("MSCS remove") | 5,301,749 |
def test_group_add(container, tmpdir):
"""Container should run with the specified uid, gid, and secondary
group.
"""
c = container.run(
user='1010:1010',
group_add=['users'],
command=['start.sh', 'id']
)
rv = c.wait(timeout=5)
assert rv == 0 or rv["StatusCode"] == 0
... | 5,301,750 |
def square_shaper(x, y, side_length=1):
"""Shaper function for a square with a given side length.
Parameters
----------
x : float or array-like
x-component of the step.
y : float or array-like
y-component of the step.
side_length : float
Square side length.
Returns
... | 5,301,751 |
def make_non_pad_mask(lengths, xs=None, length_dim=-1):
"""
See https://github.com/espnet/espnet/blob/e962a3c609ad535cd7fb9649f9f9e9e0a2a27291/espnet/nets/pytorch_backend/nets_utils.py#L179
"""
return ~make_pad_mask(lengths, xs, length_dim) | 5,301,752 |
def to_nsec(val):
"""Returns value in nanoseconds if value is ROS time/duration, else value."""
return val.to_nsec() if isinstance(val, genpy.TVal) else val | 5,301,753 |
def prob14(cur: sqlite3.Cursor) -> pd.DataFrame:
"""Show the 1984 winners and subject ordered by subject and winner name;
but list Chemistry and Physics last.
The expression subject IN ('Chemistry','Physics') can be used as a value -
it will be 0 or 1.
Parameters
----------
cur (sq... | 5,301,754 |
def instructor_get_projects():
"""
Returns all the projects created by the instructor
"""
# TODO: get the userid from the auth service
userid = "1"
# get all the project ids for this user
with db_utils.db_session() as session:
query = db.select([Project]).where(Project.columns.instru... | 5,301,755 |
def GetKDPPacketHeaderInt(request=0, is_reply=False, seq=0, length=0, key=0):
""" create a 64 bit number that could be saved as pkt_hdr_t
params:
request:int - 7 bit kdp_req_t request type
is_reply:bool - False => request, True => reply
seq: int - 8 sequence numb... | 5,301,756 |
def get_model(args, iteration: int):
"""Use the corresponding iCluster Model."""
logger.info("Setting up icluster-{} model...".format(args.mode))
save_dir = os.path.join(args.save_dir, MODEL_NAMES[args.mode],
"iteration_{}".format(iteration))
if args.mode == "vanilla":
model = iCl... | 5,301,757 |
def save_items_list(drive_service, file_location):
"""
save cloud items list in a json file
:param file_location: location where file needs to be saved
:param drive_service: servive object for drive
:return: True if list successfully saved else false
"""
files = drive_service.files().list().... | 5,301,758 |
def dashifyHeadline(line):
"""
Takes a header line from a Markdown document and
returns a tuple of the
'#'-stripped version of the head line,
a string version for <a id=''></a> anchor tags,
and the level of the headline as integer.
E.g.,
>>> dashifyHeadline('### some header l... | 5,301,759 |
def lineFileNext(fh):
"""
parses tab-sep file with headers as field names
yields collection.namedtuples
strips "#"-prefix from header line
"""
line1 = fh.readline()
while line1.startswith("##"):
line1 = fh.readline()
line1 = line1.strip("\n").strip("#")
headers = ... | 5,301,760 |
def setpos(fh, off):
"""Implementation of perl $fh->setpos method"""
global OS_ERROR, TRACEBACK, AUTODIE
try:
fh.seek(off, os.SEEK_SET)
return True
except Exception as _e:
OS_ERROR = str(_e)
if TRACEBACK:
cluck(f"setpos({off}) failed: {OS_ERROR}",skip... | 5,301,761 |
def create_pickle(data, filename):
"""
Create pickle for given data
:param data: data object to be saved
:param filename: pickle file name
:return: None
"""
with open(filename, "wb") as f:
pickle.dump(data, f) | 5,301,762 |
def check_game_has_finished(player, game):
"""
Checks if the game has finished
:param player: (Player object) Current player
:param game: current game being played
:return: (boolean) True if the game has finished, else False
"""
finished_game = False
# Check if game has finished
if ... | 5,301,763 |
def nullspace_relative_norm(A, x, tol=1e-12):
"""Compute the ratio between the norm of components of `x` that are in the
nullspace of `A` and the norm of `x`.
Args:
A (torch.Tensor): A matrix.
x (torch.Tensor): A certain vector.
tol (float): The tolerance level for determining what ... | 5,301,764 |
def get_filter(df, alt_list, mach_list, aos_list, aoa_list):
""" Get a dataframe filter for a set of parameters lists. """
filt = pd.Series(True, index=df.index)
if alt_list:
filt &= df["altitude"].isin(alt_list)
if mach_list:
filt &= df["machNumber"].isin(mach_list)
if aos_list:... | 5,301,765 |
def inet_ntoa(address):
"""Convert a network format IPv6 address into text.
@param address: the binary address
@type address: string
@rtype: string
@raises ValueError: the address isn't 16 bytes long
"""
if len(address) != 16:
raise ValueError("IPv6 addresses are 16 bytes long")
... | 5,301,766 |
def _add_debug_argument(parser: argparse.ArgumentParser):
"""
Add ``--debug`` to an :class:`argparse.ArgumentParser` enables debug logging.
"""
parser.add_argument('--debug', '-D', action='store_true', help='enable debug logging') | 5,301,767 |
def write_manifest(manifest, files, ipAddress):
"""Write manifest file for kpush. Catagorize out source, test,
tp+, ls, xml/csv files.
"""
file_list = dict()
#load in manifest if it exists
if os.path.exists(manifest):
with open(manifest) as man:
file_list = yaml.load(man, Loade... | 5,301,768 |
def parseOutputForAllowedKeys(ml, allowed_keys=None):
""" Parses the given vclient output, while accepting only
known (or allowed) keys.
Also handles void states, where line occur that are neither
a key nor a value.
"""
data = {}
# When explicit keys are defined, start in void mo... | 5,301,769 |
def getAnyRun(sha256):
"""
Retrieves information from AnyRun Service
:param sha256: hash value
:return info: info object
"""
info = {'anyrun_available': False}
if sha256 == "-":
return info
try:
response = requests.get(URL_ANYRUN % sha256, proxies=PROXY)
# print(r... | 5,301,770 |
def explore_run_save_data_path(run_data_path):
"""Save run data path
Save run data path for next load in run stage
:param run_data_path: str, represent result evaluate path
:return: bool, represent save result
"""
explore_run_inst.run_data_path = run_data_path
return True | 5,301,771 |
def test_get_release_from_bucket():
"""
Gets the release from an object stored in a S3 bucket.
"""
s3 = boto3.resource("s3")
client = boto3.client("s3")
s3.create_bucket(Bucket="test")
bucket = s3.BucketVersioning("test")
bucket.enable()
resp = client.put_object(
Bucket="te... | 5,301,772 |
def add_alias(alias: str, id: str) -> bool:
"""
This function assigns a desired alias of the user to its id.
Parameters
----------
alias : str
The alias name of the user
id : str
The id of the user
Returns
-------
bool
True if new alias has been added, otherw... | 5,301,773 |
def _weights_init(module, conv_weight_init_fn):
"""
initialize weights
"""
classname = module.__class__.__name__
if 'Conv' in classname and classname != "AvgPool2dWithConv":
conv_weight_init_fn(module.weight)
if module.bias is not None:
init.constant(module.bias, 0)
e... | 5,301,774 |
def launch_new_instance():
"""
Launch an instance of the ArchieML parser.
This is the entry function of the command-line tool `archieml`.
"""
archieml = ArchieML()
archieml.main() | 5,301,775 |
def multi_scale_retinex(image: np.ndarray, sigma_list: List) -> np.ndarray:
"""
Performs multi-scale retinex by wrapping single-scale retinex
Parameters
-----------------------------
image: np.ndarray,
Image to be enhanced
sigma_list: List
Recommended sigma values: [15, 80, 250]... | 5,301,776 |
async def update_check_notes(
db_session: Session,
check_id: uuid.UUID,
note: str,
accepted: bool,
accepted_by: Optional[str] = None,
) -> None:
"""
Updates conclusion of check note. If Check accepted,
user (accepted_by) should be provided.
"""
query = (
db_session.query(... | 5,301,777 |
def craft_unknown_asset_message(
username, emoji, channel, launch_time, cloud_provider, vps_name, tags
):
"""Function to craft a nicely formatted Slack message using blocks
for cloud assets not found in Ghostwriter.
"""
UNKNOWN_ASSET_MESSAGE = {
"username": username,
"icon_emoji": em... | 5,301,778 |
def nevow_adapter_resource(interceptors=v()):
"""
Create a Nevow ``IResource`` that executes a context and avoids as much
Nevow machinery as possible.
A ~`fugue.interceptors.nevow.nevow` interceptor will be attached to the
front of the queue to facilitate the interaction with Nevow.
"""
_im... | 5,301,779 |
def make_division_term_lookup() -> pd.DataFrame:
"""DataFrame giving salient keywords for each division.
Combines the two sources of salient terms.
"""
# Match trend terms to divisions (combining the two sources of salience data)
division_term_lookup1 = _division_term_lookup_v1()
division_ter... | 5,301,780 |
def address_has_changed(instance) -> bool:
"""
Check that the newly saved address
is different from the already saved
"""
return (instance.address != get_user_model()
.objects.get(id=instance.id).address) | 5,301,781 |
def condition(string: str) -> str:
"""Turn variable conditions into `if score`"""
def equal_int(match: re.Match) -> str:
groups = match.groups()
return f'score {groups[0]} __variable__ matches {groups[1]}'
string, success = re.subn(
f'^{Re.var}\s*(?:==|=)\s*{Re.integer}$', equal_int,... | 5,301,782 |
def keyframe(absolute: bool = False,adjustBreakdown: bool = False,animation: str = "",attribute: str = "",breakdown: bool = False,clipTime: Tuple[float, float, float] = tuple(1.0, 1.0, 1.0),controlPoints: bool = False,eval: bool = False,float: Tuple[float, float] = tuple(1.0, 1.0),floatChange: float = 1.0,hierarchy: st... | 5,301,783 |
def setup_logger():
"""Set up logging."""
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(name)24s %(levelname)8s: %(message)s")
console_handler.... | 5,301,784 |
def tilted_L1(u, quantile=0.5):
"""
tilted_L1(u; quant) = quant * [u]_+ + (1 - quant) * [u]_
"""
return 0.5 * abs(u) + (quantile - 0.5) * u | 5,301,785 |
def get_abs_path(path: str) -> str:
"""
Gets the fully evaluated absolute path for a given path.
This function uses a horrific workaround for an issue where CMD and Powershell 5 provide incorrect arguments
when called with a path with spaces which ends in a backslash, like ".\my path\".
This is pr... | 5,301,786 |
def prep_and_search(st, segment, data, indexprefix='new', returnsoltime=False):
""" Reproduces rfpipe.search.prep_and_search but calculates and
indexes noises.
"""
from rfpipe import source, search, reproduce, candidates
ret = source.data_prep(st, segment, data, returnsoltime=returnsoltime)
if... | 5,301,787 |
def update_entity(id):
"""
Update a story from the provided json
:param intent_id:
:param json:
:return:
"""
json_data = loads(request.get_data())
entity = Entity.objects.get(id=ObjectId(id))
entity = update_document(entity, json_data)
entity.save()
return 'success', 200 | 5,301,788 |
def data_augmentation(original_samples, original_labels, original_groups, augmentation_factor=2, x_coord=0, y_coord=1, c_coord=2):
"""
Pass original_samples after interpolation as a constant shape of (n_samples, NUM_FRAMES, n_keypoints, xyc)
"""
org_num_samples, org_num_frames, org_num_keypoints, org_... | 5,301,789 |
def get_sectors():
"""Get all sectors in Yahoo Finance data. [Source: Finance Database]
Returns
-------
list
List of possible sectors
"""
return fd.show_options("equities", "sectors") | 5,301,790 |
def addtracklabels(
x: np.ndarray,
y: np.ndarray,
axes: Axes,
ts: np.ndarray,
c: str,
plotall: bool,
thislabel: str,
cvs: List[str],
seonly: bool,
count: Counter,
name: str,
zorder: int = 16
) -> None:
"""Adds labels to the track lines. Specifically the start and end ... | 5,301,791 |
def getId(collection):
""" Get the ImageCollection id.
**CLIENT SIDE**
:type collection: ee.ImageCollection
:return: the collection's id
:rtype: str
"""
return collection.limit(0).getInfo()['id'] | 5,301,792 |
def _process_data_ascii(raw, metadata, verbose_acquistion=True):
"""Process raw comma separated ascii data to time values and y voltage
values as received from :func:`Oscilloscope.capture_and_read_ascii`
Parameters
----------
raw : str
From :func:`~keyoscacquire.oscilloscope.Oscilloscope.ca... | 5,301,793 |
def predict_batch(model, dataset_batcher: Batcher):
"""Predict the values using the given batcher
Parameters
----------
model: SKLearn model
dataset_batcher : Batcher
Returns
-------
np.array
Predictions array
"""
y_pred = []
for X, y in dataset_batcher:
y_... | 5,301,794 |
def migrate_file_target(target: FileTarget, copy: bool = False) -> FileTarget:
"""Apply a move, or copy of the FileTarget from source to new destination."""
_ensure_target_directory(target.target_move_path)
target = _check_existing_target_file(target)
if target.file_path == target.target_move_path:
... | 5,301,795 |
def bytes_to_human(size, digits=2, binary=True):
"""Convert a byte value to the largest (> 1.0) human readable size.
Args:
size (int): byte size value to be converted.
digits (int, optional): number of digits used to round the converted
value. Defaults to 2.
binary (bool, op... | 5,301,796 |
def softModContext(*args, **keywords):
"""
Dynamic library stub function
"""
pass | 5,301,797 |
def get_stellar_toml(domain, allow_http=False):
"""Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with
Stellar's federation protocol for a given Stellar Anchor (specified by a
domain).
:param str domain: The domain the .toml fil... | 5,301,798 |
def parseReplyBlock(s):
"""Return a new ReplyBlock object for an encoded reply block.
Raise ParseError on failure.
"""
block, length = _parseReplyBlock(s)
if length > len(s):
raise ParseError("Misformatted reply block: extra data.")
return block | 5,301,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.