content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def generate_layer_name(layer):
"""
Generates unique name for layer.
Parameters
----------
layer : BaseLayer
Returns
-------
str
"""
cls = layer.__class__
layer_id = cls.global_identifiers_map[cls]
cls.global_identifiers_map[cls] += 1
classname = cls._... | 8cce0bf0c68601dcbed2c0852a563243cd818743 | 3,615,662 |
import pkg_resources
def get_costs_gas_pipeline():
"""Return the full path with file name and extension to the default costs per km to gas connect to pipelines."""
return pkg_resources.resource_filename('cerf', 'data/costs_gas_pipeline.yml') | 1dfde6366c286665deb34bb4c9e3f58fe8b31dd6 | 3,615,663 |
import functools
def _tsvector_column(*columns):
""" Creates an expression for tsvector values with weights from a number of
columns.
"""
vectors = []
for column, weight in columns:
tsvector = db.func.to_tsvector("english", column)
if weight in ["A", "B", "C", "D"]:
... | c08e3cfda9ef1da8fecc3313a2429c77864161ca | 3,615,664 |
def minimum_weighted_distances(df1, df2, weights):
"""
Compute minimum weighted distance from one DataFrame to another.
Args:
df1 (pandas.DataFrame):
The fixed reference points. Each column is a dimension, and
each row is a point.
df2 (pandas.DataFrame):
... | f2a73337fdfbf320c79d569ddce2122ae4b81054 | 3,615,665 |
from typing import List
def merge_kwargs(config: ConfigType, markers: List[Mark]) -> ConfigType:
"""Merge all kwargs into a single dictionary to pass to `vcr.use_cassette`."""
kwargs = deepcopy(config)
for marker in reversed(markers):
kwargs.update(marker.kwargs)
return kwargs | 149737a48d61860744d6f50c65a11d5fe424e24d | 3,615,666 |
import math
import statistics
def calculate_mean(arr, log):
"""Calculate mean and sd of arr values."""
n = len(arr)
if log:
logged_arr = [math.log10(value) for value in arr if value > 0]
if not logged_arr:
return 0, 0, n
mean = math.pow(10, statistics.mean(logged_arr))
... | 9103bffe97696f4441a2d6a28352a55ee1be30cb | 3,615,667 |
def recv_meas_outcome(socket):
"""Receive the measurement outcome (0 or 1) of the server's
last measurement.
"""
return int(socket.recv(maxsize=1)) | f49717272722be1476cb9bcc08bcbe7b8525c2ba | 3,615,668 |
def profil():
"""Prikaži stran uporabnika"""
username = get_user()
cur.execute("SELECT COUNT(*) FROM recept JOIN uporabnik ON uporabnik.id = recept.uporabnik WHERE uporabnik.ime=%s", [username])
[[st_receptov]] = cur.fetchall()
cur.execute("SELECT id FROM uporabnik WHERE ime=%s", [username])
[[i... | c3a53b1d224f4e1109b7b5c92ebe1a8230850bb5 | 3,615,669 |
def siteManagerAdapter(ob):
"""Look-up a site manager/component registry for local component
lookup. This is registered in place of the one in zope.site so that
we lookup using acquisition in addition to the ``ILocation`` API.
"""
site = findSite(ob)
if site is None:
return zope.compone... | ca359600a821c7205f483a20c548368755c4e878 | 3,615,670 |
def convert_to_excel_data(lines_: list[Line]) -> tuple[list[float], list[float]]:
"""直線のリストをx座標のリストとy座標のリストに変換します。
Args:
lines_ (list[Line]): 直線のリスト
Returns:
typle[list[float], list[float]]:
x座標のリストとy座標のリスト
Examples:
>>> convert_to_excel_data([((0, 0), (1, 2)), ((1... | 1dd6d44ffdf067a484940cdbfa7fcfb88289052c | 3,615,671 |
def create_seasons(session, start_yr, end_yr):
"""
Adds Years and calendar and European Seasons records to database.
:param session: Transaction session object.
:param start_yr: Start of year interval.
:param end_yr: End of year interval, inclusive.
"""
def exists(model, **conditions):
... | 6cdefa5ee98ebc0671bc888d9ea419a965afd68b | 3,615,672 |
def mean_orientation(data: pd.DataFrame, static_moments: pd.DataFrame) -> pd.DataFrame:
"""Compute mean orientation of acceleration signal within static moment windows.
Parameters
----------
data : :class:`~pandas.DataFrame`
input data
static_moments : :class:`~pandas.DataFrame`
dat... | 3127b47a2bb8b70f3c42ba33cf0916455b524e9e | 3,615,673 |
def get_cse_policy_display_name(policy_name):
"""Remove cse specific prefix from the given policy name.
:param str policy_name: name of the policy
:return: policy name after removing cse specific prefix
:rtype: str
"""
if policy_name and \
policy_name.startswith(CSE_COMPUTE_POLICY_... | 932f73b46a06838f5e16d4c1969d94734e805459 | 3,615,674 |
def top_percentile(year=now().year, percentile_groups=PERCENTILE_GROUPS):
""" This is calculate top percentile of top_percentile_value
:return: list of (officer_id, percentile_value)
# """
if any(t not in PERCENTILE_GROUPS for t in percentile_groups):
raise ValueError("percentile_group is invali... | 593bedd74e2cd56b212bb70c05fea0860c264fa2 | 3,615,675 |
def get_shortest_dist(this_point, other_points):
"""Get shortest (distance, index of other point) from this_point (x,y) and list of other_points [(x,y), (x,y), ...]"""
dists = get_all_dists(this_point, other_points)
min_dist, other_point_ind = min((val, idx) for (idx, val) in enumerate(dists))
return mi... | 4daa4848e2700f2b0cf1ab9924fc5a96b223c93e | 3,615,676 |
def runconfiguration_transformer(values):
"""Calls transform_project_data with corresponding header"""
return transform_project_data(values, "Run configuration") | b95a11e18f2ff1fdaf2f5a45b1f78dc024332a0a | 3,615,677 |
def get_provider_manager(osid, runtime=None, proxy=None, local=False):
"""
Gets the most appropriate provider manager depending on config.
If local is True, then don't bother with the runtime/config and
try to get the requested service manager directly from the local
service implementations known t... | ddd5e9f5c38443a7b82b5b5aa35b58702234a831 | 3,615,678 |
from pathlib import Path
import xml
def read_xml_file(xmlfilename, decode='utf-8'):
"""
读取xmlfile文件,并指定文件的解码方式,默认为utf-8
返回dom树
:param xmlfilename:
:param decode:
:return:
"""
if isinstance(xmlfilename, Path):
xmlfile: Path = xmlfilename
else:
xmlfile = Path(xmlfilen... | bd67af74b99bd1b459214527b815de9f4ae54a4d | 3,615,679 |
import time
import requests
import json
def get_cap_key():
"""
获取验证码初始化 ID
:return:
"""
url = 'https://shieldcaptain.mogu.com/gettoken'
params = {
'auth': get_auth({}),
'_': int(time.time() * 1000),
'callback': ''
}
resp = requests.get(url, params=params, head... | 33a8ebd359760bb508da671e8988821816eb36c6 | 3,615,680 |
from glue.core.exceptions import IncompatibleAttribute
def facet_subsets(data_collection, cid, lo=None, hi=None, steps=5,
prefix='', log=False):
"""Create a series of subsets that partition the values of
a particular attribute into several bins
This creates `steps` new subet groups, add... | f64205077c4e76d1990b87cc814237d9eb79e2ab | 3,615,681 |
def kl_test(df_in: DataFrame, df_out: DataFrame, attr: str):
"""
df_in: the sensitive dataset
df_out: the synthetic dataset
attr: the attribute that will be calculated for KL-divergence.
"""
distribution_in = get_distribution_of_categorical_attribute(df_in[attr])
distribution_out = get_distr... | 8a2abbd93b9a2f6639b9645f70a384f1a1806b67 | 3,615,682 |
def get_or_create_data_version(paper_id: str) -> int:
"""
Get the index for the version of data produced by the current pipeline session. If a version
index hasn't yet been created for this session, create one by incrementing the last version
number found for this paper in the database.
"""
try:... | 2fbd85f34feeb1f46895a8f10f03bfd1b5643d01 | 3,615,683 |
import base64
def make_basic_auth_header(username, password):
"""
create a basic authentication header
:param username: user name [unicode on py2, str on py3]
:param password: password [unicode on py2, str on py3]
:return: basic auth header [str on py2, str on py3]
"""
# note: the coding ... | 69900bbc73a4df8e0f2f932a30e6acdb08cb9c4d | 3,615,684 |
def xavier_init(fan_in, fan_out, const=1, dtype=tf.float32):
"""Xavier initialization."""
low = -const * np.sqrt(3.0 / (fan_in + fan_out))
high = const * np.sqrt(3.0 / (fan_in + fan_out))
return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high, dtype=dtype) | ba17ef1e0b652580dc05fae4bc21d4f7eb303dd4 | 3,615,685 |
def plot_g_e(sco, log=False):
"""
plot log expression sum and detected gene counts
for cell inspect
should not be applyed to normalized expression
log:
if input data already log transformed
"""
expression = sco.expression_matrix
bm = expression > 0
if log:
x = log... | 061a06227421917fd305627620b8759a2a9ce924 | 3,615,686 |
def wrap_deepmind(env: gym.Env,
episode_life: bool = True,
clip_rewards: bool = True,
frame_stack: int = 4,
scale: bool = False,
warp_frame: bool = True,
channel_first: bool = True):
"""Configure environment for DeepMind-style Atari. Th... | 0d89c717356065af5c8ef9468aa4bbde8d2b1fc2 | 3,615,687 |
def get_test_data_path():
"""Returns the path to test datasets """
return join(dirname(__file__), "data") | 2e675f82e0bdda99f868c9172c9cf97b1a6d4d4e | 3,615,688 |
from typing import Union
def alfa_key(alfa: Union[str, int]) -> Union[str, None]:
"""
Return the numeric value of a possible alfanumeric key name. See "alfanumeric key names".
Parameters
----------
alfa : str | int
The package name from "alfa numeric names" list
or the corresponde... | f800ec179075f00264d3d797c3df6bcf1e6b80da | 3,615,689 |
import base64
import json
def get_config() -> Config:
"""Reads environment variables to a Config object."""
gcs_bucket_name = env_require("GCS_BUCKET_NAME")
gcs_bucket_prefix = env_require("GCS_BUCKET_PREFIX")
gcp_service_account_credentials_base64 = env_require(
"GCP_SERVICE_ACCOUNT_CREDENTIA... | 0bd1dbd46cb6d162bd444a42a8ac8aafb938b600 | 3,615,690 |
def log_in():
"""
The Simplest API login.
:param requestBody: require passing correct login and password of
existing user
:return JWT: encoded authorization token for given user on success,
401/404 on incorrect credentials
"""
user = request.get_json()
lgn = user['login']
pwd ... | a85e49f082ea3f03ac05a783839a1fe2e6caacf2 | 3,615,691 |
from typing import List
def truncate_blocks_text(blocks: List[SlackBlock]) -> List[SlackBlock]:
"""Modifies blocks to restrict all text to 3000 characters."""
for block in blocks:
try:
block['text']['text'] = block['text']['text'][:3000]
except KeyError:
pass
retur... | 2839f6a2bcbc335aca82b3cfc5ed81357ba4b37b | 3,615,692 |
def generate_magic(s: int, bits: int, bishop: bool):
"""Generate magic bitboards for fast lookups on sliding piece attacks.
Taken from: https://www.chessprogramming.org/Looking_for_Magics
We are precomputing the attack set considering
all variations of blockers (max 4096 == 2**12, rook on a1)
"""... | 700619b8f65b9d3d6e9a4dcb6f10eb3b49e42cd2 | 3,615,693 |
import json
import http
def user_inputsAPI():
"""API for storing new user input
payload is json style of shape:\n
{
"data": [float, float]
}
"""
data = json.loads(request.get_data())
accepted, complete = processor.process(data["data"])
content = {"clear": not accepted, 'comple... | 6ce2afc57d464de0a09211803eb6376026b2596f | 3,615,694 |
def truncated_pareto_expval(alpha, m, b):
"""
Expected value of truncated Pareto distribution.
"""
if alpha <= 1:
return inf
part1 = (m ** alpha) / (1. - (m / b) ** alpha)
part2 = 1. * alpha / (alpha - 1)
part3 = (1. / (m ** (alpha - 1)) - 1. / (b ** (alpha - 1.)))
return part1 ... | 869e71ea3bc31e277ab3a8fbe062d96e84e173d3 | 3,615,695 |
def update_team(
*,
db_session: Session = Depends(get_db),
team_contact_id: PrimaryKey,
team_contact_in: TeamContactUpdate,
):
"""Update a team contact."""
team = get(db_session=db_session, team_contact_id=team_contact_id)
if not team:
raise HTTPException(
status_code=sta... | 20083f7ceaa35bd31d62bb9cdd8cfa56d5a0255e | 3,615,696 |
def word_to_col(w):
"""Splits a hexadecimal string to a bytes column.
Parameters
----------
w : str
Hexadecimal 32-bit word.
Returns
-------
list
4 bytes column containing integers representing the input string.
"""
x = int(w, 16)
return [x >> 24, (x >> 16) & 0... | 540dabd4e42eb68ce166f608bfa849b31f1bc2fe | 3,615,697 |
def _create_documents_per_words(freq_matrix: dict) -> dict:
"""
Returns a dictionary of words and the number of documents in which they
appear.
:param freq_matrix: The frequency matrix to be summarized.
:return: A dictionary of words and the number of documents in which they appear.
"""
doc_... | 3b25081ce3452629de9fdd6afd122bd058ee9acf | 3,615,698 |
def odin_connection():
"""Connects to the database, returns a connection"""
connection_string = (
"host={0} ".format(environ.get("PGHOST")) +
"dbname={0} ".format(environ.get("PGDBNAME")) +
"user={0} ".format(environ.get("PGUSER")) +
"password={0}".format(environ.get("PGPASS"))
... | 51f2a52fea202fe70ab0d0336bb63c8fe4a39283 | 3,615,699 |
import inspect
def is_mass_profile_class(cls):
"""
Parameters
----------
cls
Some object
Returns
-------
bool: is_mass_profile_class
True if cls is a class that inherits from mass profile
"""
return inspect.isclass(cls) and issubclass(cls, mass_profiles.MassProfile... | d27423ff46d0e548b6cccce3d7f0389ba40c48a0 | 3,615,700 |
def superuser_required_or_403():
"""
Decorator to make a view only accessible as a superuser or it will raise
PermissionDenied.
Usage::
@superuser_required_or_403()
def a_view(request):
# I can assume now that the view is only accessible as a superuser.
"""
def deco... | ff949d00a987c66b197bc4b16ce682fe1392e74c | 3,615,701 |
def pullback(b, c, d, b_d, c_d, inplace=False):
"""Find the pullback from b -> d <- c.
Given h1 : B -> D; h2 : C -> D returns A, rh1, rh2
with rh1 : A -> B; rh2 : A -> C and A the pullback.
"""
if inplace is True:
a = b
else:
a = type(b)()
# Check homomorphisms
check_ho... | d27bcded897f9f2b26bda7b9b5434eb4bcfa59b9 | 3,615,702 |
def corr_therm2_sp(omega, x, y, disp=True):
"""Remove the thermal component in an OMEGA spectrum, with simultaneous retriving
of reflectance and temperature.
Parameters
==========
omega : OMEGAdata
The OMEGA observation data.
x : int
The x-coordinate of the pixel.
y : int
... | e097c500274ee6b93a76761a8b39b95f776f2a38 | 3,615,703 |
def amplitude_rate_modulation(y, sr, difficulty):
"""This function uses the average amplitude (i.e., 'loudness') of a beat and the difficulty level to determine
how many blocks will be placed within the beat. Returns a list of beat numbers."""
#Make amplitude matrix
D = np.abs(librosa.stft(y))
db =... | fc41a59de2f8b2d425ae99350ed22c93cbefb3f6 | 3,615,704 |
def _raise_missing_if_result_is_none(function):
"""
Raise MissingAccountData if function's result is None.
adapted from https://github.com/Backblaze/b2-sdk-python/blob/v1.5.0/b2sdk/account_info/in_memory.py
"""
@wraps(function)
def getter_function(*args, **kwargs):
assert function.__nam... | 97f00a0e1d3038b3d8efb324d9d1e666bcb0122f | 3,615,705 |
def nb_pixels(info_dict):
""" Compute the number of pixels affected by the target light
Parameters
----------
info_dict: dictionnary
wavelength: float
wavelength in angstrom
Returns
--------
npix: float
number of pixels affected by the target light (ceiled)
... | b2afabad96183031bb5bba80b030adffeb15fac6 | 3,615,706 |
from typing import Optional
from typing import Dict
from typing import Any
def get_rnn_layer(reservoir_weight: Optional[np.ndarray] = None,
reservoir_params: Optional[Dict[str, Any]] = None,
layer_name: str = "LSTM",
units: int = 200,
return_sequ... | fb8b4cb891fd3481413ff1ac9d86104412f4c0cf | 3,615,707 |
def generate_regenet_arch(initial_width, width_slope, quantilize, width_m, depth, bottleneck_ratio, group_width):
"""
Inspired by the observation from AnyNetXd and AnyNetXe
"""
assert width_m > 0, 'width_m must be greater than 0'
# Generate block widths and depths via Eq.2 ~ Eq.4 in the paper
w... | 2a17f308e972a810c1bfbcbd06e937faf9572841 | 3,615,708 |
def fetch(dataset, annot, cat=(0, 0, 0, 0), evt_type=None, stage=None,
cycle=None, chan_full=None, epoch=None, epoch_dur=30,
epoch_overlap=0, epoch_step=None, reject_epoch=False,
reject_artf=False, min_dur=0, buffer=0):
"""Create instance of Segments for analysis, complete with info ab... | b52886e2f297a304b5289964a3ea40bff104e567 | 3,615,709 |
def polar(a, side="right", compute_p=False):
"""
Compute the polar decomposition. This is a transcription of the
SciPy code - check scipy.linalg.polar for documentation.
"""
if side not in ['right', 'left']:
raise ValueError("must be either 'right' or 'left'")
a = np.asarray(a)
if a... | cb9cda7922c89e2424cc959a3cde96b55daf62aa | 3,615,710 |
def replace_file_type(file_name, new_type):
"""
:param file_name:
:param new_type:
:return:
"""
file_name_parts = file_name.split(".")
return file_name.replace(file_name_parts[len(file_name_parts)-1], new_type) | c6fd9e01befb0e6f1a96f8884fc9d00332741948 | 3,615,711 |
from typing import OrderedDict
def _text_to_df(text_file, encoding=None):
"""
Convert a raw E-Prime output text file into a pandas DataFrame.
"""
# Load the text file as a list.
if encoding is None:
with open(text_file, 'rb') as fo:
text_data = list(fo)
# Remove unico... | b3b702c4913978fec5ea15e18c7a63bb525cdf3f | 3,615,712 |
def findmatch1(x, xsearch, tol=1e-4):
"""RETURNS THE INDEX OF x WHERE xsearch IS FOUND"""
i = argmin(abs(x - xsearch))
if tol:
if abs(x[i] - xsearch) > tol:
print(xsearch, 'NOT FOUND IN findmatch1')
i = -1
return i | a3de2eb758d1958bad2baf9dc6cb5128da13418a | 3,615,713 |
import cProfile
def profile(func):
"""Decorator for run function profile"""
def wrapper(*args, **kwargs):
global i
profile_filename = 'profile/' + func.__name__ + '%06d' % i + '.prof'
i += 1
profiler = cProfile.Profile()
result = profiler.runcall(func, *args, **kwargs)
... | 5135f5c7275ba0997bc60a6fc262b841c849f86a | 3,615,714 |
import functools
def nonced(method):
""" Decorates a handler to only accept requests with nonce header.
If the request is missing the request handler we set the status as 400 with
a malformed message.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if self.nonce_servic... | 1cfdd6966fdd7986b0ee85a927a6f7f6acbcfdf7 | 3,615,715 |
def userToJson(user):
"""Returns a serializable User dict
:param user: User to get info for
:type user: User
:returns: dict
"""
obj = {
"id": user.id,
"username": user.username,
"name": user.get_full_name(),
"email": user.email,
}
return obj | da5e11bbc2e8cbdffb25e32e6a47e0ccabe8d33a | 3,615,716 |
def create_checkbox_group(names, kind, button_dict):
"""Creates a dictionary containing all checkboxes for set selection and a group
widget containing all of them for display."""
box_dict = {}
if kind == "Sets":
names = [set_ for set_ in names if set_ not in ["Intrigue", "Base"]]
tooltip... | fa1c5023bd9dde06ad219f58ffecabe9327c7aa6 | 3,615,717 |
from typing import DefaultDict
from typing import Set
def dijkstra(source: OrientedWay) -> SingleSourceMap:
"""Dijkstra algorithm."""
info: DefaultDict[OrientedWay, _NodeInfo]
node: OrientedWay
visited: Set[OrientedWay]
queue = FibonacciHeap()
visited = set()
source_info = _NodeInfo(0.0)
... | e3bccad8885165ca90c515846b1d57d9f0f361bc | 3,615,719 |
def gcv(data, channels=None):
"""
Calculate the geometric CV of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or... | d1e3caa02705114b2c86bca0cbb10b9f3a8dfe0f | 3,615,720 |
def compute_fail_probability(rankings, mtable):
"""
This computes experimentally how many of the M rankings fail to satisfy the mtable
:param rankings: rankings that are checked (list of lists of FairScoreDoc)
:param mtable: an mtable to check against (list of int)
:return: the ra... | 1bcfd13477918625fa0c50c88f3e98713cddb237 | 3,615,721 |
def copy_group(source_globals_file, source_groupname, dest_globals_file, delete_source_group=False):
""" This function copies the group source_groupname from source_globals_file
to dest_globals_file and renames the new group so that there is no name
collision. If delete_source_group is False the cop... | 765b2e6926327c75d647181b66deb5911770ce1c | 3,615,722 |
def build_client(username=None):
"""Build a Spotipy client scoped for use."""
username = get_username(username)
auth = util.prompt_for_user_token(
username,
scope='playlist-modify-private playlist-modify-public',
)
return spotipy.Spotify(auth=auth) | 6c941033034a36e54e05ae01118446078efdb0de | 3,615,723 |
from typing import Callable
from typing import Any
from typing import Tuple
from typing import Dict
def write_score(func: Callable[[Any, Any], Any]) -> (Tuple[Any, ...], Dict[str, Any]):
"""
Save the store data of the decorated function in a file.
:param func: a function
:precondition: input paramete... | a37ed83f6fc0c2da21ad043fe5855b16478b6d6c | 3,615,725 |
from datetime import datetime
def get_places_around_centroid(point, radius, place_type):
"""
Find places of place_type within a radius around a centroid
and add to database.
:param point: the centroid, of type Point
:param radius: radius (in metres)
:param place_type: type of place to be searc... | 6f175269838776c854777c80f4d3e8e59081258f | 3,615,726 |
def remove_indices_from_dict(obj):
"""
Removes indices from a obj dict.
"""
if not isinstance(obj, dict):
raise ValueError(u"Expecting a dict, found: {}".format(type(obj)))
result = {}
for key, val in obj.items():
bracket_index = key.find('[')
key = key[:bracket_index] i... | 60842ed62b2d79852661f83699bf3bf92b63084a | 3,615,728 |
def relative_uri(base, to):
"""Return a relative URL from ``base`` to ``to``."""
if to.startswith(SEP):
return to
b2 = base.split(SEP)
t2 = to.split(SEP)
# remove common segments (except the last segment)
for x, y in zip(b2[:-1], t2[:-1]):
if x != y:
break
b2.... | fb94a8c1e2b4fc383db26657301e8fed0988562c | 3,615,729 |
def find_block(csv, name):
"""For an Illumina SampleSheet.csv, return a tuple of the index of the
line containing the header specified by name, and the index of the
line just past the end of the data block. `range(*r)` will index
all lines for the block, starting at the header line.
"""
start = ... | 7a1fc119e6e3e889d9a18884028cb2e6a67e0cd5 | 3,615,731 |
def ootf_reverse_BT2100_HLG(F_D, L_B=0, L_W=1000, gamma=None):
"""
Defines *Recommendation ITU-R BT.2100* *Reference HLG* reverse opto-optical
transfer function (OOTF / OOCF).
Parameters
----------
F_D : numeric or array_like
:math:`F_D` is the luminance of a displayed linear component
... | 2d8d0430107c131db9f5a1974d897f15401c7391 | 3,615,732 |
def cancel_and_stop_intent_handler(handler_input):
"""Single handler for Cancel and Stop Intent."""
# type: (HandlerInput) -> Response
speech_text = "Alla prossima!"
return handler_input.response_builder.speak(speech_text).response | 73a9171b5ea01fedb7fc470dd7d6bcd232a605a0 | 3,615,733 |
from typing import Union
def make_twill_pattern(n:Union[int, tuple[int]] = 2,
warp_n:int = 2, weft_n:int = 2) -> np.ndarray:
"""Returns twill pattern matrix extended for warp and weft patterns.
n is the number of over-unders. With n = 1 we get a plain weave.
Args:
n (int,... | 02d080765dfe5577df278c16d04bea34c26f0f00 | 3,615,734 |
import operator
def assert_no_undefined_references(
snapshot=None, soft=False, session=None, df_format="table"
):
# type: (Optional[str], bool, Optional[Session], str) -> bool
"""Assert that there are no undefined references present in the snapshot.
:param snapshot: the snapshot on which to check the... | 0409b5b814dcfba73779173b279d4c02d5b66e2c | 3,615,735 |
from typing import List
def divisors(number: int) -> List[int]:
"""
This function calculates and returns a list of all divisors that a given number has, e.g.
f(number=24) -> [1, 2, 3, 4, 6, 8, 12, 24]
:param number: The number whose divisors are to be calculated
:return: A list of integer divisors... | 1683734989447f40a72f08098e9f08ef62a1cd32 | 3,615,736 |
def sim_sym_resp(emotion, ti, tf, t_plot=None, dt=0.1, plot=True, n_periods=1, d_e=None, delay=0.0):
"""
:param emotion : string that define what emotion is simulated
:param ti : time in seconds when eigenmotion starts
:param dt : time step in seconds for the simulation
... | b9a29dd89114b3b1ef76ced7680bbbc57724a26c | 3,615,737 |
def timestamp_from_sbs(data):
"""Create new timestamp from SBS data
Args:
data (hat.sbs.Data): SBS data
Returns:
Timestamp: timestamp
"""
return Timestamp(s=data['s'], us=data['us']) | f42d70886f7eaec64fae6f5787c9b7c8177e86f3 | 3,615,738 |
def buff_exists(name):
"""
Return true or false if the buffer named `name` exists
"""
return buffwinnr(name) != -1 | 5883d97b8c62ce762bc0cd1777264b5d0c921660 | 3,615,740 |
import json
def load_jsonl(filename):
"""Load json lines formatted file"""
with open(filename, "r") as f:
return list(map(json.loads, f)) | 7acb3513cf885139e62af56d17c19aa87e1c85ca | 3,615,741 |
def IntCurveSurface_TheHCurveTool_FirstParameter(*args):
"""
:param C:
:type C: Handle_Adaptor3d_HCurve &
:rtype: float
"""
return _IntCurveSurface.IntCurveSurface_TheHCurveTool_FirstParameter(*args) | c895ee73b149ebab1d696f88eb3c19f3bebd5dd4 | 3,615,742 |
def synthesize_text(text, client):
"""Synthesizes speech from the input string of text."""
# input format
input_text = texttospeech.types.SynthesisInput(text=text)
# Note: the voice can also be specified by name.
# Names of voices can be retrieved with client.list_voices().
voice = texttospeech.types.Voic... | c2d01c5dfc5bf3ac8e2eef5501bdd38370cdce3f | 3,615,744 |
def plotPotentialObjectToFile(fileobj, lowx, highx, potentialObject, steps=10000):
"""Convenience function for plotting energy of pair interactions
given by instances of :class:`atsim.potentials.Potential` obtained by calling
`potential` `.energy()` method.
Data is written to a text file as two columns (r and ... | f8ebf6eeae65036017b6114fb5e5aeda8d6ca1b4 | 3,615,745 |
def get_test_clinvar_record():
"""The test file contains an extract of ClinVar XML for the record RCV000002127."""
return [r for r in clinvar_xml_utils.ClinVarDataset(test_clinvar_record_file)][0] | fe4073ed03af58c0558309393fdd373eadf74360 | 3,615,746 |
import random
def random_genbank_accession(invalid_data):
"""
Generate Random GenBank Accession
return: string formatted to imitate a GenBank submission accession for viral
genome assemlby.
"""
# prefixs for GenBank direct submissions, excluding single letter 'U' option.
prefix = ['AF', 'AY'... | c9bd639e1ef3b10749a0c1c0e8ca3c4cb53c079f | 3,615,747 |
def entropy(p):
"""Calculate the Entropy for a sample
:param p: The probability or proportion of the samples belonging to a class
:returns: The Entropy
:rtype: float
"""
return -p * np.log2(p) - (1 - p) * np.log2(1 - p) | b3fd9f442aa30d40e49bbcfeb8f1403644ab2185 | 3,615,748 |
def to_xml(number):
"""Return the XML form of the ISAN as a string."""
number = format(number, strip_check_digits=True, add_check_digits=False)
return '<ISAN root="%s" episode="%s" version="%s" />' % (
number[0:14], number[15:19], number[20:]) | 0c4311d78365d98760b6550b4a1c3eba8d0d6b6c | 3,615,750 |
def dict_findall(dictionary, element):
"""
Returns the keys whose values in `dictionary` are `element`
or, if none exists, [].
>>> d = {1:4, 3:4}
>>> dictfindall(d, 4)
[1, 3]
>>> dictfindall(d, 5)
[]
"""
res = []
for (key, value) in dictionary.iterite... | 76d1e0aa73db87da57b3d1129dca0984ff81574f | 3,615,752 |
def set_union(a, b, validate_indices=True):
"""Compute set union of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Example:
```python
import tensorflow as tf
import collections
# [[{1, 2}, {3}], [{4}, {5, 6}]]
a = collections.OrderedDict([
... | 0bee3df212c835d54727a664a34ad0dba78f5977 | 3,615,753 |
def account_edit(request, pk=None):
"""
"""
return edit(
request, report_model=Report, form_model=AccountForm, model=Account, pk=pk
) | 7b6c2fbbda39242c70c694d27c1abbe432362d12 | 3,615,755 |
def oauth2_assertion_config(application_id, application_name,
client_string, consumer_key,
consumer_secret):
"""Convenience function for creating an OAuth2 assertion configuration.
:param application_id: The unique identifier of the client application... | eed76d2d957b701db0ebce1141de5d0f411c692d | 3,615,756 |
def drop_invalid_trip_durations(data_frame: pd.DataFrame) -> pd.DataFrame:
"""Remove rows where we couldn't calculate trip duration or it was over 90 minutes."""
data_frame = data_frame.dropna(subset=['trip_duration_minutes'])
data_frame = data_frame[data_frame['trip_duration_minutes'] <= 90]
return da... | 9d60812ba6805571b636d99a843c2c2db2b78fb9 | 3,615,757 |
import time
import requests
from bs4 import BeautifulSoup
def epidemic_163(indicator="实时"):
"""
网易网页端-新冠状病毒-实时人数统计情况
国内和海外
https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other&#map_block
https://news.163.com/special/epidemic/?spssid=93326430940df93a37229... | 576615a8e3d0b3bf79cf82babec4c8710e2d11b2 | 3,615,758 |
def getPartnerURL(request):
"""
파트너 포인트 충전 URL을 반환합니다.
- 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다.
- https://docs.popbill.com/htcashbill/python/api#GetPartnerURL
"""
try:
# 팝빌회원 사업자번호
CorpNum = settings.testCorpNum
# CHRG-파트너 포인트충전
TOGO = "CHRG"
url = htCashbil... | 86afa367e4950a7d864763138f2bde1456145bd6 | 3,615,759 |
from typing import List
def _read_get_graph_source_citation_section(jcamp_dict: dict) -> List[str]:
"""
Extract and translate from the JCAMP-DX dictionary the SciData JSON-LD
citations in the 'sources' section from the '@graph' scection.
:param jcamp_dict: JCAMP-DX dictionary to extract citations fro... | dafe4fd793dd0e47b690d6c1fd745ca89265de39 | 3,615,760 |
def set_link_state():
"""
Set link state
:return: 201 if success, a new pending link if fail
"""
message = request.get_json()
if message['state'] == 'crawled':
db_manager.operate_on_link_relation('UPDATE_STATE',
message['link'],
... | e1de294334de3447cb59b6332e29bb2f7c523491 | 3,615,761 |
def print_stdout():
""" whether or not to print to stdout
"""
return _flag(PRINT_STDOUT_KEY, 'print_stdout', 'p',
msgs=('print log to stdout as well?',)) | 1697caccd978b344c08542002f12ffab98f65c9e | 3,615,762 |
def read_input_lines():
"""Open today's input data and return it as a list of lines
Returns:
[str]
Lines in 'input.txt'
"""
with open('input.txt') as in_file:
data = in_file.read().strip().splitlines()
return data | 83b77f1b64162bc822c9890781bf758e7197c67e | 3,615,763 |
import opcode
def payToPubKeyHashScript(pkHash):
"""
payToAddrScript creates a new script to pay a transaction output to a the
specified address.
Args:
pkHash (ByteArray): The pubkey hash to pay to.
Returns:
ByteArray: The script that pays to the pubkey hash.
"""
if len(p... | 51786cfc238470d9a69389ffe7c08589896d00c6 | 3,615,764 |
def deltaify_traces(traces, final_byte_duration=9999):
"""Convert absolute start times in traces to durations.
Traces returned by `read_traces_csv` pair bytes with start times. This
function computes how long each byte remains on the bus and replaces the
start time with this value in its output. Note that the ... | 8185a9825d4706bdf8a579fcefec5e27ca8c3baa | 3,615,765 |
def lonely_pixel(pixs, pos):
"""
pixs: image.load()
pos: (x,y)
"""
x,y = pos
xy = [-1,0,1]
for i in xy:
for j in xy:
if i==0 and j==0:
continue # pixel self
try:
p = pixs[x+i,y+j]
except IndexError:
... | 7ddb9bde813e532412d2b4e47d9b61a04569410c | 3,615,766 |
def parse_ldap_file(file_name, entries=None):
""" parse the LDAP results into a coherent form
(this code is way too complex for what it needs to do ATM)
"""
f = open(file_name)
entries = defaultdict(list) if entries is None else entries
entry = {}
for line in f:
line = line.strip()
if line !=... | 4a7a3e324c8934dc2c954e3727047c13be79efb1 | 3,615,768 |
def load(cookie: str) -> domain.Session:
"""Load a session by cookie value."""
return current_session().load(cookie) | a58f07c27451c8b548479fea8566e230fae11858 | 3,615,769 |
def trnsdeq_iter(h,T):
"""
Given
"""
new_h = _np.array([[[trnsdeq_step(h,T,i,j,k) for k in range(h.shape[2])]
for j in (range(h.shape[1]))]
for i in _tqdm(range(h.shape[0]))])
return new_h/_np.sum(new_h) | 509ae4cc7fd300bc47d9697de2a0e6ba7d91239d | 3,615,770 |
def coor2coor(srs_from, srs_to, x, y):
"""
Transform coordinates from srs_from to srs_to
input:
srs_from and srs_to are EPSG number (e.g., 4326, 3031)
x and y are x-coord and y-coord corresponding to srs_from
return:
x-coord and y-coord in srs_to
"""
srs_from = pypro... | e8f03e53078b987b874c5f4901d55b75297b4c28 | 3,615,771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.