content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _highlight_scoring(
original_example, subset_adversarial_result, adversarial_span_dict
):
"""
Calculate the highlighting score using classification results of adversarial examples
:param original_example:
:param subset_adversarial_result:
:param adversarial_span_dict:
"""
original_ut... | 788f903fe471ef539fe337c79858c04468ae3137 | 3,653,239 |
def server_hello(cmd, response):
"""Test command
"""
return response | 7e0cc03d1b64afb1a4fc44264096e6888ddb5df2 | 3,653,240 |
def test_vectorised_likelihood_not_vectorised_error(model, error):
"""
Assert the value is False if the likelihood is not vectorised and raises
an error.
"""
def dummy_likelihood(x):
if hasattr(x, '__len__'):
raise error
else:
return np.log(np.random.rand())
... | 1968be0c2ba147147e2ea5d4443c8bc87050d218 | 3,653,242 |
def display_timestamps_pair(time_m_2):
"""Takes a list of the following form: [(a1, b1), (a2, b2), ...] and
returns a string (a_mean+/-a_error, b_mean+/-b_error).
"""
if len(time_m_2) == 0:
return '(empty)'
time_m_2 = np.array(time_m_2)
return '({}, {})'.format(
display_timestam... | b8bb0fa727c087a6bc1761d55e55143a12693d1e | 3,653,243 |
def get_legendre(degree, length):
"""
Producesthe Legendre polynomials of order `degree`.
Parameters
----------
degree : int
Highest order desired.
length : int
Number of samples of the polynomials.
Returns
-------
legendre : np.ndarray
A `degree`*`l... | 5f939c7d759678f6c686c84b074c4ac973df8255 | 3,653,244 |
def _get_controller_of(pod):
"""Get a pod's controller's reference.
This uses the pod's metadata, so there is no guarantee that
the controller object reference returned actually corresponds to a
controller object in the Kubernetes API.
Args:
- pod: kubernetes pod object
Returns: the refe... | 9c9e58e2fc49729c618af2c5bb9b4d033d90a831 | 3,653,246 |
from typing import Any
from typing import Dict
from typing import List
def proxify_device_objects(
obj: Any,
proxied_id_to_proxy: Dict[int, ProxyObject],
found_proxies: List[ProxyObject],
):
""" Wrap device objects in ProxyObject
Search through `obj` and wraps all CUDA device objects in ProxyObje... | 6d410245624d2992e37b5bce1832d7326caf4fe2 | 3,653,247 |
def monotonicity(x, rounding_precision = 3):
"""Calculates monotonicity metric of a value of[0-1] for a given array.\nFor an array of length n, monotonicity is calculated as follows:\nmonotonicity=abs[(num. positive gradients)/(n-1)-(num. negative gradients)/(n-1)]."""
n = x.shape[0]
grad = np.gradient(x)
... | 3ff9c37975502cb12b9e2839a5f5580412084f8c | 3,653,248 |
import attrs
def parse_value_namedobject(tt):
"""
<!ELEMENT VALUE.NAMEDOBJECT (CLASS | (INSTANCENAME, INSTANCE))>
"""
check_node(tt, 'VALUE.NAMEDOBJECT')
k = kids(tt)
if len(k) == 1:
object = parse_class(k[0])
elif len(k) == 2:
path = parse_instancename(kids(tt)[0])
... | ecb507ac9b0c3fdfbec19f807fba06236e21d7c5 | 3,653,251 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload Dyson cloud."""
# Nothing needs clean up
return True | 38a274e90c5fadc277e640cd6cc5442d5070dfd6 | 3,653,252 |
def quat_correct(quat):
""" Converts quaternion to minimize Euclidean distance from previous quaternion (wxyz order) """
for q in range(1, quat.shape[0]):
if np.linalg.norm(quat[q-1] - quat[q], axis=0) > np.linalg.norm(quat[q-1] + quat[q], axis=0):
quat[q] = -quat[q]
return quat | fc492998c5bdf2cf3b1aacbd42de72618bd74c01 | 3,653,253 |
def parse_record1(raw_record):
"""Parse raw record and return it as a set of unique symbols without \n"""
return set(raw_record) - {"\n"} | 4ffd3ebd0aaa17ddd42baf3b9d44614784c8ff33 | 3,653,255 |
import re
def isValid(text):
"""
Returns True if the input is related to the meaning of life.
Arguments:
text -- user-input, typically transcribed speech
"""
return bool(re.search(r'\byour awesome\b', text, re.IGNORECASE)) | c6e4275d53cd632b4f5e255aa62b69c80fd37794 | 3,653,257 |
def list_shared_with(uri, async_req=False):
"""Return array sharing policies"""
(namespace, array_name) = split_uri(uri)
api_instance = client.client.array_api
try:
return api_instance.get_array_sharing_policies(
namespace=namespace, array=array_name, async_req=async_req
)
... | 2a9eb78c14e5bdc31a3ae5bfc077219bd06c768f | 3,653,258 |
import html
def format_html_data_table(dataframe, list_of_malformed, addLineBreak=False):
"""
Returns the predicted values as the data table
"""
if list_of_malformed:
list_of_malformed = str(list_of_malformed)
else:
list_of_malformed = "None"
# format numeric data into string ... | cc345d2cb87ddf7905d0d9a62cc6cd61b92ddc51 | 3,653,259 |
import math
def colorDistance(col1, col2):
"""Returns a number between 0 and root(3) stating how similar
two colours are - distance in r,g,b, space. Only used to find
names for things."""
return math.sqrt(
(col1.red - col2.red)**2 +
(col1.green - col2.green)**2 +
(... | ef18dede8312f78b4ba4258e87d4630863f1243c | 3,653,260 |
from typing import Iterable
def combine_from_streaming(stream: Iterable[runtime_pb2.Tensor]) -> runtime_pb2.Tensor:
""" Restore a result of split_into_chunks into a single serialized tensor """
stream = iter(stream)
first_chunk = next(stream)
serialized_tensor = runtime_pb2.Tensor()
serialized_ten... | af88c9eeec99c1d3d7ca9e5753b72cf09a0c6c85 | 3,653,261 |
def portageq_envvar(options, out, err):
"""
return configuration defined variables. Use envvar2 instead, this will be removed.
"""
return env_var.function(options, out, err) | 8406985ac5f5d5d4bc93ded8c1392b1fe49e9ff7 | 3,653,262 |
def create_hash_factory(hashfun, complex_types=False, universe_size=None):
"""Create a function to make hash functions
:param hashfun: hash function to use
:type hashfun: callable
:param complex_types: whether hash function supports hashing of complex types,
either through nat... | 23dee13f06f754caa9f7de5a89b855adbe7313a4 | 3,653,263 |
def estimate_key(note_info, method="krumhansl", *args, **kwargs):
"""
Estimate key of a piece by comparing the pitch statistics of the
note array to key profiles [2]_, [3]_.
Parameters
----------
note_info : structured array, `Part` or `PerformedPart`
Note information as a `Part` or `Pe... | af2383ab2a94cf49a93a1f00d5bf575f19e0daa0 | 3,653,264 |
def print_parsable_dstip(data, srcip, dstip):
"""Returns a parsable data line for the destination data.
:param data: the data source
:type data: dictionary
:param scrip: the source ip
:type srcip: string
:param dstip: the destination ip
:type dstip: string
:return: a line of urls and their hitcount
"... | 9e27733a9821e184e53f21ca38af9cdb61192743 | 3,653,265 |
def OrListSelector(*selectors) -> pyrosetta.rosetta.core.select.residue_selector.OrResidueSelector:
"""
OrResidueSelector but 2+
(not a class, but returns a Or
:param selectors:
:return:
"""
sele = pyrosetta.rosetta.core.select.residue_selector.FalseResidueSelector()
for subsele in selec... | 8f4443a6ee1bbcd2e76133e6a08eea2737e01383 | 3,653,266 |
def plot_regress_exog(res, exog_idx, exog_name='', fig=None):
"""Plot regression results against one regressor.
This plots four graphs in a 2 by 2 figure: 'endog versus exog',
'residuals versus exog', 'fitted versus exog' and
'fitted plus residual versus exog'
Parameters
----------
res : r... | e4c7859c32892d2d8e94ff884652846f5f15f513 | 3,653,267 |
from typing import List
def get_circles_with_admin_access(account_id: int) -> List[Circle]:
"""
SELECT
management_style,
c_name
FROM (
SELECT
'SELF_ADMIN' AS management_style,
c.management_style AS c_management_style,
c.admin_circle A... | ef0a24d299bdad549f9b0220e4a34499097eb19d | 3,653,268 |
def combine(arr):
""" makes overlapping sequences 1 sequence """
def first(item):
return item[0]
def second(item):
return item[1]
if len(arr) == 0 or len(arr) == 1:
return arr
sarr = []
for c, val in enumerate(arr):
sarr.append((val[0], val[1], c))
sarr = s... | b46bb7f73fa6857ed4c980bdbdff77acde64b18d | 3,653,269 |
from operator import sub
def sub_fft(f_fft, g_fft):
"""Substraction of two polynomials (FFT representation)."""
return sub(f_fft, g_fft) | a559429a4d10889be3ffa776153854248ac7a496 | 3,653,270 |
def recursive_fill_fields(input, output):
"""
Fills fields from output with fields from input,
with support for nested structures.
Parameters
----------
input : ndarray
Input array.
output : ndarray
Output array.
Notes
-----
* `output` should be at least the sam... | 5508f1681eaa3f2c5ccb44b6329ad012f85c42e8 | 3,653,271 |
def handle_dat_edge(data_all):
"""
把dat_edge个每一条记录的info拆开,然后输出,方便后续的计算
为了简化计算,忽略时间信息,把所有的月份的联系记录汇总起来
"""
def cal_multi_3(string):
s = string.split(',')
month_times = len(s)
df = list(map(lambda x: list(map(eval, x.split(':')[1].split('_'))), s))
times_sum, weight_sum ... | 4ae92d337a70326bae87399809b920b1ad2cce1e | 3,653,273 |
def open_path(path, **kwargs):
"""
Parameters
----------
path: str
window: tuple
e.g. ('1990-01-01','2030-01-01')
kwargs: all other kwargs the particular file might take, see the module for details
Returns
-------
"""
info = _tools.path2info(path)
module = arm_prod... | c4e87d0649dfde2139a4ecac797775309eb6a72e | 3,653,276 |
import uuid
def generate_code() -> str:
"""Generates password reset code
:return: Password reset code
:rtype: str
"""
return str(uuid.uuid4()) | bcd8377afd5598e71f8bb8eb217c3f3fd53fc5c7 | 3,653,277 |
def decode_auth_token(auth_token):
"""
Decodes the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in again.'
except jwt... | 16fceb539f7aafb775b851e55f1b606a1c917cf9 | 3,653,279 |
import ast
def json(*arguments):
"""
Transform *arguments parameters into JSON.
"""
return ast.Json(*arguments) | 3e3333617b63dc1b5e8e4b71ea5c2f0ea08bfff8 | 3,653,281 |
def get_default_volume_size():
"""
:returns int: the default volume size (in bytes) supported by the
backend the acceptance tests are using.
"""
default_volume_size = environ.get("FLOCKER_ACCEPTANCE_DEFAULT_VOLUME_SIZE")
if default_volume_size is None:
raise SkipTest(
"Se... | ec24bfb9c07add5d1a800a1aaf9db3efb8727b3d | 3,653,282 |
import functools
def set_global_user(**decorator_kwargs):
"""
Wrap a Flask blueprint view function to set the global user
``flask.g.user`` to an instance of ``CurrentUser``, according to the
information from the JWT in the request headers. The validation will also
set the current token.
This ... | f73a89d94d188b1c258cedca3439ab9c1c94180c | 3,653,283 |
def sample_wfreq(sample):
"""Return the Weekly Washing Frequency as a number."""
# `sample[3:]` strips the `BB_` prefix
results = session.query(Samples_Metadata.WFREQ).\
filter(Samples_Metadata.SAMPLEID == sample[3:]).all()
wfreq = np.ravel(results)
# Return only the first integer value fo... | 6cb2ee0866efc9e841143c32e10cbb8feea813bc | 3,653,284 |
def mlp_hyperparameter_tuning(no_of_hidden_neurons, epoch, alpha, roh, n_iter_no_change, X_train, X_validation, y_train, y_validation):
"""
INPUT
no_of_hidden_neurons: 1D int arary contains different values of no of neurons
present in 1st hidden layer (hyperparameter)
epoch: ... | 3ec079bbeae32a5e7e6b80e833336ecb8662cbf1 | 3,653,286 |
def play(p1:list[int], p2:list[int]) -> list[int]:
"""Gets the final hand of the winning player"""
while p1 and p2:
a = p1.pop(0)
b = p2.pop(0)
if a > b:
p1 += [a, b]
else:
p2 += [b, a]
return p1 + p2 | 2a2b561474b3cd0841dcbe881e74b4767b4102b1 | 3,653,287 |
def oda_update_uhf(dFs, dDs, dE):
"""
ODA update:
lbd = 0.5 - dE / E_deriv
"""
if type(dFs) is not list:
raise Exception("arg1 and arg2 are list of alpha/beta matrices.")
E_deriv = np.sum(dFs[0] * dDs[0] + dFs[1] * dDs[1])
lbd = 0.5 * (1. - dE / E_deriv)
if lbd < 0 or lbd > 1... | fcead1536db11f80ae9eb2e912ac9857f93de669 | 3,653,288 |
def authorize(*roles):
"""Decorator that authorizes (or not) the current user
Raises an exception if the current user does not have at least
one of the listed roles.
"""
def wrapper(func):
"""wraps the protected function"""
def authorize_and_call(*args, **kwargs):
"""che... | f3fd8eb42924f8f956d0e3eae1499f64387fe96e | 3,653,289 |
import base64
import itertools
import six
def decrypt(secret, ciphertext):
"""Given the first 16 bytes of splunk.secret, decrypt a Splunk password"""
plaintext = None
if ciphertext.startswith("$1$"):
ciphertext = base64.b64decode(ciphertext[3:])
key = secret[:16]
algorithm = algor... | d4b0caca50d649633bb973d26bb174875d23b0e0 | 3,653,291 |
from unet_core.vessel_analysis import VesselTree
def load_skeleton(path):
"""
Load the skeleton from a pickle
"""
# Delayed import so script can be run with both Python 2 and 3
v = VesselTree()
v.load_skeleton(path)
return v.skeleton | d9632de40310dd738eb7d07966d6eb04360c3b81 | 3,653,292 |
def industries_hierarchy() -> pd.DataFrame:
"""Read the Dow Jones Industry hierarchy CSV file.
Reads the Dow Jones Industry hierarchy CSV file and returns
its content as a Pandas DataFrame. The root node has
the fcode `indroot` and an empty parent.
Returns
-------
DataFrame : A Pandas Data... | 9d1de27e3e01572637e7afc729e0cd07d96b14e2 | 3,653,293 |
import typing
def setup_callback(callback: typing.Awaitable):
"""
This function is used to setup the callback.
"""
callback.is_guild = False
""" The guild of the callback. """
callback.has_permissions = []
""" The permissions of the callback. """
callback.has_roles = []
""" ... | 4cb7849d9746166c95c96d18e27227b52160ff7a | 3,653,295 |
def prepare_for_training(ds, ds_name, conf, cache):
"""
Cache -> shuffle -> repeat -> augment -> batch -> prefetch
"""
AUTOTUNE = tf.data.experimental.AUTOTUNE
# Resample dataset. NB: dataset is cached in resamler
if conf["resample"] and 'train' in ds_name:
ds = oversample(ds, ds_na... | b072a7ced028b1627288a3f2bbf0233c85afbab8 | 3,653,296 |
def residual3d(inp, is_training, relu_after=True, add_bn=True,
name=None, reuse=None):
""" 3d equivalent to 2d residual layer
Args:
inp (tensor[batch_size, d, h, w, channels]):
is_training (tensor[bool]):
relu_after (bool):
add_bn (bool): add b... | 28fb8651c9a9755e8d0636c702b2bd77e7186fd1 | 3,653,297 |
def marks(family, glyph):
"""
:param family:
:param glyph:
:return: True when glyph has at least one anchor
"""
has_mark_anchor = False
for anchor in glyph.anchors:
if anchor.name:
if anchor.name.startswith("_"):
has_mark_anchor = True
brea... | 101555dcadfd78b0550606f843e32dce99de62b8 | 3,653,298 |
import re
def generate_bom(pcb_modules, config, extra_data):
# type: (list, Config, dict) -> dict
"""
Generate BOM from pcb layout.
:param pcb_modules: list of modules on the pcb
:param config: Config object
:param extra_data: Extra fields data
:return: dict of BOM tables (qty, value, foot... | 7645929bfcfd3d7447a32ae2ea3074d6da86c368 | 3,653,299 |
def validateFilename(value):
"""
Validate filename.
"""
if 0 == len(value):
raise ValueError("Name of SimpleGridDB file must be specified.")
return value | b8b3c23772437c1ddca597c44c66b239955a26fb | 3,653,302 |
def readPNM(fd):
"""Reads the PNM file from the filehandle"""
t = noncomment(fd)
s = noncomment(fd)
m = noncomment(fd) if not (t.startswith('P1') or t.startswith('P4')) else '1'
data = fd.read()
ls = len(s.split())
if ls != 2 :
name = "<pipe>" if fd.name=="<fdopen>" else "Filename = {0}".format(fd.nam... | c03633069b2b8f3302a8f28e03f4476ac7478055 | 3,653,303 |
def gdxfile(rawgdx):
"""A gdx.File fixture."""
return gdx.File(rawgdx) | 6138077fa959cecd4a7402fe3c7b6b7dee5d99f9 | 3,653,304 |
import typing
from typing import Union
from typing import Dict
from typing import Any
def AppBar(
absolute: bool = None,
app: bool = None,
attributes: dict = {},
bottom: bool = None,
children: list = [],
class_: str = None,
clipped_left: bool = None,
clipped_right: bool = None,
col... | 51de728b0d2935161bd040248d94b3d15aba5d16 | 3,653,305 |
def conjoin(*funcs):
"""
Creates a function that composes multiple predicate functions into a single predicate that tests
whether **all** elements of an object pass each predicate.
Args:
*funcs (callable): Function(s) to conjoin.
Returns:
Conjoin: Function(s) wrapped in a :class:`C... | 835c2962bcc3a2c3dcf0bf19649221aebb73b63b | 3,653,307 |
import hashlib
def calculate_file_sha256(file_path):
"""calculate file sha256 hash code."""
with open(file_path, 'rb') as fp:
sha256_cal = hashlib.sha256()
sha256_cal.update(fp.read())
return sha256_cal.hexdigest() | bfa7a43516e51a80ccd63ea3ace6be6e5e9dd2c0 | 3,653,308 |
from collections import OrderedDict
import warnings
def select_columns_by_feature_type(df, unique_value_to_total_value_ratio_threshold=.05, text_unique_threshold=.9,
exclude_strings = True, return_dict = False, return_type='categoric'):
""" Determine if a column fits into one of the followin... | 6335152405bc175805e8484ff23f58d4f6ce6f6a | 3,653,309 |
def _Counter_random(self, filter=None):
"""Return a single random elements from the Counter collection, weighted by count."""
return _Counter_randoms(self, 1, filter=filter)[0] | 95dc2ab7857b27a831b273af7dba143b8b791b27 | 3,653,310 |
def EnsureAndroidSdkPackagesInstalled(abi):
"""Return true if at least one package was not already installed."""
abiPackageList = SdkPackagesForAbi(abi)
installedSomething = False
packages = AndroidListSdk()
for package in abiPackageList:
installedSomething |= EnsureSdkPackageInstalled(packa... | b43ee6094dc4cd8f71ec1319dbd5bd32d272b55a | 3,653,311 |
def dataframe_like(value, name, optional=False, strict=False):
"""
Convert to dataframe or raise if not dataframe_like
Parameters
----------
value : object
Value to verify
name : str
Variable name for exceptions
optional : bool
Flag indicating whether None is allowed
... | 016ffcda7050ac639d04522a666526753eb52a84 | 3,653,312 |
def pcaFunc(z, n_components=100):
"""
PCA
"""
pca = PCA(n_components=100)
pca_result = pca.fit_transform(z)
re = pd.DataFrame()
re['pca-one'] = pca_result[:, 0]
re['pca-two'] = pca_result[:, 1]
re['pca-three'] = pca_result[:, 2]
# Not print Now
# print('Explained variation pe... | 1dda1542a045eab69aab5488be2c754bde555311 | 3,653,313 |
def choose_optimizer(discriminator, generator, netD, netG, lr_d=2e-4, lr_g=2e-3):
"""
Set optimizers for discriminator and generator
:param discriminator: str, name
:param generator: str, name
:param netD:
:param netG:
:param lr_d:
:param lr_g:
:return: optimizerD, optimizerG
"""... | b3784d98c1743c10e3d1e9bca76288bd45c9c99e | 3,653,314 |
def prod(*args: int) -> int:
"""
This function is wrapped and documented in `_polymorphic.prod()`.
"""
prod_ = 1
for arg in args:
prod_ *= arg
return prod_ | eec30bf6339280173e0e2fa517558e6a452b9c37 | 3,653,315 |
def field_value(field):
"""
Returns the value for this BoundField, as rendered in widgets.
"""
if field.form.is_bound:
if isinstance(field.field, FileField) and field.data is None:
val = field.form.initial.get(field.name, field.field.initial)
else:
val = field.dat... | 5dc3792e0d6cd2cb6173c2479a024881f80a6d2b | 3,653,316 |
def distances(p):
"""Compute lengths of shortest paths between all nodes in Pharmacophore.
Args:
p (Pharmacophore): model to analyse
Returns:
dist (numpy array): array with distances between all nodes
"""
if not isinstance(p, Pharmacophore):
raise TypeError("Expected Pharmac... | 40e77672ad9447ed4c7b69b14aadbc2f125cb499 | 3,653,317 |
def initial_data(logged_on_user, users_fixture, streams_fixture):
"""
Response from /register API request.
"""
return {
'full_name': logged_on_user['full_name'],
'email': logged_on_user['email'],
'user_id': logged_on_user['user_id'],
'realm_name': 'Test Organization Name'... | b85eafbf359a6c34decc866f4d1fbb494ac907f8 | 3,653,318 |
def affine_relu_backward(dout, cache):
"""
Backward pass for the affine-relu convenience layer
"""
fc_cache, relu_cache = cache
da = relu_backward(dout, relu_cache)
dx, dw, db = affine_backward(da, fc_cache)
return dx, dw, db | 201f37d4d6ac9e170a52766f41d892527681a3d1 | 3,653,319 |
from typing import List
def create_initial_population() -> List[Image]:
"""
Create population at step 0
"""
return [random_image() for _ in range(POP_SIZE)] | 895632869962014695382e34961f6e6636619fbe | 3,653,320 |
from typing import Any
def adapt(value: Any, pg_type: str) -> Any:
"""
Coerces a value with a PG type into its Python equivalent.
:param value: Value
:param pg_type: Postgres datatype
:return: Coerced value.
"""
if value is None:
return None
if pg_type in _TYPE_MAP:
re... | f040cd6fbf5aa8a396efa36879b83e13b5d89da7 | 3,653,321 |
import uuid
from datetime import datetime
def createPREMISEventXML(eventType, agentIdentifier, eventDetail, eventOutcome,
outcomeDetail=None, eventIdentifier=None,
linkObjectList=[], eventDate=None):
"""
Actually create our PREMIS Event XML
"""
eventX... | 25836d6cd4b40ad672ca3438ba3583cd147a52bb | 3,653,322 |
def get_primary_key(conn, table, columns):
""" attempts to reverse lookup the primary key by querying the table using the first column
and iteratively adding the columns that comes after it until the query returns a
unique row in the table.
:param
conn: an SQLite connection object
... | 3b74f85214e89af322fd1da1e6c8de1eba4f4ca7 | 3,653,323 |
def redirect_to_docs():
"""Redirect to API docs when at site root"""
return RedirectResponse('/redoc') | f284167e238845651eedaf3bcc1b85e64979df6a | 3,653,324 |
def init_neighbours(key):
"""
Sets then neighbouring nodes and initializes the edge count to the neighbours to 1
:param key: str - key of node to which we are searching the neighbours
:return: dictionary of neighbours with corresponding edge count
"""
neighbours = {}
neighbouring_nodes = gra... | 6fa49ffa75051eeca9bd1714ec3e4817ef429bad | 3,653,325 |
def computeNumericalGradient(J, theta):
""" Compute numgrad = computeNumericalGradient(J, theta)
theta: a matrix of parameters
J: a function that outputs a real-number and the gradient.
Calling y = J(theta)[0] will return the function value at theta.
"""
# Initialize numgrad with zeros
numgrad = np.zer... | 2d4e4ed190bbb0c5507ecb896c13d33fcd7aa1b5 | 3,653,326 |
def get_error_msg(handle):
"""
Get the latest and greatest DTrace error.
"""
txt = LIBRARY.dtrace_errmsg(handle, LIBRARY.dtrace_errno(handle))
return c_char_p(txt).value | 73d945367e3003beb29505852004f0c71b205873 | 3,653,327 |
def sigma_hat(frequency, sigma, epsilon=epsilon_0, quasistatic=False):
"""
conductivity with displacement current contribution
.. math::
\hat{\sigma} = \sigma + i \omega \\varepsilon
**Required**
:param (float, numpy.array) frequency: frequency (Hz)
:param float sigma: electrical con... | 17aee0f33ba8786934d750e37e1afd0617e8aa1d | 3,653,328 |
def encode_list(key, list_):
# type: (str, Iterable) -> Dict[str, str]
"""
Converts a list into a space-separated string and puts it in a dictionary
:param key: Dictionary key to store the list
:param list_: A list of objects
:return: A dictionary key->string or an empty dictionary
"""
... | 6cde65017d20e777e27ac86d7f8eb1d025d04947 | 3,653,329 |
async def delete_relationship(request: web.Request):
"""
Remove relationships of resource.
Uses the :meth:`~aiohttp_json_api.schema.BaseSchema.delete_relationship`
method of the schema to update the relationship.
:seealso: http://jsonapi.org/format/#crud-updating-relationships
"""
relation... | 6397ebab365b9339dca7692b4188945401d54779 | 3,653,330 |
def cost_efficiency(radius, height, cost):
"""Compute and return the cost efficiency of a steel can size.
The cost efficiency is the volume of the can divided by its cost.
Parameters
radius: the radius of the steel can
height: the height of the steel can
cost: the cost of the steel ... | e21f767676d5a1e9e5d97ba8bd8f943ecaad5060 | 3,653,331 |
def cb_xmlrpc_register(args):
"""
Register as a pyblosxom XML-RPC plugin
"""
args['methods'].update({'pingback.ping': pingback})
return args | e9f5cdde32d1a7b3145918d4fadfc80f4de7301f | 3,653,333 |
def try_except(method):
"""
A decorator method to catch Exceptions
:param:
- `func`: A function to call
"""
def wrapped(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except self.error as error:
log_error(error, self.logger, self.erro... | 069c5abd6a2f2dcab8424c829f1dae27e8a294b8 | 3,653,334 |
def sosfilter_double_c(signal, sos, states=None):
"""Second order section filter function using cffi, double precision.
signal_out, states = sosfilter_c(signal_in, sos, states=None)
Parameters
----------
signal : ndarray
Signal array of shape (N x 0).
sos : ndarray
Second order... | 387d921f86ec6bc9c814d0ca757b36f803d122af | 3,653,335 |
import logging
def node_exporter_check():
"""
Checks existence & health of node exporter pods
"""
kube = kube_api()
namespaces = kube.list_namespace()
ns_names = []
for nspace in namespaces.items:
ns_names.append(nspace.metadata.name)
result = {'category': 'observability',
... | 25a1c23107654a6b561d54ffce08aa6025ae1d2e | 3,653,337 |
def functional_domain_min(braf_gene_descr_min,
location_descriptor_braf_domain):
"""Create functional domain test fixture."""
params = {
"status": "preserved",
"name": "Serine-threonine/tyrosine-protein kinase, catalytic domain",
"id": "interpro:IPR001245",
... | 905e6b3dc4c1507c57d71879b582794cd66cdd8e | 3,653,339 |
def rsa_encrypt(rsa_key, data):
"""
rsa_key: 密钥
登录密码加密
"""
data = bytes(data, encoding="utf8")
encrypt = PKCS1_v1_5.new(RSA.importKey(rsa_key))
Sencrypt = b64encode(encrypt.encrypt(data))
return Sencrypt.decode("utf-8") | 07384216eff4d0f109e9a0b3bf45c0c1ab108b26 | 3,653,340 |
import numpy
def shuffle_and_split_data(data_frame):
"""
Shuffle and split the data into 2 sets: training and validation.
Args:
data_frame (pandas.DataFrame): the data to shuffle and split
Returns:
2 numpy.ndarray objects -> (train_indices, validation_indices)
Eac... | dfcad7edb9ec17b81057e00816fe3d5bdadc39be | 3,653,341 |
def parse_array_from_string(list_str, dtype=int):
""" Create a 1D array from text in string.
Args:
list_str: input string holding the array elements.
Array elements should be contained in brackets [] and seperated
by comma.
dtype: data type of the array elements. Default ... | b05204a1c6d516a4f4eed298819bda97c5637f37 | 3,653,342 |
def Maj(x, y, z):
""" Majority function: False when majority are False
Maj(x, y, z) = (x ∧ y) ⊕ (x ∧ z) ⊕ (y ∧ z)
"""
return (x & y) ^ (x & z) ^ (y & z) | 7d4013dfc109b4fc39fd3b0bd3f2f5947d207ff0 | 3,653,343 |
import pickle
def get_package_data():
"""Load services and conn_states data into memory"""
with open(DATA_PKL_FILE, "rb") as f:
services, conn_states = pickle.load(f)
return services, conn_states | 8bff214f2256f98e43599f4e5ce73d53232e9a7a | 3,653,344 |
def reload_county():
""" Return bird species, totals, location to map """
# receive data from drop-down menu ajax request
bird = request.args.get("bird")
county = request.args.get("county")
# get the zoom level of the new chosen county
zoomLevel = get_zoom(county)
# reset session data fr... | 6c3ad39e12483579d0c9031b5c9a56babcac3823 | 3,653,347 |
import re
def get_conv2d_out_channels(kernel_shape, kernel_layout):
"""Get conv2d output channels"""
kernel_shape = get_const_tuple(kernel_shape)
if len(kernel_shape) == 4:
idx = kernel_layout.find("O")
assert idx >= 0, "Invalid conv2d kernel layout {}".format(kernel_layout)
return... | 4b26979b873f36b79f5e29d0c814417a4c21eb32 | 3,653,348 |
def bindparam(key, value=None, type_=None, unique=False, required=False, callable_=None):
"""Create a bind parameter clause with the given key.
:param key:
the key for this bind param. Will be used in the generated
SQL statement for dialects that use named parameters. This
v... | 5dc1b311d0dfae04b31d1e869015dbaef9fc2f42 | 3,653,349 |
def create_dictionary(timestamp, original_sentence, sequence_switched, err_message, suggestion_list):
"""Create Dictionary Function
Generates and exports a dictionary object with relevant data for website interaction to take place.
"""
if len(suggestion_list) != 0:
err_message_str = "Possible e... | 057d407089a7bb4e445bd0db2632dfcb9f291ed6 | 3,653,350 |
def get_L_BB_b2_d_t(L_BB_b2_d, L_dashdash_b2_d_t):
"""
Args:
L_BB_b2_d: param L_dashdash_b2_d_t:
L_dashdash_b2_d_t:
Returns:
"""
L_BB_b2_d_t = np.zeros(24 * 365)
L_BB_b2_d = np.repeat(L_BB_b2_d, 24)
L_dashdash_b2_d = np.repeat(get_L_dashdash_b2_d(L_dashdash_b2_d_t), 24)
... | 51b3551e68e9bbccbe756156d0d623b32a47c23f | 3,653,352 |
def _get_tab_counts(business_id_filter, conversation_tab, ru_ref_filter, survey_id):
"""gets the thread count for either the current conversation tab, or, if the ru_ref_filter is active it returns
the current conversation tab and all other tabs. i.e the value for the 'current' tab is always populated.
Calls... | 9e79d7d692661496a49db93754716e10644bccf2 | 3,653,353 |
def IsInverseTime(*args):
"""Time delay is inversely adjsuted, proportinal to the amount of voltage outside the regulating band."""
# Getter
if len(args) == 0:
return lib.RegControls_Get_IsInverseTime() != 0
# Setter
Value, = args
lib.RegControls_Set_IsInverseTime(Value) | e0c1b3fef4d3c8b6a822a2946703503628a3f775 | 3,653,354 |
def create_userinfo(fname, lname, keypass):
"""
function to create new user
"""
new_userinfo = Userinfo(fname, lname, keypass)
return new_userinfo | ec7ae9a8cf79482498218571d04bee11ab767d98 | 3,653,355 |
from typing import Dict
def get_networks() -> Dict[str, SpikingNetwork]:
"""Get a set of spiking networks to train."""
somatic_spike_fn = get_spike_fn(threshold=15)
dendritic_nl_fn = get_default_dendritic_fn(
threshold=2, sensitivity=10, gain=1
)
neuron_params = RecurrentNeuronParameters(
... | d20f93eb849134c5104c22e9724bcadf09a4a141 | 3,653,356 |
import collections
def metric_group_max(df, metric_names=None):
"""Find the step which achieves the highest mean value for a group of metrics."""
# Use METRIC_NAMES defined at the top as default
metric_names = metric_names or METRIC_NAMES
group_to_metrics = collections.defaultdict(set)
for metric in metric_... | 6f58e9f3a18f6185c1956a994b47f9f4fb9936ea | 3,653,358 |
def get_settings_value(definitions: Definitions, setting_name: str):
"""Get a Mathics Settings` value with name "setting_name" from definitions. If setting_name is not defined return None"""
settings_value = definitions.get_ownvalue(setting_name)
if settings_value is None:
return None
return set... | 3d05b234f85a13746b47ca97f3db578d3c7d6856 | 3,653,359 |
def show_clusterhost(clusterhost_id):
"""Get clusterhost."""
data = _get_request_args()
return utils.make_json_response(
200,
_reformat_host(cluster_api.get_clusterhost(
clusterhost_id, user=current_user, **data
))
) | a49a0027b8f7ab1ce20e762f960b6d8285d8850c | 3,653,360 |
import math
def resize3d_cubic(data_in, scale, coordinate_transformation_mode):
"""Tricubic 3d scaling using python"""
dtype = data_in.dtype
d, h, w = data_in.shape
new_d, new_h, new_w = [int(round(i * s)) for i, s in zip(data_in.shape, scale)]
data_out = np.ones((new_d, new_h, new_w))
def _c... | 42f1a14e5c1133c7ce53b5770d62001e1dacbc6d | 3,653,361 |
def seasurface_skintemp_correct(*args):
"""
Description:
Wrapper function which by OOI default applies both of the METBK seasurface
skin temperature correction algorithms (warmlayer, coolskin in coare35vn).
This behavior is set by the global switches JWARMFL=1 and JCOOLFL=1. The
... | 80ccf63dcf961a4fa488a89023c2516e69862f86 | 3,653,362 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.