content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def prepare_create_user_db():
"""Clear a user from the database to be created."""
username = TEST_USERS[0][0]
connection = connect_db()
connection.cursor().execute('DELETE FROM Users WHERE username=%s',
(username,))
connection.commit()
close_db(connection)
ret... | beb1fd7a7f6c571f9d5e57a79d3b15c62a215789 | 3,645,533 |
def _getlocal(ui, rpath):
"""Return (path, local ui object) for the given target path.
Takes paths in [cwd]/.hg/hgrc into account."
"""
try:
wd = os.getcwd()
except OSError, e:
raise util.Abort(_("error getting current working directory: %s") %
e.strerror)
... | 4dc90dc62084e13c22b1a602fa20c552557e258c | 3,645,534 |
import hashlib
def get_size_and_sha256(infile):
"""
Returns the size and SHA256 checksum (as hex) of the given file.
"""
h = hashlib.sha256()
size = 0
while True:
chunk = infile.read(8192)
if not chunk:
break
h.update(chunk)
size += len(chunk)
... | 32c37ca6762f9c62d806e22c991b60f9d60947f4 | 3,645,535 |
def cmServiceAbort():
"""CM SERVICE ABORT Section 9.2.7"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x23) # 00100011
packet = a / b
return packet | 1ae9744fd21760775a45066ffeb11d7dea12c127 | 3,645,536 |
def get_distribution(distribution_id):
"""
Lists inforamtion about specific distribution by id.
:param distribution_id: Id of CDN distribution
"""
cloudfront = CloudFront()
return cloudfront.get_distribution(distribution_id=distribution_id) | 082c572341435423cb42ec895369af7822caee80 | 3,645,537 |
import sqlite3
def get_information_per_topic(db_path: str, topic: str, field: str):
""" Query all alert data monitoring rows for a given topic
Parameters
----------
db_path: str
Path to the monitoring database. The database will be created if
it does not exist yet.
topic: str
... | 97e95942506d15f1604d026c2a9954408ea01c29 | 3,645,538 |
def get_html_from_url(url, timeout=None):
"""Get HTML document from URL
Parameters
url (str) : URL to look for
timeout (float) : Inactivity timeout in seconds
Return
The HTML document as a string
"""
resp = reqget(url, timeout=timeout)
return resp.text | f909db702c812be029f00dd73bfaef8ac48966ba | 3,645,541 |
def clean(column, output_column=None, file_path=None, df=None, symbols='!@#$%^&*()+={}[]:;’\”/<>',
replace_by_space=True, keep_original=False):
"""
cleans the cell values in a column, creating a new column with the clean values.
Args:
column: the column to be cleaned.
output_colum... | 575d30a704c9ad37c027251ef609ef9c70445139 | 3,645,542 |
def len_lt(name, value):
"""
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: tes... | fde2db2e73d7ac711677b33518b6d5342b5dcbdb | 3,645,543 |
from typing import Iterable
def _ll_to_xy(latitude, longitude, wrfin=None, timeidx=0,
stagger=None, method="cat", squeeze=True, cache=None,
_key=None, as_int=True, **projparams):
"""Return the x,y coordinates for a specified latitude and longitude.
The *latitude* and *longitude* a... | 9d96d0d6e520731f16079c69389eff0c47c70dce | 3,645,544 |
def onedsinusoid(x,H,A,omega,phi):
"""
Returns a 1-dimensional sinusoid of form
H+A*np.sin(omega*x+phi)
"""
phi = np.pi/180 * phi
return H+A*np.sin(omega*x+phi) | 9917b462a6cd39c84a354d031ad8c6a09afcdec0 | 3,645,545 |
def number_in_english(number):
"""Returns the given number in words
>>> number_in_english(0)
'zero'
>>> number_in_english(5)
'five'
>>> number_in_english(11)
'eleven'
>>> number_in_english(745)
'seven hundred and fourty five'
>>> number_in_english(1380)
'one thousand three hu... | b3d580ed843d5d4bf3c62662c831391536e7479e | 3,645,547 |
def create_app(environment):
"""Factory Method that creates an instance of the app with the given config.
Args:
environment (str): Specify the configuration to initilize app with.
Returns:
app (Flask): it returns an instance of Flask.
"""
app = Flask(__name__)
app.config.from_obj... | 5cd5867a80ec696ee2a5647448c8e8b60fe2e023 | 3,645,548 |
def heating_design_temp(tmy_id):
"""Returns the heating design temperature (deg F) for the TMY3 site
identified by 'tmy_id'.
"""
return df_tmy_meta.loc[tmy_id].heating_design_temp | 204e219840ed5d2e04e9bb53706883d0fc1c6cfa | 3,645,549 |
def tonal_int(x):
"""
>>> tonal_int((4,7))
7
>>> tonal_int((4,7,2))
31
>>> tonal_int((6,11,-1))
-1
>>> tonal_int((0,-1,-1))
-13
>>> tonal_int((6,0,0))
12
>>> tonal_int((0,11,0))
-1
>>> tonal_int((0,11))
-1
>>> tonal_int((2, 0))
0
"""
i... | c7fb8dfd7ac5c82a81241efb807a7e45b877eee4 | 3,645,550 |
def DrtVariableExpression(variable):
"""
This is a factory method that instantiates and returns a subtype of
``DrtAbstractVariableExpression`` appropriate for the given variable.
"""
if is_indvar(variable.name):
return DrtIndividualVariableExpression(variable)
elif is_funcvar(variable.na... | a37b6e3f295e603d4ee78007dc4d4a22d22d1c3f | 3,645,553 |
def process_cv_results(cv_results):
"""
This function reformats the .cv_results_ attribute of a fitted randomized
search (or grid search) into a dataframe with only the columns we care
about.
Args
--------------
cv_results : the .cv_results_ attribute of a fitted randomized search
(or g... | a47b9cbc3fcb00f782eb46269f55259995d4b73c | 3,645,554 |
def cbow(currentWord, C, contextWords, tokens, inputVectors, outputVectors,
dataset, word2vecCostAndGradient = softmaxCostAndGradient):
""" CBOW model in word2vec """
# Implement the continuous bag-of-words model in this function.
# Input/Output specifications: same as the skip-gram model
# We will... | 5766b3c2facba8272431796b46da8abbd7264292 | 3,645,555 |
import yaml
def generate_dlf_yaml(in_yaml):
"""
Generate DLF-compatible YAML configuration file using
"templates/dlf_out.yaml" as template.
:param in_yaml: dict representation of a YAML document defining
placeholder values in "templates/dlf_out.yaml"
:type in_yaml: dict
:raises Placeholde... | c3bdf86731eb26904cae95b65c5b6181cc130ae8 | 3,645,556 |
def dice_coefficient(x, target):
"""
Dice Loss: 1 - 2 * (intersection(A, B) / (A^2 + B^2))
:param x:
:param target:
:return:
"""
eps = 1e-5
n_inst = x.size(0)
x = x.reshape(n_inst, -1)
target = target.reshape(n_inst, -1)
intersection = (x * target).sum(dim=1)
union = (x *... | c73cd86ed11bf89d94fb84db16186d6ace39d814 | 3,645,557 |
def batch_intersection_union(output, target, nclass):
"""mIoU"""
# inputs are numpy array, output 4D, target 3D
predict = np.argmax(output, axis=1) + 1 # [N,H,W]
target = target.astype(float) + 1 # [N,H,W]
predict = predict.astype(float) * np.array(target > 0).astype(float)
intersection = pre... | a62596ee500ec7525ceefeb6e6de0fd6673c522d | 3,645,558 |
import torch
def convert(trainset,testset,seed=1,batch_size=128, num_workers=2,pin_memory=True):
"""
Converts DataSet Object to DataLoader
"""
SEED = 1
cuda = torch.cuda.is_available()
torch.manual_seed(SEED)
if cuda:
torch.cuda.manual_seed(SEED)
dataloader_args = dict(shuffle=True, batch_size=128, num_w... | c380caa064b07ffc108ae33acc98361910b8f28f | 3,645,559 |
def build_gradcam(img_path, heatmap, color_map, original_image_colormap, alpha=0.5):
"""
Builds the gradcam.
Args:
img_path (_type_): Image path.
heatmap (_type_): Heatmap.
color_map (_type_): Color map.
original_image_colormap (_type_): Original image colormap.
alpha (float... | c71c24cc3fccc962b1083c1491e8da0fae9464ed | 3,645,560 |
def sample_joint_comorbidities(age, country):
"""
Default country is China.
For other countries pass value for country from {us, Republic of Korea, japan, Spain, italy, uk, France}
"""
return sample_joint(age, p_comorbidity(country, 'diabetes'), p_comorbidity(country, 'hypertension')) | 8190e73ccd637b78270a974773259c9bb4367fd5 | 3,645,561 |
import pydoc
def locate(name):
"""
Locate the object for the given name
"""
obj = pydoc.locate(name)
if not obj:
obj = globals().get(name, None)
return obj | 24f31b241ffcbd2e983889f209bff9a1ff8b1fc3 | 3,645,563 |
from stentseg.utils import PointSet
from stentseg.utils.centerline import points_from_mesh
def get_mesh_deforms(mesh, deforms, origin, **kwargs):
"""
input : mesh object
deforms forward for mesh?!
origin (from volume)
output: PointSet of mesh vertices (duplicates removed) and list ... | 710530c68d46e03d14eabc83db1fa448e76ebc2e | 3,645,564 |
def lnLikelihoodDouble(parameters, values, errors, weights=None):
"""
Calculates the total log-likelihood of an ensemble of values, with
uncertainties, for a double Gaussian distribution (two means and
two dispersions).
INPUTS
parameters : model parameters (see below)
value... | a387d0f8c52b380c57c4cd86ba06111c187db7b8 | 3,645,566 |
import urllib
def moleculeEntry(request, adjlist):
"""
Returns an html page which includes the image of the molecule
and its corresponding adjacency list/SMILES/InChI, as well
as molecular weight info and a button to retrieve thermo data.
Basically works as an equivalent of the molecule search fu... | 6a53812894b7150fc76444238597e8038f8ffa0c | 3,645,567 |
def has_user_id(id: int):
"""Checks if the Command Author's ID is the same as the ID passed into the function"""
def predicate(ctx) -> bool:
if ctx.author.id == id:
return True
raise MissingID(id, "Author")
return commands.check(predicate) | e83fff93f6ef3ebc06ebadc3470b1e74a18b3a39 | 3,645,568 |
def _polar_gbps(out, in_args, params, per_iter=False):
""" `speed_function` for `benchmark` estimating the effective bandwidth
of a polar decomposition in GB/s. The number of elements is estimated as
2 * the size of the input.
For a matrix multiplication of dimensions `m, n, k` that
took `dt` seconds, we defi... | a0428dfc9df6c4dd7f9d25712c3894d71bcd1700 | 3,645,569 |
def is_FreeMonoid(x):
"""
Return True if `x` is a free monoid.
EXAMPLES::
sage: from sage.monoids.free_monoid import is_FreeMonoid
sage: is_FreeMonoid(5)
False
sage: is_FreeMonoid(FreeMonoid(7,'a'))
True
sage: is_FreeMonoid(FreeAbelianMonoid(7,'a'))
... | d4fae223bcdec1f365406b9fb3c546f56db38565 | 3,645,570 |
import requests
def get_quote_data(ticker):
"""Inputs: @ticker
Returns a dictionary containing over 70 elements corresponding to the
input ticker, including company name, book value, moving average data,
pre-market / post-market price (when applicable), and more."""
site = "https://query1.finance.... | a23d7e091547ceca3c66f0ae90e84ea9f89d4e1c | 3,645,571 |
from typing import Dict
import click
def _import_stack_component(
component_type: StackComponentType, component_config: Dict[str, str]
) -> str:
"""import a single stack component with given type/config"""
component_type = StackComponentType(component_type)
component_name = component_config.pop("name"... | ec03abab6b005f5047dd7963ab93b83f4f891140 | 3,645,572 |
def unpack_range(a_range):
"""Extract chromosome, start, end from a string or tuple.
Examples::
"chr1" -> ("chr1", None, None)
"chr1:100-123" -> ("chr1", 99, 123)
("chr1", 100, 123) -> ("chr1", 100, 123)
"""
if not a_range:
return Region(None, None, None)
if isinsta... | f44b6069eb5e0fc8c85f01d5cbe708667a09a005 | 3,645,573 |
import torch
def _old_extract_roles(x, roles):
"""
x is [N, B, R, *shape]
roles is [N, B]
"""
N, B, R, *shape = x.shape
assert roles.shape == (N, B)
parts = []
for n in range(N):
parts.append(x[n:n+1, range(B), roles[n]])
return torch.cat(parts, dim=0) | 07a7be138558baa28ab1a10e2be2c7f17501ae96 | 3,645,574 |
def setup(i):
"""
See "install" API with skip_process=yes
"""
i['skip_process']='yes'
return install(i) | d4478adc27e444ac43dc9b4c8cd999157555c831 | 3,645,576 |
import requests
def post_merge_request(profile, payload):
"""Do a POST request to Github's API to merge.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``t... | 26131ac3dc078a9e33b7b2b785a71c51ec1d9072 | 3,645,577 |
def is_valid_table_name(cur, table_name):
"""
Checks whether a name is for a table in the database.
Note: Copied from utils.database for use in testing, to avoid
a circular dependency between tests and implementation.
Args:
cur: sqlite3 database cursor object
table_name (str): name t... | f1efc66220baa215a73f374da19842ab38c619be | 3,645,578 |
def create_mssql_pyodbc(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pyodbc.
"""
return create_engine(
_create_mssql_pyodbc(username, password, host, port, database),
**kwargs
) | dac74a0c32f1c693eb059d6a61f84d2288651969 | 3,645,579 |
def _wait_for_multiple(driver,
locator_type,
locator,
timeout,
wait_for_n,
visible=False):
"""Waits until `wait_for_n` matching elements to be present (or visible).
Returns located elements when fo... | d96c10d95877d699f8b284ea41e8b8ef5aebbf3c | 3,645,580 |
def relu(x):
"""
x -- Output of the linear layer, of any shape
Returns:
Vec -- Post-activation parameter, of the same shape as Z
cash -- for computing the backward pass efficiently
"""
Vec = np.maximum(0, x)
assert(Vec.shape == x.shape)
cash = x
return Vec, cash | 1d94d3008aca7ab613dfa92504061264111f1c28 | 3,645,581 |
def _declare_swiftdoc(
*,
actions,
arch,
label_name,
output_discriminator,
swiftdoc):
"""Declares the swiftdoc for this Swift framework.
Args:
actions: The actions provider from `ctx.actions`.
arch: The cpu architecture that the generated swiftdoc... | 589828527b8fe775aafca8fb1bee677d716a88c6 | 3,645,582 |
def threshold_image(gray_image, name_bw, threshold):
"""
This computes the binary image of the input image using a threshold
:param gray_image: input image
:param threshold: input threshold
:param name_bw: name of the binary image
:return: BW image
"""
# perform Gaussian blurring to re... | 98c14281a322b110594e12a4e2b10016a8d6533f | 3,645,583 |
import re
def sub_repeatedly(pattern, repl, term):
"""apply sub() repeatedly until no change"""
while True:
new_term = re.sub(pattern, repl, term)
if new_term == term:
return term
term = new_term | e57c648fb057f81e35e0fc2d2dc57edd0b400baf | 3,645,585 |
from typing import Tuple
def _dtw(distance_matrix: np.ndarray, gully: float = 1., additive_penalty: float = 0.,
multiplicative_penalty: float = 1.) -> Tuple[np.ndarray, np.ndarray, float]:
"""
Compute the dynamic time warping distance between two sequences given a distance matrix.
DTW score of lo... | 388b070d4bd2bbca42371b85d27f0807f86ae09b | 3,645,586 |
async def _ensure_meadowgrid_security_groups() -> str:
"""
Creates the meadowgrid coordinator security group and meadowgrid agent security
group if they doesn't exist. The coordinator security group allows meadowgrid agents
and the current ip to access the coordinator, as well as allowing the current ip... | b0fc2c0e1fb767c5cfbb365d0c58cf39d327caf3 | 3,645,587 |
def _create_pairs_numba(
to_match, indexer, first_stage_cum_probs, group_codes_per_individual, seed
):
"""
Args:
to_match (np.ndarry): 2d boolean array with one row per individual
and one column sub-contact model.
indexer (numba.List): Numba list that maps id of county to a numpy... | 5c7bed67a644104dc7b22b79d3858fc5e27cf14d | 3,645,588 |
def filter_known_bad(orbit_points):
"""
Filter some commands that are known to be incorrect.
"""
ops = orbit_points
bad = np.zeros(len(orbit_points), dtype=bool)
bad |= (ops['name'] == 'OORMPEN') & (ops['date'] == '2002:253:10:08:52.239')
bad |= (ops['name'] == 'OORMPEN') & (ops['date'] == '... | c8f64b541be5d2f7fce3554dc83c7f36ee8bc0a4 | 3,645,590 |
def create_lexicon(word_tags):
"""
Create a lexicon in the right format for nltk.CFG.fromString() from
a list with tuples with words and their tag.
"""
# dictionary to filter the double tags
word_dict = {}
for word, tag in word_tags:
if tag not in word_dict:
word_dict[ta... | 3a91671d559f5924ec9326520db6e11a1672fee4 | 3,645,591 |
def display_time(seconds, granularity=2):
"""Display time as a nicely formatted string"""
result = []
if seconds == 0:
return "0 second"
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
... | d8fe16585a66d085a08941b7b038d448fee23570 | 3,645,593 |
def reciprocal(x):
"""
Returns the reciprocal of x.
Args:
x (TensorOp): A tensor.
Returns:
TensorOp: The reciprocal of x.
"""
return ReciprocalOp(x) | 3678efa2d69948e85ccaae43f34492783a77cef9 | 3,645,594 |
def csv_saver_parser():
"""
Csv saver parser. Returns tuple with args as dictionary
and sufix that needs to be removed.
:return: tuple
"""
csv_saver_parser = ArgumentParser(description='Parser for saving data into CSV files.')
csv_saver_parser.add_argument('--F-csvsave',
... | d98fd53217eafa24826df56e114720a7881f17bb | 3,645,596 |
def get_var(expr: Expression) -> Var:
"""
Warning: this in only true for expressions captured by a match statement.
Don't call it from anywhere else
"""
assert isinstance(expr, NameExpr)
node = expr.node
assert isinstance(node, Var)
return node | f8bec4c919858f6aaa5126fc4e55f825f2ca677c | 3,645,597 |
def sight(unit_type: int):
"""Return the sight range of a unit, given its unit type ID
:param unit_type: the unit type ID, according to :mod:`pysc2.lib.stats`
:type unit_type: int
:return: the unit's sight range
:rtype: float
"""
return __data['Sight'][unit_type] | 84c3b8fdbfaaede81e7abc10cc190830df9e2c86 | 3,645,598 |
def decode_jwt(encoded_jwt):
"""
解码jwt
"""
global key
# 注意当载荷里面申明了 aud 受众的时候,解码时需要说明
decoded_jwt = jwt.decode(encoded_jwt, key, audience='dev', algorithms=["HS256"])
return decoded_jwt | 467bfcce7c5264813ab57f420da277b7674976db | 3,645,599 |
from typing import OrderedDict
async def bulkget(ip, community, scalar_oids, repeating_oids, max_list_size=1,
port=161, timeout=DEFAULT_TIMEOUT):
# type: (str, str, List[str], List[str], int, int, int) -> BulkResult
"""
Delegates to :py:func:`~puresnmp.aio.api.raw.bulkget` but returns si... | 6795f7d9ff7ac1952406922395e2308346ff244d | 3,645,600 |
def repo_version_db_key() -> bytes:
"""The db formated key which version information can be accessed at
Returns
-------
bytes
db formatted key to use to get/set the repository software version.
"""
db_key = c.K_VERSION.encode()
return db_key | 090a70e59d1a2c7d4a3f4589b9f4a2ef975e2585 | 3,645,601 |
def retrieve_psd_cdf(path):
"""interact with hdf5 file format for marginal CDFs for a set of PSDs"""
with h5py.File(path, 'r') as obj:
group = obj['PSD_CDF']
Npsd = group.attrs['num_psds']
freqs = group['frequencies'][...]
data = group['CDFs'][...]
vals = data[:,0,:]
cdf... | f0ee184d972ddcbedeb94345f15fcab9d08e8458 | 3,645,602 |
def get(context: mgp.ProcCtx) -> mgp.Record(tracks=list):
"""Returns a list of track_ids of trendy songs.
Calculates recently popular tracks by comparing the
popularity of songs using the `followers`, `created_at`,
and proximity to other popular songs (pagerank).
Example usage:
CALL trendy_... | 182d8a3d26028f472f1cc64bd993b6a29635daf5 | 3,645,603 |
import ipaddress
def ip_only(value):
"""
Returns only the IP address string of the value provided. The value could be either an IP address,
and IP network or and IP interface as defined by the ipaddress module.
Parameters
----------
value : str
The value to use
Returns
-----... | 149b202969c0ccb4e0c5e55417ce0231f1b5fc11 | 3,645,604 |
from typing import Tuple
from datetime import datetime
from typing import Optional
def get_data_by_isin(isin: str, dates: Tuple[datetime.date], is_etf: bool) -> Tuple[Optional[np.ndarray], str]:
"""Retrieves stock/ETF prices in EUR by ISIN for the given dates. Cached to make sure this is only queried once for
... | d4d46b45f480488fb67d3a6116a3b2e90c736efc | 3,645,607 |
from typing import Dict
from typing import Any
def get_result_qiskit() -> Dict[str, Dict[str, Any]]:
"""Fixture for returning sample experiment result
Returns
-------
Dict[str, Dict[str, Any]]
A dictionary of results for physics simulation and perfect gates
A result dictionary... | 7dc44fe110687b92f5e8b23c24798b06dd19e71e | 3,645,608 |
def all_budgets_for_student(user_id):
"""Returns a queryset for all budgets that a student can view/edit
i.e. is the submitter, president, or treasurer for any of the organization's budgets"""
query = Q(budget__submitter=user_id) | Q(budget__president_crsid=user_id) | Q(budget__treasurer_crsid=user_id)
... | 2048f2b579c2e8903ca34c34990e9c2c5215f79c | 3,645,609 |
import torch
def uniform_weights(x, x_mask):
"""Return uniform weights over non-masked x (a sequence of vectors).
Args:
x: batch * len * hdim
x_mask: batch * len (1 for padding, 0 for true)
Output:
x_avg: batch * hdim
"""
alpha = Variable(torch.ones(x.size(0), x.size(1)))
... | a1b88fc88ac65886283159d077e9550dab95c8de | 3,645,611 |
from operator import inv
def mixed_estimator_2(T1, T2, verbose=False):
"""
Based on the Lavancier and Rochet (2016) article.
The method combines two series of estimates of the same quantity taking into account their correlations. The individual measureements are assumed independent. The current implement... | 8f9ee282b0756dd41ff98e9ae596e46ddf6947a3 | 3,645,612 |
def e_add_const(pub, a, n):
"""Add constant n to an encrypted integer"""
return a * modpow(pub.g, n, pub.n_sq) % pub.n_sq | 37be82c71da3114f94d8b2ebe08f54a0726ec655 | 3,645,613 |
def area_triangle(base, height):
"""
"""
return (base * height) / 2.0 | 474e1a090dc7af9d68eaab35e6b04e5e165b6777 | 3,645,614 |
def _getAtomInvariantsWithRadius(mol, radius):
""" Helper function to calculate the atom invariants for each atom
with a given radius
Arguments:
- mol: the molecule of interest
- radius: the radius for the Morgan fingerprint
Return: list of atom invariants
"""
inv = []
for i ... | 8b8565a62af7f94c79604342077918a5b4261410 | 3,645,615 |
def radcool(temp, zmetal):
""" Cooling Function
This version redefines Lambda_sd
(rho/m_p)^2 Lambda(T,z) is the cooling in erg/cm^3 s
Args:
temp : temperature in the unit of K
zmetal: metallicity in the unit of solar metallicity
Return:
in the unit of erg*s*cm^3
"""
... | 720ed6625c9fe348ebe78aa80127c4bcc4e911a9 | 3,645,617 |
def L_model_forward(X, parameters):
"""
Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
Arguments:
X -- data, numpy array of shape (input size, number of examples)
parameters -- output of initialize_parameters_deep()
Returns:
AL -- last post-... | b086f172e1fc0d8dad2353af1b35a8f6bd3f13dc | 3,645,618 |
def linalg_multiply(a):
"""
Multiple all elements in vector or matrix
Parameters:
* a (array or matrix): The input to multiply
Return (number): The product of all elements
"""
return np.prod(a) | bac2457c61813cb5d662cef37fb2b48d8e65ba34 | 3,645,619 |
def lambda_handler(event, context):
"""
This method selects 10% of the input manifest as validation and creates an s3 file containing the validation objects.
"""
label_attribute_name = event['LabelAttributeName']
meta_data = event['meta_data']
s3_input_uri = meta_data['IntermediateManifestS3Uri'... | f6e0313155a47110e47567320e03e241bb6dde37 | 3,645,620 |
def get_table_6():
"""表 6 蓄熱の採用の可否
Args:
Returns:
list: 表 6 蓄熱の採用の可否
"""
table_6 = [
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可',... | 4ecd4526ed9ce67b7a5d22b67dd804059807e94d | 3,645,621 |
import random
def is_prime(number, num_trials=200):
"""Determines whether a number is prime.
Runs the Miller-Rabin probabilistic primality test many times on the given number.
Args:
number (int): Number to perform primality test on.
num_trials (int): Number of times to perform the Miller... | 78478437c08bcbd5e4c690466e4fe51bb4fad5ce | 3,645,622 |
def extract_labels(filenames):
"""
Extract class labels of the images from image path list.
# Arguments
filenames: List of paths to image file.
# Returns
List of image labels.
"""
return LabelEncoder().fit_transform([extract_label(filename) for filename in filenames]) | 53f708a0abb105d3ffce0202117b6eae812a9ede | 3,645,623 |
def reverseList(head):
"""
:type head: ListNode
:rtype: ListNode
"""
current = head;
# temp is first
counter = 0;
flag = 'Y';
while current is not None and flag != 'N':
# store the current element
# print(f"Current: {current... | 06f07ad9c5dbb13d2e288ea2ff14ef31febf87b9 | 3,645,624 |
def validate(data: BuildParams):
"""
Makes sure a valid combination of params have been provided.
"""
git_repo = bool(data.source.git_repo)
dockerfile = bool(data.source.dockerfile)
build_context = bool(data.source.build_context)
git_valid = git_repo and not dockerfile and not build_context
... | 708335092018339aa4f64b58d5ec8d2cb09751c3 | 3,645,625 |
import pickle
def load_model(filepath=FILEPATH) -> TrainingParams:
"""
Load
:param filepath:
:return:
"""
with open(filepath, "rb") as handler:
model = pickle.load(handler)
return model | f2a1ed631bdb7b1f7e6fd372ca604ef4ef6890f2 | 3,645,626 |
def is_symmetric(m):
"""Check if a sparse matrix is symmetric
https://mail.python.org/pipermail/scipy-dev/2014-October/020117.html
Parameters
----------
m : sparse matrix
Returns
-------
check : bool
"""
if m.shape[0] != m.shape[1]:
raise Valu... | 84523c1c4bf0120025d6e7a0bcc9cf2e489b1ae8 | 3,645,627 |
def render_raster_map(bounds, scale, basemap_image, aoi_image, id, path, colors):
"""Render raster dataset map based on bounds. Merge this over basemap image
and under aoi_image.
Parameters
----------
bounds : list-like of [xmin, ymin, xmax, ymax]
bounds of map
scale : dict
map... | f24c3b48911c7c322d3c02e9808f0013354c567d | 3,645,629 |
def str2num(s):
"""Convert string to int or float number.
Parameters
----------
s : string
String representing a number.
Returns
-------
Number (int or float)
Raises
------
TypeError
If `s` is not a string.
ValueError
If the string does ... | 5dfaed567a66fc7d3ee46cbb70d9c408d38fcbfe | 3,645,630 |
def new_log(infile_history=None, extra_notes=None, git_repo=None):
"""Create a new command line log/history.
Kwargs:
infile_history (dict): keys are input file names and values are the logs for those files
extra_notes (list): List containing strings of extra information (output is one list item p... | f1bbf4b9c84442d7abf700fec98277eb9e2283ea | 3,645,632 |
from typing import OrderedDict
import inspect
def _get_new_args_dict(func, args, kwargs):
"""Build one dict from args, kwargs and function default args
The function signature is used to build one joint dict from args and kwargs and
additional from the default arguments found in the function signature. Th... | ad7553e7b778b8f7b499217c7ee4ad7328958809 | 3,645,633 |
def hellinger_funct(x,P,Q):
"""
P,Q should be numpy stats gkde objects
"""
return np.sqrt(P(x) * Q(x)) | 198f0cf72ef75cece3c59248d8cd1215fa4299a1 | 3,645,634 |
from datetime import datetime
def human_date(date):
""" Return a string containing a nice human readable date/time.
Miss out the year if it's this year
"""
today = datetime.datetime.today()
if today.year == date.year:
return date.strftime("%b %d, %I:%M%P")
return date.strftime("%... | 7088617b58c0d3b3193e11885fcd7b7ef075f627 | 3,645,636 |
def compute_thickness(wmP, kdTreegm, kdTreewm):
"""
This function..
:param wmP:
:param kdTreegm:
:param kdTreewm:
:return:
"""
# Find the closest point to the gray matter surface point
gmIndex = kdTreegm.FindClosestPoint(wmP)
gmP = kdTreegm.GetDataSet().GetPoint(gmIndex)
# c... | c2c13a8c17eb997843c9e5752c6ae05f0854a7e5 | 3,645,637 |
def cytoband_interval():
"""Create test fixture for Cytoband Interval."""
return CytobandInterval(
start="q13.32", end="q13.32"
) | d052e2dcf7276dc24c680d0b1168ebea6f779eac | 3,645,639 |
def _get_proxy_class(request):
""" Return a class that is a subclass of the requests class. """
cls = request.__class__
if cls not in _proxy_classes:
class RequestProxy(cls):
def __init__(self, request):
self.__dict__ = request.__dict__
self.__request = re... | 72113c9d38bdf91650fa88d4297a25457f34b9f8 | 3,645,640 |
import csv
def rebuilt_emoji_dictionaries(filename):
"""
Rebuilds emoji dictionaries, given a csv file with labeled emoji's.
"""
emoji2unicode_name, emoji2sentiment = {}, {}
with open(filename) as csvin:
for emoji in csv.DictReader(csvin):
for key, value in emoji.items():
... | 69bf1438a524ea54bd7bef2d4537a0c61cd0bc3d | 3,645,641 |
def send_message(receiver, message):
"""
Send message to receivers using the Twilio account.
:param receiver: Number of Receivers
:param message: Message to be Sent
:return: Sends the Message
"""
message = client.messages.create(
from_="whatsapp:+14155238886", body=message, to=f"what... | 05022f40104d8b38ffe096ee01941ef04da5f076 | 3,645,642 |
def stem_list(tokens: list) -> list:
"""Stems all tokens in a given list
Arguments:
- tokens: List of tokens
Returns:
List of stemmed tokens
"""
stem = PorterStemmer().stem
return [stem(t) for t in tokens] | 6086bda0bce5ce042156a12617a2c09b4b8f9cc8 | 3,645,643 |
def unique(s):
"""Return a list of the elements in s, but without duplicates.
For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].
For best speed... | 055d2d6e748e1a4ee22057fcd3e73d4e8c8e8081 | 3,645,644 |
def get_ground_truth_assignments_for_zacharys_karate_club() -> jnp.ndarray:
"""Returns ground truth assignments for Zachary's karate club."""
return jnp.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1,
0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) | fc2050072293d9857b50425a4f31137a0872096d | 3,645,646 |
from typing import List
from typing import Tuple
def sort_places_versus_distance_from_coordinates(
list_places: List[Place], gps_coord: Tuple[float, float]
) -> List[Place]:
"""Oder list of places according to the distance to a reference coordinates.
Note: this helper is compensating the bad results of t... | 3089503406bf0959dd1caac5746693f812eb449c | 3,645,648 |
from typing import List
from typing import Tuple
def solve_part2_coordinate_subdivision(boxes: List[Tuple[str, Box]]) -> int:
""" An alternative method to solve part 2 which uses coordinate subdivisions to make a new grid.
On the puzzle input, this is roughly a 800x800x800 grid, which actually takes some time... | 5a283b0de558755f7ec95ff9cde091ca95b245de | 3,645,649 |
def decodeSignal(y, t, fclk, nbits) :
"""
This file reads in digitized voltages outputted from the
QCM Antenna Master Controller Board and outputs time,logic code number
pairs.
The encoding scheme is as follows:
HEADER: 3 clock cycles HIGH, followed by 3 clock cycles LOW
SIGNAL: 1 clock cycle LOW, followed by 1... | 72b812267e172ee245cb5c7f59366105baad40dc | 3,645,650 |
def find_dead_blocks(func, cfg):
"""Find all immediate dead blocks"""
return [block for block in cfg if not cfg.predecessors(block)
if block != func.startblock] | 3f72e0a573b1ef617511f2b9ec3d2e30c7ba6554 | 3,645,653 |
def _mcse_sd(ary):
"""Compute the Markov Chain sd error."""
_numba_flag = Numba.numba_flag
ary = np.asarray(ary)
if _not_valid(ary, shape_kwargs=dict(min_draws=4, min_chains=1)):
return np.nan
ess = _ess_sd(ary)
if _numba_flag:
sd = np.float(_sqrt(svar(np.ravel(ary), ddof=1), np.... | 4fcf966b7ec98cad193418f7e623c96154646b5f | 3,645,654 |
def dfs_predecessors(G, source=None):
"""Return dictionary of predecessors in depth-first-search from source."""
return dict((t,s) for s,t in dfs_edges(G,source=source)) | 6929d25c981fec9b932c0f978b1ee45f37e0e565 | 3,645,655 |
def merge_all_sections(prnt_sctns, child_sctns, merge_within_sections=False):
""" Merge the doc-sections of the parent's and child's attribute into a single docstring.
Parameters
----------
prnt_sctns: OrderedDict[str, Union[None,str]]
child_sctns: OrderedDict[str, Union[None,str]]
Returns
... | c692d1b08db1a49545eb39e6385040fafc10e149 | 3,645,656 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.