content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def generate_module_selector_keyboard(language: str) -> ReplyKeyboardMarkup:
"""Create an return an instance of `module_selector_keyboard`
**Keyword arguments:**
- language (str) -- The desired language to generate labels
**Returns:**
ReplyKeyboardMarkup instance
"""
return (
Re... | 8440d4984533a525261a9ad3798234082a67bb75 | 57,207 |
def menu(layout: Layout) -> dict:
"""
Layout menu
This method takes a Layout class object as an argument and presents the user
with a suite of options in a command line interface (CLI). The options
include the generation technical documentation for the layout, or validation
of a csv file, with ... | b66dfc37c152f052b0a4f463990d6d17084c9bdf | 57,208 |
def parseargs(p):
"""
Add arguments and `func` to `p`.
:param p: ArgumentParser
:return: ArgumentParser
"""
p.set_defaults(func=func)
p.description = "Create the DIRECTORY(ies), if they do not already " + "exist."
p.add_argument("directory", nargs="+")
p.add_argument(
"-p",... | a95766b51c743de467bc7bba2de0f7b536a7c9bb | 57,209 |
def cfn_context():
""" Context object, blank for now """
return "" | a71bffc39ce00e00236667040feb156bb9a4f9a2 | 57,211 |
import re
def parse_to_query_term_list(str_query):
"""
Take a string and parse the field names and field data clauses to q list of
SolrQueryTerms
NOTE: this is only used by testSearchSyntax to produce term_lists!
>>> str = "dreams_xml:mother AND father AND authors:David Tuckett A... | 84d7e15afa9f04621f3f47d8ca84c202e59468f3 | 57,213 |
def ws_message_event_fixture(ws_message_event_data):
"""Define a fixture to represent an event response."""
return {
"data": ws_message_event_data,
"datacontenttype": "application/json",
"id": "id:16803409109",
"source": "messagequeue",
"specversion": "1.0",
"time... | a99b4987712c4aac350c7b712642cf5c690261dd | 57,214 |
def hello_world():
"""Just an empty route with a string."""
return "Hello there. This route doesn't do anything." | f6dcaa52d51aab51234f51b4f7a46e6e55aeb524 | 57,215 |
def load_data_and_labels(one_data_file, two_data_file, three_data_file, five_data_file, eight_data_file, thirteen_data_file, twentyone_data_file):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
# Load data from files
... | d3976424229344cf751fdaaa730e5546de1aa09c | 57,216 |
def dict2tsv(condDict):
"""Convert a dict into TSV format."""
string = str()
for i in condDict:
string += i + "\t" + "{%f, %f}" % condDict[i] + "\n"
return string | c73f8e3158ade699cc4589d541f05397f559d190 | 57,217 |
def choose_by_idc(dest_idc, local_idc, ips):
"""
net.choose_by_idc(dest_idc, my_idc, ip_list)
:param dest_idc: is a string representing an IDC where the ips in `ip_list` is.
:param local_idc: is a string representing the IDC where the function is running.
:param ips: is a list of ip in the `dest_idc... | 0878ce74f45f03f5a89b903a76a259c65194eb9a | 57,218 |
def statuses_retweeters_ids(auth, **params):
"""
Returns a collection of up to 100 user IDs belonging to users
who have retweeted the tweet specified by the id parameter.
"""
maxitems = params.pop("maxitems", 0)
if maxitems > 0:
return cursor_iter(statuses_retweeters_ids, maxitems, auth... | eac656d1927725c3055a9f789109e9b7e452ff3d | 57,220 |
def _get_s3_arn_given_smb_file_share(smb_file_share_arn: str) -> str:
""" Return S3 ARN associated with a named SMB file share ARN """
s3_arn = ''
client = boto3.client('storagegateway')
for file_share in client.describe_smb_file_shares(FileShareARNList=[smb_file_share_arn])['SMBFileShareInfoList']:
... | 39b57ca85d47b7a5ca95488940c0aea2b72c9923 | 57,221 |
def rescale_score_by_abs(score, max_score, min_score):
"""
Normalize the relevance value (=score), accordingly to the extremal relevance values (max_score and min_score),
for visualization with a diverging colormap.
i.e. rescale positive relevance to the range [0.5, 1.0], and negative relevance to the ... | fe1df85166bb6ab34f6f30d06003d7946a92138e | 57,223 |
def calculate_percentile_rank(array, score):
"""Get a school score's percentile rank from an array of cohort scores."""
true_false_array = [value <= score for value in array]
if len(true_false_array) == 0:
return
raw_rank = float(sum(true_false_array)) / len(true_false_array)
return int(roun... | bfdc64168c10d00c33294bf05851982e0712e230 | 57,224 |
def create_histogram(samples):
"""Returns a pair of arrays (values,counts), where size(values)=size(counts),
corresponding to the (sorted) unique values seen in the sample along with the
number of times they appear."""
samples.sort()
values=[]
counts=[]
counter=None
prev=None
for sam... | 5e559bf4e83bffd379828e1fc78df20505143e49 | 57,225 |
def string_interleave(s1, s2):
"""Interleave a character from a small string to a big string
Args:
s1 (str): input string
s2 (str): input string
Returns:
(str): the string that already interleave
Raises:
TypeError: if s1 or s2 is not a string
Examples:
>>> str... | be0765a3822c657999e3223ae5adcddaa0bb4ed6 | 57,226 |
def season_acquire(month: str) -> str:
""" Chose the season that correspond with the month
:param month: The month when the animation starts to broadcast
:return: Corresponding season
"""
if month in ('1', '2', '3', '01', '02', '03'):
season = '01-Winter'
if month in ('4', '5', '6', '04... | 65c45726037f9bfb8ca17d4cc81e5eda8b6f4e5c | 57,227 |
def add_default_processor(xml_tree, processor_name):
"""
Add processor to lqn-model tree.
:param xml_tree: lqn-model tree
:param processor_name: string
:return: Created processor
"""
processor = add_processor_element(xml_tree, processor_name=processor_name)
task = add_task_to_processor(p... | ab9f8cd81602bea1bb4f781ee5a91f49f04a1a33 | 57,228 |
def set_window(pixel_array, window_level, window_width):
"""Sets the window level and width for the image"""
scale_img = np.array(pixel_array)
# Getting low and high values
low = window_level - window_width/2
high = window_level + window_width/2
def bin_function(i, window_level, window_width, high, low):
... | 295bddb3317990034f8d194889eaf736346f8276 | 57,229 |
def find_conjugated_systems(atoms, res_names):
"""Finds conjugated systems within a BioPython residue object, and returns them as individual customized BioPython
Residue objects.
Parameters
---------
atoms: array-like
List of atoms in the residue
res_names: arary-like
List of al... | 5fe37c498866bdf7fbb0b033a1f18d68bfa9a9a5 | 57,231 |
def sym_reflection(Rp, semi_a, phase, Ab):
"""Symmetric reflection component of the phase curve.
Args:
Rp (float): radius of the planet in m
a (float): semi major axis of the planet in m
phase (array): phase angles of the planet in radians
Ag (float): geometric albedo of the planet
Returns:
array, normal... | 50ee27c6b49f63fe24a23d3ba2cc8a42763c22ac | 57,233 |
import ctypes
def getHistogram(values, bins):
"""
Build an histogram counting the occurences of `values' in the
`len(bins) - 1' intervals of values in `bins'.
Parameters
----------
values : float array-like
Values to count.
bins : float array-like
Limits of the bins.
... | 2fba87b7f4b2697e8d75e977ae6cc165cfd23e7c | 57,235 |
from typing import Callable
import torch
def mc_dropout_max_entropy(classifier: BaseEstimator, X: modALinput, n_instances: int = 1,
random_tie_break: bool = False, dropout_layer_indexes: list = [],
num_cycles: int = 50, sample_per_forward_pass: int = 1000,
... | a3768021b9c3b0c9e513e3b276467057e2e0170c | 57,236 |
def plot_map(
ds,
hist=True,
label=None,
coarsen=0,
extent=[-180 + 1e-3, 180 - 1e-3, - 60 + 1e-3, 90 - 1e-3],
histogram_placement=[0.04, 0.15, 0.23, 0.3],
ax=None,
figsize=(14, 7),
subplot_kw={},
cbar_kw={},
hist_kw={},
**kw... | 9f4e077036b56cc8b8bb3f7a40a5d289e0c43d13 | 57,237 |
def make_plots(data, env, run='run_name', condition='param_run'):
"""
Make plots by second, timestep, and episode
"""
figure, axes = plt.subplots(ncols=3, nrows=1, figsize=(3 * 6, 6))
# plot episodes
plot1 = plot_data(
data, 'Smoothed_total_reward', 'Iteration',
run, condition,... | d31f41b1be8526042045bcfd14f13a454e6833c6 | 57,238 |
def incident_priority_select_block(
db_session: Session, initial_option: IncidentPriority = None, project_id: int = None
):
"""Builds the incident priority select block."""
incident_priority_options = []
for incident_priority in incident_priority_service.get_all_enabled(
db_session=db_session, p... | 3b1a72c705575058c30fa3fa8bb9f9855011b603 | 57,239 |
def gen_fm_track(N, f0, df):
"""
Generate a Frequency-Modulated sinusoid in the presence of noise, to test
instantaneous-frequency tracking code
Parameters
----------
N : int
Number of samples to generate
f0 : float
Center frequency of sinusoid to generate (in normal... | 392414388fb480d5a119a565407ab8edf57990bb | 57,240 |
def evaluate(labels, predictions):
"""
Given a list of actual labels and a list of predicted labels,
return a tuple (sensitivity, specificty).
Assume each label is either a 1 (positive) or 0 (negative).
`sensitivity` should be a floating-point value from 0 to 1
representing the "true positive ... | b161c4593da7e850b3344925b97ca37e6319b6d1 | 57,241 |
def add_time_to_time(time1, time2, result_format='number',
exclude_millis=False):
"""Adds time to another time and returns the resulting time.
Arguments:
- ``time1:`` First time in one of the supported `time formats`.
- ``time2:`` Second time in one of the support... | b736c49eea1ae941f7d195f5ab88e9c5548fbea1 | 57,242 |
def mase(y, y_hat, y_train, seasonality=1):
"""
Calculates the M4 Mean Absolute Scaled Error.
MASE measures the relative prediction accuracy of a
forecasting method by comparinng the mean absolute errors
of the prediction and the true value against the mean
absolute errors of the seasonal naiv... | 13eb9ef5a63f19f3bdd0ff6d702985de80975a38 | 57,243 |
def get_first_value(param, param_pools, on_missing=None, error=True):
"""
Get the value for a particular parameter from the first pool in the provided
priority list of parameter pools.
:param str param: Name of parameter for which to determine/fetch value.
:param Sequence[Mapping[str, object]] para... | a863b6edb06f127337f2bc22676aee7b03ca1d85 | 57,244 |
def deep_sort(data):
""" In-place sort of any lists in a nested dict/list datastructure. """
if isinstance(data, list):
data.sort()
for item in data:
deep_sort(item)
elif isinstance(data, dict):
for item in data.itervalues():
deep_sort(item)
return None | 2d97b4d83ae444b20047c8f4b0eccfb3996e4ae9 | 57,245 |
def fidelity_est(testSignals):
"""
Estimate the optimal fidelity by estimating the probability distributions.
"""
rangeMin = np.min(testSignals)
rangeMax = np.max(testSignals)
groundProb = np.histogram(testSignals[::2], bins=100, range=(rangeMin, rangeMax), density=True)[0]
excitedProb, binEdges = np.histogram(... | 39e7f4e38ab627610c9db5781d05deccd199009e | 57,246 |
from ..forward.phonon import computeSQESet, kelvin2mev
def sqe2dos(sqe, T, Ecutoff, elastic_E_cutoff, M, initdos=None, update_weights=None):
"""
Given a single-phonon SQE, compute DOS
The basic procedure is
* construct an initial guess of DOS
* use this DOS to compute 1-phonon SQE
* for bo... | bcbcb8e1be76c14729633f20a4c6b772ee647c73 | 57,247 |
def _one_recursive_step(
list_pair,
size_task,
current_doubled_size_task):
""" """
i = 0
j = 0
a_list = list_pair[:size_task]
b_list = list_pair[size_task:]
c_list = []
for k in range(current_doubled_size_task):
#print 'i',i, 'j', j, 'size_task', size_task
... | ae0fe3440b8af38730de80fde4762f3c7fa94623 | 57,248 |
def getTotalCountFilteredSubreddit(keyword):
"""
docstring
"""
try:
connection = postgresqlConnection.createConnectionToDatabase()
cursor = connection.cursor()
create_table_query = f'''select count(*) from subreddits where topicTitle like '%{keyword}%' '''
cursor.execut... | 0a144f2aa2ec0d0e376c0a120de69634ac6d94dd | 57,250 |
def list_histogram(data: list, color="b", title="Histogram of element frequency.", x_label="", y_label="Frequency", fig_name="hist.png", mute=False):
"""
:param data: the origin list
:param color: color of the histogram bars
:param title: bottom title of the histogram
:param x_label: label of x axis... | b63bb54a70c96276a3cb5ebfd9a18c99cab67d4b | 57,251 |
def make_delay(delay):
"""
Create a delay event with a given delay.
See also Sequence.addBlock
"""
if (not np.isfinite(delay)) or (delay <= 0):
raise ValueError('Delay (' + str(delay*1e3) + 'ms) is invalid.')
return Delay('delay', delay) | 45cc382c64ce430181049dd90b0c56b361cec7b4 | 57,252 |
def get_rules(rulesdir, ignore_rules):
"""Get rules"""
rules = RulesCollection(ignore_rules)
rules_dirs = [DEFAULT_RULESDIR] + rulesdir
try:
for rules_dir in rules_dirs:
rules.extend(
RulesCollection.create_from_directory(rules_dir))
except OSError as e:
L... | 302ca9272c0b8e9a9bf231e6619dd3156eaf0d78 | 57,253 |
def detector_model_specialised(p, parameters):
"""
Detector model, specialised for use with emcee
"""
(varying_parameters, Y0, variable_parameters,
radon_concentration_timeseries) = unpack_parameters(p, parameters)
parameters.update(varying_parameters)
# link recoil probability to screen... | 59ee008d9ddde43d0265901b3af294cac734285c | 57,254 |
def _get_edges(data, pad_length, mode='extrapolate', extrapolate_window=None, **pad_kwargs):
"""
Provides the left and right edges for padding data.
Parameters
----------
data : array-like
The array of the data.
pad_length : int
The number of points to add to the left and right ... | 03c45a0ff4321370610643eb39e4e15ef8037048 | 57,255 |
async def async_handle_message(hass, config, request, context=None):
"""Handle incoming API messages."""
assert request[API_DIRECTIVE][API_HEADER]['payloadVersion'] == '3'
if context is None:
context = ha.Context()
# Read head data
request = request[API_DIRECTIVE]
namespace = request[A... | fff43a12ec0b1ca2bb42a061de259a351da6e023 | 57,256 |
import numpy
def hermitian_conjugated(operator):
"""Return Hermitian conjugate of operator."""
# Handle FermionOperator
if isinstance(operator, FermionOperator):
conjugate_operator = FermionOperator()
for term, coefficient in operator.terms.items():
conjugate_term = tuple([(ten... | a5b89beff70ef03c8cd1615f61194634b1ef4d78 | 57,257 |
def tria_compute_rotated_f(tria, vfunc):
"""
Compute function whose level sets are orthgonal to the ones of vfunc.
Inputs: v vertices
t triangles
vfunc scalar function at triangles
Outputs: vfunc rotated function
This is done by r... | fbdaaa319244b4cdf95161b8607f49245840c91d | 57,258 |
def preproc_eyetribe_data(sam, msg, blink_gap=6, blink_interp=BLINK_INTERP):
""" Preprocess EyeTribe gaze and pupil data from a single participant dataset """
BLINK_THRESH = 0.00001
# Drop blinks (set to NaN)
# Note that blink gap is specified in #samples, not ms!
blinks = (sam.pa < BLINK_T... | 8c4407cd347ae01f2122ee9760b95338f3e8b7fa | 57,259 |
import numpy
def ndarray_to_imagedatadict(nparr):
"""
Convert the numpy array nparr into a suitable ImageList entry dictionary.
Returns a dictionary with the appropriate Data, DataType, PixelDepth
to be inserted into a dm3 tag dictionary and written to a file.
"""
ret = {}
dm_type = None
... | 1d4e1fd30d36811798872f385d2ebc23ebc53626 | 57,260 |
def view_color_histogram(image):
"""
Args: View the histogram of a color image
image: Float array of the image
Returns: Hist and its bin array
"""
hist_all = []
for i in range(image.shape[2]):
hist, bins = np.histogram(image[:, :, i].ravel(), 256, [0, 256])
# Convert to ... | 97249a8f67ad11d963c67118054773dcef516232 | 57,261 |
def load_sample_image(image_name):
"""Load the numpy array of a single sample image.
Read more in the :ref:`User Guide <sample_images>`.
Parameters
----------
image_name : {`china.jpg`, `flower.jpg`}
The name of the sample image loaded
Returns
-------
img : 3D array
Th... | 5e95cd808ada569e2741292ee93f2bf0d42b5d98 | 57,262 |
from typing import Dict
def angry_expression(misty: Misty) -> Dict:
"""Misty expresses anger.
Args:
misty (Misty): The Misty to perform the expression.
Returns:
Dict: The dictionary with `"overall_success"` key (bool) and keys for every action performed (dictionarised Misty2pyResponse).
... | 238a5c9c9e5e0422f2685b3aa0f5145cfda43c19 | 57,263 |
def _integral_luk_leq_M(model, l, u, k):
"""Compute :math:`I(l,u,k)` for :math:`0<k<M+1`. Assumes that :math:`a<l,u<b`."""
ag = model.alpha - model.gamma
om = 2 * B.pi * k / (model.b - model.a)
return (1 / (ag ** 2 + om ** 2)) * (
(ag * B.cos(om * (u - model.a)) + om * B.sin(om * (u - model.a)))... | 3fa6ace016c393ca89b3c587137fbdb6c3bd22e2 | 57,266 |
from persistent_settings.models import Variable
def variable_factory(db):
"""
Returns a Variable instance.
"""
def factory(value, name="FOO"):
return Variable.objects.create(name=name, value=value)
return factory | 5723a22ea6f673524f23c11e16b7e6f0b1d39e9b | 57,267 |
def gain_com(exp, num, value):
"""Change the pmt gain in a job.
Return a list with parts for the cam command.
"""
return [
("cmd", "adjust"),
("tar", "pmt"),
("num", str(num)),
("exp", str(exp)),
("prop", "gain"),
("value", str(value)),
] | d0bd65b62c4ef0f9f002cef9b929ec37a725389c | 57,268 |
def get_taxon_from_scientific_name(scientific_name):
"""
Function retrieves a taxon object from a colon delimited item_scientific_name string
:param scientific_name: colon delimited item_scientific_name string, e.g. 'Rodentia:Muridae:Golunda gurai'
:return: returns a taxon object.
"""
clean_name... | a37cc559281f8fbb8957d4425dcbb9626f3eac72 | 57,269 |
def get_data(methylation_files, names, window, smoothen=5):
"""
Import methylation data from all files in the list methylation_files
Data can be either frequency or raw.
data is extracted within the window args.window
Frequencies are smoothened using a sliding window
"""
return [read_meth(... | 6dc3ebb000a9b6b665cc6e56ed8088671c76f512 | 57,271 |
from .treemodels import ObjectTreeStore
def wrap_treenode_property_to_treemodel(model, prop):
"""
Convenience function that (sparsely) wraps a TreeNode property
to an ObjectTreeStore. If the property is a Gtk.TreeModel instance,
it returns it without wrapping.
"""
return wrap_prope... | 283be5fc2b75ae19d8f548e9625f3e2135d24694 | 57,272 |
def gaussian(size, rin=0.8, rout=1.0):
"""Return a complex gaussian probe distribution.
Illumination probe represented on a 2D regular grid.
A finite-extent circular shaped probe is represented as
a complex wave. The intensity of the probe is maximum at
the center and damps to zero at the borders ... | d6e8b73206c6ae628ce8f9ac7e5a0e6b088b23f3 | 57,273 |
async def get_scorekeepers():
"""Retrieve an array of Scorekeepers objects, each containing:
Scorekeepers ID, name, slug string, and gender.
Results are stored by scorekeeper name."""
try:
scorekeeper = Scorekeeper(database_connection=_database_connection)
scorekeepers = scorekeeper.ret... | 96b94cff265d65e0ffe023ccedfe8f8d3fac001a | 57,274 |
def _phi(x, m, r):
"""Computes the number of template vector pairs having a smaller distance
than tolerance. Required for sample entropy estimation.
"""
N = len(x)
x_ = [[x[j] for j in range(i, i + m - 1 + 1)] for i in range(
N - m + 1)]
C = [len([1 for j in range(len(x_)) if i != j and
... | 04a5af5bb179813dcc771002aecdbb08b5d6aa9a | 57,275 |
def make_divisible(v, divisible_by, min_value=None):
"""
This function is taken from the original tf repo.
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
"""
if min_value is None:
min_value = divisible_by
new_v = max(min_value, int(v + divisibl... | 3327381e8e79d45223635832ddfca80de629fc12 | 57,276 |
def find_corners(img):
""" Find chessboard corners
"""
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Find the chessboard corners
return cv2.findChessboardCorners(gray, (NUM_CHESSBRD_CORNERS_X, NUM_CHESSBRD_CORNERS_Y), None) | 989992c3658006483a05b923fed1dad08e0512d8 | 57,277 |
def RF_features_select(rdd_feature_vd, n=10, m=7, s = 50):
"""
Implements random forest classifier to the opcodes counts in each document
Returns the importance of each opcodes
>> Input (hash, label, features), Output (features, importance)
"""
data_feature = rdd_feature_vd.map(lambda x: (x[1], ... | fa37f1bb1d38961ec4b271010e8e1b384040979c | 57,279 |
from typing import List
async def get_all_users_in_database(
db: DatabaseManager = Depends(get_database),
) -> List[User]:
"""Get all users from users mongodb collection"""
users = await db.user_get_all()
if users:
return JSONResponse(status_code=status.HTTP_200_OK, content=users)
raise HT... | 6abf9c39d6a9a51c0fb0f417e5bf11ce898d21a8 | 57,280 |
def F1(yp, yt):
"""F1 score.
Args:
yp (array): predictions
yt (array): targets
Returns:
float: F1 score
"""
tp = true_positive(yp, yt)
fp = false_positive(yp, yt)
fn = false_negative(yp, yt)
f1 = 2 * tp / (2 * tp + fp + fn)
return f1 | c02b7b16fe85eb7aff0a9015011e3b96954ad5ea | 57,281 |
def get_line_buffer(): # real signature unknown; restored from __doc__
"""
get_line_buffer() -> string
return the current contents of the line buffer.
"""
return "" | 9242593c8f39a3175c17ea3f5ce07d8024d1ad03 | 57,283 |
from typing import List
from typing import Dict
from typing import Any
def global_metrics_fn(all_confusion_mats: List[jnp.ndarray],
dataset_metadata: Dict[str, Any]) -> Dict[str, float]:
"""Returns a dict with global (whole-dataset) metrics."""
# Compute mIoU from list of confusion matrices:... | ced566bad90d407f279cffac98a44993de12b38e | 57,284 |
def get_lib_dpath_list(root_dir):
"""
input <root_dir>: deepest directory to look for a library (dll, so, dylib)
returns <libnames>: list of plausible directories to look.
"""
'returns possible lib locations'
get_lib_dpath_list = [
root_dir,
join(root_dir, 'lib'),
join(ro... | b608336a76ac2e52e6668af26571f8697365ed67 | 57,285 |
def authenticate():
"""Function for handling Twitter Authentication. Please note
that this script assumes you have a file called credentials.py
which stores the 4 required authentication tokens:
1. CONSUMER_API_KEY
2. CONSUMER_API_SECRET
3. ACCESS_TOKEN
4. ACCESS_TOKEN_SEC... | 9a9010d9329217bf03704c024da359785e48d905 | 57,286 |
def get_rhs(lhs):
"""
Return the possible RHS of a given LHS.
:param lhs: token or list of tokens
:return: list of tuples
"""
return _ppdb_dict.get_rhs(lhs) | 9d522cdb7725ad70c9786a20a1c05599592067c9 | 57,287 |
def root():
"""Returns hola perro."""
return 'Welcome' | c83c0d159cbabdb82905595b01058d531a03ddd1 | 57,288 |
def avgpool2d(expr, type_map):
"""Rewrite a avgpool op"""
arg = expr.args[0]
t = type_map[arg]
arg = relay.op.cast(arg, "int32")
out = relay.op.nn.avg_pool2d(arg, **expr.attrs)
out = relay.op.cast(out, t.dtype)
return [out, t.scale, t.zero_point, t.dtype] | 00384ae01594b326188fe7eebced6c86437b4e53 | 57,290 |
from typing import Optional
def get_export_configuration(export_id: Optional[str] = None,
resource_group_name: Optional[str] = None,
resource_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetE... | d0efe9cf0a41944b66fdd87650649dc50f76f31e | 57,291 |
def decrypt(key, ciphertext):
"""
Decrypts `plaintext` with `key` using AES-128, an HMAC to verify integrity,
and PBKDF2 to stretch the given key.
The exact algorithm is specified in the module docstring.
"""
# if(len(ciphertext)%16 != 0):
# ciphertext = pad(ciphertext)
# assert len(cip... | 7220c018db4f05aa56aa490499ed266cf810bfad | 57,293 |
def view_showcases(request):
""" Shows the project showcase page """
showcase_settings = ShowcaseSiteSettings.objects.first()
if not showcase_settings:
return render(request, 'showcase.html', {
'top_results': None,
'all_showcases': None,
})
showcase_hackathons = ... | fb3954c132ee620bc74220edcca2c538edbcb837 | 57,294 |
import torch
def get_models(flags: GetModelsProto, modality: str):
"""
Get the wanted classifier for specific modality
"""
# argument feature_extractor_img is only used for mimic_main.
# Need to make sure it is unset when training classifiers
flags.feature_extractor_img = ''
assert modalit... | 9a13fa6a323bf0812f3c1e8a1da7bc03dfadd24b | 57,295 |
from datetime import datetime
def cite(headline, source, link, HTMLclass, author=""):
"""
Return a MLA-ish citation for a given headline in HTML. Adds citation along with headline info to firestore. Delets old headline from that source.
"""
dateAccessed = datetime.now()
citation = ""
if a... | 4dea2923745cd66fec40a261cbd72929c2793bf6 | 57,296 |
def add_label(w, t, n, s='http://portainer:9000/api', e='1'):
"""Deploy swarm stack.
Deploy a swarm stack with the Portainer api.
Args:
w: Swarm id
t: Authorization token
n: Stack name
d: Path to docker-compose
y: Deployment type 1 (Swarm) 2 (Compose)
s: Por... | 8059f672fd3f54467153b63b760dc133c551472c | 57,298 |
def leaky_relu_backward(dA, cache, alpha=0.01):
"""
Implements the backward propagation for a single leaky_RELU unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with ... | 212926e6e71ebf4edfc51f99f2957643d3e6a7e5 | 57,299 |
import re
def deduce_look_back(in_features, target_features):
"""From the feature names, determine how large of a look back is used.
Args:
in_features (list of str): Names of input features
target_features (list of str): Names of target features.
Returns:
int: Number of look ... | bae20baec986c888acfff159b491635e2e75a455 | 57,300 |
def parse_response(resp: dict, city: City) -> Temperature:
"""parse json response from Weather API into a Temperature Obj"""
data = resp.get("main", {})
city.country = resp.get("sys", {}).get("country", "")
city.name = resp.get("name", city.name)
return Temperature(
temp_max=data.get("temp_m... | 04e9d96d4d679aa0b6e469f62ad6694adf6c1f33 | 57,301 |
from typing import List
async def create_journal_entry_tags(
db_session: Session,
journal_spec: JournalSpec,
tag_request: CreateJournalEntryTagRequest,
user_group_id_list: List[str] = None,
) -> List[JournalEntryTag]:
"""
Tags the given journal entry.
"""
journal = await find_journal(
... | aa69c795258727fb3a253ded9a39af1d0da989dc | 57,302 |
def runFairOracles(chosed_atts,current_file,alpha_default=0.05,k_threshold=200,k_percentage=0.5):
"""
Run all fairness oracles: FA*IR, Pairwise and Proportion
Attributes:
chosed_atts: list of sensitive attributes
current_file: file name that stored the data (with out ".csv" suffix)
... | c9e3f23f91fe6b70637893a2261179c803f62368 | 57,303 |
def is_v2_behavior_enabled():
"""Returns if user called tf.enable_v2_behavior."""
# Since there is no actual tf.is_v2_behavior enabled, check that the
# settings were enabled.
return tf2.enabled() | 202e4f07f9bc68da76da278f0b999d9e3b71b8fb | 57,304 |
def calc_burst(data):
"""
Recalculate values from d_calc for a run with bursts where each measurement is one pulse form the burst
:param data:
:return:
"""
pulse_energy = []
burst_energy = 0
burst = len(data)
freq = data[0]['burst_f']
print("Burst with "+str(burst) + ' pulses')
... | 4c099d11ea7e0b6e8cff1912bb72d9d9e996f5b3 | 57,305 |
def reorder_inplace(x, y, ordv, midx, midy):
"""
This function plays an integral role in tree formation and does
several things:
1) Determine which points belong to which subnodes
2) Reorder x, y, and ordv variables
3) Compute the number of points in each new subnode
Inputs:
... | 452cb0891f43ec8f134d1df7d989397d1baed5a8 | 57,306 |
def restore_origin_data(data, make_copy=True):
"""
:param data: xarray
:param make_copy: if True the initial data isn't changed
:return: xarray with origin data
"""
if make_copy:
data = data.copy()
dims = data.dims
data = data.transpose(ds.FIELD, ds.TIME, ds.ASSET)
data.loc[f... | 5b8848447f9903cacd2e0adf47f6b2cd86acd8f4 | 57,307 |
import inspect
def use_np_shape(func):
"""A decorator wrapping a function or class with activated NumPy-shape semantics.
When `func` is a function, this ensures that the execution of the function is scoped with NumPy
shape semantics, such as the support for zero-dim and zero size tensors. When
`func` ... | 2bf86970984c2128c76fda6ce9004c5d611607f2 | 57,308 |
import json
import requests
def discover_device(ip_address, headers, discover_user_name, discover_password, list_of_ip, device_type):
""" Discover devices """
discover_payloads = get_discover_device_payload()
discover_payload = discover_payloads.get(device_type)
discover_payload["DiscoveryConfigModels... | 0dbf6bcf717c74e8fef84d2ff3db07e0f6602abd | 57,309 |
def plaintext(text, keeplinebreaks=True):
"""Extract the text elements from (X)HTML content
:param text: `unicode` or `genshi.builder.Fragment`
:param keeplinebreaks: optionally keep linebreaks
"""
if isinstance(text, Fragment):
text = text.generate().render('text', encoding=None)
else:... | 4e26b05065e64a77099a8e2238d5aa834686bc50 | 57,310 |
def permutations_deprecated(s):
"""Get all the permutations of a string, i.e. anagrams
E.g.
'abc' => ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
"""
if len(s) == 0:
all_permutations = []
elif len(s) == 1:
all_permutations = [s]
else:
all_permutations = []
stri... | a486a10a4a41175fcd6ba7819369161494177af3 | 57,311 |
from typing import Union
from typing import Tuple
def _expand_kernel(
kernel_size: Union[int, Tuple[int,...]],
n: int = 2
) -> Tuple:
"""
Expand an integer kernel size to tuple
Arguments:
kernel_size : int or tuple of ints that determines the kernel's spatial dimensions
... | 12388a0e61b0fcd447a33b9155a62d359effcd1d | 57,312 |
from operator import sub
def strd(V):
""" Stretching Deformation
<div class=jython>
STRD ( V ) = DDX ( u ) - DDY ( v )
</div>
"""
return sub(ddx(ur(V)),ddy(vr(V))) | 374d16444e6e00e91201d602a909f767ac085bc1 | 57,314 |
def get_all_network(tenant_id):
"""Get all networks for a tenant.
:param tenant_id: Neutron tenant identifier
"""
session = db.get_session()
with session.begin():
model = HuaweiSwitchNetwork
none = None
all_network = (session.query(model).
filter(model.te... | 5e80c90ecdee10c237e61a59c8b9f0dbd7ba2472 | 57,315 |
def bbox_transform_inv(bbox):
"""convert a bbox of form [xmin, ymin, xmax, ymax] to [cx, cy, w, h]. Works
for numpy array or list of tensors.
"""
with tf.variable_scope('bbox_transform_inv') as scope:
xmin, ymin, xmax, ymax = bbox
out_box = [[]]*4
width = xmax - xmin + 1.0
height = ymax - ymin ... | 2fa1a38915a0e90e5af211e4761dda1b68c33eb1 | 57,316 |
from typing import Optional
from typing import List
from typing import Tuple
def _pedigree_checks(
b: hb.Batch,
samples_df: pd.DataFrame,
reference: hb.ResourceGroup,
sites: hb.ResourceFile,
ped_file: hb.ResourceFile,
overwrite: bool, # pylint: disable=unused-argument
fingerprints_bucket:... | 8566af9b4cf0d11dc3f9e5bd7ac7292c984498b9 | 57,318 |
def insert_paragraphs(renderable_items):
"""Returns a new list of renderable_items where contiguous items of type
TEXT and URL are collapsed into a ParagraphItem instance.
"""
new_renderable_items = []
curr_paragraph = []
def _end_curr_paragraph():
if curr_paragraph:
renderable_item = Renderable... | da26210660142d7db4c663f289913c73b587d51c | 57,319 |
def round_based_player(*bot_moves):
""" A Player which makes a decision dependent on the round index
in a dict or list. (Or anything which responds to moves[idx].)
Parameters
----------
moves : list or dict of moves
the moves to make, a move is determined by moves[round]
"""
def mov... | 2c3e57aae7d6a89c76f735bd7a267ff965d67256 | 57,320 |
def view_newsletter_contact(request, slug, uidb36, token):
"""Visualization of a newsletter by an user"""
newsletter = get_object_or_404(Newsletter, slug=slug)
contact = untokenize(uidb36, token)
ContactMailingStatus.objects.create(newsletter=newsletter,
contact=c... | 1142431ed982ae75a2e404f44c2f6ac1edc9666a | 57,322 |
def to_Mw(rho):
""" Converts from Tape2012 magnitude parameter to moment magnitude
"""
return ((np.log10(rho/np.sqrt(2))-9.1)/1.5) | 3d75cd040704abc3ba8bc681ba47f163722ff126 | 57,324 |
import re
def add_post(post, title=None, link=None, tags=None, author=None, to=None,
private=False, type='post', auto_subscribe=True, files=None):
"""
Add a new post
"""
if isinstance(post, Post):
if post.id:
raise PostUpdateError
elif isinstance(post, (str, unicode)):
... | 0492a76272faa1bf4b69baab0cde453521eba0ed | 57,325 |
def permutations_exact(n, k):
"""Calculates permutations by integer division.
Preferred method for small permutations, but slow on larger ones.
Note: no error checking (expects to be called through permutations())
"""
product = 1
for i in range(n - k + 1, n + 1):
product *= i
retur... | 4244e446aad6b36185575c8c7991bd05984b0796 | 57,327 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.