content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def Mux(sel, val1, val0):
"""Choose between two values.
Parameters
----------
sel : Value, in
Selector.
val1 : Value, in
val0 : Value, in
Input values.
Returns
-------
Value, out
Output ``Value``. If ``sel`` is asserted, the Mux returns ``val1``, else ``val0... | 62fa5abf293a1321af5e4a209427b896756e5617 | 10,271 |
def get_identity_list(user, provider=None):
"""
Given the (request) user
return all identities on all active providers
"""
identity_list = CoreIdentity.shared_with_user(user)
if provider:
identity_list = identity_list.filter(provider=provider)
return identity_list | f5a9a7e461813edbc293338dca242d4dd4877281 | 10,272 |
def get_user_pool_domain(prefix: str, region: str) -> str:
"""Return a user pool domain name based on the prefix received and region.
Args:
prefix: The domain prefix for the domain.
region: The region in which the pool resides.
"""
return "%s.auth.%s.amazoncognito.com" % (prefix, regio... | dc1eec674379d04bd8b23318207ac5b2e6a905f3 | 10,273 |
def add_dep_info(tgt_tokens, lang, spacy_nlp, include_detail_tag=True):
"""
:param tgt_tokens: a list of CoNLLUP_Token_Template() Objects from CoNLL_Annotations.py file
:param spacy_nlp: Spacy language model of the target sentence to get the proper Dependency Tree
:return:
"""
doc = spacy_nlp.to... | 0083d16f4344a6afaeb5fba9a6b2e9282d617ef3 | 10,275 |
async def apod(request: Request) -> dict:
"""Get the astronomy picture of the day."""
http_client = request.app.state.http_client
async with http_client.session.get(
f"https://api.nasa.gov/planetary/apod?api_key={NASA_API}"
) as resp:
data = await resp.json()
return {
"titl... | edc526732904c5f0a29c144023df7fefb6d7743c | 10,276 |
def main_view(request, url, preview=False):
"""
@param request: HTTP request
@param url: string
@param preview: boolean
"""
url_result = parse_url(url)
current_site = get_site()
# sets tuple (template_name, posts_on_page)
current_template = get_template()
language = get_language... | 6febddd1e98f94865a364b8cf9a339574a303809 | 10,277 |
def parse_configs(code_config, field_config, time_config):
"""
Wrapper to validate and parse each of the config files. Returns a
a dictionary with config types as keys and parsed config files as values.
"""
# performing basic validation of config paths, obtaining dictionary of
# config types a... | 1d625e0b56ea4d197280b91a7993a16c82a2461d | 10,278 |
def butter_highpass_filter_eda(data):
""" High pass filter for 1d EDA data.
"""
b, a = eda_hpf()
y = lfilter(b, a, data)
return y | 1449d09a810e0c1ff78ab325106a6235cb94d26b | 10,279 |
def normalize_null_vals(reported_val):
"""
Takes a reported value and returns a normalized NaN is null, nan, empty, etc.
Else returns reported value.
"""
if is_empty_value(reported_val):
return np.NaN
else:
return reported_val | 790ebbad188390752401699f2d04fddbd08bcc7e | 10,280 |
def test_insert(type):
"""
>>> test_insert(int_)
[0, 1, 2, 3, 4, 5]
"""
tlist = nb.typedlist(type, [1,3])
tlist.insert(0,0)
tlist.insert(2,2)
tlist.insert(4,4)
tlist.insert(8,5)
return tlist | a0eb1f5bbf861863b47c6639d1159afffb63093e | 10,282 |
def get_next_month_range(unbounded=False):
"""获取 下个月的开始和结束时间.
:param unbounded: 开区间
"""
return get_month_range(months=1, unbounded=unbounded) | 989054b3e523400ed28ab0d3d9a840d6606ee8cc | 10,283 |
import functools
def probit_regression(
dataset_fn,
name='probit_regression',
):
"""Bayesian probit regression with a Gaussian prior.
Args:
dataset_fn: A function to create a classification data set. The dataset must
have binary labels.
name: Name to prepend to ops created in this function,... | b4cca9054d0ebd8c349cdb148443246616ed6120 | 10,284 |
def block_inception_c(inputs, scope=None, reuse=None):
"""Builds Inception-C block for Inception v4 network."""
# By default use stride=1 and SAME padding
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d],
stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockI... | b6cfe5d6eeaaef2d4a02420577884393f4bfcd4b | 10,285 |
import six
from datetime import datetime
def from_json(js):
"""
Helper to parse json values from server into python types
"""
if js is None or js is True or js is False or isinstance(js, six.text_type):
# JsNull, JsBoolean, JsString
return js
if not isinstance(js, dict) or 'type' ... | 0e4f94e8fdfb634ea3a1f1f84d3ff3d5bb125175 | 10,286 |
def exposexml(func):
"""
Convenience decorator function to expose XML
"""
def wrapper(self, data, expires, contentType="application/xml"):
data = func(self, data)
_setCherryPyHeaders(data, contentType, expires)
return self.templatepage('XML', data=data,
... | 57c62490e51693551801aa4722de2e08d3fd3817 | 10,287 |
def transform_categorical_by_percentage(TRAIN, TEST=None,
handle_unknown="error", verbose=0):
"""
Transform categorical features to numerical. The categories are encoded
by their relative frequency (in the TRAIN dataset).
To be consistent with scikit-learn transfo... | ce2c568b40109e11d1920a211314aebdc076be7f | 10,289 |
def buildDescription(flinfoDescription='', flickrreview=False, reviewer='',
override='', addCategory='', removeCategories=False):
"""Build the final description for the image.
The description is based on the info from flickrinfo and improved.
"""
description = '== {{int:filedesc}}... | 94a529e5a26a4390536359e0233f26d32465e3ed | 10,290 |
def allowed_file(filename, extensions):
"""
Check file is image
:param filename: string
:param extensions: list
:return bool:
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in extensions | c61e77205e40cd05fc0ea6e4e4f770180f15e6d8 | 10,291 |
def get_number_of_recovery_codes(userid):
"""
Get and return the number of remaining recovery codes for `userid`.
Parameters:
userid: The userid for which to check the count of recovery codes.
Returns:
An integer representing the number of remaining recovery codes.
"""
return d... | f292fbbc2e2ed55f53136988ef7d6f13ab2881e6 | 10,294 |
async def mailbox_search(search_term: str, Authorize: AuthJWT = Depends(),Token = Depends(auth_schema)):
"""Search email with a search term"""
Authorize.jwt_required()
try:
return JSONResponse(dumps({"success": True, "email": database.search(search_term)}))
except Exception as err:
retur... | 28d82605b78e124eb029125e9b2c9625bc207a64 | 10,296 |
def otel_service(docker_ip, docker_services):
"""Ensure that port is listening."""
# `port_for` takes a container port and returns the corresponding host port
port = docker_services.port_for("otel-collector", 4317)
docker_services.wait_until_responsive(
timeout=30.0, pause=5, check=lambda: is_p... | 19bd5f21ce30fa3cf5202369bf8e0a43456fdf9e | 10,297 |
from re import T
import numpy
def broadcast(vec: T.Tensor, matrix: T.Tensor) -> T.Tensor:
"""
Broadcasts vec into the shape of matrix following numpy rules:
vec ~ (N, 1) broadcasts to matrix ~ (N, M)
vec ~ (1, N) and (N,) broadcast to matrix ~ (M, N)
Args:
vec: A vector (either flat, row... | 3d471489ecef50a70a668db0262d0d21a8b76c86 | 10,298 |
def neighbour_list_n_out(nlist_i: NeighbourList,
nlist_j: NeighbourList) -> np.ndarray:
"""
Compute n^out between two NeighbourList object.
Args:
nlist_i (NeighbourList): A NeighbourList object for neighbour lists at time 0.
nlist_j (NeighbourList): A NeighbourL... | 15069fbb3995f7f65f61b9145353df7116d45e23 | 10,299 |
import re
def id_label_to_project(id_label):
"""
Given a project's id_label, return the project.
"""
match = re.match(r"direct-sharing-(?P<id>\d+)", id_label)
if match:
project = DataRequestProject.objects.get(id=int(match.group("id")))
return project | bd5f322b986776b95a3b3b9203e67c2caaa81c8a | 10,301 |
def payoff_blotto_sign(x, y):
"""
Returns:
(0, 0, 1) -- x wins, y loss;
(0, 1, 0) -- draw;
(1, 0, 0)-- x loss, y wins.
"""
wins, losses = 0, 0
for x_i, y_i in zip(x, y):
if x_i > y_i:
wins += 1
elif x_i < y_i:
losses += 1
if wins > losses:
... | 5a34ce81fdff8f90ee715d9c82fc55abf7eb2904 | 10,302 |
def import_trips(url_path, dl_dir, db_path, taxi_type, nrows=None, usecols=None,
overwrite=False, verbose=0):
"""Downloads, cleans, and imports nyc tlc taxi record files for the
specified taxi type into a sqlite database.
Parameters
----------
url_path : str or None
Path to... | 8e017873a1b17f493ee5b2df4457690a2fbc7b63 | 10,303 |
def householder(h_v: Vector) -> Matrix:
"""Get Householder transformation Matrix"""
return Matrix.identity(h_v.size()).subtract(2 * h_v * h_v.transpose() / (h_v * h_v)) | 686e8088eff5bf1b14e1438f0668a865a59a13d4 | 10,304 |
def _suppression_loop_body(boxes, iou_threshold, output_size, idx):
"""Process boxes in the range [idx*_NMS_TILE_SIZE, (idx+1)*_NMS_TILE_SIZE).
Args:
boxes: a tensor with a shape of [batch_size, anchors, 4].
iou_threshold: a float representing the threshold for deciding whether boxes
overlap too much... | 4adcb176d8d7269bded2b684d830a90a371d0df5 | 10,305 |
from typing import Iterable
import hashlib
import json
def calculate_invalidation_digest(requirements: Iterable[str]) -> str:
"""Returns an invalidation digest for the given requirements."""
m = hashlib.sha256()
inputs = {
# `FrozenOrderedSet` deduplicates while keeping ordering, which speeds up t... | 1fb2f014ad0b0ea98031d022ed02942e1b6ac1d0 | 10,306 |
def to_base_str(n, base):
"""Converts a number n into base `base`."""
convert_string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < base:
return convert_string[n]
else:
return to_base_str(n // base, base) + convert_string[n % base] | bc137d41c9543ef1a201f4bb14234fa277067a77 | 10,307 |
def number_of_photons(i,n=6):
"""Check if number of photons in a sample is higher than n (default value is 6)"""
bitstring = tuple(i)
if sum(bitstring) > n:
return True
else:
return False | 6c7cfea354aa4948d2c94469708f250e6d5b659d | 10,308 |
from typing import List
from typing import Optional
from typing import Dict
def _build_conflicts_from_states(
trackers: List[TrackerWithCachedStates],
domain: Domain,
max_history: Optional[int],
conflicting_state_action_mapping: Dict[int, Optional[List[Text]]],
tokenizer: Optional[Tokenizer] = Non... | 651a200dfd94518b4eb9da76d915794a761c9777 | 10,309 |
def inception_d(input_layer, nfilt):
# Corresponds to a modified version of figure 10 in the paper
"""
Parameters
----------
input_layer :
nfilt :
Returns
-------
"""
l1 = bn_conv(input_layer, num_filters=nfilt[0][0], filter_size=1)
l1 = bn_conv(l1, num_filters=nfilt[0][1]... | cb1a192ef210239c0eafe944126eb965dbcf6357 | 10,310 |
def generate_response(response, output):
"""
:param response:
:return dictionary
"""
status, command = None, None
if isinstance(response, dict):
status = response.get('ok', None)
response.get('command', None)
elif isinstance(response, object):
status = getattr(respo... | ea8764dd3e8f0205a0ec1dd278164140a414dadc | 10,311 |
def check_add_predecessor(data_predecessor_str_set, xml_data_list, xml_chain_list, output_xml):
"""
Check if each string in data_predecessor_str_set is corresponding to an actual Data object,
create new [Data, predecessor] objects lists for object's type : Data.
Send lists to add_predecessor() to write ... | d6bef7af0e32202825705ac36c3b4f09b3aa62ce | 10,312 |
def try_wrapper(func, *args, ret_=None, msg_="", verbose_=True, **kwargs):
"""Wrap ``func(*args, **kwargs)`` with ``try-`` and ``except`` blocks.
Args:
func (functions) : functions.
args (tuple) : ``*args`` for ``func``.
kwargs (kwargs) : ``*kwargs`` for ``func``.
ret_ (any... | 6098c966deffd5ac5ae4bba84219088b2052d878 | 10,313 |
def hnet_bsd(args, x, train_phase):
"""High frequency convolutions are unstable, so get rid of them"""
# Sure layers weight & bias
order = 1
nf = int(args.n_filters)
nf2 = int((args.filter_gain)*nf)
nf3 = int((args.filter_gain**2)*nf)
nf4 = int((args.filter_gain**3)*nf)
bs = args.batch_s... | 0c44775d5d342b73975cd7ffd00971d4f98fb4aa | 10,314 |
import numpy
def hdrValFilesToTrainingData(input_filebase: str, target_varname: str):
"""Extracts useful info from input_filebase.hdr and input_filebase.val
Args:
input_filebase -- points to two files
target_varname -- this will be the y, and the rest will be the X
Returns:
Xy: 2d arra... | de1427340dfed2dc36cdd05f43841399f54ac6a0 | 10,315 |
def create_column(number_rows: int, column_type: ColumnType) -> pd.Series:
"""Creates a column with either duplicated values or not, and either of string or int type.
:param number_rows: the number of rows in the data-frame.
:param column_type: the type of the column.
:returns: the data-frame.
"""
... | 0280f914960b222d589ae13b648339f1ff7ae562 | 10,316 |
import ctypes
def PumpEvents(timeout=-1, hevt=None, cb=None):
"""This following code waits for 'timeout' seconds in the way
required for COM, internally doing the correct things depending
on the COM appartment of the current thread. It is possible to
terminate the message loop by pressing CTRL+C, whi... | 4b24bfc7e68b0953c98b507e6ba5176e4b060011 | 10,318 |
def check_mix_up(method):
"""Wrapper method to check the parameters of mix up."""
@wraps(method)
def new_method(self, *args, **kwargs):
[batch_size, alpha, is_single], _ = parse_user_args(method, *args, **kwargs)
check_value(batch_size, (1, FLOAT_MAX_INTEGER))
check_positive(alpha,... | 528c30d73df3a26d8badc6df17508c6c2e6f69ae | 10,319 |
def generate_motif_distances(cluster_regions, region_sizes, motifs, motif_location, species):
"""
Generates all motif distances for a lsit of motifs
returns list[motif_distances]
motif_location - str location that motifs are stored
species - str species (for finding stored motifs)
... | 4694db72aaf550cac210387e50187fe910e21bf3 | 10,320 |
def sig_to_vrs(sig):
""" Split a signature into r, s, v components """
r = sig[:32]
s = sig[32:64]
v = int(encode_hex(sig[64:66]), 16)
# Ethereum magic number
if v in (0, 1):
v += 27
return [r, s, v] | 48884e4718de7bdda0527470d4e608e8f6b563b8 | 10,321 |
def index_to_string_table_from_tensor(mapping, default_value="UNK", name=None):
"""Returns a lookup table that maps a `Tensor` of indices into strings.
This operation constructs a lookup table to map int64 indices into string
values. The mapping is initialized from a string `mapping` 1-D `Tensor` where
each el... | 22ba72e1fe6ab28c5eb16a32152de4094d8d2e73 | 10,322 |
def test_profile_reader_no_aws_config(monkeypatch, tmp_path, capsys):
"""Test profile reader without aws config file."""
fake_get_path_called = 0
def fake_get_path():
nonlocal fake_get_path_called
fake_get_path_called += 1
return tmp_path
monkeypatch.setattr(awsswitch, "get_pat... | 549e2f08cfac1f3f579906a80f3853cba8d2501e | 10,323 |
def get_exclusion_type(exclusion):
"""
Utility function to get an exclusion's type object by finding the exclusion type that has the given
exclusion's code.
:param exclusion: The exclusion to find the type for.
:return: The exclusion type if found, None otherwise.
"""
for exclusion_type in E... | 778efc4cbd6481ae25f76985f30aa593e1e786fa | 10,324 |
def generatePlans(update):
"""
For an update object provided this function references the updateModuleList which lets all exc
modules determine if they need to add functions to change the state of the system when new
chutes are added to the OS.
Returns: True in error, as in we should stop with thi... | d764b2b18cebb81c450ef54aaa1a8b6893ec16c8 | 10,325 |
from typing import Dict
def get_str_by_path(payload: Dict, path: str) -> str:
"""Return the string value from the dict for the path using dpath library."""
if payload is None:
return None
try:
raw = dpath_util.get(payload, path)
return str(raw) if raw is not None else raw
exce... | bf8077838c2dd2278cd9209b6c560271faaa78cb | 10,326 |
import requests
import json
def get_token_from_code(request):
"""
Get authorization code the provider sent back to you
Find out what URL to hit to get tokens that allow you to ask for
things on behalf of a user.
Prepare and send a request to get tokens.
Parse the tokens using the OAuth 2 cl... | 00edc369150ddb18023799768c4843333079944e | 10,327 |
def DeWeStartCAN(nBoardNo, nChannelNo):
"""Dewe start CAN"""
if f_dewe_start_can is not None:
return f_dewe_start_can(c_int(nBoardNo), c_int(nChannelNo))
else:
return -1 | f810bb73152899fbfbb89caccec469a647c90223 | 10,328 |
def mw_wo_sw(mol, ndigits=2):
"""Molecular weight without salt and water
:param ndigits: number of digits
"""
cp = clone(mol) # Avoid modification of original object
remover.remove_water(cp)
remover.remove_salt(cp)
return round(sum(a.mw() for _, a in cp.atoms_iter()), ndigits) | 32b83d5e74eec3fdc4d18012dc29ed5e3d85edf3 | 10,329 |
def get_contact_list_info(contact_list):
"""
Get contact list info out of contact list
In rgsummary, this looks like:
<ContactLists>
<ContactList>
<ContactType>Administrative Contact</ContactType>
<Contacts>
<Contact>
... | 18d82190ad971b2a2cabb60706fc1486a91a32a5 | 10,330 |
import requests
def enableLegacyLDAP(host, args, session):
"""
Called by the ldap function. Configures LDAP on Lagecy systems.
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the ldap subcommand
@param session: the ... | 7ae9763930c6a0de29f8eac032b3e58d5cd64791 | 10,331 |
from typing import List
from typing import Dict
from typing import OrderedDict
def retrieve_panelist_appearance_counts(panelist_id: int,
database_connection: mysql.connector.connect
) -> List[Dict]:
"""Retrieve yearly apperance count f... | 27a5ccb192cf55714fed8316d647f53bce0ffbb2 | 10,332 |
from datetime import datetime
def chart(
symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"),
start=datetime.datetime(2008, 1, 1),
end=datetime.datetime(2009, 12, 31), # data stops at 2013/1/1
normalize=True,
):
"""Display a graph of the price history for the list of ticker symbols provide... | 2b4272daa353e21c7f1927e1d8ad68b6c184d97b | 10,333 |
def create_table(peak_id, chrom, pstart, pend, p_center, min_dist_hit, attrib_keys, min_pos, genom_loc, ovl_pf, ovl_fp, i):
"""Saves info of the hit in a tabular form to be written in the output table. """
if attrib_keys != ["None"]:
# extract min_dist_content
[dist, [feat, fstart, fend, strand,... | 476f0e272fe604c5254b68e93fa059f2ae942b2d | 10,334 |
def _get_tests(tier):
"""Return a generator of test functions."""
return TEST_TIERS[tier] | 364b263f2dc64b375092de6f2de9e771dbc020c2 | 10,335 |
def get_first_of_iterable(iterable):
"""
Return the first element of the given sequence.
Most useful on generator types.
:param iterable iterable: input iterable
:returns: tuple(iterable, first_element). If a generator is passed,
a new generator will be returned preserving the original val... | a16ae6795eb656a98ad6c620ae4f177d9cfc2387 | 10,336 |
import sqlite3
def getTiers(connection=None):
"""
"""
# Open the master database if it is not supplied.
flag = False
if connection is None:
connection = sqlite3.connect(MASTER)
flag = True
# Create a cursor from the connection.
cursor = connection.cursor()
# Execute ... | 1689f9aec4f84f5427e04352e1ce546e548eb505 | 10,337 |
from typing import Any
from typing import get_type_hints
from typing import get_origin
from typing import Union
from typing import get_args
def get_repr_type(type_: Any) -> Any:
"""Parse a type and return an representative type.
Example:
All of the following expressions will be ``True``::
... | fe74d79c1fcc74ff86d0c41db3f8f9da37dbf69a | 10,338 |
from datetime import datetime
import calendar
def get_month_range_from_dict(source):
"""
:param source: dictionary with keys 'start' and 'end
:return: a tuple of datatime objects in the form (start, end)
"""
now = timezone.now()
start = source.get('start')
end = source.get('end', datetime... | af68ad0ebcd63444c627fe5b408e1b59dc54e985 | 10,339 |
def softmax_ad_set_dim_func(head, data, axis):
"""Look up the softmax_ad_set_dim_map, and return hash_value, hash_key."""
key = []
key.append(tuple(data.shape))
key.append(data.dtype)
key.append(axis)
hash_key = str(tuple(key))
if hash_key in softmax_ad_set_dim_map.keys():
return ct... | c2077a70c47bb45dcbc79325e7620d4c63324560 | 10,340 |
import csv
def parse_latency_stats(fp):
"""
Parse latency statistics.
:param fp: the file path that stores the statistics
:returns an average latency in milliseconds to connect a pair of initiator and responder clients
"""
latency = []
with open(fp) as csvfile:
csvreader = csv.Dict... | c50c730b5c5bea704bd682d003baa0addfd7ee89 | 10,341 |
def micro_jaccard(y_true, y_pred):
"""
Calculate the micro Jaccard-score, i.e. TP / (TP + FP + FN).
:param y_true: `numpy.array` of shape `(n_samples,)` or `(n_samples, n_classes)`. True labels or class assignments.
:param y_pred: `numpy.array` of shape `(n_samples,)` or `(n_samples, n_classes)`. Predi... | b2be25baa6b161dabd676bcb4e58b2682485725f | 10,343 |
def round_to_nreads(number_set, n_reads, digit_after_decimal=0):
"""
This function take a list of number and return a list of percentage, which represents the portion of each number in sum of all numbers
Moreover, those percentages are adding up to 100%!!!
Notice: the algorithm we are using here is 'Lar... | c7a50b5caffb072b3fb6de9478b4acf83f701780 | 10,344 |
def _get_raster_extent(src):
"""
extract projected extent from a raster dataset
(min_x, max_x, min_y, max_y)
Parameters
----------
src : gdal raster
Returns
-------
(min_x, max_x, min_y, max_y)
"""
ulx, xres, xskew, uly, yskew, yres = src.GetGeoTransform()
lrx = ulx + (... | 49ed0b3c583cbfa5b9ecbc96d94aec42aeba3a32 | 10,345 |
def joined_table_table_join_args(joined_table: SQLParser.JoinedTableContext) -> dict:
"""
Resolve a joinedTable ParseTree node into relevant keyword arguments for TableJoin.
These will be pushed down and applied to the child TableRef.
"""
assert isinstance(joined_table, SQLParser.JoinedTableContext)... | 7419e63d28a4a34a49fe50e917faa478b246cb09 | 10,346 |
def find_by_name(name):
"""
Find and return a format by name.
:param name: A string describing the name of the format.
"""
for format in FORMATS:
if name == format.name:
return format
raise UnknownFormat('No format found with name "%s"' % name) | 3626316b961d913217036ddc58eaa71dbdaea1a7 | 10,347 |
def create_neighborhood_polygons(gdf):
""" an attempt to muild neighborhoods polygons from asset points"""
gdf = gdf.reset_index()
neis = gdf['Neighborhood'].unique()
gdf['neighborhood_shape'] = gdf.geometry
# Must be a geodataframe:
for nei in neis:
gdf1 = gdf[gdf['Neighborhood'] == nei... | 7ca77acfd73a4b13f9088e3839121076d1a70730 | 10,349 |
def custom_gradient(f=None):
"""Decorator to define a function with a custom gradient.
This decorator allows fine grained control over the gradients of a sequence
for operations. This may be useful for multiple reasons, including providing
a more efficient or numerically stable gradient for a sequence of oper... | 6c6432ab9a10c219d811651db2cbbf2321e43b95 | 10,350 |
def Field(name,
ctype,
field_loader=FieldLoaderMethod.OPTIONAL,
comment=None,
gen_setters_and_getters=True):
"""Make a field to put in a node class.
Args:
name: field name
ctype: c++ type for this field
Should be a ScalarType like an int, string or enum ty... | 9f3f84be56213640ca9d7368d35bdca8eb9958b2 | 10,351 |
from typing import Tuple
from typing import List
def sql(dataframe: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame, List[str], str]:
"""Infer best fit data types using dataframe values. May be an object converted to a better type,
or numeric values downcasted to a smallter data type.
Parameters
--... | d64a2d44cb3a89896aa3b7c19ec1a11bb8fcc2ff | 10,352 |
def calculateDeviation(img, lineLeft,lineRight, ):
"""This function calculates
the deviation of the vehicle from the center of the
image
"""
frameCenter = np.mean([lineLeft.bestx,lineRight.bestx] , dtype=np.int32)
imgCenter = img.shape[1]//2
dev = frameCenter - imgCenter
xm_p... | 79d16240a2d606cb25360532ac77e4fbe834e23d | 10,353 |
import requests
def post_new_tracker_story(message, project_id, user):
"""Posts message contents as a story to the bound project."""
if ";" in message:
name, description = message.split(";", maxsplit=1)
else:
name, description = (message, "")
story_name = "{name} (from {user})".format(... | b26391ad07159df3087cf22c136e5959a7fb6f4b | 10,354 |
def nz2epsmu(N, Z):#{{{
""" Accepts index of refraction and impedance, returns effective permittivity and permeability"""
return N/Z, N*Z | 3173df57ab5ad573baab87cd4fd6f353fcf69e2c | 10,355 |
import scipy
def logdet_symm(m, check_symm=False):
"""
Return log(det(m)) asserting positive definiteness of m.
Parameters
----------
m : array-like
2d array that is positive-definite (and symmetric)
Returns
-------
logdet : float
The log-determinant of m.
"""
... | 4e4358cb9094d671ba393d653adf685a916c4fa3 | 10,356 |
def merge(left, right):
""" Merge helper
Complexity: O(n)
"""
arr = []
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(right):
# Sort each one and place into the result
if left[left_cursor] <= right[right_cursor]:
arr.append(l... | c6730a0fe5bfcaf713c6c3fa8f2e777db50e4445 | 10,357 |
def validate_form_data(FORM_Class):
"""
Validates the passed form/json data to a request and passes the
form to the called function.
If form data is not valid, return a 406 response.
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
form = FOR... | d0287479d3c5da32c5fbd48a8f2047b64bce5e2b | 10,358 |
def set_axis_tick_format(
ax, xtickformat=None, ytickformat=None, xrotation=0, yrotation=0
):
"""Sets the formats for the ticks of a single axis
:param ax: axis object
:param xtickformat: optional string for the format of the x ticks
:param ytickformat: optional string for the format of the y ticks... | 06b7f6cc5ba78fa093cf517a5df414fa1bb6f504 | 10,359 |
def two_body(y, t):
"""
Solves the two body problem
:param y: state vector
y = [rx,ry,rz,vx,vy,vz]
:param t: time
:return: dy
"""
rx, ry, rz = y[0], y[1], y[2]
vx, vy, vz = y[3], y[4], y[5]
r = np.array([rx, ry, rz])
v = np.array([vx, vy, vz])
r_mag = np.linalg.norm... | 5a04f279caa3a540f76d3af488344414f4b3547e | 10,360 |
def DD_carrier_sync(z,M,BnTs,zeta=0.707,type=0):
"""
z_prime,a_hat,e_phi = DD_carrier_sync(z,M,BnTs,zeta=0.707,type=0)
Decision directed carrier phase tracking
z = complex baseband PSK signal at one sample per symbol
M = The PSK modulation order, i.e., 2, 8, or 8.
BnTs = t... | 77bcd1dd49a7bb9dfd40b8b45c9a9eb129ed674d | 10,362 |
from typing import Dict
from typing import Any
def rubrik_gps_vm_snapshot_create(client: PolarisClient, args: Dict[str, Any]) -> CommandResults:
"""
Trigger an on-demand vm snapshot.
:type client: ``PolarisClient``
:param client: Rubrik Polaris client to use
:type args: ``dict``
:param args:... | b065c29e58043b2785f48cf788fb1414262b0eee | 10,363 |
def CT_freezing_first_derivatives(SA, p, saturation_fraction):
"""
Calculates the first derivatives of the Conservative Temperature at
which seawater freezes, with respect to Absolute Salinity SA and
pressure P (in Pa).
Parameters
----------
SA : array-like
Absolute Salinity, g/kg
... | af3aa120e2e2620f16d984b29d42d583ed9fd347 | 10,365 |
def get_territory_center(territory: inkex.Group) -> inkex.Vector2d:
"""
Get the name of the territory from its child title element. If no title, returns
Warzone.UNNAMED_TERRITORY_NAME
:param territory:
:return:
territory name
"""
center_rectangle: inkex.Rectangle = territory.find(f"./{Sv... | 90f9e8ae7eebc5f3acf3d6e4100dec36ef5839d9 | 10,367 |
def batch_norm_relu(inputs, is_training, data_format):
"""Performs a batch normalization followed by a ReLU."""
# We set fused=True for a significant performance boost. See
# https://www.tensorflow.org/performance/performance_guide#common_fused_ops
inputs = tf.layers.batch_normalization(
inputs=inputs, ax... | 3d9d08000cd4dc5b90b64c6fdce7fca0039c5a03 | 10,368 |
def score_to_rating_string(score):
"""
Convert score to rating
"""
if score < 1:
rating = "Terrible"
elif score < 2:
rating = "Bad"
elif score < 3:
rating = "OK"
elif score < 4:
rating = "Good"
else:
rating = "Excellent"
return rating | 0c6a5aba0cb220a470f2d40c73b873d11b1a0f98 | 10,370 |
def deconv1d_df(t, observed_counts, one_sided_prf, background_count_rate, column_name='deconv', same_time=True,
deconv_func=emcee_deconvolve, **kwargs):
"""
deconvolve and then return results in a pandas.DataFrame
"""
#print("working on chunk with length {}".format(len(observed_counts)))
... | bc773398762ac7e82876d935b6ca0b0351960865 | 10,371 |
def create_parser() -> ArgumentParser:
"""Create a parser instance able to parse args of script.
return:
Returns the parser instance
"""
parser = ArgumentParser()
version = get_distribution('hexlet-code').version
parser.add_argument('first_file', help='path to JSON or YAML file')
pa... | 93f06dd056ab9121be1ad1312b67024312a4108f | 10,372 |
def remap_key(ctx, origin_key, destination_key, *, mode=None, level=None):
"""Remap *origin_key* to *destination_key*.
Returns an instance of :class:`RemappedKey`.
For valid keys refer to `List of Keys
<https://www.autohotkey.com/docs/KeyList.htm>`_.
The optional keyword-only *mode* and *level* a... | f4a8f7cddea2f82a13d06b5f3f3c4031e862e32b | 10,374 |
def get_anime_list(wf):
"""Get an Animelist instance.
:param Workflow3 wf: the Workflow3 object
:returns: Animelist object
:rtype: Animelist
"""
try:
animelist = Animelist(
wf.settings['UID'], wf.get_password('bangumi-auth-token')
)
except Exception as e:
... | a16a063afd2ac6a3fba4877665185a30971e8387 | 10,375 |
def use_linear_strategy():
"""
Uses a linear function to generate target velocities.
"""
max_velocity = kmph2mps(rospy.get_param("~velocity", 40))
stop_line_buffer = 2.0
def linear_strategy(distances_to_waypoints, current_velocity):
# Target velocity function should be a line
# ... | 7f0be5e0e11c7d29bb68ce7007e911f0fd14d6e2 | 10,376 |
def recomputation_checkpoint(module: nn.Module):
"""Annotates the output of a module to be checkpointed instead of
recomputed"""
def recompute_outputs(module, inputs, outputs):
return tuple(poptorch.recomputationCheckpoint(y) for y in outputs)
return module.register_forward_hook(recompute_outp... | a39f106f05e84b36ab21a948044adb14fb44b6cd | 10,377 |
import requests
import json
def get_random_quote() -> str:
"""Retrieve a random quote from the Forismatic API.
Returns:
str: The retrieved quote
"""
quote = ""
while quote == "":
response = requests.get(
"http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&forma... | bd189878c76a4da1544a6d3762c2a67f69ad1846 | 10,378 |
def has_datapoint(fake_services, metric_name=None, dimensions=None, value=None, metric_type=None, count=1):
"""
Returns True if there is a datapoint seen in the fake_services backend that
has the given attributes. If a property is not specified it will not be
considered. Dimensions, if provided, will ... | 59797809cb73644236cdc8d35cf9698491fff83a | 10,379 |
def optimizeMemoryUsage(foregroundTasks, backgroundTasks, K):
"""
:type foregroundTasks: List[int]
:type backgroundTasks: List[int]
:type K: int
:rtype: List[List[int]]
"""
res = []
curr_max = 0
if len(foregroundTasks) == 0:
for j in range(len(backgroundTasks)):
... | be7de70bf39ea1872ad1d5bbb9c5209ae3978c8c | 10,380 |
import itertools
def cv_indices(num_folds,num_samples):
"""
Given number of samples and num_folds automatically create a subjectwise cross validator
Assumption: per subject we have 340 samples of data
>>> cv_set = cv_indices(2,680)
>>> cv_set
>>> (([0:340],[340:680]),([340:680,0:340]))
Alg... | ce0d983458a089919f5581ebc0a650f73cf4c423 | 10,381 |
import pkg_resources
import json
import jsonschema
def load_schema(schema_name: str) -> dict:
"""Load a JSON schema.
This function searches within apollon's own schema repository.
If a schema is found it is additionally validated agains Draft 7.
Args:
schema_name: Name of schema. Must be fi... | b8ebed15394fef7ec1bb9ab735e4f8cb2201df0b | 10,382 |
def question_12(data):
"""
Question 12 linear transform the data, plot it, and show the newly created cov matrix.
:param data: data
:return: data after linear transformation
"""
s_mat = np.array([[0.1, 0, 0], [0, 0.5, 0], [0, 0, 2]])
new_data = np.matmul(s_mat, data)
plot_3d(new_data, "Q... | e0904f6a36d2833b48e064ff62d3071d07ab448b | 10,383 |
def update_storage(user_choice):
"""It updates the Coffee Machine resources after a beverage is ordered."""
resources["water"] = resources["water"] - MENU[user_choice]["ingredients"]["water"]
resources["milk"] -= MENU[user_choice]["ingredients"]["milk"]
resources["coffee"] -= MENU[user_choice]["ingredie... | 48c642fad80a124fd802a2ae1e1fc440ffa20203 | 10,384 |
def second_test_function(dataset_and_processing_pks):
"""
Pass a result of JSON processing to a function that saves result on a model.
:param dataset_and_processing_pks: tuple of two (Dataset PK, Processing PK)
:return: tuple of two (Dataset PK; JSON (Python's list of dicts))
"""
# unpack tuple... | b21960b1349c825b00997281dfbef4ef924846d0 | 10,385 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.