content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
async def async_setup(hass, config):
"""
Wiser smart uses config flow for configuration.
But, a "wiserSmart:" entry in configuration.yaml will trigger an import flow
if a config entry doesn't already exist. If it exists, the import
flow will attempt to import it and create a config entry, to assist ... | a103274832569b09b7472190cf179a1a5f24486f | 3,598,130 |
def check_underexposed(image, gray):
"""Returns the (cropped) image with GAMMA applied if underexposition
is detected.
"""
uexp = cv2.calcHist([gray], [0], None, [256], [0, 256])
if sum(uexp[-26:]) < GAMMA_THRES * sum(uexp):
image = gamma(image, GAMMA)
return image | 4be6ef656b53b67db31b4335bfbcf3c9a227561e | 3,598,131 |
def average(in_list):
""" Helper function to calculate average of items in the given list """
if len(in_list) == 0:
return None
return two_digit_float(sum(in_list) / len(in_list)) | 97f0432ce2a0b956befdf361c97391ec5be78fb9 | 3,598,133 |
def get_slice(ds, i, slicedim, datatype=''):
"""Retrieve a single slice from a 3D array."""
if slicedim == 0:
slc = ds[i, :, :]
elif slicedim == 1:
slc = ds[:, i, :]
elif slicedim == 2:
slc = ds[:, :, i]
if datatype:
slc = slc.astype(datatype)
return slc | 31b094694e3cf22b9037e3546136ae40d6238fc9 | 3,598,134 |
def create_img_lines(lines, shape):
"""
:param lines: np.array containing the lines to plot. Should be the same format than the output of a HoughLinesP function.
:param shape: (height, width) of the output image.
:return: np.array containing the image with the lines plotted.
"""
line_img = np.z... | 5670a2a7ee13bc0f118cdaabccb6fc5f1acc1369 | 3,598,135 |
import math
def compute_tile_numbers(lat, lon, zoom):
"""
The formula implemented based on
https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#lon.2Flat_to_tile_numbers.
Returns xtile, ytile (int, int).
"""
lat_rad = math.radians(lat)
n = 2.0 ** zoom
xtile = int((lon + 180.0) / 36... | 0b936c56c92c0d0940a6d0b98844598edb3f66a1 | 3,598,137 |
def deactivated_equalities_set(block):
"""
Method to return a ComponentSet of all deactivated equality Constraint
components in a model.
Args:
block : model to be studied
Returns:
A ComponentSet including all deactivated equality Constraint components
in block
"""
r... | 8d25df7701eb4d075c1b0edcf47abb5809e67a6f | 3,598,139 |
import unicodedata
import bisect
import functools
import operator
def decode(words: str) -> bytes:
"""Extract the raw entropy bytes from a BIP-0039 mnemonic."""
words = unicodedata.normalize("NFKD", words).split(" ")
raw: list[int] = []
for word in words:
i = bisect.bisect_left(wordlist, word)... | eb2501209e42e7449155719a8096625e6ac64562 | 3,598,140 |
def about():
"""Expose /about GET endpoint."""
response = make_response(_DESCRIPTION)
response.mimetype = 'text/plain'
return response | d0e4456d6de0aa3506eab8fec260eb64d6a8e2d6 | 3,598,142 |
def search_up_for_reverse(G, visited_edges, node, out_idx, transpose, edge_list):
"""Search up the graph for transpose sequences"""
if len(G.out_edges(node.name)) > 1 or isinstance(node, SensitiveToOrder):
return []
if isinstance(node, Transposable) and node.transpose_out:
if reverses_trans... | a10e5de2df36efd308f29ee4a37db4a8cd91ab17 | 3,598,143 |
def delete_user(user_repository_spy): # pylint: disable=W0621
"""Fixture para montar o objeto DeleteUser"""
return DeleteUser(user_repository_spy) | ce569d9dfbf4a633ddace5b1b1c685b62ee529c0 | 3,598,144 |
def cancel():
""" Logged in user can cancel pending requests not approved yet by admins/editors"""
context = {'user': toolkit.g.get('user') or toolkit.g.get('author')}
organization_id = toolkit.request.args.get('organization_id', None)
try:
toolkit.get_action('member_request_cancel')(
... | cb98a9d4bfb3195e2589cb75076aab7054b2b9dc | 3,598,145 |
import http
from typing import Optional
def sql_connection_edit(
request: http.HttpRequest,
pk: Optional[int] = None,
) -> http.JsonResponse:
"""Respond to the request to create/edit an SQL connection object.
:param request: HTML request
:param pk: Primary key
:return:
"""
conn = None... | 943baed9d2322c6711492187457691770caa989c | 3,598,146 |
def getMatrixFromVector(forward, up=None, forward_axis='z', location=None):
"""
Creates a rotation from given forward direction and up direction. Which is then used to calculate a matrix.
Args:
forward (Any): Vector that faces forward.
up (Any): Vector that faces up. If none given will use... | 3bb3db92cc6dbca5c482028166d210687fa3aeec | 3,598,147 |
def CC(G: CausalDiagram, X: str):
""" an X containing c-component of G """
return G.c_component(X) | 66b90f70f39a8e8f3a7e1094291dc6aab9ad4cef | 3,598,148 |
def set_game_score(token, user_id, score, force=None, disable_edit_message=None, chat_id=None, message_id=None,
inline_message_id=None):
"""
Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise ... | ccaea76ceb388936f4be6537760bd121225d78cc | 3,598,150 |
def _hierarch_keywords(names):
"""
Prepend the 'HIERARCH ' string to all keywords > 8 characters
Avoids FITS VerifyWarning.
Parameters
----------
names : list
keywords
Returns
-------
new_names : list
keywords with HIERARCH prepended as apprpriate
"""
new_na... | 73fc3f1594bf12a7c4a2c79d320aa490eb3d39e9 | 3,598,151 |
def vulnerable(version):
"""checks vulnerability"""
return version == LooseVersion("10.13.1") | bc44d5bc58fc67d63e250b8406dd7e3c06a96c74 | 3,598,152 |
def replace_unknown(tokens, cut_off):
""" Replace tokens which appear (<= cutoff) times in the corpus with <UNK>.
:param tokens: (list of str) the tokens comprising the corpus.
:param cut_off: (int) the bound of cutting the token.
:return: The same list of tokens with each singleton replace... | 9d26387f17614a07761c65e1d9b59c4db3c5ec14 | 3,598,153 |
def _GetOperationStatus(client, request, tracker, messages):
"""Returns a Boolean indicating whether the request has completed."""
operation = client.projects_locations_operations.Get(request)
if operation.error:
raise exceptions.StatusToFunctionsError(
operation.error, error_message=OperationErrorToS... | 098153aec6380735c1555364919431f5a8bef188 | 3,598,154 |
def get_noise(p_meas, p_gate):
"""Define a noise model."""
error_meas = pauli_error([('X', p_meas), ('I', 1 - p_meas)])
error_gate1 = depolarizing_error(p_gate, 1)
error_gate2 = error_gate1.tensor(error_gate1)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(
error_mea... | d984f7e435f2943ad9383b5de34886d20e9fde5c | 3,598,155 |
def is_valid_zip(zip_code):
"""Returns whether or not the zip code is a valid WA zip code"""
return zip_code in ALL_ZIPS | cdd5986ea15493546461dfd2a4eb7f85cfdadce7 | 3,598,156 |
def get_point_uuid(msg):
""" Returns a point uuid that is either the passed message """
point_uuid = str(msg)
return point_uuid | 60939e6f81e3cb076b7b67306f83e1d48dbb50b6 | 3,598,157 |
def hydrograph_visualization(scenario_id = ''):
"""
This function is for hydrograph visualization
"""
return render_template('hydrograph_vis.html', scenario_id = scenario_id) | 402746f40a7623cdaabda06e032357ad1f505e00 | 3,598,158 |
import math
def gps_to_dms(gps_data):
"""
坐标转为度、分、秒(double)
116.397451
:param gps_data:
:return:
"""
# 度:向下取整
gps_degree = math.floor(gps_data)
gps_data_temp1 = (gps_data - gps_degree) * 60
# 分
gps_minute = math.floor(gps_data_temp1)
gps_data_temp2 = gps_data_temp1 -... | 568cbf65e5bf479c52c2591511af0c2d85bded9a | 3,598,159 |
def docopt_subcl():
"""
Compute the list of sub-commands from the output of docopt_exp
"""
exp = docopt_exp()
rv = [z for z in exp.keys() if '-' not in z and '<' not in z]
return rv | 110b6851afc24705516bcd13bb3f65cdff3bd97f | 3,598,160 |
import uuid
def get_client_id(prefix):
"""
Generates a client id, based on the given prefix
Args:
prefix (str): A non-empty str
Returns:
str: The client id which consists of the prefix combined with the hostname and thread id, separated by '_'
"""
assert validators.PanoptesVa... | 87a0a25cc606de7754b1bbc49e5e6e7ce036e36a | 3,598,161 |
def fix_z0_shape(z0: NumberLike, nfreqs: int, nports: int) -> npy.ndarray:
"""
Make a port impedance of correct shape for a given network's matrix
This attempts to broadcast z0 to satisfy
npy.shape(z0) == (nfreqs,nports)
Parameters
----------
z0 : number, array-like
z0 can be:
... | 54ce33c4919b9a9d47ddd309118dbd06a9ba7b70 | 3,598,162 |
def testfunc():
"""
this is version 0.6
"""
return 1 | 78b41057859d0dcecdf707dcab414d08a1cff27b | 3,598,163 |
def get_size_of_corpus(filepaths):
""" Given a list of filepaths, it will return the total number of lines
Parameters
----------
filepaths : [ str ]
A list of filepaths
Returns
-------
num_lines : int
The total number of lines in filepaths
... | 46d166f7ae21ed345c45c38b782c7405790a8de2 | 3,598,164 |
def numpy_array_2d_via_fits_from(
file_path: str, hdu: int, do_not_scale_image_data: bool = False
):
"""
Read a 2D NumPy array from a .fits file.
After loading the NumPy array, the array is flipped upside-down using np.flipud. This is so that the structures
appear the same orientation as .fits file... | 176fa6d26f776671e1d7b78fcdd3f37713f57ff4 | 3,598,166 |
def open_prod(inpath, s3_instrument, resolution):
"""Open SNAP product.
Use snappy to open a Sentinel-3 product. If the instrument is SLSTR, then
the 2 resolution products are returned (500m and 1km).
Args:
inpath (str): Path to a S3 OLCI image xfdumanisfest.xml file
s3_instrument (s... | 96a8059af6657e47617f2a5edf9990d0772aae88 | 3,598,167 |
async def kapibara_exception_handler(request: Request, exception: StarletteHTTPException):
"""Custom exceptions handler
This exception handler standardizes the responses so that even _"magic"_
performed by FastAPI under the hood obeys and complies with the desired
documented format of error responses.
... | 426e096a07784a65cb412730887c78984c35a72e | 3,598,168 |
def getSpanVectors(normal, c, d):
""" getSpanVectors(normal, prevA, prevB) -> (a,b)
Given a normal, return two orthogonal vectors which are both orthogonal
to the normal. The vectors are calculated so they match as much as possible
the previous vectors.
"""
# Calculate a from prev... | 5a0a99b8920ceb55f61edcf440a4af12f4fb2343 | 3,598,169 |
def ParseFlags(argv):
"""Define and parse gflags parameters."""
gflags.DEFINE_string('database', 'hardware.db',
'Full path to shared hardware database file.')
gflags.DEFINE_string('config', None,
'Full path to test fixture hardware configuration file.')
gflags.MarkF... | 8e3097040300b8d59521b9ebce07a1f03307ade6 | 3,598,170 |
import time
import warnings
def tv_chambolle(image_set, weight, max_stacking=None, eps=0.0002, verbose=True):
"""Performs chambolle filtering using the skimage library.
:param image_set:
:param weight:
:param eps:
:param max_stacking:
:return:
"""
if verbose:
print('Applying To... | 33d3636d4d328e9969e56c99e9a0261d38924254 | 3,598,171 |
import numpy
def create_dataset(dataset, look_back):
"""
构造数据的特征列和类标
"""
data_x, data_y = [], []
for i in range(len(dataset) - look_back):
a = dataset[i:(i + look_back), 0]
data_x.append(a)
data_y.append(dataset[i + look_back, 0])
return numpy.array(data_x), numpy.array... | a0b6a17d72b435f2dae79f0c4e2aad98e9f19178 | 3,598,172 |
import urllib
import time
def safe_request(req):
"""
Wrapper to handle HTTPErrors when scraping data.
Will send equests again infinitely instead of raising an error.
"""
try:
html = urllib.request.urlopen(req)
# Try sending again (infinitely) if HTTPError is raised
except HTTPErro... | 3c7af9ac05997720162244fd350335294687517b | 3,598,173 |
def merge_random_states(*rngs):
"""
Merge several random states, by generating an avarage of random integers.
"""
seed = 0.0
rngs = list(filter(None, rngs))
for rng in rngs:
# divide it first to avoid numerical overflow
seed += generate_random_seed(rng) / len(rngs)
return np.... | 8b306c22d3977c174f599526d59171eddc93f24b | 3,598,174 |
def mapfunc_detector_recursive(lines):
"""Recursively detect nested Case 2 function in a list of lines.
Args:
lines ([list]): A list with Javascript code as strings.
Returns:
[list]: A list with Javascript code (as string) in groups.
Examples:
>>> from ee_extra import mapfunc... | 435aadcbd3cb058926a4ab947f5dfdf372c3b21f | 3,598,176 |
from struct import unpack
from typing import Union
from pathlib import Path
def _tiff2xml(path: Union[Path, str]) -> bytes:
"""Extract OME XML from OME-TIFF path.
This will use the first ImageDescription tag found in the TIFF header.
Parameters
----------
path : Union[Path, str]
Path to ... | 6bd35d09c5edfd6362379ae3375e888e99f4609a | 3,598,177 |
import shlex
def run_cli(module, cli):
"""
Method to execute the cli command on the target node(s) and returns the
output.
:param module: The Ansible module to fetch input parameters.
:param cli: The complete cli string to be executed on the target node(s).
:return: Output/Error or Success msg... | fca5119a0f337952760922ee89c06a1c8578273f | 3,598,178 |
def encrypt_rsa(data : bytes, public_key : rsa.key.PublicKey) -> bytes:
"""
Encrypt data with the given key
===============================
Parameters
----------
data : str
Data to encrypt.
public_key : rsa.key.PublicKey
Public key to encrypt with.
Returns
-------
... | b627b23cee7adf83315bf4b12a34de130272afa8 | 3,598,180 |
def coin_snapshot(from_curr, to_curr):
"""
Get data for a currency pair. It returns general block explorer information,
aggregated data and individual data for each exchange available.
:param from_curr: From symbol
:param to_curr: To symbol
:return: dict
"""
return __get_url(__cs_url ... | b191dea242004ae8f861da9552781d352a6876b5 | 3,598,181 |
def im_detect_rpn(net, im):
"""Detect object classes in an image given object proposals.
Arguments:
net (caffe.Net): Fast R-CNN network to use
im (ndarray): color image to test (in BGR order)
boxes (ndarray): R x 4 array of object proposals or None (for RPN)
Returns:
scores... | dc5d405851563e57eb6c91a072467a1f6f0874f3 | 3,598,186 |
def schedule_conv2d_nchw(cfg, outs):
"""Create the schedule for conv2d_nchw"""
outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs
s = te.create_schedule([x.op for x in outs])
def _callback(op):
if op.tag == "conv2d_nchw":
schedule_direct_cim(cfg, s, op.output(0)) #should ... | ce4e3dafaef4c15ceffbe5082d345ffe6c69d2f1 | 3,598,187 |
def svn_client_proplist4(*args):
"""svn_client_proplist4(char const * target, svn_opt_revision_t peg_revision, svn_opt_revision_t revision, svn_depth_t depth, apr_array_header_t changelists, svn_boolean_t get_target_inherited_props, svn_proplist_receiver2_t receiver, svn_client_ctx_t ctx, apr_pool_t scratch_pool) -... | 75dc058b72dca4d0618ba56ed3b86da20f5e09e4 | 3,598,188 |
def calc_ns_rad(lat):
""" Calculates the North/South radius
Args:
lat (float) latitude in radians
Returns:
(float): North/South radius in meters
"""
return EQ_RAD * (1 - ECCENTRICITY**2) / (1 - ECCENTRICITY**2
* np.sin(lat)**2)**1.5 | 75e40ae3e3394c5262e434ba410b77a5c1095b2a | 3,598,189 |
def get_arg_name(arg_spec: spec.ArgSpec) -> str:
"""get name of an argument according to an ArgSpec"""
if isinstance(arg_spec['name'], str):
return arg_spec['name'].strip('-')
else:
for name in arg_spec['name']:
if name[0] != '-' or name.startswith('--'):
return ... | 5733318e3f7f175182c860dbe3c9a7a6c692512f | 3,598,190 |
import collections
def combine_groups_by_trials(group1, group2):
"""
For combining neuron groups from the same experiment with different trials
The two groups need to have the same neurons (based on id)
:param group1: a NeuronGroup object
:param group2: a NeuronGroup object
:return: the combin... | fa534188c0ee618cc49adca6d3af8dd4e3adba1e | 3,598,191 |
from typing import Union
from typing import Type
def _map_dictparameter(value: str, dtype: Union[None, Type] = None) -> dict:
"""
Map a string dictionary into a python dictionary
:param value: str, tries to evaluate string into a dictionary
i.e. "dict(a=1, b=2)" or {'a':1, 'b': 2}
... | 9c3a241d5b37232136755721f5d572d7e80d4a82 | 3,598,192 |
def get_all_acc(database: DatabaseInterface):
"""
returns all accounts which are saved in the database
if not existent returns an empty list []
"""
with database.get_session() as session:
accs = database.get_all_acc(session)
database.expunge_all(session)
return accs | b09588617b3e8264a471df9811d10a9764be646c | 3,598,193 |
def createTournament():
"""Creates a new tournament and returns its id."""
with get_cursor() as c:
c.execute("INSERT INTO tournament (id) VALUES (DEFAULT) RETURNING id")
tournament_id = c.fetchone()[0]
return tournament_id | fcf1f64ff3f8b8c6d2f70258a086a636793f474d | 3,598,195 |
def _accessor_header_include_get(dataset):
"""Returns the string to include the accessor header file"""
return '"{}"'.format(_accessor_header_name_get(dataset)) | fc4c2fd72198ccb684383c170ea17c3b0c6a0b5d | 3,598,196 |
def genius():
"""pytest fixture, returns an instance of Genius()"""
token = get_token()
return Genius(token) | d75f5f2e0b1460134a82fe23352b755442476075 | 3,598,197 |
def get_depth(count):
""" returns the depth of the tree
- count -- 32 bit value
eg: If any number between 9 and 16 is passed the function returns 4
"""
l = count
depth = 0
l = l>> 1
while l != 0:
depth = depth + 1
l = l>> 1
#more than one 1s in the binary r... | 705790d8353e65dd1fa16e36f5c6ea79d4bbbe27 | 3,598,198 |
def substituted_mol(self, mol, checkI):
"""
Returns a molecule object in which all metal atoms specified in args.metal_atoms
are replaced by Iodine and the charge is set depending on the number of
neighbors.
"""
Neighbors2FormalCharge = dict()
for i, j in zip(range(2, 9), range(-3, 4)):
Neighbors2FormalCharg... | e6b122aad37f2e11543231b6fbe1834039d65f8f | 3,598,199 |
import six
def setupTranslationMap():
"""prepare translation map to remove all control characters except
tab, new-line and carriage-return"""
ctrls = trans = ""
for n in range(0, 32):
char = six.unichr(n)
ctrls += char
if char in "\t\n\r":
trans += char
else... | b59a5808e9a8bd2edb10f1cbd55254ed047f3737 | 3,598,200 |
def init_spacy_document(
lattice,
token_key="token",
):
"""
Given List of word-level dicts, initializes Spacy Doc
using WhitespaceTokenizer
:param: lattice: List[Dict];
inner dicts contain token-level information for each token in input text
:param: token_key: key in Dicts containing... | 5d0f5a4d331b70dbcbd414969acc1fb7008fc0af | 3,598,201 |
def get_rev_by_cat(date_start, date_end):
"""
Return the total revenue for each category within the time range.
"""
sql = f"""
select productcategory.name, sum(sales.total)
from sales, product, productcategory
where salesdate between to_date('{date_start}', 'YYYY-MM-DD') and to_date('{date_e... | 0e5204ea7fd86f5918e6d3504ccd42eae5e793b4 | 3,598,203 |
def get_metaschema():
"""
Patches and returns the JSON Schema Draft 4 metaschema.
"""
return json_merge_patch.merge(json_load('metaschema/json-schema-draft-4.json'),
json_load('metaschema/meta-schema-patch.json')) | 64ecf14cd8cf996896600a800b70048f984b1564 | 3,598,204 |
import re
def is_url(filePath):
"""
Checks wether or not the file path
is a valid url.
:param str filePath: file path
:return: returns true if path matches pattern starting with
http:// or https://
:rtype: boolean
"""
regex = re.compile(r'^https?:\/\/', re.IGNORECASE)
return re... | 8d86e07c8585f30bb8927ba9cfa7f1a8d128b598 | 3,598,205 |
def reportAPIError(response, exception, sendEmail, extraErrorMessage=""):
"""
reportAPIError reports an APIError offering configuration options in the reporting
:param response: the response from the http request
:param exception: the python exception that was thrown
:param sendEmail: bool, whether ... | 3f95aff537c6ff3136c4e82b17ed9fcdf6507f29 | 3,598,206 |
def dump_identifier(value):
"""dump identifier"""
if value is True:
return "y"
return "n" | 45d5fded4a5a6f12488385c35321eb94e10a06e1 | 3,598,207 |
def get_productions_simple(**kwargs):
"""Load a DataFrame of productions with the most typical query
Parameters
----------
**kwargs
Optional arguments that are passed to get_credentials()
Returns
-------
prods_df : pandas DataFrame
DataFrame of all productions
"""
q... | 8e8d617aaa71a669b816d6e24481399280d758b6 | 3,598,208 |
def directpose_resnet_lpf_fpn(cfg):
"""
Create a ResNetFPNDirectPose instance from config.
Returns:
ResNetFPNDirectPose: a :class:`ResNetFPNDirectPose` instance.
"""
depth = cfg.CONFIG.MODEL.RESNETS.DEPTH
out_features = cfg.CONFIG.MODEL.RESNETS.OUT_FEATURES
num_blocks_per_stage = {5... | 6581e5f5cfcfddbab70a03a8e71a4f7f4ffb4685 | 3,598,209 |
def select_results(results, selector_strings):
"""select the results by the specified selectors.
Paramters
---------
results : array-like, shape(n,)
The results after scanning the directory for documents
with valid headers.
selector_strings : array-like, shape(m,)
The list ... | e919115fdc6878ba3ca0946415c8fc43d3fbb6a7 | 3,598,210 |
def DistanceFromMatrix(matrix):
"""Returns function(i,j) that looks up matrix[i][j].
Useful for maintaining flexibility about whether a function is computed
or looked up.
Matrix can be a 2D dict (arbitrary keys) or list (integer keys).
"""
def result(i, j):
return matrix[i][j]
retu... | f3cb95aace0cfe70bfeef9d8778947df16cdd4b1 | 3,598,211 |
def job_response(request,**args):
"""
Job application/ job response
"""
if request.method=="get" or request.method== "GET":
# get job response form and send back to client
form=forms.JobresponseForm()
return form
if request.method=="post" or request.meth... | eb5bc02eb12e15983a66e680d9f41c7144ae1dae | 3,598,212 |
def _are_orders_renormed(exposures_data, input_key):
"""
:param exposures_data:
:param input_key:
:return:
"""
exposures_all = list(exposures_data.keys())
n_renorm = 0
for exp_id in exposures_all:
orders_all = _valid_orders_from_keys(exposures_data[exp_id].keys())
n_orde... | 668802f8d9c7ec2ed4ca9be16522802411217d70 | 3,598,213 |
def preprocess_captions(data, word2vec, emoji2vec):
""" Preprocess the captions: remove non-english or punctuation characters,
remove captions shorter than the minimum, lowercase captions """
lengths = []
for row, caption in enumerate(data['Caption']):
if type(caption) != str or len(caption... | bc836958e5e20794957ac47c1908b15550d57de9 | 3,598,214 |
def get_bprop_bias_add(self):
"""Grad definition for `BiasAdd` operation."""
bias_grad = SG.BiasAddGrad(self.data_format)
def bprop(x, w, out, dout):
return dout, bias_grad(dout)
return bprop | cb75d0bda0df246ec28c56fea352d7de75abc6b7 | 3,598,215 |
from pathlib import Path
def homedir() -> str:
"""Return the user's home directory."""
return str(Path.home()) | dbd65e7db4cdbf2bd06c1ab42ed1ea3503e14ac2 | 3,598,216 |
from typing import Optional
def get_raster_with_trajectories_as_rgb(
pixel_size: float,
raster: Raster,
target_trajectory: Optional[Trajectory] = None,
predicted_trajectory: Optional[Trajectory] = None,
background_color: Color = Color.BACKGROUND,
roadmap_color: Color = ... | 64b0a01f4af292be0f21f8ffddc7b21184fb6d2c | 3,598,217 |
import re
def natural_keys(text):
"""
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
"""
... | d3a017c9f0426175bfa8fe53ab779a501a3ec24c | 3,598,219 |
def contributor_or_delegate_required(view_func):
"""
Decorator for views that checks that the user is logged in, has edit rights
for at least one course or is a delegate for such a person or is a
contributor.
"""
def check_user(user):
return user.is_contributor_or_delegate
return use... | e8475e30fb3f02dbff3e230bfe4cbc81f13f55c3 | 3,598,220 |
def read_label(fig, label, whitelist=LABEL_WHITELIST):
""" Reads a label paragraph objects using ocr
:param numpy.ndarray img: Input unprocessedimage
:param Label label: Label object containing appropriate bounding box
:rtype List[List[str]]
"""
size = 5
img = convert_greyscale(fig.img)
... | e026186e2e6cd76c09777333a1896e3b78e06a24 | 3,598,221 |
def remove_accented_chars(text):
"""remove accented characters from text, e.g. café"""
text = unidecode.unidecode(text)
return text | 05afba1091a8bba2e7d6381a04e22addf022dca3 | 3,598,222 |
import itertools
def _optimal_path(input_sets, output_set, idx_dict, memory_limit):
"""Copied from _optimal_path in numpy/core/einsumfunc.py
Computes all possible pair contractions, sieves the results based
on ``memory_limit`` and returns the lowest cost path. This algorithm
scales factorial with res... | ba2735b208f50d117349ea12148138a1857b66b7 | 3,598,223 |
from pathlib import Path
def inside_container() -> bool:
"""
The developer's machine is not sandboxed and should not run any testing snippets,
at the risk of being damaged.
So, it is important to make sure that the code execution only happens inside a container.
See:
* https://stackoverflow.c... | fb5377cb2cef8da20bcc18a01087b2dca7b5d2ac | 3,598,224 |
import warnings
def _check_psd_eigenvalues(lambdas, enable_warnings=False):
"""Check the eigenvalues of a positive semidefinite (PSD) matrix.
Checks the provided array of PSD matrix eigenvalues for numerical or
conditioning issues and returns a fixed validated version. This method
should typically be... | be5fd1dd800e3a709462bbdfe5c627ba0bdcac2f | 3,598,225 |
def test_function_with_no_args():
"""This cannot be called because meta is always passed."""
return "look, no args!" | a6f83e1e5265f39a3037a764803a8abc6d358744 | 3,598,226 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_picku... | bc13196f150172c10fdbc15e80d1ad96d60441cd | 3,598,227 |
def test_query_device_do_bypass(monkeypatch):
"""Test setting the bypass status on devices matched by a query."""
_was_called = False
def _bypass(url, body, **kwargs):
nonlocal _was_called
assert url == "/appservices/v6/orgs/Z100/device_actions"
assert body == {"action_type": "BYPAS... | 0e0b1c07da2c932afac843592d5b3bf8776462c1 | 3,598,228 |
def KK_RC19(w, Rs, R_values, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
return (
Rs
+ (R_values[0] / (1 + w * 1j * t_values[0]))
+ (R_values[1] / (1 + w * 1j * t_values[1]))
+ (R_values[2] / (... | b0c492edd63c6c5e9a07b9d7206f08e2cea8d594 | 3,598,229 |
def cdf_from_pdf_file(data_file):
"""
Computes CDF from PDF values stored in a file
Creates a Cumulative Distribution Function from Probability Density
Function data file. Each line must be a pair of numbers x y=pdf(x).
It returns the CDF as two lists; first on is the list of x-values,
second o... | ef1251357b602141a1899ea957c3240b0adb1fb4 | 3,598,230 |
def image_to_numpy(image, background_color):
"""Sets background of 4d image to the specified color."""
image = np.asarray(image)
assert(image.shape[-1] == 4)
background = image[..., 3] == 0
image = image[..., :3].copy()
image[background] = background_color
return image | 927c9935c052c656b1970b06a520709a4c6f4bb3 | 3,598,231 |
import numpy
def li_kernel(view_zenith, solar_zenith, relative_azimuth):
"""Calculate Li Kernel - Li X. and Strahler A. H., (1986) - Geometric-Optical Bidirectional Reflectance Modeling of a Conifer Forest Canopy.
Args:
view_zenith (numpy array): view zenith.
solar_zenith (numpy array): solar... | 0c7eef7d9fb1ec56566e77df67267fb6dc14bdd1 | 3,598,232 |
import re
def parse_sphinx_substitutions():
"""
Parse the file containing definitions in Sphinx format into a dict.
Example:
.. |short_name| replace::
A detailled definition
becomes "short_name: A detailled definition"
"""
file_name = "../sheepdog/docs/api_reference/subst... | e0f1afcd812bb04af5a73de77f0226d55279fdc8 | 3,598,233 |
def get_invalid_parameter(value):
""" Read everything up to the next ';'.
This is outside the formal grammar. The InvalidParameter TokenList that is
returned acts like a Parameter, but the data attributes are None.
"""
invalid_parameter = InvalidParameter()
while value and value[0] != ';':
... | 6c0af359e269606796139a55049b03816433af69 | 3,598,234 |
def idfreader1(
fname, # type: str
iddfile, # type: str
theidf, # type: IDF
conv=True, # type: Optional[bool]
commdct=None, # type: List[List[Dict[str, Any]]]
block=None, # type: Optional[List]
):
# type: (...) -> Tuple[Dict[str, Any], Optional[List[Any]], Any, List[List[Dict[str, Any]... | d56bb795b9a2a33cb147c4c0d1ad32c2a4c8d6f3 | 3,598,235 |
def create_account(ac_name,us_name,ac_pswd):
"""
Function to create a new account
"""
new_account= Credential(ac_name,us_name,ac_pswd)
return new_account | 78bc04b2c973da57ed693da142dec7f5d1fca93d | 3,598,236 |
from typing import OrderedDict
def _q_calc(fatigue_life, h, v0, sn, method='brentq'):
"""
Calculate Weibull scale parameter (q) that gives specified fatigue life using closed form expression
in DNV-RP-C03 (2016) eq. F.12-1.
Parameters
----------
fatigue_life: float
Fatigue life [years... | 0aa35d4359dafaf1c5ea83fc75f4d02661cebe85 | 3,598,237 |
def make_attention_mask_3d(source_block, target_block):
"""
Returns a 3-dimensional (3-D) attention mask
:param source_block: 1-D array
:param target_block: 1-D array
"""
mask = (target_block[:, None, :] >= 1) * (source_block[:, :, None] >= 1)
# (batch, source_length, target_length)
# ma... | d06e44da4dfdcf2312583d4601642a34094399db | 3,598,238 |
from typing import Dict
def schema_as_dict(schema: SchemaDefinition) -> Dict:
"""
Translates a SchemaDefinition object into a python dictionary, removing redundant elements
This is a wrapper to standard runtime dumper methods, but will produce a more compact schema, in particular:
* prefix maps are ... | faa88349ba797ca81fe67c3963b4d66c9c09a533 | 3,598,240 |
def build_window_mixture_model(model, initial_states, cells, inputs,
batch_size,
window_components, character_inputs,
char_seq_len):
"""
Append window mixture model to model
"""
assert len(cells) == 3, "Expectin... | 57db2c632b16628e189e000799c9370417074a70 | 3,598,241 |
def addDropShadowSimple(image: Image.Image, offset: list[int]) -> Image.Image:
"""Add a simple drop shadow.
Args:
image (Image.Image): Base image to give a drop shadow
offset (list[int, int]): Offset of the shadow as [x,y]
Returns:
Image.Image: A PIL Image
"""
border = max(abs(x) for x in offset)
return a... | b9d691f8c950e487481656b6ec828dcffc341353 | 3,598,242 |
def hello_world():
"""Welcome route"""
return jsonify({"message": "Welcome to Dukaan Rating API"}) | 12a63e5e8f9eae8ce034c60d4d70cf72d8926889 | 3,598,243 |
def frame_width(camera, target, fov = 30):
"""
Get frame width from camera, target positions and field of view
**ARGUMENTS**
camera : array
Camera position. A 1D array
target : array
Target position. A 1D array
fov : float
Field of view (degrees) of the camera... | c490d6d4c52f74e646fca609362513625b164815 | 3,598,244 |
def length(v):
"""Length of vector"""
return sqrt(v.dot(v)) | 32c43a425c9fc10faa5790271fde2068eb391a4f | 3,598,245 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.