content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
async def async_setup_entry(hass, entry):
"""Set up the Samsung TV platform."""
# Initialize bridge
data = entry.data.copy()
bridge = _async_get_device_bridge(data)
if bridge.port is None and bridge.default_port is not None:
# For backward compat, set default port for websocket tv
d... | a5e411560c8f3f1e609d6675061a72000984e0ce | 3,016 |
def bring_contact_bonus_list(pb_client, obj_pb_ids, arm_pb_id, table_pb_id):
""" For some bring goals, may be useful to also satisfy an object touching table and
not touching arm condition. """
correct_contacts = []
for o in obj_pb_ids:
o2ee_contact = len(pb_client.getContactPoints(o, arm_pb_id)... | 6c0033b0bfb1d3f4d08c8ca114855e089fe852f7 | 3,017 |
def topic(**kwargs):
"""
:param to: Topic ID
:return:
"""
return api_request('topic', kwargs) | 2d2af8f74db1ffde7732ecff529911b7058154bf | 3,018 |
def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
daily_temp_df = pd.read_csv(filename, ... | 381eac22a1c3c0c9ad85d0c416fb1c182429153e | 3,019 |
def group_intents(input_file, intent_file, slot_file):
"""
Groups the dataset based on the intents and returns it.
Args:
input_file : The path to the input file
intent_file : The path to the intent file
slot_file : The path to the slot file
Returns:
A dict mapping intents to a list of tuples. ... | 8db186fc91ddc3adfbc163ef63e66cc408f3b47d | 3,020 |
def _get_path(string): # gets file path from variable name
"""
Gets path that a variable holds, convert it to start from root (.),
esolves any symbolic link and returns the converted path.
"""
varname = string.replace("(long)", "")
try:
path = c.VAR_STACK[varname]
except KeyError:
... | 794660ed9571dded27f5907c4ac1d9cdc99f41b6 | 3,021 |
def create_service_endpoint(service_endpoint_type, authorization_scheme, name,
github_access_token=None, github_url=None,
azure_rm_tenant_id=None, azure_rm_service_principal_id=None,
azure_rm_service_prinicipal_key=None, azure_rm_subscr... | 75ad8fdb237d4dac9105bc33b96273f67482375f | 3,022 |
import math
def voronoi_diagram_interpolation(interpolationcellid, id0, id1, voronoiDataset0,
voronoiDataset1, centerlines, step,
clippingPoints):
"""Given two Voronoi datasets interpolate the data sets along the centerline.
Args:
in... | 13c719b89f737bac625cf76c7d64a5c34a856fdd | 3,023 |
def plot_kde_matrix(df, w, limits=None, colorbar=True, refval=None):
"""
Plot a KDE matrix.
Parameters
----------
df: Pandas Dataframe
The rows are the observations, the columns the variables.
w: np.narray
The corresponding weights.
colorbar: bool
Whether to plot th... | a0272a0f819fc5bca6144c9a8293f29f415327b8 | 3,024 |
import logging
def _submit_to_all_logs(log_list, certs_chain):
"""Submits the chain to all logs in log_list and validates SCTs."""
log_id_to_verifier = _map_log_id_to_verifier(log_list)
chain_der = [c.to_der() for c in certs_chain]
raw_scts_for_cert = []
for log_url in log_list.keys():
re... | 16081a2ddbc924c0490af5f7c3ffc625300486cd | 3,029 |
import sqlite3
def create_connection(db_file: str):
"""Create database file."""
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
return conn | a50dff80de36e391aeea7f6867cc85334f4bc690 | 3,031 |
def _simplex_gradient(op, grad_wrt_weight):
"""Register gradient for SimplexInterpolationOp."""
grad_wrt_input = simplex_gradient(
input=op.inputs[0],
weight=op.outputs[0],
grad_wrt_weight=grad_wrt_weight,
lattice_sizes=op.get_attr('lattice_sizes'))
return [grad_wrt_input] | 58447f073cdf4feb6e1f115b039c8573ab1048ca | 3,032 |
def generate_experiment():
"""
Generate elastic scattering experiments which are reasonable but random
"""
exp_dict = {}
exp_keys = ['qmin', 'qmax', 'qbin', 'rmin', 'rmax', 'rstep']
exp_ranges = [(0, 1.5), (19., 25.), (.8, .12), (0., 2.5), (30., 50.),
(.005, .015)]
for n, k... | f913cbfc6f871fa290dd6cdb3e5da874b06243b4 | 3,033 |
def connectDB():
"""function to start the database connection using MongoClient from pymongo and the connection link from .env file path. Using certifi to provide certificate in order to enable the connection
Returns:
Cursor: database white-shark
"""
try:
client = MongoClient(f"{MONGO_U... | 6d04fbc03ed45d5ec2b868dd52270f7dd1d7339d | 3,034 |
import gzip
def load_dicom(filename):
"""Loads in a given dicom file using a pydicom library
:param filename: a path to the .dcm.gz or .dcm file
:type filename: Union[str, os.path]
:return: pydicom.dataset.FileDataset or pydicom.dicomdir.DicomDir
:raises TypeError: raised if the file extension do... | 898b2003049dd91d53f57e28208ad82b5449632e | 3,035 |
import torch
def load_pytorch_policy(fpath, itr, deterministic=False):
""" Load a pytorch policy saved with Spinning Up Logger."""
fname = osp.join(fpath, 'pyt_save', 'model'+itr+'.pt')
print('\n\nLoading from %s.\n\n'%fname)
model = torch.load(fname)
# make function for producing an action giv... | d368f9b120c78c00e446ab6a4b2b63e893507de7 | 3,036 |
def make_server(dashboard):
"""
Creates the server by mounting various API endpoints and static file content for the dashboard
Parameters
----------
dashboard : plsexplain.Dashboard
The dashboard instance to server
Returns
-------
FastAPI
The application instance that h... | a7e7e599ba8166d4a27818dcc21da25bb66a4171 | 3,037 |
def bash_complete_line(line, return_line=True, **kwargs):
"""Provides the completion from the end of the line.
Parameters
----------
line : str
Line to complete
return_line : bool, optional
If true (default), will return the entire line, with the completion added.
If false, ... | 571e0822cd7a4d44e19c969072d624123640d1f1 | 3,038 |
def use_board(name):
"""
Use Board.
"""
_init_pins()
return r_eval("pins::use_board(\"" + name + "\")") | 5f08450f48fca6ca827383f4a57f006ee6e50836 | 3,039 |
def add_parameter(name, initial_value=1.0, **kwargs):
"""Adds a new global parameter to the model.
:param name: the name for the new global parameter
:type name: str
:param initial_value: optional the initial value of the parameter (defaults to 1)
:type initial_value: float
... | 8fa0839f1a38fa78add8ab35b2eb03f0c3d4bbd8 | 3,040 |
from samplesheets.models import GenericMaterial
def get_sample_libraries(samples, study_tables):
"""
Return libraries for samples.
:param samples: Sample object or a list of Sample objects within a study
:param study_tables: Rendered study tables
:return: GenericMaterial queryset
"""
if ... | 284d08b313d982a4b6d6fe9d780f1a668f036455 | 3,041 |
def parse_next_frame(data):
"""
Parse the next packet from this MQTT data stream.
"""
if not data:
return None, b''
if len(data) < 2:
# Not enough data yet
return None, data
packet_type, flag1, flag2, flag3, flag4 = bitstruct.unpack('u4b1b1b1b1', data[0:1])
length =... | ce725ce871fdbd45fbf5d7367049171e7001469b | 3,042 |
import random
def pick_glance_api_server():
"""Return which Glance API server to use for the request
This method provides a very primitive form of load-balancing suitable for
testing and sandbox environments. In production, it would be better to use
one IP and route that to a real load-balancer.
... | e32e75b675f0b3e07c71ae172423b6393f213a4d | 3,043 |
def remove_punctuation(transcriptions):
"""
:param: transcriptions is the dictionary containing text file that has been
converted into an array.
:return: cleaned string of words
This function removes punctuations from the story """
parsed_string = dumps(transcriptions)
punctuations = '''[],!... | 5800a97a2a232f41161c9c8357cd826212d8302e | 3,044 |
def snakify(str_: str) -> str:
"""Convert a string to snake case
Args:
str_: The string to convert
"""
return str_.replace(" ", "_").lower() | c40d972fc99f2cb99f3c2b4a83296e793018c32b | 3,045 |
def search_images(
project,
image_name_prefix=None,
annotation_status=None,
return_metadata=False
):
"""Search images by name_prefix (case-insensitive) and annotation status
:param project: project name or folder path (e.g., "project1/folder1")
:type project: str
:param image_name_prefi... | dc5733e0c22419f850592ee2f8dd3b13e177c99b | 3,046 |
def bibtexNoteszotero(bibtex_names):
"""
params:
bibtex_names, {}
response, {}
return: notes_dict, {}
"""
#
notes_dict = {}
notes_dict["itemType"] = "note"
notes_dict["relations"] = {}
notes_dict["tags"] = []
notes_dict["note"] = bibtex_names["notes"].strip()
#
r... | 97e30f746f59ee5e1cfed8581a2dc272fc4b477f | 3,047 |
def iliev_test_5(N=10000,
Ns=10,
L=15. | units.kpc,
dt=None):
"""
prepare iliev test and return SPH and simplex interfaces
"""
gas, sources = iliev_test_5_ic(N, Ns, L)
conv = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc)
sph = ... | f4675e8c7f51c18cb31644295a1d5945e453de5b | 3,048 |
def run(model, model_params, T,
method, method_params, num_iter,
tmp_path="/tmp/consistency_check.txt",
seed=None,
verbose=False,
simplified_interface=True):
"""
Wrapper around the full consistency check pipeline.
Parameters
----------
model : str
Name ... | 152eb33e3e6c68306c3f965f734bc8d7ddeb4010 | 3,049 |
def clean_street(address: str) -> str:
"""
Function to clean street strings.
"""
address = address.lower()
address = _standardize_street(address)
address = _abb_replace(address)
address = _ordinal_rep(address)
if address in SPECIAL_CASES.keys(): # Special cases
address = SPECIAL_... | af166bd9ebd51e1a157135587c4efdb6469181ea | 3,050 |
def unroll_policy_for_eval(
sess,
env,
inputs_feed,
prev_state_feed,
policy_outputs,
number_of_steps,
output_folder,
):
"""unrolls the policy for testing.
Args:
sess: tf.Session
env: The environment.
inputs_feed: dictionary of placeholder for the input modalities.
prev_s... | 59979b74f7ff7dcdaf7c875ce93d3333f467cd0d | 3,051 |
def is_iterable(o: any) -> bool:
"""
Checks if `o` is iterable
Parameters
----------
o : any
The value to be checked.
Examples
--------
>>> is_iterable(list(range(5)))
True
>>> is_iterable(5)
False
>>> is_iterable('hello world')
True
>>> is_iterable(N... | f3124d5ead76977c45899c589e0c6873abafd773 | 3,053 |
def fit(init_file, semipar=False):
""" """
check_presence_init(init_file)
dict_ = read(init_file)
# Perform some consistency checks given the user's request
check_presence_estimation_dataset(dict_)
check_initialization_dict(dict_)
# Semiparametric Model
if semipar is True:
qua... | 05d484c0aae6e739881714eb7ec81c982503cf15 | 3,054 |
def date2gpswd(date):
"""Convert date to GPS week and day of week, return int tuple (week, day).
Example:
>>> from datetime import date
>>> date2gpswd(date(2017, 5, 17))
(1949, 3)
>>> date2gpswd(date(1917, 5, 17))
Traceback (most recent call last):
...
ValueError: Invalid date: 191... | 29000e900ffb743b29d41fa752fc4da5f470e1b8 | 3,055 |
import html
def __make_sliders(no, f):
"""Create dynamic sliders for a specific field"""
style = {'width':'20%', 'display': 'none'}
return html.Div(id={'index': f'Slider_{no}', 'type':'slider'},
children=[__make_slider(no, i) for i in range(1,f+1)], style=style) | b4fb97042e22d06e903f77a13381f9323acacacf | 3,056 |
def kurtosis(iterable, sample=False):
""" Returns the degree of peakedness of the given list of values:
> 0.0 => sharper peak around mean(list) = more infrequent, extreme values,
< 0.0 => wider peak around mean(list),
= 0.0 => normal distribution,
= -3 => flat
"""
a = iterab... | ba53f2425de5ffbf6cff0724e7128953554c829b | 3,057 |
def gen_data(shape, dtype, epsilon):
"""Generate data for testing the op."""
var = random_gaussian(shape, miu=1, sigma=0.3).astype(dtype)
m = random_gaussian(shape, miu=1, sigma=0.3).astype(dtype)
v = random_gaussian(shape, miu=1, sigma=0.3).astype(dtype)
grad = random_gaussian(shape, miu=1, sigma=0... | 75f790eda84ab2e718d504d26a303a6639775829 | 3,058 |
def factor_tmom_T1_RTN_60(df: pd.DataFrame):
"""
factor example
"""
factor = df['return'].rolling(60).sum()
return factor | 53b5700902bf409015f4e1c2063f741cea3736ee | 3,059 |
def get_dataset_info(dataset_name='mnist'):
"""Method to return dataset information for a specific dataset_name.
Args:
dataset_name: a string representing the dataset to be loaded using tfds
Returns:
A dictionary of relevant information for the loaded dataset.
"""
ds_info = tfds.builder(dataset_nam... | b4e36c966a34a3eacd327484e8d88d54303c0ea8 | 3,060 |
def full_model(mode, hparams):
"""Make a clause search model including input pipeline.
Args:
mode: Either 'train' or 'eval'.
hparams: Hyperparameters. See default_hparams for details.
Returns:
logits, labels
Raises:
ValueError: If the model returns badly shaped tensors.
"""
if hparams.us... | 3ab3a089628f9460b9f1ae9800ec9003fdae5d17 | 3,061 |
def aggregatePredictions(df_pred, threshold=0.8):
"""
Aggregates probabilistic predictions, choosing the
state with the largest probability, if it exceeds
the threshold.
:param pd.DataFrame df_pred:
columns: state
rows: instance
values: float
:param float threshold:
:return pd.Series:
... | a5d8efbe24d45279e80ff461e900dd3ac4921659 | 3,062 |
from typing import Any
def is_input_element(obj: Any) -> bool:
"""
Returns True, if the given object is an :class:`.InputElement`, or a
subclass of InputElement.
"""
return isinstance(obj, InputElement) | c3fbaea9588d40e2fa370aab32688c7e926bd265 | 3,064 |
def line_intersects_grid((x0,y0), (x1,y1), grid, grid_cell_size=1):
""" Performs a line/grid intersection, finding the "super cover"
of a line and seeing if any of the grid cells are occupied.
The line runs between (x0,y0) and (x1,y1), and (0,0) is the
top-left corner of the top-left grid ce... | f9710a61bcb101202295e50efb86800e855f00d5 | 3,065 |
def SimuGumbel(n, m, theta):
"""
# Gumbel copula
Requires:
n = number of variables to generate
m = sample size
theta = Gumbel copula parameter
"""
v = [np.random.uniform(0,1,m) for i in range(0,n)]
X = levy_stable.rvs(alpha=1/theta, beta=1,scale=(np.cos(np.pi/(2*theta)))... | 55eba3c327b99b0bd6157b61dff9d161feda0519 | 3,066 |
import math
def Norm(x, y):
"""求一个二维向量模长"""
return math.pow(math.pow(x, 2) + math.pow(y, 2), 0.5) | 4c161ada3c446d996f6e33be602a9475948f5bf8 | 3,067 |
from typing import Optional
from typing import Union
from typing import Callable
from typing import List
def make_roi(ms_experiment: ms_experiment_type, tolerance: float,
max_missing: int, min_length: int, min_intensity: float,
multiple_match: str, targeted_mz: Optional[np.ndarray] = None,
... | f8b3edbe24091082d1d20af6fdd7875449716a43 | 3,068 |
def get_all_zcs_containers(session, start=None, limit=None, return_type=None,
**kwargs):
"""
Retrieves details for all Zadara Container Services (ZCS) containers
configured on the VPSA.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Sessi... | 6d2d6ba7037323174d93d2191aef93c072bd0030 | 3,069 |
def jordan_wigner(n):
"""
Generates the Jordan-Wigner representation of the fermionic creation, annihilation,
and Majorana operators for an n-mode system.
The convention for the Majorana operators is as follows:
c_j=aj^{dag}+aj
c_{n+j}=i(aj^{dag}-aj)
"""
s = ket(2, 0) @ dag(k... | 193a2b91f84e2789b46a8767900938bcac8f83f9 | 3,070 |
import logging
def make_update(label: str, update_time: str, repeat: str, data: str, news: str) -> list[dict]:
"""Schedules an update with name 'label' to happen in 'interval' seconds. Updates saved covid
data, news and repeats the update depending on the content of the respective parameters. Adds
to glob... | d284d51695229005650eed58de10297ad200c8e4 | 3,071 |
def performTest(name, test): #{{{
"""
Given a series of writes in `test', generate a format string
and pass it to the vulnerable program. If the writes were successful
without destroying any other memory locations, return True.
Terminates after 2 seconds to handle infinite loops in libformatstr.
... | 829e19dbb45cfcc1788365f1c3a5459209c42e5e | 3,072 |
def readsignal_VEC(name , fa):
"""
Reads the time signal stored in the file var.txt and
written in a single column format. Returns the signal into the
single vector signal.
fa is an instrumental amplification factor
"""
path = '../data/'
channel = np.loadtxt(path + name + '.txt')
... | 2365988aa8baf717f332a021e24c1a7ca6d24243 | 3,073 |
import socket
def connect(host="localhost", port=27450):
"""Connect to server."""
client = socket(AF_INET, SOCK_DGRAM)
client.connect((host, port))
return client | c60bd35b75ee9b3b5aee898b0ee58b95562627c1 | 3,075 |
def is_coroutine_generator(obj):
"""
Returns whether the given `obj` is a coroutine generator created by an `async def` function, and can be used inside
of an `async for` loop.
Returns
-------
is_coroutine_generator : `bool`
"""
if isinstance(obj, AsyncGeneratorType):
code =... | fea1d344f32a0fffe7fe0bb344299e5fd54a6baa | 3,076 |
def get_scheme(scheme_id):
"""
Retrieve the scheme dict identified by the supplied scheme ID
Returns: An scheme dict
"""
for node in sd["nodes"]:
if scheme_id == node["id"]:
return node | 41c4b30496656201c58563fd5cc3ab3abe7ecf95 | 3,077 |
def Axicon(phi, n1, x_shift, y_shift, Fin):
"""
Fout = Axicon(phi, n1, x_shift, y_shift, Fin)
:ref:`Propagates the field through an axicon. <Axicon>`
Args::
phi: top angle of the axicon in radians
n1: refractive index of the axicon material
x_shift, y_shift: shift from ... | a333d29c94e79bdee1ef17ceb3993b28f2e9bd5d | 3,078 |
import urllib
import types
def addrAndNameToURI(addr, sname):
"""addrAndNameToURI(addr, sname) -> URI
Create a valid corbaname URI from an address string and a stringified name"""
# *** Note that this function does not properly check the address
# string. It should raise InvalidAddress if the address lo... | fd54c23b4e3396b224341fa54c106e4523b55314 | 3,079 |
def blkdev_uname_to_taptype(uname):
"""Take a blkdev uname and return the blktap type."""
return parse_uname(uname)[1] | e7165a9bd987d4820ed5486a06a1ceceec9c5564 | 3,080 |
def detection_layer(inputs, n_classes, anchors, img_size, data_format):
"""Creates Yolo final detection layer.
Detects boxes with respect to anchors.
Args:
inputs: Tensor input.
n_classes: Number of labels.
anchors: A list of anchor sizes.
img_size: The input size of the mo... | 85ada39e57c80eced3dbdc145759a1caa609607d | 3,081 |
from operator import pos
def create_position_tear_sheet(returns, positions,
show_and_plot_top_pos=2, hide_positions=False,
sector_mappings=None, transactions=None,
estimate_intraday='infer', return_fig=False):
"""
Gen... | 87338d6acb2852f9d45fa21cb4005c602cbfc909 | 3,082 |
import csv
def statement_view(request, statement_id=None):
"""Send a CSV version of the statement with the given
``statement_id`` to the user's browser.
"""
statement = get_object_or_404(
Statement, pk=statement_id, account__user=request.user)
response = HttpResponse(mimetype='text/csv... | c5a475086ee4a75fa76efae9cdf7bd185c8aa78a | 3,083 |
def get_proton_gamma(energy):
"""Returns relativistic gamma for protons."""
return energy / PROTON_MASS | 049e92cf85824561a50f559ef54045865da2a69b | 3,084 |
def demandNameItem(listDb,phrase2,mot):
"""
put database name of all items in string to insert in database
listDb: list with datbase name of all items
phrase2: string with database name of all items
mot: database name of an item
return a string with database name of all items separated with ','
... | 67af8c68f0ba7cd401067e07c5de1cd25de9e66c | 3,085 |
def escape_yaml(data: str) -> str:
"""
Jinja2 фильтр для экранирования строк в yaml
экранирует `$`
"""
return data.replace("$", "$$") | d1142af7447ad372e6b0df5848beb28e0dd84e68 | 3,086 |
def stokes_linear(theta):
"""Stokes vector for light polarized at angle theta from the horizontal plane."""
if np.isscalar(theta):
return np.array([1, np.cos(2*theta), np.sin(2*theta), 0])
theta = np.asarray(theta)
return np.array([np.ones_like(theta),
np.cos(2*theta),
... | a35f342ee32cdf54e432ee52e1faefbfb3b24382 | 3,087 |
import re
from datetime import datetime
def validate_item_field(attr_value, attr_form):
"""
:param attr_value: item的属性
:param attr_form: item category的属性规则
:return:
"""
if not isinstance(attr_form, dict):
return -1, {"error": "attr_form is not a dict."}
required = attr_form.get('re... | ac4687b576bb29707f55a2cb4627dc67ff07b2fa | 3,088 |
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.... | 4268d08a7e413a0558e2b0386cbd184ffaba05ba | 3,089 |
import json
def read_squad_examples(input_file, is_training):
"""Read a SQuAD json file into a list of SquadExample."""
with tf.io.gfile.GFile(input_file, "r") as reader:
input_data = json.load(reader)["data"]
examples = []
for entry in input_data:
for paragraph in entry["paragraphs"]:
paragrap... | 1c893c8f443bca9c707498650142ecd5262d619d | 3,090 |
def qarange(start, end, step):
"""
Convert the cyclic measurement and control data into the required array
:param start:
:param end:
:param step:
:return: np.array
"""
if Decimal(str(end)) - Decimal(str(start)) < Decimal(str(step)) or step == 0:
return [start]
start_decimal =... | 6e0331160f6501b4106c9e6379762f9c4bf87f1b | 3,092 |
def get_default_render_layer():
"""Returns the default render layer
:return:
"""
return pm.ls(type='renderLayer')[0].defaultRenderLayer() | b134b52bf35a46c10460ab612b14fcea44895a45 | 3,093 |
def translation(shift):
"""Translation Matrix for 2D"""
return np.asarray(planar.Affine.translation(shift)).reshape(3, 3) | 2b77265545194cabfc44728dbc7c5c95d808da38 | 3,094 |
def pad(adjacency_matrices, size):
"""Pads adjacency matricies to the desired size
This will pad the adjacency matricies to the specified size, appending
zeros as required. The output adjacency matricies will all be of size
'size' x 'size'.
Args:
adjacency_matrices: The input list of adjac... | dc015eb4dd41dcf3f88ef6317dab2e3f57709453 | 3,095 |
def mapping_activities_from_log(log, name_of_activity):
"""
Returns mapping activities of activities.
:param name_of_activity:
:param log:
:return: mapping
"""
mapping_activities = dict()
unique_activities = unique_activities_from_log(log, name_of_activity)
for index, activity in e... | 82fc23f08e9ae3629c654a5c04bcfcecb76a8cb3 | 3,096 |
def labels_to_1hotmatrix(labels, dtype=int):
"""
Maps restricted growth string to a one-hot flag matrix. The input and
the output are equivalent representations of a partition of a set of
n elelements.
labels: restricted growth string: n-vector with entries in {0,...,n-1}.
The fi... | eef80548e340477bf6881d0d14e434e0ee2f44da | 3,098 |
import select
def recall(logits, target, topk=[1,5,10], typeN=8):
"""Compute top K recalls of a batch.
Args:
logits (B x max_entities, B x max_entities x max_rois):
target (B x max_entities, B x max_entities x max_rois):
topk: top k recalls to compute
Returns:
N: numb... | ea3ec996808e25566e5bd3dd33f1a56232e5ba7a | 3,099 |
def n(request) -> int:
"""A test fixture enumerate values for `n`."""
return request.param | faec9637483670bec5d2bc687f2ee03d8c3839ea | 3,100 |
def decode(ciphered_text):
"""
Decodes the ciphered text into human readable text.
Returns a string.
"""
text = ciphered_text.replace(' ', '') # We remove all whitespaces
return ''.join([decode_map[x] if decode_map.get(x) else x for x in text]) | 717e837a4750d4c281e2ca635e141f40cf1e30ee | 3,101 |
from datetime import datetime
def parse(s):
""" Date parsing tool.
Change the formats here cause a changement in the whole application.
"""
formats = ['%Y-%m-%dT%H:%M:%S.%fZ','%d/%m/%Y %H:%M:%S','%d/%m/%Y%H:%M:%S', '%d/%m/%Y','%H:%M:%S']
d = None
for format in formats:
try:
... | c665dd91a03a6d9876b8c36a46699b813c540cea | 3,102 |
def openstack(request):
""" Context processor necessary for OpenStack Dashboard functionality.
The following variables are added to the request context:
``authorized_tenants``
A list of tenant objects which the current user has access to.
``regions``
A dictionary containing informati... | c914beb55a8609f2c363ac5e070f5531d7ce6abc | 3,103 |
def get_align_mismatch_pairs(align, ref_genome_dict=None) -> list:
"""input a pysam AlignedSegment object
Args:
align (pysam.AlignedSeqment object): pysam.AlignedSeqment object
ref_genome_dict (dict, optional): returned dict from load_reference_fasta_as_dict(). Defaults to None.
Returns:
... | 79886dbbdc764e115a72728060faaf155f3fea7a | 3,104 |
def get_int(name, default=None):
"""
:type name: str
:type default: int
:rtype: int
"""
return int(get_parameter(name, default)) | 4a07f1286e54fd9e55b97868af1aa1bae595b795 | 3,105 |
def run_test(series: pd.Series, randtest_name, **kwargs) -> TestResult:
"""Run a statistical test on RNG output
Parameters
----------
series : ``Series``
Output of the RNG being tested
randtest_name : ``str``
Name of statistical test
**kwargs
Keyword arguments to pass to... | 045ebe4756c24672cffdb3c43d6f0158809967d1 | 3,106 |
def radians(x):
"""
Convert degrees to radians
"""
if isinstance(x, UncertainFunction):
mcpts = np.radians(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.radians(x) | 49facfcfbeac91e9ac40b91ed8dc43b25ce157a6 | 3,107 |
def screen_poisson_objective(pp_image, hp_w,hp_b, data):
"""Objective function."""
return (stencil_residual(pp_image, hp_w,hp_b, data) ** 2).sum() | 43a1ff6594cd493a0122e8c1305b84f25550fb59 | 3,108 |
def learn(request, artwork_genre=None):
"""
Returns an art genre.
"""
_genre = get_object_or_404(Genre, slug=artwork_genre)
return render_to_response('t_learn.html',
{'genre': _genre},
context_instance=RequestContext(request)) | fe4e4477e7d2764ac41a58967ad1bc5296f10715 | 3,109 |
def plot_column(path: str, column: str, outpath: str = ""):
"""Plot a single column and save to file."""
df = to_df(path)
col_df = df.set_index(["name", "datetime"])[column].unstack("name")
ax = col_df.plot(grid=True)
ax.set_xlabel("Time")
ax.set_ylabel(LABEL_MAP[column])
if outpath:
... | 58d5033a3bb86986e30582bf3fedf36842aeded9 | 3,110 |
def get_loader():
"""Returns torch.utils.data.DataLoader for custom Pypipes dataset. """
data_loader = None
return data_loader | 0e3b0107e355169049dbdfa45cba9abdf479dcbe | 3,111 |
def attention_decoder_cell_fn(decoder_rnn_cell, memories, attention_type,
decoder_type, decoder_num_units, decoder_dropout,
mode, batch_size, beam_width=1, decoder_initial_state=None, reuse=False):
"""Create an decoder cell with attention. It takes decoder... | ffd0199d7c0bf9f9bfb5d4a6e1d7eac4767e84d3 | 3,112 |
async def post_user_income(user: str, income: Income):
"""
This functions create a new income in the DB. It checks whether
the user exists and returns a message in case no user exists.
In the other case, creates a new document in DB with the users
new Income.
user: users uuid.
income: Incom... | 3d155d72fc1e00f45ca93b804d25d1051e7c47ab | 3,113 |
from typing import Optional
def bind_rng_to_host_device(rng: jnp.ndarray,
axis_name: str,
bind_to: Optional[str] = None) -> jnp.ndarray:
"""Binds a rng to the host/device we are on.
Must be called from within a pmapped function. Note that when binding to
... | a7b50e6be3fd88f6a1341e0e43017baea305c31c | 3,114 |
def get_child_ids(pid, models, myself=True, ids: set = None) -> set:
"""
获取models模型的子id集合
:param pid: models模型类ID
:param models: models模型对象
:param myself: 是否包含pid
:param ids: 所有ID集合(默认为None)
:return: ids(所有ID集合)
"""
if ids is None:
ids = set()
queryset = models.objects.fi... | b5d9b10497eada8b3cafc32f4260ace091bbc0bf | 3,115 |
def get_tenant_id(khoros_object, community_details=None):
"""This function retrieves the tenant ID of the environment.
.. versionadded:: 2.1.0
:param khoros_object: The core :py:class:`khoros.Khoros` object
:type khoros_object: class[khoros.Khoros]
:param community_details: Dictionary containing c... | 7fe29990d7b6b99e4b677edfdb1cd32ca785654a | 3,116 |
import tokenize
def obfuscatable_variable(tokens, index):
"""
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a variable name that can be safely
obfuscated.
Returns '__skipline__' if the rest of the tokens on this line should be skipp... | 487bfd926b77260980875496991a7bcc2bc8df3f | 3,117 |
import csv
def concat_data(labelsfile, notes_file):
"""
INPUTS:
labelsfile: sorted by hadm id, contains one label per line
notes_file: sorted by hadm id, contains one note per line
"""
with open(labelsfile, 'r') as lf:
print("CONCATENATING")
with open(notes_file, 'r') a... | b6403c4ec7797cd7d08e01e7b9a9365708bdee6f | 3,118 |
def replace_text_comment(comments, new_text):
"""Replace "# text = " comment (if any) with one using new_text instead."""
new_text = new_text.replace('\n', ' ') # newlines cannot be represented
new_text = new_text.strip(' ')
new_comments, replaced = [], False
for comment in comments:
if c... | 4b1284966eb02ca2a6fd80f8f639adcb4f1fde6c | 3,119 |
def init_show_booking_loader(response, item=None):
"""
init ShowingBookingLoader with optional ShowingBooking item
"""
loader = ShowingBookingLoader(response=response)
if item:
loader.add_value(None, item)
return loader | 2d9c790e487ab7009c70e83a8ecb5d5e93732ff7 | 3,120 |
def get_dpifac():
"""get user dpi, source: node_wrangler.py"""
prefs = bpy.context.preferences.system
return prefs.dpi * prefs.pixel_size / 72 | dc598635eb8fdf0b3fe8b6acc3f497a65a18f099 | 3,121 |
from typing import List
def seq_row(
repeats: int = 1,
trigger: str = Trigger.IMMEDIATE,
position: int = 0,
half_duration: int = MIN_PULSE,
live: int = 0,
dead: int = 0,
) -> List:
"""Create a 50% duty cycle pulse with phase1 having given live/dead values"""
row = [
repeats,
... | 5d331f1f67f5799165f3966249e199ca43e0ec27 | 3,122 |
def call_nelder_mead_method(
f,
verts,
x_tolerance=1e-6,
y_tolerance=1e-6,
computational_budget=1000,
f_difference=10,
calls=0,
terminate_criterion=terminate_criterion_x,
alpha=1,
gamma=2,
rho=0.5,
sigma=0.5,
values=[],
):
"""Return an approximation of a local op... | 02e16b477a977239a8dc256150cdbc983235f81c | 3,123 |
def get_auth_claims_from_request(request):
"""Authenticates the request and returns claims about its authorizer.
Oppia specifically expects the request to have a Subject Identifier for the
user (Claim Name: 'sub'), and an optional custom claim for super-admin users
(Claim Name: 'role').
Args:
... | 1e2aaf4f26b11defea65796331f160fd22267cf2 | 3,124 |
import io
def decrypt(**kwargs):
"""
Returns a CryptoResult containing decrypted bytes.
This function requires that 'data' is in the format generated by the
encrypt functionality in this SDK as well as other OCI SDKs that support
client side encryption.
Note this function cannot decrypt data... | ba27e39abd0c72db5acd2530b7a4128b3f073dc6 | 3,125 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.