content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _svd_classification(dataset='mnist_small'):
"""
svd on classificaiton dataset
Inputs:
dataset: (str) name of dataset
Outputs:
accuracy on predicted values
"""
if dataset=='rosenbrock':
x_train, x_valid, x_test, y_train, y_valid, y_test = load_dataset('rosenbrock', n... | 55eae147130a4552ba33f466f6127ab5df1323b9 | 30,420 |
def set_answer(set_number):
"""
get result answer
>>> set_answer(600851475143)
6857
>>> set_answer(3000)
5
"""
while True:
prime_fac = prime_factorization(set_number)
if prime_fac < set_number:
set_number //= prime_fac
else:
return set_numb... | b601a764123b737993c1b822ff466f47ca5caea6 | 30,421 |
import torch
def model_infer(model, test_images, test_affinities, test_beliefs, args):
"""
Parameters:
model: object with the trained model
test_images: batch of images (float32), size: (test_batch_size,3,x,y)
test_affinities: batch of affinity maps (float32), size: (test_batch_size,16,x/8,y/8)
... | 32534691056c96e3c96adaebfc112da7525ef6dd | 30,422 |
import re
def clean_value(value, suffix):
"""
Strip out copy suffix from a string value.
:param value: Current value e.g "Test Copy" or "test-copy" for slug fields.
:type value: `str`
:param suffix: The suffix value to be replaced with an empty string.
:type suffix: `str`
:return: Strippe... | d2ec3b3affbf71411039f234c05935132205ae16 | 30,423 |
def list_devices_to_string(list_item):
"""Convert cfg devices into comma split format.
Args:
list_item (list): list of devices, e.g. [], [1], ["1"], [1,2], ...
Returns:
devices (string): comma split devices
"""
return ",".join(str(i) for i in list_item) | 717f40d3fd0c24b93d5859491d3f9f16a2b0a069 | 30,424 |
def trace_module(no_print=True):
""" Trace plot series module exceptions """
mname = 'series'
fname = 'plot'
module_prefix = 'putil.plot.{0}.Series.'.format(mname)
callable_names = (
'__init__',
'data_source',
'label',
'color',
'marker',
'interp',
'li... | b46e69836257de525e55346872f01cb338e036c9 | 30,425 |
def get_ids(values):
"""Transform numeric identifiers, corpora shortcodes (slugs),
and two-letter ISO language codes, into their corresponding numeric
identifier as per the order in CORPORA_SOURCES.
:return: List of indices in CORPORA_SOURCES
:rtype: list
"""
if "all" in values:
ids... | 482c3940a0a8492820d94d5a9af41c5891c82406 | 30,426 |
import click
def quiet_option(func):
"""Add a quiet option."""
def _callback(ctx, unused_param, value):
_set_verbosity(ctx, -value)
return value
return click.option('-q', '--quiet', count=True,
expose_value=False, help='Decreases verbosity.',
... | b13dd670cd06136fbccfccff23ed27233efcb7bd | 30,427 |
def _compute_gaussian_fwhm(spectrum, regions=None):
"""
This is a helper function for the above `gaussian_fwhm()` method.
"""
fwhm = _compute_gaussian_sigma_width(spectrum, regions) * gaussian_sigma_to_fwhm
return fwhm | b5e83752141830911a3d1e26cce10c82b1414740 | 30,428 |
from re import T
from typing import Optional
from typing import Callable
from typing import Any
from typing import List
async def sorted(
iterable: AnyIterable[T],
*,
key: Optional[Callable[[T], Any]] = None,
reverse: bool = False,
) -> List[T]:
"""
Sort items from an (async) iterable into a n... | 628336093c282f340f3ad2f750227e1286ceefef | 30,429 |
def config_split(config):
"""
Splits a config dict into smaller chunks.
This helps to avoid sending big config files.
"""
split = []
if "actuator" in config:
for name in config["actuator"]:
split.append({"actuator": {name: config["actuator"][name]}})
del(config["actua... | 2006534ece382c55f1ba3914300f5b6960323e53 | 30,430 |
def transl(x, y=None, z=None):
"""
Create or decompose translational homogeneous transformations.
Create a homogeneous transformation
===================================
- T = transl(v)
- T = transl(vx, vy, vz)
The transformation is created with a unit rotation... | d3b47af2ea8f130559f19dea269fbd1a50a8559c | 30,431 |
def find_next_square2(sq: int) -> int:
"""
This version is just more compact.
"""
sqrt_of_sq = sq ** (1/2)
return -1 if sqrt_of_sq % 1 != 0 else int((sqrt_of_sq + 1) ** 2) | 62246b78cc065b629961a7283671e776481a8659 | 30,432 |
import colorsys
def hex_2_hsv(hex_col):
"""
convert hex code to colorsys style hsv
>>> hex_2_hsv('#f77f00')
(0.08569500674763834, 1.0, 0.9686274509803922)
"""
hex_col = hex_col.lstrip('#')
r, g, b = tuple(int(hex_col[i:i+2], 16) for i in (0, 2 ,4))
return colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0) | a80e9c5470dfc64c61d12bb4b823411c4a781bef | 30,433 |
from pathlib import Path
def _drivers_dir() -> str:
"""
ドライバ格納ディレクトリのパスを返します
:return: ドライバ格納ディレクトリのパス
"""
return str(Path(__file__).absolute().parent.parent.joinpath('drivers')) | 45b173099f6df24398791ec33332072a7651fa4f | 30,434 |
import types
def create_list_response_value(
*,
authorization: types.TAuthorization,
uri: types.TUri,
auth_info: types.CredentialsAuthInfo,
) -> types.TResponseValue:
"""
Calculate the response for a list type response.
Raises NotFoundError when the uri is not linked to a known spec.
... | 492d5a93b7db393dafde48c66d323dda64c7e32c | 30,435 |
def get_variables(expr):
"""
Get variables of an expression
"""
if isinstance(expr, NegBoolView):
# this is just a view, return the actual variable
return [expr._bv]
if isinstance(expr, _NumVarImpl):
# a real var, do our thing
return [expr]
vars_ = [... | 6326ae90f0fa6daa04e0dedc95cf52f4081fa359 | 30,436 |
def tousLesIndices(stat):
"""
Returns the indices of all the elements of the graph
"""
return stat.node2com.keys()
#s=stat.node2com.values()
global globAuthorIndex
global globTfIdfTab
#pprint(globAuthorIndex)
#pprint(stat.node2com.values())
#glob node->index
return [glo... | fa847ee3913d521778ee3462c8e946f0ff001c76 | 30,437 |
def edit_tx_sheet(request, sheet_id):
"""Allows the user to edit treatment sheet fields and updates the date of the sheet"""
tx_sheet = get_object_or_404(TxSheet, id=sheet_id)
form = TxSheetForm(instance=tx_sheet)
if request.user == tx_sheet.owner:
if request.method == 'POST':
for... | 04ef22e069cc329d4eceae5ae567867fb31f787c | 30,438 |
import warnings
def system(
W, L_x, L_sc_up, L_sc_down, z_x, z_y, a, shape, transverse_soi,
mu_from_bottom_of_spin_orbit_bands, k_x_in_sc, wraparound, infinite,
sc_leads=False, no_phs=False, rough_edge=None,
phs_breaking_potential=False):
"""Create zigzag system
Parameters
... | 101f3fffeb333cb9c53c2ef930e17fa0f7e08966 | 30,439 |
def get_state_x1_pure_state_vector() -> np.ndarray:
"""Returns the pure state vector for :math:`|-\\rangle`.
:math:`|-\\rangle := \\frac{1}{\\sqrt{2}} (|0\\rangle - |1\\rangle)`
Returns
-------
np.ndarray
the pure state vector.
"""
vec = (1 / np.sqrt(2)) * np.array([1, -1], dtype=n... | 81d52d34492a0b57206d3cf55ceb9dd939a7cdf8 | 30,441 |
def user_create(user_data):
""" Cria um usuário no banco de dados e retorna o objeto criado """
user_model = get_user_model()
user = user_model.objects.create_user(**user_data)
return user | 163c742601d25a7b04e572ea6b32de6625b99de5 | 30,442 |
from typing import Counter
def shannon_entropy(text: str) -> float:
"""
same definition as in feature processor for feature extraction
calculates shannon entropy of a given string
"""
content_char_counts = Counter([ch for ch in text])
total_string_size = len(text)
entropy: float = 0
fo... | e3092f8620b809a3d935ad16290d077122f6b1df | 30,443 |
def solve(inputmatrix):
"""
This function contains a solution to the data in 4be741c5.json posed by the Abstraction and
Reasoning Corpus (ARC).
The problem presents an n x m grid, with some rows containing 0-m coloured squares with repetition over a row or colomuns.
The solution req... | 33f27b9bd57ce00972d8c29e7ae3a0ac71dd2455 | 30,444 |
def compute_rewards(s1, s2):
"""
input: s1 - state before action
s2 - state after action
rewards based on proximity to each goal
"""
r = []
for g in TASKS:
dist1 = np.linalg.norm(s1 - g)
dist2 = np.linalg.norm(s2 - g)
reward = dist1 - dist2
r.append(rew... | 1a6ee67ce581dc07d735e15fe62d09561cf0453f | 30,445 |
import ipaddress
def decode(i_dunno):
"""
Decode an I-DUNNO representation into an ipaddress.IPv6Address or an ipaddress.IPv4Address object.
A ValueError is raised if decoding fails due to invalid notation or resulting IP address is invalid.
The output of this function SHOULD NOT be presented to huma... | 557da5af7b33d988754f67ecd4574be9bdc85784 | 30,446 |
def location_descriptors():
"""Provide possible templated_sequence input."""
return [
{
"id": "NC_000001.11:15455",
"type": "LocationDescriptor",
"location": {
"sequence_id": "ncbi:NC_000001.11",
"interval": {
"start... | da13824ff6f91caa635700759a29fb1f36aae1be | 30,448 |
from typing import Optional
def positional_features_gamma(positions: tf.Tensor,
feature_size: int,
seq_length: Optional[int] = None,
bin_size: Optional[int] = None,
stddev=None,
... | 20dc2154a194d99ec1a9931e10fca2b43d360a6e | 30,449 |
from typing import List
def _get_frame_data(mapAPI: MapAPI, frame: np.ndarray, agents_frame: np.ndarray,
tls_frame: np.ndarray) -> FrameVisualization:
"""Get visualisation objects for the current frame.
:param mapAPI: mapAPI object (used for lanes, crosswalks etc..)
:param frame: the ... | 65f3733e858f595877af83e0574bb53c5568390c | 30,450 |
def calculate_gc(x):
"""Calculates the GC content of DNA sequence x.
x: a string composed only of A's, T's, G's, and C's."""
x = x.upper()
return float(x.count('G') + x.count('C')) / (x.count('G') + x.count('C') + x.count('A') + x.count('T')) | aae64ff550ef26e75518bdad8a12b7cda9e060d2 | 30,451 |
def no_float_zeros(v):
"""
if a float that is equiv to integer - return int instead
"""
if v % 1 == 0:
return int(v)
else:
return v | a33321408c43d164a8ca2c7f1d1bc6270e5708ec | 30,453 |
import torch
def quat_mult(q_1, q_2):
"""Multiplication in the space of quaternions."""
a_1, b_1, c_1, d_1 = q_1[:, 0], q_1[:, 1], q_1[:, 2], q_1[:, 3]
a_2, b_2, c_2, d_2 = q_2[:, 0], q_2[:, 1], q_2[:, 2], q_2[:, 3]
q_1_q_2 = torch.stack(
(
a_1 * a_2 - b_1 * b_2 - c_1 * c_2 - d_1... | dac82e246221f9af552f44ca26089443b8eaadd7 | 30,454 |
def _flip_dict_keys_and_values(d):
"""Switches the keys and values of a dictionary. The input dicitonary is not modified.
Output:
dict
"""
output = {}
for key, value in d.items():
output[value] = key
return output | b861fc3bd194d26ee05b9a56faad3394939064bf | 30,455 |
from typing import Tuple
from typing import Optional
def set_dative_bonds(
mol: Chem.rdchem.Mol, from_atoms: Tuple[int, int] = (7, 8)
) -> Optional[Chem.rdchem.Mol]:
"""Replaces some single bonds between metals and atoms with atomic numbers in fromAtoms
with dative bonds. The replacement is only done if t... | 8e67732e7f10ac273e51a0ae1b3f6c3cff27b291 | 30,456 |
from typing import Optional
def _b2s(b: Optional[bool]) -> Optional[str]:
"""转换布尔值为字符串。"""
return b if b is None else str(b).lower() | 6030b7fd88b10c4bdccd12abd1f042c518e8a03f | 30,457 |
from typing import Set
def color_csq(all_csq: Set[str], mane_csq: Set[str]) -> str:
"""
takes the collection of all consequences, and MANE csqs
if a CSQ occurs on MANE, write in bold,
if non-MANE, write in red
return the concatenated string
NOTE: I really hate how I've implemented this
:p... | 1e6792bf446799a4c4c22770c7abfc1718c88516 | 30,458 |
def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | f3a2fc308d041ed0de79e3389e30e02660a1d535 | 30,459 |
def pano_stretch_image(pano_img, kx, ky, kz):
"""
Note that this is the inverse mapping, which refers to Equation 3 in HorizonNet paper (the coordinate system in
the paper is different from here, xz needs to be swapped)
:param pano_img: a panorama image, shape must be [h,w,c]
:param kx: stretching a... | f5b151e3e124e3333304b8ff6c217971fb10ba35 | 30,460 |
def blue_process(infile, masterbias=None, error=False, rdnoise=None, oscan_correct=False):
"""Process a blue frame
"""
# check to make sure it is a blue file
ccd = ccdproc.CCDData.read(infile, unit=u.adu)
try:
namps = ccd.header['CCDAMPS']
except KeyError:
namps = ccd.header['CCD... | c3b251a3ae99031b54e8dc5af4d5c95511f31c75 | 30,461 |
def _rand_sparse(m, n, density, format='csr'):
"""Helper function for sprand, sprandn"""
nnz = max(min(int(m*n*density), m*n), 0)
row = np.random.random_integers(low=0, high=m-1, size=nnz)
col = np.random.random_integers(low=0, high=n-1, size=nnz)
data = np.ones(nnz, dtype=float)
# duplicate ... | 08221cdc9798e0ddf9266b5bf2ca3dfe21451278 | 30,462 |
import random
def _generate_trace(distance):
"""
生成轨迹
:param distance:
:return:
"""
# 初速度
v = 0
# 位移/轨迹列表,列表内的一个元素代表0.02s的位移
tracks_list = []
# 当前的位移
current = 0
while current < distance - 3:
# 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细
a = random.randint(10000, 12000)... | 6ce298de2a1977c7662f83346e7554c546b41131 | 30,464 |
import sqlite3
def update_nt_uid_acc(cachepath, uid, accession):
"""Update nt UID GenBank accession."""
# Path must be string, not PosixPath, in Py3.6
conn = sqlite3.connect(str(cachepath))
results = []
with conn:
cur = conn.cursor()
cur.execute(SQL_UPDATE_UID_ACC, (accession, uid)... | 45c9514ffeca9281269c8f27ac09b3b863de2eff | 30,465 |
def bool_env(env_val):
""" check for boolean values """
if env_val:
if env_val in TRUE_LIST:
return True
if env_val in FALSE_LIST:
return False
# print("Return:%s" % env_val)
return env_val
else:
if env_val in FALSE_LIST:
return Fa... | afb9d2f35c6469a1fd6f32250376b94a05db1de0 | 30,466 |
import json
def try_parse_json(json_):
"""Converts the string representation of JSON to JSON.
:param str json_: JSON in str representation.
:rtype: :class:`dict` if converted successfully, otherwise False.
"""
if not json_:
return False
try:
return json.loads(json_)
excep... | 077819cf82e307aacf3e56b11fbba26a79559968 | 30,467 |
def svn_ra_get_file(*args):
"""
svn_ra_get_file(svn_ra_session_t session, char path, svn_revnum_t revision,
svn_stream_t stream, apr_pool_t pool) -> svn_error_t
"""
return _ra.svn_ra_get_file(*args) | 2e887ace5ed3538ac7f3e401be9fa71ddfc100cc | 30,468 |
def version_microservices(full=True):
"""
Display Zoomdata microservice packages version.
CLI Example:
full : True
Return full version. If set False, return only short version (X.Y.Z).
.. code-block:: bash
salt '*' zoomdata.version_microservices
"""
ms_version = ''
ms... | aff0ece640e33e2d880c3e4a13ad7e13911aaa68 | 30,469 |
def KGCOVID19(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "current", **kwargs
) -> Graph:
"""... | 24e419d80cd9634f5dab352f37db1fd6a19661d2 | 30,473 |
def is_gh_online():
"""
Check if GitHub is online.
The different services of GitHub are running in seperat services
and thus just being GitHub online does not mean,
that required parts are online.
"""
return _is_online("github.com", "/", 200, "OK") | 8c5dc7090f9d851e5b5c303ffa376da5f926202a | 30,475 |
import math
def get_items_with_pool(
source_key: str, count: int, start_index: int = 0, workers: int = 4
) -> Items:
"""Concurrently reads items from API using Pool
Args:
source_key: a job or collection key, e.g. '112358/13/21'
count: a number of items to retrieve
start_index: an ... | cbf07015872fc72bfa0e70be5c6a4553e5bef363 | 30,476 |
from typing import Tuple
def calc_portfolio_holdings(initial_investment: int, weights: pd.DataFrame, prices: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Calculate the initial portfolio holdings given am amount of cash to invest.
:param initial_investment: The initial investment used to purchas... | 7adf46894b27c679eec16f94a80bcad3c7539c88 | 30,478 |
def ford_fulkerson(G, s, t, capacity='capacity'):
"""Find a maximum single-commodity flow using the Ford-Fulkerson
algorithm.
This is the legacy implementation of maximum flow. See Notes below.
This algorithm uses Edmonds-Karp-Dinitz path selection rule which
guarantees a running time of `O(nm^2)`... | dd8e8e351829feb98cd144f4148f8c9bf62cb239 | 30,479 |
def index():
"""
Show the main page of Stream4Flow
:return: Empty dictionary
"""
# Do not save the session
session.forget(response)
return dict() | 531c10ca17406086fcf14a5dfcdcecce5cc60119 | 30,480 |
from typing import Type
def create_temporary_table_sql(model: Type[Model]) -> str:
"""
Get the SQL required to represent the given model in the database as a
temporary table.
We cache the results as this will be called for each request, but the model
should never change (outside of tests), so we ... | 3074b4e6bb0c9147faa9da3243d0d66a3fee7517 | 30,481 |
def field_paths(h5, key='externalFieldPath'):
"""
Looks for the External Fields
"""
if key not in h5.attrs:
return []
fpath = h5.attrs[key].decode('utf-8')
if '%T' not in fpath:
return [fpath]
path1 = fpath.split('%T')[0]
tlist = list(h5[path1])
pa... | 578e1a2d0971a94afa665f368e9b72c8f6e449d3 | 30,482 |
def get_quantifier(ch, input_iter):
"""
Parse a quantifier from the input, where "ch" is the first character in the
quantifier.
Return the minimum number of occurrences permitted by the quantifier and
either None or the next character from the input_iter if the next character
is not part of the... | 36dea445aa416be79e86bb1e7c6f9dbe454c6c2a | 30,483 |
from typing import List
def get_defined_vars(
operation: "OperationDefinitionNode",
) -> List["VariableNode"]:
"""
Retrieve a list of VariableNode defined inside the variableDefinitionNode list of an OperationDefinitionNode
:param operation: the operation definition node to look through
:type ope... | f39cd2b205bdfba5347884e9b675949e08877a5f | 30,484 |
def snv(img):
"""
standard normal variates (SNV) transformation of spectral data
"""
mean = np.mean(img, axis=0)
std = np.std(img, axis=0)
return (img - mean[np.newaxis, ...])/std[np.newaxis, ...] | 63c549f1e319ab4cc4b4beb4ea602b136d71168f | 30,485 |
def fredkin(cell: int, live_count: int, neighbors: Neighbors = None) -> int:
"""\"Fredkin\" Game of Life rule
This rule can be specified using these strings:
- ``B1357/S02468``
- ``2468/1357``
- ``fredkin``
Parameters
----------
cell: int
Value of the current cell. ... | ef08d99fa90c6d615bf3aabd6a4fe72903ecfb62 | 30,486 |
def mad(arr):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays.
med = np.median(arr)
... | f02919fcb082c815602d8b57cb59d5c71cb6a219 | 30,487 |
def get_logs_directory():
"""Return path of logs directory"""
LDAModel_directory = get_LDAModel_directory()
logs_directory = LDAModel_directory / 'logs'
if not logs_directory.is_dir():
create_directory(logs_directory)
return logs_directory | eb37ca64a07280d55584ac0146b6babc02051b3d | 30,488 |
def svn_ra_rev_proplist(*args):
"""
svn_ra_rev_proplist(svn_ra_session_t session, svn_revnum_t rev, apr_hash_t props,
apr_pool_t pool) -> svn_error_t
"""
return apply(_ra.svn_ra_rev_proplist, args) | 2f6c1f25f6b62d1306aa746dc0dc04f39370aa0e | 30,489 |
from datetime import datetime
def parse_date(s):
"""
Given a string matching the 'full-date' production above, returns
a datetime.date instance. Any deviation from the allowed format
will produce a raised ValueError.
>>> parse_date("2008-08-24")
datetime.date(2008, 8, 24)
>>> parse_date("... | d21ab8b08d52bf155d5e8af192f19036307568b5 | 30,491 |
def setup_config(quiz_name):
"""Updates the config.toml index and dataset field with the formatted
quiz_name. This directs metapy to use the correct files
Keyword arguments:
quiz_name -- the name of the quiz
Returns:
True on success, false if fials to open file
"""
try:
... | 28aba9399926f27da89953c8b0c6b41d95a12d96 | 30,492 |
def unitary_connection(h_pre, h_post, n_pre, n_post, X):
"""
Gives the connectivity value between the n_pre unit
in the h_pre hypercolumn and the n_post unit in the h_post column
"""
hits_pre = X[:, h_pre] == n_pre
hits_post = X[:, h_post] == n_post
return np.sum(hits_pre * hits_post) | d272b92abfed50d7f89c2d4b40ff3c4e5a417d5e | 30,493 |
def mase(y, y_hat, y_train, seasonality=1):
"""Calculates the M4 Mean Absolute Scaled Error.
MASE measures the relative prediction accuracy of a
forecasting method by comparinng the mean absolute errors
of the prediction and the true value against the mean
absolute errors of the seasonal naive mode... | 7373ef660ae9784ecd83a83457c143debb721685 | 30,494 |
def _resize_along_axis(inputs, size, axis, **kwargs):
""" Resize 3D input tensor to size along just one axis. """
except_axis = (axis + 1) % 3
size, _ = _calc_size_after_resize(inputs, size, axis)
output = _resize_except_axis(inputs, size, except_axis, **kwargs)
return output | a7cc206171ffe1cf6df22da3756cefcc6c5fcd86 | 30,495 |
def getTournamentMatches(tourneyId):
"""
Return a dictionary from match id to match data for a tournament.
"""
if tourneyId not in matchDatas:
refreshMatchIndex(tourneyId)
return matchDatas[tourneyId] | a6d5386e9034b126405aedee75ba36b1718c3dc9 | 30,496 |
def compute_protien_mass(protien_string):
"""
test case
>>> compute_protien_mass('SKADYEK')
821.392
"""
p={'A':'71.03711','C':'103.00919','D':'115.02694','E':'129.04259','F':'147.06841','G':'57.02146','H':'137.05891','I':'113.08406','K':'128.09496','L':'113.08406','M':'131.04049','N':'114.04293... | 86a3ffd0ce3e95fcdf6d510d2865b35aeb93d779 | 30,497 |
import logging
def find_duration(data):
"""Finds the duration of the ECG data sequence
Finds the duration by looking at the last time value
as the first value is always at time = 0 seconds
:param data: 2D array of time sequences and voltage sequences
:return: Time duration of data sequence
... | e65135457e23886c402e0671d720fe9c5ed257a1 | 30,498 |
def response(data, **kwd):
"""Returns a http response"""
return HttpResponse(data, **kwd) | 8d88295751ee5f53f99ea8a134d01e1df7cb1fd5 | 30,499 |
from typing import List
def load_actions(action_file: str) -> List[str]:
"""
Load unique actions from an action file
"""
return load_uniq_lines(action_file) | a5ffe3ccac462bc8277da6174a5eb81071a6fb84 | 30,500 |
def ConvertFile(filename_in, filename_out, loglevel='INFO'):
"""
Converts an ANSYS input file to a python pyansys script.
Parameters
----------
filename_in : str
Filename of the ansys input file to read in.
filename_out : str
Filename of the python script to write a translation... | b044b565193ca0d78edd77706cdeb1711d95f063 | 30,502 |
from typing import Optional
def get_metadata_saml(idp_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMetadataSamlResult:
"""
Use this data source to retrieve SAML IdP metadata from Okta.
## Example Usage
```python
import pulumi
imp... | 5b4e1fdf72d7e11d7f4eee878e88e174b452cfa5 | 30,503 |
from typing import Dict
def _average_latency(row: Dict):
"""
Calculate average latency for Performance Analyzer single test
"""
avg_sum_fields = [
"Client Send",
"Network+Server Send/Recv",
"Server Queue",
"Server Compute",
"Server Compute Input",
"Serve... | f321cb4d55af605298225f2f0146a9a71ee7895b | 30,504 |
def _(expr, assumptions):
"""
Integer**Integer -> !Prime
"""
if expr.is_number:
return _PrimePredicate_number(expr, assumptions)
if ask(Q.integer(expr.exp), assumptions) and \
ask(Q.integer(expr.base), assumptions):
return False | da1b018ef6fdb6987666806ce34ee784d03cff9b | 30,506 |
import tqdm
import torch
def train(model, trainLoader, optimizer, loss_function, device, trainParams):
"""
Function to train the model for one iteration. (Generally, one iteration = one epoch, but here it is one step).
It also computes the training loss, CER and WER. The CTC decode scheme is always 'gree... | f2726ad6f63997abd670c5f4614b1cef1e35dec7 | 30,507 |
def reorder(A, B):
"""Change coefficient order from y**2 xy x**2 to x**2 xy y**2 in both A and B.
Parameters
----------
A : array
polynomial coefficients
B : array
polynomial coefficients
Returns
-------
A2, B2: numpy arrays
coefficients with changed order
... | 6a4740a0423bc3a804e66b0cda4a444a7f58072e | 30,508 |
import functools
import collections
def collate_revs(old, new, key=lambda x: x, merge=lambda old, new: new):
"""
Given revision sets old and new, each containing a series
of revisions of some set of objects, collate them based on
these rules:
- all items from each set are yielded in stable order
... | 06f37d895fd906513aa3b85fb2ff48e0f2f2b625 | 30,509 |
from typing import Tuple
from typing import List
def load_conversation(
filename: str,
dictionary: corpora.Dictionary,
with_symbol: bool=True
) -> (Tuple[List[int], List[int]]):
"""対話コーパスをロードする。
Args:
filename (str): コーパスファイル
コーパスファイルの一行は
何 が 好き です か ?,Python ... | fb7aec9ea228fe528d6744564c1a2b298a33575c | 30,510 |
def close_incons_reduction(incons: list):
"""
Two step:
0. under the same backends pair
1. the same input, choose largest.(done before)
* 2. different inputs with small distance. Do not update(not used)
"""
def is_duplicate(t: tuple, li: list):
"""unique inconsistency"""
for... | 5fd581471ff361d2351b2dd8285d606399667e21 | 30,511 |
def mf2tojf2(mf2):
"""I'm going to have to recurse here"""
jf2={}
items = mf2.get("items",[])
jf2=flattenProperties(items,isOuter=True)
#print jf2
return jf2 | 399fa35f592bb6ec042003ed2884f94078ac01fd | 30,512 |
def import_all(filename):
""" Imports file contents from user with parameters from nueral net and later calculations
currently not robust to missing or incorrect arguments from file
currently does not convert values to int; done in later functions
inputs: filename - name of input file, curre... | ab5b2fecb6cadd2754d52cc9333d110955ca10c7 | 30,513 |
from typing import Union
from pathlib import Path
from typing import Dict
from typing import Tuple
from typing import Any
def fill_database(path: Union[str, Path], settings: SettingsConfig,
inputs: MeasurementInputs, alchemy: Alchemy,
parent_location_id: int, sex_id: int, child_pri... | 39836b397a7cf384bf3ca493914f9d024baf9f6f | 30,514 |
def ydhms2dt(year,doy,hh,mm,ss):
"""
ydhms2dt Take a year, day-of-year, etc and convert it into a date time object
Usage: dto = ydhms2dt(year,day,hh,mm,ss)
Input: year - 4 digit integer
doy - 3 digit, or less integer, (1 <= doy <= 366)
hh - 2 digit, or less int, (0 <= hh <... | 3d8fd1a6086f3dd35c80c2d862e820b7aecc5e5b | 30,515 |
def create_test_db(verbosity=1, autoclobber=False):
"""
Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.
"""
# If the database backend wants to create the test DB itself, let it
creation_module = get_creat... | 87659029e01399f6d46780dbd3e2809bc809b70c | 30,516 |
import _ctypes
def key_import(data, key_type=KEY_TYPE.SYMMETRIC, password=b''):
"""Imports a key or key generation parameters."""
key = _ctypes.c_void_p()
_lib.yaca_key_import(key_type.value, _ctypes.c_char_p(password),
data, len(data), _ctypes.byref(key))
return Key(key) | 9cbe8dfcab3e854b096a5628c6be52d6873e8ca1 | 30,517 |
def test_training_arguments_timestamp(monkeypatch, grim_config):
"""Test TrainingWrapperArguments correctly applies a timestamp."""
def mock_return():
return '2019-06-29_17-13-41'
monkeypatch.setattr(grimagents.common, "get_timestamp", mock_return)
grim_config['--timestamp'] = True
argume... | 391b2fdbf716bfdc22f8449a3692679d6018f200 | 30,518 |
def to_vsizip(zipfn, relpth):
""" Create path from zip file """
return "/vsizip/{}/{}".format(zipfn, relpth) | 6f5baf380bd7ab8a4ea92111efbc0f660b10f6f8 | 30,519 |
def flw3i8e(ex, ey, ez, ep, D, eq=None):
"""
Compute element stiffness (conductivity)
matrix for 8 node isoparametric field element.
Parameters:
ex = [x1,x2,x3,...,x8]
ey = [y1,y2,y3,...,y8] element coordinates
ez = [z1,z2,z3,...,z8]
ep = [ir] ... | 90377f5ba6205e0f3bf1bc4f1fa0b84a4c69eec9 | 30,522 |
def cidr_to_netmask(value):
"""
Converts a CIDR prefix-length to a network mask.
Examples:
>>> "{{ '24'|cidr_to_netmask }}" -> "255.255.255.0"
"""
return str(netaddr.IPNetwork("1.1.1.1/{}".format(value)).netmask) | 232f4fb65be712bfb040d75ada40ed0450d84e2d | 30,523 |
def rgb_to_name(rgb_triplet: IntTuple, spec: str = CSS3) -> str:
"""
Convert a 3-tuple of integers, suitable for use in an ``rgb()``
color triplet, to its corresponding normalized color name, if any
such name exists.
The optional keyword argument ``spec`` determines which
specification's list o... | fdce9304c4d16d348fe37a920ae7cf44f3c3f56b | 30,524 |
def get_rr_Lix(N, Fmat, psd, x):
"""
Given a rank-reduced decomposition of the Cholesky factor L, calculate
L^{-1}x where x is some vector. This way, we don't have to built L, which
saves memory and computational time.
@param N: Vector with the elements of the diagonal matrix N
@param Fma... | 3658342296f18f3afdedf2cc790e1d0062e6c49d | 30,525 |
def ParameterSet_Create(*args):
"""
Create() -> ParameterSet
ParameterSet_Create(std::string const & publicID) -> ParameterSet
"""
return _DataModel.ParameterSet_Create(*args) | c6d6ef68505119b1b146d2be267a416341e09271 | 30,526 |
def generate_html_from_cli_args(cli_dict_for_command):
"""
Turn the dict into an html representation of the cli args and options.
:param cli_dict_for_command:
:return str:
"""
# def arg_md(opt, long_opt, default, help):
# return f"*) {opt}, {long_opt}, {help}\n"
text = ""
# ev... | 15c3b6f98141ab989cbe229a2b30778d5c664c9a | 30,527 |
def conical_sigma_Mach_walldeflection(Mach, deflection, gamma=defg._gamma):
"""computes shock angle sigma from upstream Mach number and wall deflection
Args:
Mach: param deflection:
gamma: Default value = defg._gamma)
deflection:
Returns:
"""
def local_def(sig):
"""inte... | 97fc3ac999f4a598860dcf25b4fd537bfcaf9326 | 30,528 |
def get_hashrate_info(results, miner, algo):
"""
Get Hashrate Information for a particular Miner and Algo
Returns:
dict
"""
# do the lookup
hashrate_info = results.get_hashrate_info(miner, algo)
if hashrate_info is None:
logger.warning("Model/Algo combination does not ex... | e94d0d7345a54181a9d5547afd1209419a92b497 | 30,529 |
import hashlib
def verify_verification_code(doctype, document_name, verification_code):
"""This method verfies the user verification code by fetching the originally sent code by the system from cache.
Args:
doctype (str): Name of the DocType.
document_name (str): Name of the document of the D... | 4013d2c2ff3eb318c16af8d43ca8b50af53379ea | 30,530 |
def orient1(ppos, apos, bpos):
"""
ORIENT1 return orientation of PP wrt. the line [PA, PB].
"""
#---------------------------------------------- calc. det(S)
smat = np.empty(
(2, 2, ppos.shape[0]), dtype=ppos.dtype)
smat[0, 0, :] = \
apos[:, 0] - ppos[:, 0]
smat[0, 1, :] = \
... | 705a27bde14c31262471b5d6a3621a695d8c091d | 30,531 |
def get_storm_data(storm_path):
""" Obtain raster grid of the storm with rasterio
Arguments:
*storm_path* (string) -- path to location of storm
"""
with rio.open(storm_path) as src:
# Read as numpy array
array = src.read(1)
array = np.array(array,dtype='flo... | 6db69cbd6970da467021a186f3062beaa6ed7387 | 30,532 |
import functools
def wrap_with_spectral_norm(module_class,
sn_kwargs=None,
pow_iter_collection=None):
"""Returns a constructor for the inner class with spectral normalization.
This function accepts a Sonnet AbstractModule class as argument (the class,
*no... | 5c849f2ee4dd8cd818ff7bebfb0564857bbb18de | 30,533 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.