content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dc_loss(embedding, label):
"""
Deep clustering loss function.
Args:
embedding: (T,D)-shaped activation values
label: (T,C)-shaped labels
return:
(1,)-shaped squared flobenius norm of the difference
between embedding and label affinity matrices
"""
xp = cuda.get_array... | 8f1fb8a9307dc6af465f43e8236dee45b19fea86 | 3,627,356 |
import urllib
import json
import time
def ScrapeAdMetadataByKeyword(CurrentSession, Seed, NumAds = 2000):
"""
Returns a list of dictionaries that includes metadata of the Ad and
also includes it's performance details. Our program crawls 5000
ads in the first iteration and then 500 ads in the subsequ... | e9446fb44d28c984bb3b252183d522d7438d9fab | 3,627,357 |
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities):
"""Set up the platform from config_entry."""
# We should scan options for alert configs and then if at least 1 listener is enabled subscribe for the stream
hik_client = hass.data[const.DOMAIN][config_entry.entry... | 907de6fbb5245fc98b0de2cbac8387bdf147dee6 | 3,627,359 |
def image_pil2cv(img):
"""Convert a PIL image to an opencv image.
Args:
img (PIL image): A PIL image of uint8 between 0 and 255 using RGB channels.
Returns:
np.array: A numpy image loaded with opencv of uint8 between 0 and 255 using BGR channels.
Examples:
>>> img ... | a3e44b1f290dd412afd4af62e8ee8fcd138c1aba | 3,627,360 |
def _ww3_ounf_contents(run_date, run_type):
"""
:param run_date: :py:class:`arrow.Arrow`
:param str run_type:
:return: ww3_ounf.inp file contents
:rtype: str
"""
start_date = (
run_date.format("YYYYMMDD")
if run_type == "nowcast"
else run_date.shift(days=+1).format("... | 62618639265e419b5ad1ff9c7364e6d83aeca1c0 | 3,627,361 |
from typing import Tuple
def _search(matrix: np.ndarray, tour: np.ndarray, x: int, y: int, z: int) -> Tuple[int, float]:
""" Поиск лучшей замены, среди всех возможных замен
matrix: Матрица весов
tour: Список городов
x, y, z: Города, для которых пробуем найти изменение тура
return: Тип переворота, ... | 0bd0468c2b1f206f27020ee3d9c5029606e1a8e8 | 3,627,362 |
import itertools
def new_min_max(_builtin_func, *args, **kwargs):
"""
To support the argument "default" introduced in python 3.4 for min and max
:param _builtin_func: builtin min or builtin max
:param args:
:param kwargs:
:return: returns the min or max based on the arguments passed
"""
... | 4aae098143c4c96b53ec6b5fa9b240de936b9ecc | 3,627,364 |
def article(word, function=INDEFINITE, gender=MALE, role=SUBJECT):
""" Returns the indefinite (ein) or definite (der/die/das/die) article for the given word.
"""
return function == DEFINITE \
and definite_article(word, gender, role) \
or indefinite_article(word, gender, role) | fe21fdc34253c1736bcc17dae25f14d502ce301e | 3,627,367 |
import requests
def get_workbooks(server, auth_token, user_id, site_id):
"""
Queries all existing workbooks on the current site.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
'user_id' ID of user with access to... | 4a91fe94e5f71e6599689e3430f75239e8efd4aa | 3,627,368 |
from datetime import datetime
from typing import MutableMapping
from typing import Any
def get_significant_states_with_session(
hass: HomeAssistant,
session: Session,
start_time: datetime,
end_time: datetime | None = None,
entity_ids: list[str] | None = None,
filters: Filters | None = None,
... | 2e2767d07e3b9a2bfa75acb4664a2a93c5d10472 | 3,627,370 |
def vc_to_oct(solution):
"""Convert a VertexCover solution into an OCT solution.
This is done by undoing the graph doubling done to reduce
OCT to VC. The certificate is recovered as the vertes
whose counterparts are both in the VC certificate.
Parameters
----------
solution : Solution
... | e08425dbc31f89dc4e0d79c257f83c884efb0714 | 3,627,371 |
def class_of ( object ):
""" Returns a string containing the class name of an object with the
correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
'a PlotValue').
"""
if isinstance( object, py3compat.string_types ):
return add_article( object )
return add_article( ob... | 4cfad61c30afd3ab726f52bcf5906a59dd711866 | 3,627,372 |
def saturated_vapour_pressure_inst(t_air_i):
"""Like :func:`saturated_vapour_pressure` but as an instantaneous value
Parameters
----------
t_air_i : float
instantaneous air temperature
:math:`T_{a,i}`
[C]
Returns
-------
svp_i : float
instantaneous saturated... | f5b45c6c354dfedf6e16d12bebd9b9f499e413ee | 3,627,374 |
from typing import Tuple
from typing import Optional
from datetime import datetime
def format_timestamp_range(
timestamp_range: Tuple[int, int],
timestamp_unit: Optional[str],
timestamp_format: Optional[str]
) -> str:
"""
Format a time range with unit.
:param timestamp_range: rang... | f0cf3cf0465ec8ebaafa73fd9a60e7b589df3c19 | 3,627,375 |
def make_eeg_average_ref_proj(info, activate=True, verbose=None):
"""Create an EEG average reference SSP projection vector
Parameters
----------
info : dict
Measurement info.
activate : bool
If True projections are activated.
verbose : bool, str, int, or None
If not None... | 125a9320d1e018de2bc709f1e777cbb34cf8f127 | 3,627,376 |
def generate_degree2_invariants_from_different(coeffs1, coeffs2):
"""
Generate degree 2 invariants from density projection coefficients.
Parameters
----------
coeffs1 : array[num_envs, num_species, nmax1, (lmax+1)**2]
Density projection coefficients. This could include the spherical
... | abdfa4806d32f4c5b34e6c8cccbc841b9cadbe19 | 3,627,377 |
def ts_css(text):
"""applies nice css to the type string"""
return '<span class="ts">%s</span>' % text | a505f4ffc8359bc886f0011295fb5309529be5bf | 3,627,378 |
import typing
def noop(val: typing.Any, *_args, **_kwargs) -> typing.Any:
"""A function does nothing.
>>> noop(1)
1
"""
return val | 99841c0b291a654d83741500e83441482f59d45a | 3,627,379 |
def method_detect(method: str):
"""Detects which method to use and returns its object"""
if method in POSTPROCESS_METHODS:
if method == "rtb-bnb":
return RemovingTooTransparentBordersHardAndBlurringHardBorders()
elif method == "rtb-bnb2":
return RemovingTooTransparentBord... | 4d3a065b25ac25a15e24681a723b5aa9e2354bc9 | 3,627,380 |
def normalized_difference():
"""
Returns class instance of `NormalizedDifference`.
For more details, please have a look at the implementations inside `NormalizedDifference`.
Returns
-------
NormalizedDifference :
Class instance implementing all 'normalized_difference' processes.
""... | e3325e48c1ea7d8b775d7d9613425c445cad4f57 | 3,627,381 |
def detect_event_no_plot(VLMuscle, VRMuscle, Time, Threshold):
"""
This function calculates the start, end and duration of swimming episode, as defined by a threshold.
Does not plot the result
:param VLMuscle: list or 1-D numpy array
:param VRMuscle: list or 1-D numpy array
:param Time: list or... | 3a7eae3a3b7b8e16e6c4365f7390227084676dc9 | 3,627,382 |
import torch
def build_dgl_graph_v15(nodes, edges, sent_nodes):
"""
Build DGL homogeneous graph based on New Graph structure.
1112: checked graph through visualisation
1116: qo_node feature: [-10, opt id]
1201: hotpotQA, store node separately and combine
"""
# split entity nodes and q_opt ... | 6e8e5da0a3ff6d37006606a818a708998fa206e2 | 3,627,383 |
def entropy_bubble(signal, delay=1, dimension=3, alpha=2, **kwargs):
"""**Bubble Entropy (BubblEn)**
Introduced by Manis et al. (2017) with the goal of being independent of parameters such as
*Tolerance* and *Dimension*. Bubble Entropy is based on :func:`permutation entropy <entropy_permutation>`,
but ... | 0574f271acc7922a85ef9f6d411386bd5e8d2ac4 | 3,627,385 |
from typing import ClassVar
from typing import Sequence
from typing import Optional
def open_set(dataset_class: ClassVar, public_classes: Sequence[str],
private_classes: Optional[Sequence[str]] = ()) -> ClassVar:
"""
Convert a dataset into its open-set version.
In other words, those samples w... | 6bb48c1f7b40ae88e30adeb9dbf5dff922ebe115 | 3,627,386 |
import string
import random
def generate_random_string(length,
using_digits=False,
using_ascii_letters=False,
using_punctuation=False):
"""
Example:
opting out for 50 symbol-long, [a-z][A-Z][0-9] string
would yiel... | d1606c450911183bd72353f6e4793dbc8d997271 | 3,627,387 |
def get_blocking_times_of_all_states_using_direct_approach(
lambda_1, mu, num_of_servers, threshold, system_capacity, buffer_capacity
):
"""Solve M*X = b using numpy.linalg.solve() where:
M = The array containing the coefficients of all b(u,v) equations
b = Vector of constants of equations
... | 7fe8954e1f2f6e7cf3401557990d29e035292953 | 3,627,388 |
def create_read_only_text(title: str, example: str, value: str, layout: QLayout) -> QLineEdit:
"""
Creates and returns a read-only one-line text widget (QLineEdit)
with the given title, example contents and value in the given layout.
"""
widget = create_text(title, example, value, layout)
widget... | 046ec074cc46ba3717f03be8febb7e0dd657c925 | 3,627,389 |
def find_lane_pixels_around_poly(binary_warped, left_fit, right_fit, margin = 100):
"""
Returns the pixel coordinates contained within a margin from left and right polynomial fits.
Left and right fits shoud be from the previous frame.
PARAMETER
* margin: width around the polynomial fit
"""
#... | 16e852fbf502424a44d80ff1c9177455a1a99151 | 3,627,390 |
def log_softmax_v2(logits, axis=None, name=None):
"""Computes log softmax activations.
For each batch `i` and class `j` we have
logsoftmax = logits - log(reduce_sum(exp(logits), axis))
Args:
logits: A non-empty `Tensor`. Must be one of the following types: `half`,
`float32`, `float64`.
axis... | 549fb730f89790230b8422607dd39ba23471695c | 3,627,391 |
def apply_reflection(reflection_name, coordinate):
"""
Given a reflection type and a canonical coordinate, applies the reflection
and describes a circuit which enacts the reflection + a global phase shift.
"""
reflection_scalars, reflection_phase_shift, source_reflection_gates = reflection_options[
... | 2ef16ecb01747d216717438413f30b7a2b4f9f22 | 3,627,393 |
import json
def _get_vcpus_from_pricing_file(instance_type):
"""
Read pricing file and get number of vcpus for the given instance type.
:param instance_type: the instance type to search for.
:return: the number of vcpus or -1 if the instance type cannot be found
"""
with open(pricing_file) as... | 43d83826ef9d59101ed6928567e921173e58cbda | 3,627,394 |
def rot_mol(rot, struct, wrt="origin", degrees=True, seq="xyz"):
"""
Rotate molecule using rotation matrix.
Arguments
---------
rot: array
Can be either a list of 3 euler angles in the given order or a 3,3
rotation matrix.
wrt: str
Rotation performed with respect... | 19ae4c586a84f2130389456a527a960ae3a03afc | 3,627,396 |
def fit_naive_bayes_model(matrix, labels):
"""Fit a naive bayes model.
This function should fit a Naive Bayes model given a training matrix and labels.
The function should return the state of that model.
Feel free to use whatever datatype you wish for the state of the model.
Args:
matrix... | 637a355434911b6cf25f12d704f6bc9680d5c548 | 3,627,398 |
from typing import Union
from contextlib import suppress
def get_checkBox_entry(checkBox: etree._Element) -> str:
"""Create text representation for a checkBox element.
:param checkBox: a checkBox xml element
:returns:
1. attempt to get ``checked.w:val`` and return "\u2610" or "\u2612"
2. ... | d71e7821ac5fb7bafe9d5db5b579def2fe369609 | 3,627,399 |
def use_scratch_dir(original_wf, scratch_dir):
"""
For all RunVaspCustodian tasks, add the desired scratch dir.
Args:
original_wf (Workflow)
scratch_dir (path): Path to the scratch dir to use. Supports env_chk
Returns:
Workflow
"""
for idx_fw, idx_t in get_fws_and_tasks(... | 0e45b317d477b84fe92359f10a6294d86b5ff670 | 3,627,400 |
def auto_peak_finder(prominence, x_data, y_data):
"""
automatic peak finding routine which finds peaks given a user supplied prominence, and presents the peaks until user
is happy
:param prominence: height from noise to tip of peaks
:param x_data: x_data as np array
:param y_data: y_data as np a... | 1e23d23c0edc679a3429b3ef0f91b905c34e91d7 | 3,627,402 |
from typing import OrderedDict
def dataframe_reg_as_panel(df,against='index',regfunc='OLS'):
"""
Perform regression for each of the columns of the dataframe, and return
the regression result as panel.
Parameters:
-----------
against: the variable used as the independent variable in the re... | fac0d6c768b4c8bd9fbafad4ba5e3216e539f28d | 3,627,403 |
import threading
def serve_pyr(name, url, root_path, config='config.ini'):
"""Serve the Pyramid app locally in a separate thread that forks a
subprocess that invokes the pserve executable. Return a function that stops
serving the Pyramid app.
"""
process = _fork_server_process(url, root_path, conf... | a21e182b27b424bb7bf0e669209391a429d81541 | 3,627,404 |
def order_line_needs_automatic_fulfillment(line_data: OrderLineInfo) -> bool:
"""Check if given line is digital and should be automatically fulfilled."""
digital_content_settings = get_default_digital_content_settings()
default_automatic_fulfillment = digital_content_settings["automatic_fulfillment"]
co... | baa85396d3da44670ce634353db55a589ca27387 | 3,627,405 |
def docker_setup(project_path: str) -> bool:
""" Tries to find evidence of a docker setup in the project. """
_file_names = ['[Dd]ockerfile', '[Dd]ocker-compose.yml']
for name in _file_names:
_findings = search_filename(
base_folder=project_path,
file_name=name,
... | 6f1e18d83cbcfdac21105b89a6dedb8c17e1d026 | 3,627,406 |
def prac_q_count(year, month, day, hour, qtemplate):
""" Fetch the practice count for the given time/qtemplate or return
False if not found. Can be used when deciding if to INSERT or UPDATE.
Note: may return 0 if count is zero, is not same as not exist (False)
"""
sql = """SELECT "qtemplate"... | adc90d18d8f55ab76a4f3939b622f6ba30a86c66 | 3,627,407 |
import getpass
import base64
def get_headers(gargs):
"""Get the required headers. """
headers = {
'Content-type': 'application/json'
}
if gargs.no_passwd:
return headers
if gargs.passwdfile is not None:
passwd = open(gargs.passwdfile, "r").read().strip()
auth_str ... | 04d7a9da9e30fbfdf86b0a09d23dc178a0615d27 | 3,627,408 |
import torch
def highest_prob_class(y_predicted: torch.Tensor, y_true: torch.Tensor, **kwargs) -> _TensorOrTensors:
"""
Get the index of class with highest probability.
"""
y_predicted = y_predicted.max(dim=-1)[1]
assert y_true.shape == y_predicted.shape
return y_predicted, y_true | 8107c2f960e22d7da9c042242365ebb1f2e96722 | 3,627,409 |
def vectorized_local_axes(three_atoms_coords):
"""
Takes as an argument a Nx3x3 block of reference atom coordinates to construct N local axes systems (Nx3x3)
"""
u12 = vectorized_unit_vector(three_atoms_coords[:, [0,1], :])
u23 = vectorized_unit_vector(three_atoms_coords[:, [1,2], :])
if np.any(... | 2f19924b516ce76fc4f769e675c78f0e5ddfd3c1 | 3,627,410 |
def set_option(option, value):
"""Set a single option using the flat format, i.e ``section.option``
Parameters
----------
option: str
Option name in the ``section.option`` format
value:
Value to set
Example
-------
.. ipython:: python
@suppress
from xoa... | a5cb71e60da6d80bf0409c91945dd31a9e44be74 | 3,627,411 |
def dict_to_capabilities(caps_dict):
"""Convert a dictionary into a string with the capabilities syntax."""
return ','.join("%s:%s" % tpl for tpl in caps_dict.items()) | 12a321ba5f337f8da116ec7adec68d717fbc776f | 3,627,412 |
import numpy
def delta(flag, F, K, t, r, sigma):
"""Returns the Black delta of an option.
:param flag: 'c' or 'p' for call or put.
:type flag: str
:param F: underlying futures price
:type F: float
:param K: strike price
:type K: float
:param t: time to expiration in years
... | b3439872aa41e697d42d1e2ef503996e82651db8 | 3,627,413 |
def main(X, Y, X0, Y0, depth, omegaX, omegaY, omegaZ, ax, ay, az, opening, nu, verbose=False):
"""
Test CDM with test input parameters
X0, Y0, depth: define the position of the dislocation
omegaX, omegaY, omegaZ: define the orientation (clockwise rotations) of the dislocation
ax, ay, az: define the ... | 40a887b8282cd29c7b63c15882eaf4191a0658f4 | 3,627,414 |
def extend_view(response, fetch_page_data, fetch_multimedia, raise_errors):
"""
Extends view query results with pronunciation URLs, multimedia URLs, and extended hanja
information by scraping the dictionary website.
This function modifies the response in-place, and returns the modified object.
See ... | 0c35341fb146144f8bc3efa4a98d89419d625e1a | 3,627,415 |
def mean(vector):
"""
Calculates the arithmetic mean of the given vector.
Args:
-----
vector : list
A non-empty list/array of numbers to be averaged.
Returns:
--------
mean : float
The arithmetic mean of the given vector.
"""
return sum(vector) /... | 71bd9a37cb0bfb166632866d0a29be9b14236364 | 3,627,416 |
import math
def get_hamming_window(w, h, rot, sx, sy, out_size_w, out_size_h):
"""
A hamming window map
:param w: init ellipse w
:param h: init ellipse h
:param rot: rotation angle(rad)
:param sx: center x coordinate of the window
:param sy: center y-coordinate of the window
:param out... | 4611eb52ba8abd00c1c78a78fb60b62ae13a5755 | 3,627,418 |
def reconstructimage(lpyramid, f):
""" Reconstruct image from Laplacian pyramid
Args:
lpyramid: Laplacian pyramid
f: 2d filter kernel
Returns:
Reconstructed image as (H, W) np.array clipped to [0, 1]
"""
#
# You code here
#
lpyramid_flip = np.flip(lpyramid)
g... | 2cc70a899ab5694846010fcd6980e245d25671f1 | 3,627,419 |
def convert_to_pressure_levels(mv, plevs, dataset, var, season):
"""
Given either test or reference data with a z-axis,
convert to the desired pressure levels.
"""
mv_plv = mv.getLevel()
# var(time,lev,lon,lat) convert from hybrid level to pressure
if mv_plv.long_name.lower().find('hybrid') ... | b4f14f9a62356f3e3718fce7a71f8c3efc2d347e | 3,627,420 |
def matrix2xzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray:
"""
Ry(k3) @ Rz(k2) @ Rx(k1) = [[c2c3, -c1s2c3+s1s3, s1s2c3+c1s3],
[s2, c1c2, -s1c2],
[-c2s3, c1s2s3+s1c3, -s1s2s3+c1c3]]
"""
rotation_matrices = rotation_matrices.resha... | 9371a5b459f9c92354752e94a9fb292add1dca96 | 3,627,421 |
from datetime import datetime
def do_auth():
"""
perform authentication using API_KEY,
stores token and stored timestamp in integration context,
retrieves new token when expired
"""
auth = demisto.getIntegrationContext()
now_epoch = int(datetime.today().strftime('%s'))
if ("token" in ... | 875c4dd44c2e253b62382a1ffb37ab0fbc5c3333 | 3,627,422 |
async def write_credential_def(controller, schema_id):
"""
Writes Credential Definition to the ledger
Parameters:
----------
controller: AriesController
The aries_cloudcontroller object
Schema id
Returns:
-------
write_cred_response :dict
"""
write_cred_response =... | 4825dc30aa0ecf4097b654d7119fb2a9be41818a | 3,627,423 |
def guess_cloudwatch_log_group(alarm_name):
"""
Guess the name of the CloudWatch log group most likely to contain
logs about the error.
"""
if alarm_name.startswith("loris-"):
return "platform/loris"
if alarm_name.startswith("catalogue-api-romulus"):
return "ecs/catalogue_api_gw... | 94822c16ce6c84b154be40581eb74e25e2cbe898 | 3,627,424 |
def update_attrs(orig, keys, override):
"""Utility function for altering and adding the specified attributes to a particular repository rule invocation.
This is used to make a rule reproducible.
Args:
orig: dict of actually set attributes (either explicitly or implicitly)
by a particu... | 82498f78604924c281da1fab372a871d5f224010 | 3,627,425 |
def GetCreateLabelsFlag(extra_message='', labels_name='labels',
validate_values=True):
"""Makes the base.Argument for --labels flag."""
value_type = VALUE_FORMAT_VALIDATOR if validate_values else None
format_help = [KEY_FORMAT_HELP]
if validate_values:
format_help.append(VALUE_FORMAT... | aa8e5e6f40d2a9ab53668ff16b5c9227bca42541 | 3,627,426 |
import six
def unflatten(d, splitter='tuple', inverse=False):
"""Unflatten dict-like object.
Parameters
----------
d : dict-like object
The dict that will be unflattened.
splitter : {'tuple', 'path', Callable}
The key splitting method. If a Callable is given, the Callable will be
... | 44100cfcc8d3cc399f94bd6d3f6e7e780d7a1012 | 3,627,427 |
def get_mapped_to_elements(mapper):
"""
The mapper list contains all the element names that have been mapped to by
other elements
"""
mapper_list = []
for element in mapper:
for list_element in mapper[element]:
if list_element not in mapper_list:
mapper_list.a... | 6f8d940997f4b871b6934db0592663448343e031 | 3,627,428 |
def psd(time, rate, norm='leahy'):
"""
Returns power spectral density from a (real) time series
with Leahy normalization.
Args:
time: array of times (evenly binned).
rate: array of rate in counts/s.
Kwargs:
norm: Normalization (only Leahy for ... | 878dda8fc3821560335d7b14fc0d8863b2f0f84e | 3,627,429 |
async def session_fetch(
handle: SessionHandle, category: str, name: str, for_update: bool = False
) -> EntrySetHandle:
"""Fetch a row from the Store."""
category = encode_str(category)
name = encode_str(name)
return await do_call_async(
"askar_session_fetch",
handle,
categor... | ab3c0a9ec2006e4b83b8c2018c3dcf529f9f532d | 3,627,430 |
def login(hostname, username, password):
"""Login to the switch and return the console with the prompt at `#`"""
try_again = True
alternatives = [r'[\r\n]+.+#',
"Permission denied",
"[Pp]assword: *",
">",
"(ibmnos-cli/iscli):*",... | b705470108c07ca88497e883e1c55325596ad36c | 3,627,431 |
def _ComputeImageDiff(failure_image, golden_image):
"""Compute mask showing which pixels are different between two images."""
return (ImageChops.difference(failure_image, golden_image)
.convert('L')
.point(lambda i: 255 if i else 0)) | e830aff6434928d1b32b76bfc61b7fc366c24a36 | 3,627,432 |
def load_pytest_conf(path, parser):
"""loads a ``pytestconf.py`` file and update default parser
and / or tester.
"""
namespace = {}
exec(open(path, 'rb').read(), namespace)
if 'update_parser' in namespace:
namespace['update_parser'](parser)
return namespace.get('CustomPyTester', PyTe... | 435584078584538adadd0feb7455f2010e1cdc4c | 3,627,433 |
def svn_client_import3(*args):
"""
svn_client_import3(svn_commit_info_t commit_info_p, char path, char url,
svn_depth_t depth, svn_boolean_t no_ignore,
svn_boolean_t ignore_unknown_node_types, apr_hash_t revprop_table,
svn_client_ctx_t ctx,
apr_pool_t pool) -> svn_error_t
"... | a10005cfcafa90fab40efaa84b8c69f461a7e772 | 3,627,434 |
def labs(**kwargs):
"""
Change plot title, axis labels and legend titles.
Parameters
----------
kwargs:
A list of new names in the form aesthetic='new name',
e.g. title='Plot title' or aes-name='Scale label'
Returns
--------
Axis label specification.
Note
-... | 84820d0a626e623919957ff48b5a95f4a28d3756 | 3,627,435 |
def _filter(paths, cgroups, rgroups):
""" Keep only paths with the appropriate cgroups and/or rgroups
"""
kept = []
for path in paths:
valid_cgroup = (cgroups is None or _cname(path) in cgroups)
valid_rgroup = (rgroups is None or _rname(path) in rgroups)
if valid_cgroup and valid... | a90b89be831bcad3da9ed4e692c0d78d232537b3 | 3,627,436 |
def patch(target, new):
"""Simplified module monkey patching via context manager.
Args:
target: Target class or object.
new: Object or value to replace the target with.
"""
def _import_module(target):
components = target.split('.')
import_path = components.pop(0)
... | c5d9fbf37d35991938838bc813ebc443c9934304 | 3,627,437 |
def _load_with_pydub(filename, audio_format):
"""Open compressed audio file using pydub. If a video file
is passed, its audio track(s) are extracted and loaded.
This function should not be called directely, use :func:`from_file`
instead.
:Parameters:
`filename`:
path to audio file.
... | b16fa9897afd63650c2de66765aec6710ae131cc | 3,627,438 |
from typing import Optional
def get_storage(store: Optional[StorageEngine] = None) -> StorageEngine:
"""Get current storage method."""
if store is not None:
return store
else:
if _storage_stack.top is not None:
out: StorageEngine = _storage_stack.top
return out
... | eeeaa059feacd22aa8c3b79e10b9826d49108af5 | 3,627,439 |
def UniformDot(d=100, p=100, tol=1e-2):
"""
Let U be a random `d` x `p` matrix with i.i.d. uniform
entries. Then Sigma = ``cov2corr``(U^T U)
"""
U = np.random.uniform(size=(d, p))
V = np.dot(U.T, U)
V = cov2corr(V)
return cov2corr(shift_until_PSD(V, tol=tol)) | a8c491c01f9f47dc1442f476c363bff1ae588f3a | 3,627,440 |
def get_supported_eline_list(*, lines=None):
"""
Returns the list of the emission lines supported by ``scikit-beam``
Parameters
----------
lines : list(str)
tuple or list of strings, that defines, which emission lines are going to be included
in the output list (e.g. ``("K",)`` or ... | c711a66b2d8b8c1017d75024e93d18668d0b8106 | 3,627,441 |
def visualize_test(test_data_full, test_data, thetas):
"""
Visualize Test for Testing Results
:param test_data_full: the test data set (full) with labels and data
:param thetas: model parameters
:return: fig
"""
fig, ax = plt.subplots()
ax.scatter(test_data_full... | 2d84204578b7cb26ebda381c5f2a25319d0fee93 | 3,627,442 |
def normalization(data, dmin=0, dmax=1, save_centering=False):
"""
Normalization in [a, b] interval or with saving centering
x` = (b - a) * (xi - min(x)) / (max(x) - min(x)) + a
Args:
data (np.ndarray): data for normalization
dmin (float): left interval
dmax (float): right interval
save_centering (bool): if... | acfa7aaae1bb7eb5752751f5c929ddb7868ccf49 | 3,627,443 |
def normalize_adjacency_matrix(adjacency_matrix):
"""
Helper function for denoise_predictions.
Arguments:
adjacency_matrix: A matrix of size h * w,
https://en.wikipedia.org/wiki/Adjacency_matrix
For this type of normalization, should be symmetric - i.e. from an... | 60043f8ee4ee8cf19c33dec683b0c8fc28d3d1fb | 3,627,445 |
import six
import struct
def dl_parse_bsd_lo(link_packet):
"""parse bsd loopback packet"""
if len(link_packet) < 4:
return None, None
# first 4 bytes are packet size which always less then 256, may be LE or BE
if six.byte2int(link_packet) == 0 and six.indexbytes(link_packet, 1) == 0:
p... | 2d1a7eb62742ce8f43b11b836e9ad8fe78d3a097 | 3,627,446 |
def energycalc(spcode0, climatezone, dbh_orig, height, azimuth, distance, vintage, shade_reduction, lu_conversion_shade, lu_conversion_climate, eqpt_cooling_potential, eqpt_heating_potential):
"""Calculates avoided emissions values given tree and building relationship data.
Args:
spcode0 - species cod... | 3164bf258aef232093541f6f421becd034461cbe | 3,627,447 |
def _create_scene_object(token: str, object_type: TrackedObjectType) -> Agent:
"""
:param token: a unique instance token
:param object_type: agent type.
:return: a random Agent
"""
scene = SceneObject.make_random(token, object_type)
return Agent(
tracked_object_type=object_type,
... | 1d71b8a25980f40768900aaf22874b11b5b3fc99 | 3,627,448 |
def conv3x3_group(in_planes, out_planes, groups=1, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, groups=groups, stride=stride,
padding=1, bias=False) | f594509979bffc438fb459b15ddc3a64c9a1220d | 3,627,449 |
def named(name):
"""Change the name of something (via a decorator)."""
def decorator(obj):
obj.__name__ = name
return obj
return decorator | 5b4873e7e6475e23ab13cd1fc203d6c79622d96d | 3,627,450 |
def split_repo_and_dir(repo):
"""
Split the input string
org-name/repo-name/subdir-name/more/sub/dirs
(where '/subdir-name/more/sub/dirs' is optional) into
org-name/repo-name
and
subdir-name/more/sub/dirs
The second part might be the empty string if no subdir-name was given.
"""
parts = repo.s... | c5cfb58fa0780af0391fc07fa78279af4f5c2790 | 3,627,451 |
import requests
def hits_recorded(pitcher_id=None):
"""Get the number of hits recorded by each historical pitcher. If pitcherId is specified, only that pitcher is returned.
`pitcher_id` is a single string UUID or list of string UUIDs.
Returns dictionary {pitcher_id: count}"""
params = {}
if pitch... | 3b0b2e81ce35ad0437c1721a18518ab3b6ed53ff | 3,627,453 |
def calculateOnlineVariance(data):
"""
Returns the variance of the given list.
:param data: A list of numbers to be measured (ie. the window)
:returns: The variance of the data.
"""
n, mean, M2 = 0, 0, 0
for x in data:
n = n + 1
delta = x - mean
mean = mean + delta/n
M2 = M2 + delta*(x-mean)
varian... | bf8d70cd736471e4723db07fb609aff6a7ccec50 | 3,627,454 |
def clamp(x, xmin, xmax):
"""Constrain a value to lie between two further values, element-wise.
The returned value is computed as `min(max(x, xmin), xmax)`.
The arguments can be scalars or :class:`~taichi.Matrix`,
as long as they can be broadcasted to a common shape.
Args:
x (:mod:`~taichi... | 80b4ef6224031502cf444b86141398ba60c77bda | 3,627,455 |
def anim_curve_exists(attr_curve_name):
"""
"""
anim_curve = get_anim_curve(attr_curve_name)
if not anim_curve:
return True
else:
return False | 03f84bf231fa6100574c4ff3c6cc516e48a5a95b | 3,627,456 |
from datetime import datetime
def create_string(item):
"""Create strings for tests."""
return WEBEX_TEAMS_TEST_STRING_TEMPLATE.substitute(
prefix=WEBEX_TEAMS_TEST_STRING_PREFIX,
item=item,
datetime=str(datetime.datetime.now())
) | b6c9ebfc38a7a3b875b2bfec531a5fc64e94eb59 | 3,627,457 |
from typing import List
def save_image_with_legends_and_labels(save_path: str, image: np.ndarray, legends: List[Rectangle],
labels: List[str]) -> (plt.Figure, plt.Axes):
"""
Saves the given image with the given legends rects and labels
Args:
save_path: the p... | 6c485c8fb367fcc7301ad68d08c674f615574bf9 | 3,627,458 |
from datetime import datetime
import time
def nod_uploadkey(private, own=False, date=None):
"""Generate the key for the next News of the Day entry.
>>> nod_uploadkey("USK@foo,moo,goo/WebOfTrust/0", own=False, date=datetime.datetime(2010,1,1))
'SSK@foo,moo,goo/nod-shared-2010-01-01'
>>> nod_uploadkey(... | ec51a0b56e3922c0c5d9f74d2885086e582d729d | 3,627,459 |
def is_struct(struct):
""" Checks if the message is a data structure or an rpc
request/response"""
return (not struct.name.endswith("Request") and
not struct.name.endswith("Response")) | 0dbce36cad826988cc18d86a31b91f2090d5e338 | 3,627,460 |
def relative_round(value, relative_digits):
"""Rounds to a given relative precision"""
if isinstance(value, tuple):
return tuple((relative_round(x, relative_digits) for x in value))
if value == 0 or isinstance(value, str) or np.isnan(value) or np.isinf(value):
return value
value_preci... | 932665f95969c603b053e6ce18415f78abd43891 | 3,627,461 |
import xmlrpc
def get_pypi_proxy():
"""Returns a RPC ServerProxy object pointing to the PyPI RPC
URL.
:rtype: xmlrpclib.ServerProxy
:return: the RPC ServerProxy to PyPI repository.
"""
return xmlrpc.client.ServerProxy(PYPI_XMLRPC) | 26439fb81911aeb3ca864f1883be9b84d176752c | 3,627,462 |
def replace_labels(code):
"""
Replaces free labels in `code` with integers, and accordingly any label call / branch.
For example, code:
('BRANCH', 'L0')
('LABEL', '2+')
('1+',)
('EXIT',)
('LABEL', 'L0')
returns:
('BRANCH', 1)
('LABEL', 0)
... | 92384d83020021543d2e2f85a79d4df9f6e9017e | 3,627,463 |
import pandas as pd
from typing import Union
from pathlib import Path
import tarfile
def read_tarfile_csv(path: Union[str, Path], inner_path: str, sep: str = "\t", **kwargs):
"""Read an inner CSV file from a tar archive.
:param path: The path to the tar archive
:param inner_path: The path inside the tar ... | 24b3183da5787c095e78fc1bc7a1ed4e4012d6d2 | 3,627,464 |
def hasReturnType(matcher):
"""Match a function/method with a specified return type
>>> from glud import *
>>> config = '''
... class X {};
... X u();
... int v();
... '''
>>> m = functionDecl(hasReturnType(builtinType()))
>>> for c in walk(m, parse_string(config).cursor):
... ... | dbc9ab35f5bd3184080252c5feb9858df573217f | 3,627,465 |
from pathlib import Path
def calc_path(filename):
"""Calculate a filepath based off of current file"""
logger.info("calc_path filename: %s", filename)
if filename is None:
return None
filepath = Path(filename)
if not filepath.is_absolute():
filepath = Path(__file__, "..", filepath)... | ee5ef9a645194a4c6ea334d57a3499dbbc7a50f0 | 3,627,466 |
def get_enum_map(mri, name):
""" Returns enum value to name and name to enum value map.
@param mri mri instance
@param name name of enum """
ret = {}
tdm = mri.engine.tdm
n = len(name) + 1
roles = tdm.getByHierarchicalName(name)
constants = roles.getConstants()
for c... | e781790c7e7f5a24e12fb986e2e45d735157a7b6 | 3,627,467 |
import time
def CreateWebsList(AssetInfo, TimePause, TimesFetch):
""" Get web pages """
AssetTickers = list(AssetInfo.keys())
# Create a linked list for every asset
WebsLists = dict()
for s in AssetTickers:
WebsLists[s] = WebLinkedList.WebList()
# Start crawling
for t in range(Tim... | f1bb57d56360d596d33769100f101d9f7ba74ef7 | 3,627,468 |
def spatial_filter(x, y, z, dx, dy, sigma=3.0):
"""
des: outlier filtering within the defined spatial region (dx * dy).
arg:
x, y: coord_x and coord_y (m)
z: value
dx, dy: resolution in x (m) and y (m)
n_sigma: cut-off value
thres: max absolute value of data
retu... | ff1f5f8af17b2cce453ec1c75e4df5eafbaf5957 | 3,627,469 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.