content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def presentations():
"""Shows a list of selected presentations"""
return render_template(
'table.html',
title='Presentations',
data=PRESENTATIONS,
target='_blank',
) | 643c1b7a6595f4c8c84abc47019a0346b414df56 | 3,642,485 |
def get_consensus_mask(patient, region, aft, ref=HIVreference(subtype="any")):
"""
Returns a 1D vector of size aft.shape[-1] where True are the position that correspond to consensus sequences.
Position that are not mapped to reference or seen too often gapped are always False.
"""
ref_filter = traje... | da7699350609ffc29d20b9922fa03c0d1944b57d | 3,642,486 |
def return_next_entry_list_uri(links):
"""続くブログ記事一覧のエンドポイントを返す"""
for link in links:
if link.attrib["rel"] == "next":
return link.attrib["href"] | 0c4c4139270ef8dedbb106f2db852097f4cd3028 | 3,642,488 |
def none(**_):
""" Input: anything
Return: 0.0 (float)
Descr.: Dummy method to handle no temperature correction"""
return 0.0 | e06b22f91d5a73450ddb4ca53fbb2569d567dcf1 | 3,642,489 |
def paths_and_labels_to_rgb_dataset(image_paths, labels, num_classes, label_mode):
"""Constructs a dataset of images and labels."""
path_ds = dataset_ops.Dataset.from_tensor_slices(image_paths)
img_ds = path_ds.map(lambda path: load_rgb_img_from_path(path))
label_ds = dataset_utils.labels_to_dataset(lab... | 7c72b3d628937fe999d89f5524d4d079ef20d9da | 3,642,490 |
def get_custom_headers(manifest_resource):
"""Generates the X-TAXII-Date-Added headers based on a manifest resource"""
headers = {}
times = sorted(map(lambda x: x["date_added"], manifest_resource.get("objects", [])))
if len(times) > 0:
headers["X-TAXII-Date-Added-First"] = times[0]
head... | 6c3acf2ea330b347387bfec574b4f8edfffa69ab | 3,642,491 |
def checkCulling( errs, cullStrings ) :
"""
Removes all messages containing sub-strings listed in cullStrings. cullStrings can be either a string or a
list of strings. If as list of strings, each string must be a sub-string in a message for the message to
be culled.
"""
def checkCullingMatch( m... | 5414e52df999a8aef7ed34328a689efa1582aabb | 3,642,492 |
def gram_matrix(x, ba, hi, wi, ch):
"""gram for input"""
if ba is None:
ba = -1
feature = K.reshape(x, [ba, int(hi * wi), ch])
gram = K.batch_dot(feature, feature, axes=1)
return gram / (hi * wi * ch) | 6e6145d9941c2e63120c7d030ac5b6b1ccd5d97e | 3,642,493 |
import csv
def read_pinout_csv(csv_file, keyname="number"):
"""
read a csv file and return a dict with the given keyname as the keys
"""
reader = csv.DictReader(open(csv_file))
lst = []
for row in reader:
lst.append(row)
d = {}
for item in lst:
d[item[keyname]] = item
... | 07a30b1191d311fee315c87773e3b3c1111d7624 | 3,642,494 |
async def start(hub, ctx, name, resource_group, **kwargs):
"""
.. versionadded:: 1.0.0
Power on (start) a virtual machine.
:param name: The name of the virtual machine to start.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-... | 74a09ef57ea735ea6a5af2ee5d10d3407e770980 | 3,642,495 |
def Render(request, template_file, params):
"""Render network test pages."""
return util.Render(request, template_file, params) | a30e34297de9ec44982dc8bc19231c471cc080c4 | 3,642,496 |
import logging
from pathlib import Path
def setup_global_logger(log_filepath=None):
"""Setup logger for logging
Args:
log_filepath: log file path. If not specified, only log to console
Returns:
logger that can log message at different level
"""
logger = logging.getLogger(__name__... | 74a8911243947387352b5c20e81ef0a304b48aa5 | 3,642,497 |
def calculate_class_recall(conf_mat: np.array) -> np.array:
"""
Calculates the recall for each class from a confusion matrix.
"""
return np.diagonal(conf_mat) / np.sum(conf_mat, axis=1) | 715f20b3e957dee25630bb413aff48140cf6aad3 | 3,642,498 |
def findall(element, path):
""" A helper function around a :attr:`lxml.etree._Element.findall` that passes the
element's namespace mapping.
"""
return element.findall(path, namespaces=element.nsmap) | 20da8cb66ac591751501e5c944f6f95235582e80 | 3,642,499 |
def subplots(times,nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
gridspec_kw=None, **fig_kw):
""" create figure and subplot axes with same time (x) axis
Non-Market hours will not be included in the plot.
Notably a custom projection is used for the time axis, and the time values
... | dd10ae6939587cac36e9b4bff67e2426357c6635 | 3,642,501 |
def test_env(testenv, agent, config):
"""
Test of a GYM environment with an agent deciding on actions based
on environment state. The test is repeated for the indicated
iterations. Status of environment in each step is displayed if
verbose activated. Test results (frequency count) a... | 7a32e942f22f983e6377568be6e2019a72574eac | 3,642,502 |
def kldivergence(p, q):
"""Kullback-Leibler divergence D(P || Q) for discrete distributions
Parameters
----------
p, q : array-like, dtype=float, shape=n
Discrete probability distributions.
"""
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
return np.sum(np.wher... | 0c0bff8e1f4d9c5ca57b555cffe5d827350106b5 | 3,642,503 |
def sortPermutations(perms, index_return=False):
"""
Sort perms with respect (1) to their length and (2) their lexical order
@param perms:
"""
ans = [None] * len(perms)
indices = np.ndarray(len(perms), dtype="int")
ix = 0
for n in np.sort(np.unique([len(key) for key in perms])):
... | d20833936756f3617e394fdb62f45e798c5cc416 | 3,642,505 |
def get_laplacian(Dx,Dy):
"""
return the laplacian
"""
[H,W] = Dx.shape
Dxx, Dyy = np.zeros((H,W)), np.zeros((H,W))
j,k = np.atleast_2d(np.arange(0,H-1)).T, np.arange(0,W-1)
Dxx[j,k+1] = Dx[j,k+1] - Dx[j,k]
Dyy[j+1,k] = Dy[j+1,k] - Dy[j,k]
return Dxx+Dyy | 77dce6adecdf1effd4922f18dc0ec1d20f4e69f4 | 3,642,506 |
def recipes_ending(language: StrictStr, ending: StrictStr):
"""
Show the recipe for a word-ending.
Given an input language and an ending, present the user with
the recipe that will be used to build grammatical cases
for that specific ending.
And this path operation will:
* returns a singl... | 5584f4005d76a0ac13a73cfffd35b7e1f5d5d538 | 3,642,507 |
def blur(grid, blurring):
"""
Spreads probability out on a grid using a 3x3 blurring window.
The blurring parameter controls how much of a belief spills out
into adjacent cells. If blurring is 0 this function will have
no effect.
"""
height = len(grid)
width = len(grid[0])
center... | dec94ad3d2f14d4ac12b6799d8ee581afe73f53d | 3,642,508 |
def _row_adress(addr='1'):
"""returns the rown number for a column adress"""
return _cell_address(''.join(['A', addr]))[1] | eba4cc5a30a539b6bf021279698070c4ae10ee20 | 3,642,509 |
def split(x, num, axis):
"""
Splits a tensor into a list of tensors.
:param x: [Tensor] A TensorFlow tensor object to be split.
:param num: [int] Number of splits.
:param axis: [int] Axis along which to be split.
:return: [list] A list of TensorFlow tensor objects.
... | 6461e346261cc01e5b2ddc0bee164b49ea03035b | 3,642,510 |
def delete_sensor_values(request):
"""Delete values from a sensor
"""
params = request.GET
action = params.get('action')
sensor_id = params.get('sensor')
delete_where = params.get('delete_where')
where_value = params.get('value')
where_start_date = params.get('start_date')
where_end... | 049119e50ea2613c8f8c2ccaa674fd99a35c07e8 | 3,642,511 |
import collections
def _parse_voc_xml(node):
"""
Extracted from torchvision
"""
voc_dict = {}
children = list(node)
if children:
def_dic = collections.defaultdict(list)
for dc in map(_parse_voc_xml, children):
for ind, v in dc.items():
def_dic[ind].a... | 58ef998cdf36ce4620042736ff27fc06d4c277a6 | 3,642,512 |
def log_exp_sum_1d(x):
"""
This computes log(exp(x_1) + exp(x_2) + ... + exp(x_n)) as
x* + log(exp(x_1-x*) + exp(x_2-x*) + ... + exp(x_n-x*)), where x* is the
max over all x_i. This can avoid numerical problems.
"""
x_max = x.max()
if isinstance(x, gnp.garray):
return x_max + gnp.l... | 4e0fcf4831e052e1704394e783bd0a76157a123f | 3,642,514 |
def connect_intense_cells(int_cells, conv_buffer):
"""Merge nearby intense cells if they are within a given
convective region search radius.
Parameters
----------
int_cells: (N, M) ndarray
Pixels associated with intense cells.
conv_buffer: integer
Distance to search... | 079ab9f1dad2ee4b45e5e96923bb05b3e3e59c01 | 3,642,515 |
from typing import Union
def _encode_decimal(value: Union[Decimal, int, str]):
"""
Encodes decimal into internal format
"""
value = Decimal(value)
exponent = value.as_tuple().exponent
mantissa = int(value.scaleb(-exponent))
return {
'mantissa': mantissa,
'exponent': expone... | 089bd0dd79d6d75dfb4278c46c801df32f5be608 | 3,642,516 |
def getPristineStore(testCase, creator):
"""
Get an Axiom Store which has been created and initialized by C{creator} but
which has been otherwise untouched. If necessary, C{creator} will be
called to make one.
@type testCase: L{twisted.trial.unittest.TestCase}
@type creator: one-argument calla... | f3be2f5bfff30af298de250d7c2ecf1664cd503f | 3,642,517 |
def data_to_CCA(dic, CCA):
"""
Returns a dictionary of ranking details of each CCA
{name:{placeholder:rank}
"""
final_dic = {}
dic_CCA = dic[CCA][0] #the cca sheet
for key, value in dic_CCA.items():
try: #delete all the useless info
del value["Class"]
except Ke... | fedd8a55e4310c024ede4f474c89463f71a0ecb6 | 3,642,518 |
from astropy.coordinates import Angle
def deg2hms(x):
"""Transform degrees to *hours:minutes:seconds* strings.
Parameters
----------
x : float
The degree value to be written as a sexagesimal string.
Returns
-------
out : str
The input angle written as a sexagesimal string... | d4172d8cfe5b71115b6fde93469019a4644edce6 | 3,642,520 |
def get_waveforms_scales(we, templates, channel_locations):
"""
Return scales and x_vector for templates plotting
"""
wf_max = np.max(templates)
wf_min = np.max(templates)
x_chans = np.unique(channel_locations[:, 0])
if x_chans.size > 1:
delta_x = np.min(np.diff(x_chans))
else:
... | 98ece821ab449d2cbdfe5c81635b7948de88083e | 3,642,521 |
import time
def rec_findsc(positions, davraddi, davradius='dav', adatom_radius=1.1,
ssamples=1000, return_expositions=True,
print_surf_properties=False, remove_is=True, procs=1):
"""It return the atom site surface(True)/core(Flase) for each atoms in
for each structure pandas da... | 7f48d6c7732a23827879f22fba97c109456d01f8 | 3,642,522 |
from typing import Optional
async def accept_taa(
controller: AcaPyClient, taa: TAARecord, mechanism: Optional[str] = None
):
"""
Accept the TAA
Parameters:
-----------
controller: AcaPyClient
The aries_cloudcontroller object
TAA:
The TAA object we want to agree to
Re... | 40557b41aa2f43a3174dacf20252b11be4b6679d | 3,642,523 |
def discoverYadis(uri):
"""Discover OpenID services for a URI. Tries Yadis and falls back
on old-style <link rel='...'> discovery if Yadis fails.
@param uri: normalized identity URL
@type uri: six.text_type, six.binary_type is deprecated
@return: (claimed_id, services)
@rtype: (six.text_type, ... | 11ec5cb250f331e17fb84a4bc699c4396d4040ad | 3,642,524 |
def mapper_to_func(map_obj):
"""Converts an object providing a mapping to a callable function"""
map_func = map_obj
if isinstance(map_obj, dict):
map_func = map_obj.get
elif isinstance(map_obj, pd.core.series.Series):
map_func = lambda x: map_obj.loc[x]
return map_func | 5da5497b68dc71aec10231f80580fcbaab86c00e | 3,642,525 |
def int_finder(input_v, tol=1e-6, order='all', tol1=1e-6):
"""
The function computes the scaling factor required to multiply the
given input array to obtain an integer array. The integer array is
returned.
Parameters
----------
input1: numpy.array
input array
tol: float
... | c7168a9146def4990174be56c7811663b62e82a2 | 3,642,526 |
def cell_info_for_active_cells(self, porosity_model="MATRIX_MODEL"):
"""Get list of cell info objects for current case
Arguments:
porosity_model(str): String representing an enum.
must be 'MATRIX_MODEL' or 'FRACTURE_MODEL'.
Returns:
List of **CellInfo** objects
**CellInfo ... | f2b211e72bc5c2f651d67fa383dc750b6b9f5c5a | 3,642,527 |
def features(x, encoded):
"""
Given the original images or the encoded images, generate the
features to use for the patch similarity function.
"""
print('start shape',x.shape)
if len(x.shape) == 3:
x = x - np.mean(x,axis=0,keepdims=True)
else:
# count x 100 x 256 x 768
... | 1f3e1514dc67908207c38d75914954cb1af8178b | 3,642,528 |
from datetime import datetime
def create_processing_log(s_url,s_status=settings.Status.PENDING):
"""
Creates a new crawler processing status. Default status PENDING
:param s_url: str - URL/name of the site
:param s_status: str - The chosen processing status
:return: SiteProcessingLog - The new pr... | 05fd2e5b01289f982789b1f7d88b401b25d445c3 | 3,642,529 |
import torch
def pick_action(action_distribution):
"""action selection by sampling from a multinomial.
Parameters
----------
action_distribution : 1d torch.tensor
action distribution, pi(a|s)
Returns
-------
torch.tensor(int), torch.tensor(float)
... | ac7ceb0df860876ec209563eaa6bdd3f8bd09189 | 3,642,530 |
from typing import List
def word_tokenizer(text: str) -> List[str]:
"""Tokenize input text splitting into words
Args:
text : Input text
Returns:
Tokenized text
"""
return text.split() | dc6e4736d7a1f564bcfc6fed081a1869db38eea5 | 3,642,531 |
from google.cloud import datacatalog_v1beta1
def lookup_bigquery_dataset(project_id, dataset_id):
"""Retrieves Data Catalog entry for the given BigQuery Dataset."""
datacatalog = datacatalog_v1beta1.DataCatalogClient()
resource_name = '//bigquery.googleapis.com/projects/{}/datasets/{}'\
.format(... | 847ce43ccea5f462ccf696bc5a098c0e26f27852 | 3,642,532 |
def indicator_structure(Template, LC_instance):
""" given a Template A and a LC instance Sigma
builds the indicator structure of Sigma over A
and passes the identification object """
in_vars, in_cons = LC_instance
# Construct the domain of the indicator by factoring
arities = dict(in_va... | 0652fd3af1a16892496b232e42c2fbdb2525fc78 | 3,642,533 |
def add_depth_dim(X, y):
"""
Add extra dimension at tail for x only. This is trivial to do in-line.
This is slightly more convenient than writing a labmda.
Args:
X (tf.tensor):
y (tf.tensor):
Returns:
tf.tensor, tf.tensor: X, y tuple, with X having a new trailing dimension.
... | 972bcc5df0e333186b39d306c9cec46c23117c9a | 3,642,534 |
import functools
import warnings
import traceback
def catch_exceptions(warning_msg="An exception was caught and ignored.", should_catch=True):
"""Decorator that catches exceptions."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not should_catch:
... | 4242512d6416ecd97ef0c241d0d719fcdaedd797 | 3,642,535 |
def setSC2p5DAccNodes(lattice, sc_path_length_min, space_charge_calculator, boundary = None):
"""
It will put a set of a space charge SC2p5D_AccNode into the lattice as child nodes of the first level accelerator nodes.
The SC nodes will be inserted at the beginning of a particular part of the first level AccNode ele... | f40c21f625da435ff7b42b157dbce803ebd0bf82 | 3,642,536 |
def transmuting_ring_sizes_score(mapping: LigandAtomMapping):
"""Checks if mapping alters a ring size"""
molA = mapping.molA.to_rdkit()
molB = mapping.molB.to_rdkit()
molA_to_molB = mapping.molA_to_molB
def gen_ringdict(mol):
# maps atom idx to ring sizes
ringinfo = mol.GetRingInfo(... | fb09a123eea6eb155c6c8aecccedf82838ee40ff | 3,642,537 |
def test_translate_six_frames(seq_record):
"""
Given a Biopython sequence record with a DNA (or RNA?) sequence,
translate into amino acid (protein) sequences in six frames.
Returns translations as list of strings.
"""
translation_list = []
for strand, nuc in [(+1, seq_record.seq), (-1, seq_record.... | ce230ee2d8c48d55b269b89e828782456389fc39 | 3,642,538 |
import math
import tokenize
def from_sequence(seq, partition_size=None, npartitions=None):
""" Create dask from Python sequence
This sequence should be relatively small in memory. Dask Bag works
best when it handles loading your data itself. Commonly we load a
sequence of filenames into a Bag and t... | d408f73211af6713f5bf621daf262d3d217419a1 | 3,642,539 |
def _get_instances(consul_host, user):
"""Get all deployed component instances for a given user
Sourced from multiple places to ensure we get a complete list of all
component instances no matter what state they are in.
Args
----
consul_host: (string) host string of Consul
user: (string) us... | fa8b85d0c917b20676b74b2123d00f0d4dab41f5 | 3,642,541 |
from typing import Sequence
import glob
async def pool_help(p: 'Player', c: Messageable, msg: Sequence[str]) -> str:
"""Show information of all documented pool commands the player can access."""
prefix = glob.config.command_prefix
cmds = []
for cmd in pool_commands.commands:
if not cmd.doc or... | a21f894585995cfc80717c301906da9634641b30 | 3,642,542 |
def filter_params(params):
"""Filter the dictionary of params for a Bountysource account.
This is so that the Bountysource access token doesn't float
around in a user_info hash (considering nothing else does that).
"""
whitelist = ['id', 'display_name', 'first_name', 'last_name', 'email', 'avatar_ur... | d471ecfa413f6a6821202f14a2506a89e55353b2 | 3,642,543 |
from typing import Counter
def build_vocab(tokens, glove_vocab, min_freq):
""" build vocab from tokens and glove words. """
counter = Counter(t for t in tokens)
# if min_freq > 0, use min_freq, otherwise keep all glove words
if min_freq > 0:
v = sorted([t for t in counter if counter.get(t) >= ... | 797718d6c5d91ac1318b318ca0c254903383304a | 3,642,544 |
def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True):
"""
Checks the equality of two masked arrays, up to given number odecimals.
The equality is checked elementwise.
"""
def compare(x, y):
"Returns the result of the loose comparison between x and y)."
return ap... | 1551ef5b723718644805901fdd041594900cffd2 | 3,642,545 |
def to_bits_string(value: int) -> str:
"""Converts unsigned value to a bit string with _ separators every nibble."""
if value < 0:
raise ValueError(f'Value is not unsigned: {value!r}')
bits = bin(value)[2:]
rev = bits[::-1]
pieces = []
i = 0
while i < len(rev):
pieces.append(rev[i:i + 4])
i +=... | 07dea253378686a1c65c97fad3d0b706e02335c4 | 3,642,546 |
import collections
def comp_days_centered(ndays, offset=0):
"""Return days for pre/onset/post composites centered on onset.
Parameters
----------
ndays : int
Number of days to average in each composite.
offset : int, optional
Number of offset days between pre/onset and onset/post
... | afe62411e5540c9088e929ecc502994a66a4d272 | 3,642,547 |
def linreg_fit_bayes(X, y, **kwargs):
"""
Fit a Bayesian linear regression model.
This is a port of linregFit.m from pmtk3.
:param X: N*D design matrix
:param y: N*1 response vector
"""
pp = preprocessor_create(add_ones=True, standardize_X=False) # default
prior = kwargs['prior'] if '... | 0ba43ff80a4dbc96a8111beadb3efcb7adb7c8eb | 3,642,549 |
def getrv(objwave, objflam, refwave, refflam, maxrv=[-200.,200.], waverange=[-np.inf,np.inf]):
"""
Calculates the rv shift of an object relative to some reference spectrum.
Inputs:
objwave - obj wavelengths, 1d array
objflam - obj flux, 1d array
refwave - ref wavelengths, 1d arr... | 4bf9bea90da74476e38e465d142fa83092e5c3c7 | 3,642,550 |
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that some hosts may not respond to a ping request even if the host name is valid.
"""
# Ping parameters as function of OS
ping_param = "-n 1" if system_name().lower()=="windows" else "-c 1"
# Pinging
re... | 1d19f5f01593099c5a534c0afa4d7bde85ba9d47 | 3,642,551 |
from typing import Counter
def remove_unpopulated_classes(_df, target_column, threshold):
"""
Removes any row of the df for which the label in target_column appears less
than threshold times in the whole frame (not enough populated classes)
:param df: The dataframe to filter
:param target_column: ... | 2ed31cfd3883a3856501dabff935028824141181 | 3,642,552 |
def get_longest_substrings(full_strings):
"""Return a dict of top substrings with hits from a given list of strings.
Args:
full_strings (list[str]): List of strings to test against each other.
Returns:
dict: substrings with their respective frequencies in full_strings.
"""
combos =... | 1eed90129d286988c0ff7e5e5e1229bf871b48bd | 3,642,553 |
def num_weekdays():
"""
Creates a function which returns the number of weekdays in a pandas.Period, typically for use as the average_weight parameter for other functions.
Returns:
callable: Function accepting a single parameter of type pandas.Period and returning the number of weekdays within this
... | bbcb2f8eca0398d46d72cc784f6ec1575159e36d | 3,642,554 |
import inspect
def add_special_param_to_dependency(
*,
dependency_param: inspect.Parameter,
dependant: Dependant,
) -> bool:
"""Check if param is non field object that should be passed into callable.
Arguments:
dependency_param: param that should be checked.
dependant: dependency ... | d4fa82c6fca8d79ca8b19e8b2aa3447ad38dbd48 | 3,642,556 |
from typing import Dict
async def ga4gh_info(host: str) -> Dict:
"""Construct the `Beacon` app information dict in GA4GH Discovery format.
:return beacon_info: A dict that contain information about the ``Beacon`` endpoint.
"""
beacon_info = {
# TO DO implement some fallback mechanism for ID
... | ceb223ff97313bcd0a15b39b3ecf1afa5c16ac8b | 3,642,558 |
def Random_Forest_Classifier_Circoscrizione(X, y, num_features, cat_features):
"""
Funzione che crea, fitta, testa e ritorna una pipeline con il RFC regressor,
(questa volta in riferimento al problema della classificazione di circoscrizioni)
con alcune caratterstiche autoevidenti da codice
Input: X ... | a23253d8fcb724dc3456c7e3506cd2ecf975ba0f | 3,642,559 |
def convert_data_set(data_set, specific_character_set):
""" Convert a DICOM data set to its NIfTI+JSON representation.
"""
result = {}
if odil.registry.SpecificCharacterSet in data_set:
specific_character_set = data_set[odil.registry.SpecificCharacterSet]
for tag, element in data_set.items(... | 68d9eaa54ba244b5b1c31e0d4ffb0af82b564174 | 3,642,560 |
import math
def calc_distance(
p1: Location,
p2: Location
) -> float:
"""
Args:
p1 (Location): planet 1 of interest
p2 (Location): planet 1 of interest
"""
if p1.coords.galaxy != p1.coords.galaxy:
distance = 20000 * math.fabs(p2.coords.galaxy - p1.coords.plane... | 725d7401fee19925b8b154495dc17368b19534fc | 3,642,561 |
def reset_noise_model():
"""Return test reset noise model"""
noise_model = NoiseModel()
error1 = thermal_relaxation_error(50, 50, 0.1)
noise_model.add_all_qubit_quantum_error(error1, ['u1', 'u2', 'u3'])
error2 = error1.tensor(error1)
noise_model.add_all_qubit_quantum_error(error2, ['cx'])
re... | 967ce6da9328f4ed4635d72f67036befde661bcb | 3,642,562 |
def parse_to_timestamp(dt_string):
"""Attempts to parse to Timestamp.
Parameters
----------
dt_string: str
Returns
-------
pandas.Timestamp
Raises
------
ValueError
If the string cannot be parsed to timestamp, or parses to null
"""
timestamp = pd.Timestamp(dt_s... | 766a1028b97e3a5c96430c9fcc5da9610315767a | 3,642,563 |
def __factor(score, items_sum, item_count):
"""Helper method for the pearson correlation coefficient algorithm."""
return score - items_sum/item_count | 2f92b4a5be4375e3083ace9b3855a170f7372460 | 3,642,564 |
from typing import Callable
from typing import Tuple
def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray,
scoring: Callable[[np.ndarray, np.ndarray, ...], float], cv: int = 5) -> Tuple[float, float]:
"""
Evaluate metric by cross-validation for given estimator
Para... | 2d656171a2043cdc7fd07ad199c6e0598de43900 | 3,642,565 |
def global_info(request):
"""存放用户,会话信息等."""
loginUser = request.session.get('login_username', None)
if loginUser is not None:
user = users.objects.get(username=loginUser)
# audit_users_list_info = WorkflowAuditSetting.objects.filter().values('audit_users').distinct()
audit_users_list... | 12ac1b296fed2a89fbefd8630da00c585e531e8d | 3,642,567 |
def arcsech(val):
"""Inverse hyperbolic secant"""
return np.arccosh(1. / val) | e1a90e1dec3ad7a2e427dc0e93421fd9b9f2b061 | 3,642,568 |
def addEachAtomAutocorrelationMeasures(coordinates, numAtoms):
"""
Computes sum ri*rj, and ri = coords for a single trajectory. Results are stored in different array indexes for different atoms.
"""
rirj = np.zeros((1, 3*numAtoms), dtype=np.float64)
ri = np.zeros((1, 3*numAtoms), dtype=np.float6... | 7413cad78c159af961784f7d2d221ea16c9c9c32 | 3,642,569 |
def api_posts_suggest(request):
"""サジェスト候補の記事をJSONで返す。"""
keyword = request.GET.get('keyword')
if keyword:
post_list = [{'pk': post.pk, 'title': post.title} for post in Post.objects.filter(title__icontains=keyword)]
else:
post_list = []
return JsonResponse({'post_list': post_list}) | 328ec626a6ed477b29ff7f31c82321643a551004 | 3,642,570 |
from typing import Tuple
from typing import List
def read_task_values(task_result: TaskResult) -> Tuple[bool, str, List[float], int]:
"""Reads unitary and federated accuracy from results.json.
Args:
fname (str): Path to results.json file containing required fields.
Example:
>>> print(rea... | 3b562709492c4bfad834236aba1ed97ee3dcc393 | 3,642,573 |
def get_two_dots(full=1):
""" return all posible simple two-dots """
bg= bottomGates()
two_dots = [dict({'gates':bg[0:3]+bg[2:5]})] # two dot case
for td in two_dots:
td['name'] = '-'.join(td['gates'])
return two_dots | 3529e4b6f1056930f0cc864d86ebe8ec5bfbd9b6 | 3,642,574 |
def read_values_of_line(line):
"""Read values in line. Line is splitted by INPUT_FILE_VALUE_DELIMITER."""
if INPUT_FILE_VALUE_DELIMITER == INPUT_FILE_DECIMAL_DELIMITER:
exit_on_error(f"Input file value delimiter and decimal delimiter are equal. Please set INPUT_FILE_VALUE_DELIMITER and INPUT_FILE_DECIMA... | 5450211b5aa10bbf7cca208ddce511b688abeb85 | 3,642,575 |
def find_allergens(ingredients):
"""Return ingredients with cooresponding allergen."""
by_allergens_count = sorted(ingredients, key=lambda i: len(ingredients[i]))
for ingredient in by_allergens_count:
if len(ingredients[ingredient]) == 1:
for other_ingredient, allergens in ingredients.it... | b5fde42cae0138f3bd819eb60629bb2d7ddf2f38 | 3,642,576 |
def send_calendar_events():
"""Sends calendar events."""
error_msg = None
try:
with benchmark("Send calendar events"):
builder = calendar_event_builder.CalendarEventBuilder()
builder.build_cycle_tasks()
sync = calendar_event_sync.CalendarEventsSync()
sync.sync_cycle_tasks_events()
ex... | 501941c968e67178cd2f1d7c6eac293e1617e4a5 | 3,642,577 |
def gaussian(x, p):
"""
Gaussian function
@param x : variable
@param p : parameters [height, center, sigma]
"""
return p[0] * (1/np.sqrt(2*pi*(p[2]**2))) * np.exp(-(x-p[1])**2/(2*p[2]**2)) | 1a42fabe572d9be2794ccf6e06c8ba2c0cc162fc | 3,642,580 |
def get_exploration_ids_subscribed_to(user_id):
"""Returns a list with ids of all explorations that the given user
subscribes to.
WARNING: Callers of this function should ensure that the user_id is valid.
Args:
user_id: str. The user ID of the subscriber.
Returns:
list(str). IDs o... | 2d8ff3570705ffd59fbf5a83ae23a4b07f49c6a7 | 3,642,581 |
def check_all_flash(matrix_2d):
"""
Check if all octopuses flashed.
:param matrix_2d: 2D matrix
:return: Boolean
"""
for line in matrix_2d:
for digit in line:
if digit != 0:
return True
return False | 9dca0174cd0272773e9b9330977bd3fac86f413a | 3,642,583 |
def cache_get(cache, key, fcn, force=False):
"""Get key from cache, or compute one."""
if cache is None:
cache = {}
if force or (key not in cache):
cache[key] = fcn()
return cache[key] | b358bf01dc657d8cd983830d18ef5a85a48d69ec | 3,642,585 |
def _BreadthFirstSearch(to_visit, children, visited_key=lambda x: x):
"""Runs breadth first search starting from the nodes in |to_visit|
Args:
to_visit: the starting nodes
children: a function which takes a node and returns the nodes adjacent to it
visited_key: a function for deduplicating node visits.... | 1c7153f61af81bb4bd9a06e0213bfcee4aab5cb8 | 3,642,586 |
def get_receptor_from_receptor_ligand_model(receptor_ligand_model):
"""
This function obtains the name of receptor based on receptor_ligand_model
Example of input: compl_ns3pro_dm_0_-_NuBBE_485_obabel_3D+----+20
"""
separator_model = get_separator_filename_mode()
separator_receptor = "_-_"
s... | 58b83ad160181bb04c533feb7fa3d37de44303ef | 3,642,587 |
import tokenize
def build_model():
"""
Selects the best model with optimal parameters
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('svd', TruncatedSVD()),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier(c... | 99aea3019fd55b84f7252e0c72cc7bf2bdb8d4e6 | 3,642,588 |
import copy
def monthly_expenses(costs, saleprice, propvalue, boyprincipal, rent):
"""Calculate monthly expenses
costs list of MonthlyCost objects
saleprice sale price of the property
propvalue actual value of the property
boyprincipal principal at beginning of year to ca... | 92887f624ce8d87d2f787087f6bb23f80c8186c7 | 3,642,589 |
def _create_player_points(
pool: pd.DataFrame,
teams: np.ndarray,
n_iterations: int,
n_teams: int,
n_players: int,
team_points: np.ndarray
) -> np.ndarray:
"""Calculates playerpoints
Args:
pool (pd.DataFrame): the player pool
statscols... | c6b7d55ce5041552a113436faf450ca96c84a15e | 3,642,591 |
def get_SolverSettings(instance):
""" get solver settings """
instance.sSolver = ""
instance.dicPyomoOption = {}
instance.dicSolverOption = {}
file_setting = "../Input/1_model_config/01_SolverConfig.csv"
dt_data = genfromtxt(file_setting, dtype = str, skip_header=0, delimiter=',')
... | aa9a1299d3a1a1ea7c3f2315117b097641ed22be | 3,642,592 |
import signal
def demod_from_array(mod_array, faraday_sampling_rate = 5e6, start_time = 0, end_time = 'max', reference_frequency = 736089.8, reference_phase_deg = 0, lowpas_freq = 10000, plot_demod = False, decimate_factor = 4, time_stamp = '', label = '', save = False):
"""
Sweet lord above this function washes t... | 7661ba4dbb39a5a3bd2336e386605b1361a6b287 | 3,642,593 |
import click
def cli_num_postproc_workers(
usage_help: str = "Number of workers to post-process the network output.",
default: int = 0,
) -> callable:
"""Enables --num-postproc-workers option for cli."""
return click.option(
"--num-postproc-workers",
help=add_default_to_usage_help(usag... | a34c1f75e26bfe8aca9569dd7e3102d20315deab | 3,642,595 |
import json
def create_cluster(redshift, iam, ec2, cluster_config, wait_status=False):
""" Create publicly available redshift cluster per provided cluster configuration.
:param redshift: boto.redshift object to use
:param iam: boto.iam object to use
:param ec2: boto.ec2 object to use
:param clust... | 2f93e8bcf3c2f9a43a370fb34f513df56dc312e7 | 3,642,596 |
def index():
""" Application entry point. """
return render_template("index.html") | fa84b6a2f6ae8c0ef7f976a6e58419913e8cbc1a | 3,642,597 |
from typing import Callable
def silhouette_to_prediction_function(
silhouette: np.ndarray
) -> Callable[[np.ndarray], bool]:
"""
Takes a silhouette and returns a function.
The returned function takes x,y point and
returns wether it is in the silhouette.
Args:
silhouette:
Re... | 802bf4dc83739fff171178f0b2b95e6900c1f725 | 3,642,599 |
from datetime import datetime
import calendar
def create_calendar(year=None, month=None):
"""
Create an inline keyboard with the provided year and month
"""
now = datetime.datetime.now()
if year is None:
year = now.year
if month is None:
month = now.month
data_ignore = crea... | edd7dd0245bbcb4269eaa4767cf16eb382db29e8 | 3,642,600 |
def read_image(link, size):
""" Read image on link and convert it to given size
Usage:
image = readImage(link, size)
Input variables:
link: path to image
size: output size of image
Output variables:
image: read and resized image
"""
image ... | 8465fc3ef8f6d8829da251cc924b442a4b7f3d07 | 3,642,601 |
def make_send_data(application_preset):
"""Generate the data to send to the protocol."""
if application_preset == 'none':
# data = bytes([i for i in range(32)])
# data = bytes([i for i in range(54)]) # for teensy 4.0
data = bytes([i for i in range(54)]) # for teensy lc & micro
... | 2b04a0bf977e44c3bd2a2aa6df0834ad458364bc | 3,642,602 |
def fileexists(filename):
"""Replacement method for os.stat."""
try:
f = open( filename, 'r' )
f.close()
return True
except:
pass
return False | 126460a04e7a8faf7517cb46c480670f5a067b1a | 3,642,604 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.