content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def __get_type_from_resource(resource_arn):
"""
Récupère le type d'une ressource donnée
:param resource_arn: Ressource AWS arn
:type resource_arn: str
:return: default/maintenance
:rtype: str
"""
return __get_tag_value_from_resource(resource_arn, con... | 5be4f187775ac14c54962bb404196e568246b976 | 40,856 |
import random
def random_gaussian(gene):
"""
Random float from gaussian dist.
Args:
gene (Gene): A gene with a set `mu` and `sig`.
Returns:
float: Random number.
"""
stepped_value = random.normal(loc=gene.mu, scale=gene.sig)
while stepped_value > gene.gene_max or stepped... | 3e25cdfbb88fae304514384d0d2736ce04321e37 | 40,857 |
def group_get_object_permissions_as_int_list(self, instance):
"""
Get a list of strings representing the user's permissions for this object
"""
return self.get_object_perm(instance, 'int_list') | 861cd60e932f5a83e6e3871fc35aed678bb90fea | 40,858 |
def put_device(sn):
"""PUT a device"""
data = request.json
i = Instrument.query.filter_by(sn=sn).first()
if i is None:
abort(400)
# Don't update the sn
if 'sn' in data.keys():
data.pop('sn')
# Update the device
i.from_dict(data, partial_update=True)
db.session.add... | 83f58e1473de047813e86c3d5f314bdc5f08738e | 40,859 |
import yaml
def deserialize(stream_or_string, **options):
"""
Deserialize any string of stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower yaml module.
"""
options.setdefault('Loader', BaseLoader)
... | 2632c638446ed7abedb38ea7db5e9e4b8900357d | 40,860 |
def ReadDir(*args):
"""ReadDir(char const * utf8_path) -> char **"""
return _gdal.ReadDir(*args) | 8752dd32478f3cf3a0c4fe8821a0abe4341a425b | 40,861 |
def clocks(now=posix_safe_datetimes()):
"""
Build ``twisted.internet.task.Clock`` instances set to a time built by
``now``.
"""
def clock_at_time(when):
c = Clock()
c.advance((when - _POSIX_EPOCH).total_seconds())
return c
return now.map(clock_at_time) | 6b4f3146533bd7f404b3bf0e17665376ee7e88ed | 40,862 |
def get_recorded_functions_legend_fig():
"""Get Plotly figure used as recorded functions legend.
i.e., whether a mutation has recorded functions
:return: Plotly figure containing indel legend
:rtype: go.Figure
"""
ret = go.Figure(get_recorded_functions_legend_graph_obj())
ret.update_layout... | 94d99b20af89811d3a66540deef89349a23c225f | 40,864 |
def quote_string(s, force=True):
"""Places a string in double quotes, returning the quoted string.
force
Always quote the string, defaults to True. If False then valid
tokens are not quoted but returned as-is.
This is the reverse of :py:func:`decode_quoted_string`. Note that
only the... | f1bcb8bcfc9d12fbedd3e108bef0d81400055df0 | 40,865 |
import math
import numpy
def getMatrix3(eulerdata, inplane=False):
"""
math from http://mathworld.wolfram.com/EulerAngles.html
EMAN conventions - could use more testing
tested by independently rotating object with EMAN eulers and with the
matrix that results from this function
"""
#theta is a rotation about th... | 365b158cd6d5f3150c725a6f8df0d14160168dae | 40,866 |
def constant_value(value_or_tensor_or_var, dtype=None):
"""Returns value if value_or_tensor_or_var has a constant value.
Args:
value_or_tensor_or_var: A value, a `Tensor` or a `Variable`.
dtype: Optional `tf.dtype`, if set it would check it has the right
dtype.
Returns:
The constant value or N... | c870531ae2a6c4bb5746a96605286ff199f160fb | 40,867 |
def generate_data_batch(batch_size=100, max_seq_length=150, vocabulary=None, embeddings=None, training_split=0.8, train=True):
"""
Generate a random training batch of size batch_size.
"""
df = load_split_amzn_reviews()
train_test_split_idx = int(training_split * len(df))
if train:
df = d... | edbde497289e13127f9844cc6e029725f5d0236c | 40,868 |
def upper_camel(name, split_char="_"):
"""Converts a given name into upper camel case
:param name: The name to be converted
:type name: str
:param split_char: The character that separates words in the name.
:type split_char: str
:return: str
"""
return "".join(w.capitalize() for w in na... | 25fe4f07612d2402f3b0107ada9f9efb9133e5dd | 40,870 |
def _py_gaussian_kernel(ksize=3, sigma=-1.0):
"""Returns a 2D Gaussian kernel.
See cv2.getGaussianKernel for details.
Args:
ksize: aperture size, it should be odd and positive.
sigma: Gaussian standard deviation. If it is non-positive, it is computed
from ksize as sigma = 0.3 * ((ksize - 1) * 0.5 ... | 073f62d2f047f2124878c0d6bc245dbc737bfc82 | 40,871 |
def abundant(n):
""" A number n is called abundant if the sum of its proper divisors is more
than n. Returns True if n is an abundant number, False otherwise.
"""
return sum(primes.divisors_proper(n)) > n | 3b2c370322d7855be9f340cd1582e27e9fe4625f | 40,872 |
def appres_phase_from_data(survey):
"""
Compute apparent resistivity and phase given impedances
(real and imaginary components)
and the frequency.
"""
data = survey.dobs
frequency = survey.frequency
# data are arranged (Zxy_real, Zxy_imag) for each frequency
Zxy_real = data.reshape((... | 528fb0e78b1b9f947986ffc59a6e30215ce712a1 | 40,873 |
from typing import Collection
def remove_space(toks: Collection):
"""
Do not include space for bag-of-word models.
:param list[str] toks: list of tokens
:return: list of tokens where space tokens (" ") are filtered out
:rtype: list[str]
"""
res = []
for t in toks:
if t != " "... | 6f638cffa11417ebe975955b3cd2780a07a4a500 | 40,875 |
def defaultkeys(root):
"""keydefs lezen uit keyboard.txt - mapping maken van deze op ...
vooralsnog alleen omschrijving
"""
data = {}
ky = []
ky_desc = ''
join_keys = False
temp = read_lines(root)
for x in temp[6:]:
x = x.rstrip()
if x == "":
break
... | f68059bd048f6c87e72120cfe5f17169d5993818 | 40,876 |
def _decompose_unit(unit):
"""unit should be a Quantities Dimensionality object
Returns (conversion, base_unit_str)
"""
assert isinstance(unit, pq.dimensionality.Dimensionality)
if len(unit) != 1:
raise NotImplementedError("Compound units not yet supported") # e.g. volt-metre
uq, n = u... | 9e60224e37df19fdba9db2ecf705d3bfe30699cd | 40,878 |
import json
def unknown_method_request():
"""Sample unknwon/invalid method request for testing purposes."""
return json.dumps(
{
"method": "some_random_method",
"params": {},
}
) | 50fcfda030df632a0d1275bcb55c58e2f80e8c6b | 40,880 |
def plot_targets(targets=None, assignments=None, iexp=0,
robots=True, hexagon=True, categories=[],
observatory='apo'):
"""Plot targets in the field
Parameters
----------
targets : ndarray
target information as stored in Field
assignments : ndarray
... | dcd94f98dfe65876ec50f6abf0b5e9123d454c44 | 40,881 |
def python_text(text="is cool"):
"""prints Python is cool"""
text = text.replace("_", " ")
return "Python %s" % text | e63ac18466433973aa4a3fd9f0b7151309c62464 | 40,882 |
def matchesSyntax(line):
""" parses a configuration line and returns whether it conforms to the syntax"""
line = line[1:] # strip leading '+' or '-'
s = line.split()
(ok0, msg0) = matchesPatternSyntax(s[0])
if len(s) < 1 or ok0:
pass
else: return (False, msg0)
(ok1, msg1) = match... | b9ebd090396bd7d63e0d7c2724b8075123e0720c | 40,883 |
def linear_warmup_and_polynomial_decayed_lr(settings, global_step):
""" settings.learning_rate_base
settings.warmup_steps
settings.decay_steps
settings.learning_rate_minimum
settings.lr_power
settings.lr_cycle
"""
learning_rate = tf.constant(value = settings.learning_... | 2e1bb6ad6c015f81f5907041ad379e44346a42cb | 40,884 |
def get_doc_string_generator():
"""Returns the currently registered doc string generator."""
return _generate_doc_string_func | 6b28cea0463b71fa4a5f2a03458c02e5cc6caf27 | 40,885 |
def _dual_bootstrap(variances):
""" helper function to perform the dual bootstrap
Takes a 3x... array of variances and computes the corrections assuming:
variances[0] are the variances in the double bootstrap
variances[1] are the variances in the rdm bootstrap
variances[2] are the variances in the ... | e27353c9bd3804c361bad35709314a160968b7df | 40,886 |
def load_ref_system():
""" Returns l-ascorbic_acid as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
H 0.6888 -1.5618 -0.6197
C 0.3271 -0.5321 -0.3981
O 0.5813 -0.3520 ... | c7e43dec47d33beb6ddbc47c6703697c19783c73 | 40,887 |
def medfilt_along_axis(x, n, axis=-1):
"""Applies median filter smoothing on one axis of an N-dimensional array.
"""
kernel_size = np.array(x.shape)
kernel_size[:] = 1
kernel_size[axis] = n
return medfilt(x, kernel_size) | f6b5d9a64ff7f7fbfcff3a06156998ee574afd52 | 40,888 |
def as_float_array(array: np.ndarray, min_float=np.float32) -> np.ndarray:
"""Convert array to a floating point array."""
array = np.asanyarray(array)
dtype = np.result_type(array, min_float)
return np.asanyarray(array, dtype=dtype) | ce6a9d2d5bbf3eecd61e87b1e64e0e3c64b6454b | 40,889 |
def pcy(series, n=1):
"""Percent change over n years"""
return (series/series.shift(n*series.index.freq.periodicity)-1)*100 | a18bff66c60bf2620f524e104cf0b9842a85acf4 | 40,890 |
def to_eval_str(value):
"""
Returns an eval(str(value)) if the value is not None.
:param value: None or a value that can be converted to a str.
:return: None or str(value)
"""
if isinstance(value, str):
value = eval(str(value))
return value | 4cb13ad95095b8a6ee494265e600f989d98be05e | 40,891 |
def random_weights(w_cnt, op=lambda l: l):
""" Generate random normalized weights
Args:
w_cnt: size of the weight vector
op: additional operation to perform on the generated weight vector
"""
weights = np.random.random(w_cnt)
weights = op(weights)
weights /= np.sum(... | 20fcc4d8a3f18fc34d9b5647f7437a9dfd29a51b | 40,892 |
import string
import random
def get_random_string(size=8, chars=string.ascii_uppercase + string.digits):
"""
Получает случайную строку указанного размера и с указанными символами.
"""
return ''.join(random.SystemRandom().choice(chars) for _ in range(size)) | b546c9a397720d7adef504cb5982c14785038b42 | 40,893 |
def company_denomination_year(denomination, year):
"""
Retrieve company information for a given year by company denomination. Path
is /company/denomination/<string:denomination> GET method only and no strict slash.
:param denomination: String, denomination of the company.
:param year: Year of... | 198ce546a33c5e859a22801ebe24ab1909b999c2 | 40,894 |
from re import A
def TripleDes_Encryption24(data: A, key: A) -> A:
"""
:type key: object
:type data: object
"""
encrypted_data = triple_des(key).encrypt(data, padmode=PAD_PKCS5)
return encrypted_data | a19572b517b64b2e57482ab1cf9aa79f15a00c17 | 40,895 |
from typing import Callable
from typing import Any
def raises(exception: Exception, pattern=None, matching=None) -> Matcher[Callable[..., Any]]:
"""Matches if the called function raised the expected exception.
:param exception: The class of the expected exception
:param pattern: Optional regular expr... | 442bc1a90504e7f5eb6143792f0a1d131d87c9c7 | 40,896 |
def GammaW(tempk, pres):
"""Function to calculate the moist adiabatic lapse rate (deg C/Pa) based
on the environmental temperature and pressure.
INPUTS:
tempk (K)
pres (Pa)
RH (%)
RETURNS:
GammaW: The moist adiabatic lapse rate (Deg C/Pa)
REFERENCE:
http://glossary.ametsoc.org... | 6b8588ca09a72f65261970b69d1f4acf8d56f8e5 | 40,897 |
def np_concatenate(paths):
"""
:param paths: list of paths of .npy arrays
:return c: concatenated array
"""
aa = []
print("\n".join(paths))
for path in paths:
a = np.load(path)
aa.append(a)
pass
c = np.concatenate(aa)
return c | f9d33451b399d370daebe512080fdc29d29564e1 | 40,898 |
from typing import Union
from typing import TextIO
from typing import Iterator
import re
def read_multilayer_svg(
file: Union[str, TextIO],
quantization: float,
crop: bool = True,
simplify: bool = False,
parallel: bool = False,
default_width: float = _DEFAULT_WIDTH,
default_height: float =... | 990b6a321d46e48ca40c28044778d1c77299930a | 40,899 |
def win_path_check(path):
"""
Format a file path correctly for Windows
"""
if IS_WIN:
return path.replace("\\", "/").replace(":", "\\:")
return path | ef338386462af2f38cc2c645c36b02f25be014ff | 40,900 |
from typing import Callable
def signal_or() -> Callable[[int, int], int]:
"""A circuit element performing a bitwise OR on two signals."""
return lambda x, y: limit_signal(x | y) | 1ffceeda3c6d74ed4a433a3eb50cbeff0c5d0aaf | 40,901 |
import requests
def create_github_issue_helper(ctx, issue):
"""Logic for dev command"""
url = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/issues"
headers = dict(Authorization=f"token {GITHUB_PAT}",
Accept="application/vnd.github.v3+json")
data = {
"title": issue,... | 88c9e21a9da4fed67cbe6dba73c2afbf2ec2d648 | 40,902 |
def add_user():
"""
Endpoint to add user
Json passed by POST: ex. { "id": "jibao" }
:return: 201, object created or
409, object already exist
"""
user_id = request.json['id']
obj_created = db_manager.add_user(user_id)
if not obj_created:
abort(409)
return make_re... | 69b25ff7e4cf8724762ec1772fe77e3ab915216a | 40,904 |
def get_report_format(self, filename):
"""各帳票フォーマットの格納場所を取得する。
:param self:
:param filename:
:return:
"""
prefix = 'reports/{}/'.format(self.parking_lot.name)
return prefix + filename | 206804eb32803db12cf8de74b22574f2e94e510e | 40,905 |
def read_float(field: str) -> float:
"""Read a float."""
return float(field) if field != "" else float('nan') | ce6f862c9696e3f84ba20b58a0acdce5c1e212b0 | 40,907 |
from datetime import datetime
def seconds_into_year(now):
"""Compute the number of seconds into the current year.
Args:
now: Current time.
Returns:
Number of seconds since January 1 at midnight on the same year as now.
"""
year_start = datetime.datetime(now.year, 1, 1, 0, 0, 0, tzinf... | 371dcd25cad62a9d769a8145c88c332256625d2e | 40,908 |
def get_available_quantity_for_stock(stock):
"""Count how many stock items are available."""
quantity_allocated = get_quantity_allocated_for_stock(stock)
return max(stock.quantity - quantity_allocated, 0) | f56420858effd12373a42939c7a1a329205506a3 | 40,909 |
def _to_rnn_cell(cell_or_type, num_units, num_layers):
"""Constructs and return an `RNNCell`.
Args:
cell_or_type: Either a string identifying the `RNNCell` type, a subclass of
`RNNCell` or an instance of an `RNNCell`.
num_units: The number of units in the `RNNCell`.
num_layers: The number of laye... | fe5629d6dd525af91b92dcd0c8fcf3a37f5cdf19 | 40,910 |
from typing import List
from typing import Dict
from typing import Counter
def layout_aware_vocabulary_vector(
results: List[Dict],
number_of_words: int,
classification_targets: List[str]
) -> List[str]:
"""Create a layout aware vocabulary vector
Finds the most popular words per l... | 38aa95768863c1ca70a07b43d608a278713b1461 | 40,911 |
def main_menu_bar(widget):
""" Create a main menu bar.
This requires setting `menu_bar=True` in the `concur.integrations.glfw.main` method.
Otherwise, space wouldn't be reserved for the menu bar, and it would lay on top of
window contents.
Main menu bar must be created outside any windows.
Se... | e811ffeeb9cb3cf361e845b79f6f387c6148f64b | 40,912 |
import re
def GetDestFromParam(param, prefix=None):
"""Returns a conventional dest name given param name with optional prefix."""
name = param.replace('-', '_').strip('_')
if prefix:
name = prefix + '_' + name
return resource_property.ConvertToSnakeCase(
re.sub('s?I[Dd]$', '', name)).strip('_') | 7f2274d4bdc322dbc24e3cee252615db37078b18 | 40,913 |
def get_trigger_name(operation, source_table, when):
"""Non-PostgreSQL trigger name"""
op_initial = operation.lower()[0]
when_initial = when.lower()[0]
return f"trigger_{source_table}_{when_initial}{op_initial}r" | 4e67005512fee99dd1bf5ed8b5d979e747d27b9f | 40,914 |
def cycle_graph(n: int) -> Graph:
"""
Construct the unweighted cycle graph on :math:`n` vertices.
:param n: The number of vertices in the graph
:return: The cycle graph on :math:`n` vertices, as a `Graph` object.
:raises ValueError: if the number of vertices is not a positive integer.
:Example... | 37f378c0cf1c13aa33cdec644cfb2c4863d83109 | 40,915 |
def mailing_keyboard(mailing_status, notification_status, language_code):
"""Make keyboard for mailing parameters"""
keyboard = [
[
# buttons names and callback according to current states
make_button(
(buttons.ALLOW_MAILING
if mailing_status == c... | 1127179bfb2155c165374db8560d7fc79110e2c2 | 40,917 |
def calculate_fold_change(reads, normalized_counts, control_samples, treatment_samples, pseudocount, replicate):
"""
Create a dataframe with index as guide ids
Calculate log2 ratio (foldchange) between treated and control reads
:param reads: Dataframe containing read counts (guide level)
:param norm... | 2f92d7afd3f8738a4d911bf4cd64db7b8898bdac | 40,918 |
import functools
import asyncio
def wrap_coroutine(func, event_loop, before_test):
"""Return a sync wrapper around an async function to be executed in the event loop."""
@functools.wraps(func)
def inner(**kwargs):
if before_test is not None:
before_test()
coro = func(**kwargs)
... | 1ddc4bc70a2def3ce989b1fdc44262bcdb0e35f8 | 40,919 |
def get_deprt(lista):
"""Add together from row with same index."""
base = []
for item in lista:
base.append(item)
resultado = set(base)
return resultado | ecc3026d7674fcd90100db7d0b82cbc4376f1e4e | 40,920 |
def get_events_with_abstract_reviewer_convener(user, dt=None):
"""
Return a dict of event ids and the abstract reviewing related
roles the user has in that event.
:param user: A `User`
:param dt: Only include events taking place on/after that date
"""
data = defaultdict(set)
# global re... | 84274d5e93ff3183d9f4a1348492e91ea24f6fef | 40,922 |
def h5gr_to_workup_input(gr, format):
"""Return a dictionary containing important parameters for working up a phasekick
dataset.
The dictionary contains:
y: Cantilever oscillation data
dt: spacing between
t0: Initial time
t1: Time with V = V_1
t2: Time wit... | 0b89955de12922805558bd55da49c2bdbe564618 | 40,923 |
import contextlib
def colocation_cm(colocation, name=None, op=None):
"""Gets a context manager to colocate ops."""
if colocation:
return tf.colocate_with(tf.no_op(name) if op is None else op)
return contextlib.suppress() | eaab7ad7f8fba9bd25d2af028a4afc371c4cbedb | 40,924 |
def inverse_helper_col_row_multiply(matrix, i, j, value):
"""Helper to multiply matrix with identity matrix having replaced value.
Args:
matrix: A matrix (list of lists).
i: A column index.
j: A row index.
value: A value to place at the given row/column.
Returns:
A ... | 559ea43939b9d78b73c4ac718a26e9d897775b29 | 40,925 |
def get_dummy_image_name():
"""
Returns the name of the dummy image
"""
return "python-logo.jpeg" | 0a3a3664d06449641eb5ca32e03edd64d31eb63b | 40,926 |
def s(*args, **kwargs):
"""
Create a RedisCluster instance with 'init_slot_cache' set to false
"""
s = _get_client(RedisCluster, init_slot_cache=False, **kwargs)
assert s.connection_pool.nodes.slots == {}
assert s.connection_pool.nodes.nodes == {}
return s | b3975a6b65798fc33080ec138c8f5ad406e592e1 | 40,928 |
def svd_thresh(input_data, threshold=None, n_pc=None, thresh_type='hard'):
"""Threshold the singular values.
This method thresholds the input data using singular value decomposition.
Parameters
----------
input_data : numpy.ndarray
Input data array, 2D matrix
threshold : float or numpy... | 8b897b0fccb150138f9b95824e0c26258b5a2d73 | 40,929 |
import base64
def decode_image(field):
"""Decode a base64 encoded image to a list of floats.
Args:
field: base64 encoded string
Returns:
numpy.array
"""
array = np.frombuffer(base64.b64decode(field), dtype=np.uint8)
image_array = cv2.imdecode(array, cv2.IMREAD_ANYCOLOR) # BGR
... | 939dfb7658eb8a41757bf855c2e5388f6b8162ba | 40,930 |
def compute_layer_style_cost(a_S, a_G):
"""
Arguments:
a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S
a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G
Returns:
J_style_layer... | 5210fa06e6145fd864adc6b6733e397114947c75 | 40,931 |
def check_punctuation(words):
"""Check to see if there's a period in the sentence."""
punctuation = [".", ",", "?"]
return [word for word in words if word in punctuation] | 4de89db149924ae3d457e57a3f9edac5dd4ae18a | 40,932 |
def log_users():
"""
API for authentication microservice.
Creates an entry to be stored temporarily in a global dictionary. '''
"""
global logged_in_users_flag
# Receive response from Authenticate microservice
new_user = request.json
logged_in_users_flag[new_user[0]] = new_u... | 04c529737eeb47d3d276e36bd8d7dea9733465e8 | 40,933 |
def _GetIngressChanges(args):
"""Returns changes to ingress traffic allowed based on the flags."""
platform = platforms.GetPlatform()
if platform == platforms.PLATFORM_MANAGED:
return config_changes.SetAnnotationChange(service.INGRESS_ANNOTATION,
args.ingress)
e... | 6b22ae1b0b9642072cd69c4419b1036cb35fd08f | 40,934 |
def get_page(page_number: int,
cards: str,
page_template: str,
section_template: str,
contexts: list,
is_card_backs: bool=False,
is_filler: bool=False,
exclude_section: bool=False) -> str:
""" Populate a page with cards. """
... | 37b238fdd7dfe6c257ae3729db1660134318a311 | 40,936 |
def prepare_updates_dict(updates):
"""
Prepare a Theano `updates` dictionary.
Ensure that both keys and values are valid entries.
NB, this function is heavily coupled with its clients, and not intended for
general use..
"""
def prepare_key(key, val):
if not isinstance(key, SharedVa... | c8f8c829cc7608a06d63aced4cadd3278447ddeb | 40,937 |
def get_label_conf(y_vec):
"""
Returns the confidence and the label of the most probable class given a vector of class confidences
:param y_vec: (np.ndarray) vector of class confidences, nb of instances as first dimension
:return: (np.ndarray, np.ndarray) confidences and labels
"""
assert len(y_... | b5205cee207451eb6bd897657ab23bd3bbaf035c | 40,939 |
def unique_rows_tol(data, tol=1e-12, return_index=False, return_inverse=False):
"""
This function returns the unique rows of the input matrix within that are within the
specified tolerance.
Parameters
----------
data: numpy array (m x n)
tol: double
tolerance of comparison for each ... | 11223616645f56199c40f8a71ad5f20283636b84 | 40,940 |
def transformed_retrace(
q_tm1: ArrayLike,
q_t: ArrayLike,
a_tm1: ArrayLike,
a_t: ArrayLike,
r_t: ArrayLike,
discount_t: ArrayLike,
pi_t: ArrayLike,
mu_t: ArrayLike,
lambda_: float,
eps: float = 1e-8,
stop_target_gradients: bool = True,
tx_pair: TxPair = IDENTITY_PAIR,
) ... | 50390be415af3d45bb5220ccd2ddefd21ca7916d | 40,941 |
def api_all_feeds(request):
""" This views to retreive feeds
"""
if request.is_ajax():
return JsonResponse(get_feeds()) | 92287f3d1cf9da484c8734eb634728f48bfde0c8 | 40,942 |
import requests
import time
def get_clip_info(clip_id, user):
"""Use given clip id to fetch info from Twitch API."""
# Note: Twitch recommends giving the API 15 seconds to fetch a newly
# created clip. If 15 seconds passes and we receive nothing, we can
# assume that no clip was created.
failures... | 341075ed180b5e241f6a7f278aade55276fcb2e2 | 40,944 |
import torch
def Accuarcy_find(pred, tar, device):
"""
This function calculates the the accuarcy and confussion matrix
"""
if device == "cpu":
ft = torch.FloatTensor
else:
ft = torch.cuda.FloatTensor
tar = tar.view(-1, tar.shape[-1])
art_pred = pred[:, 1] >= 0.5 # what the... | 83e1d5825360afaa549835cecd6b1d85665311f1 | 40,945 |
def resolve_ipv6(name, flags=0):
"""Lookup an AAAA record for a given *name*.
To disable searching for this query, set *flags* to ``QUERY_NO_SEARCH``.
Returns (ttl, list of packed IPs).
"""
waiter = Waiter()
core.dns_resolve_ipv6(name, flags, waiter.switch_args)
result, _type, ttl, addrs = ... | 2aad1a3d77cfd08e11f898626cfc700c596be3a7 | 40,946 |
from typing import Optional
def knn_assigned_text_sectors(
run: Optional[Run] = None,
clustered: bool = True,
):
"""the text sectors of the K nearest neighbours after reassignment"""
run = run or get_run("ClusterReassignFlow")
if clustered:
return run.data.knn_assigned_text_sectors
els... | 1dbd82b838f3986246eec8b0b2b1cc1dced2c2cd | 40,947 |
import array
from operator import inv
def arma_forecast(time_series, phis=array([]), thetas=array([]), mu=0.,
sigma=1., future_periods=20):
"""
Return forecasts for a time series modeled with the given ARMA model.
Parameters
----------
time_series : ndarray of shape (n,1)
The ... | f525551193f2f9f3055cd4ab2e19309aaea257ed | 40,949 |
def sign_assertion(root, cert1, cert2, key):
"""Sign the SAML assertion in the response using the IdP key"""
try:
print('[*] Signing the SAML assertion')
assertion_id = root.find("{urn:oasis:names:tc:SAML:2.0:assertion}Assertion").get("ID")
signer = XMLSigner(c14n_algorithm="http://www.w... | 51f5b6d4383248a180b9ef05bc82dd91209c776a | 40,950 |
def poweriter(A,numiter):
"""
poweriter(A,numiter)
Perform `numiter` power iterations with the matrix `A`, starting from a random vector, and return a vector of eigenvalue estimates and the final eigenvector approximation.
"""
n = A.shape[0]
x = randn(n)
x = x/norm(x,Inf)
gamma = zeros(numiter)
for k in range... | d838678e51c4b220312d96b557157dacef092b32 | 40,951 |
import itertools
def opendata_postal_codes_v1(db):
"""
API v1 data postal codes route.
Example::
GET /api/v1/opendata/postal_codes
.. note::
Filtering can be done through the ``filter`` GET param, according
to JSON API spec (http://jsonapi.org/recommendations/#filtering).
... | a22f9db460edb71da5d9c81d18b1ba25f0074a31 | 40,952 |
def get_valid_group(id, name):
""" Returns a valid group object """
group = Group()
group.id = id
group.name = name
return group | bdca0f5f019dab318244510405d16527930a1e50 | 40,953 |
def svn_repos_authz_check_access(*args):
"""
svn_repos_authz_check_access(svn_authz_t authz, char repos_name, char path, char user,
svn_repos_authz_access_t required_access,
apr_pool_t pool) -> svn_error_t
"""
return _repos.svn_repos_authz_check_access(*args) | 9aa1295a4e8794a35afca8d9143862bfa151d482 | 40,954 |
def mark_for_testing(**kwargs):
"""Mark module for testing."""
def decorator(cls):
_MARKED_CLASSES.append(MarkedClass(cls, **kwargs))
return cls
return decorator | 9ab69a2899efd940fda600d25494a27cfd4b45d0 | 40,955 |
def load_ref_system():
""" Returns propane as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
H 1.9131 -0.1215 1.0479
C 1.2683 -0.0636 0.1619
H 1.5702 0.8259 -0.4068... | dbc076a7ede811be956af3f2037c6885e442eee1 | 40,956 |
import calendar
from datetime import datetime
def make_test_time_old() -> context.Time:
"""Generates unix timestamp for an old date."""
return test_context.TestTime(calendar.timegm(datetime.date(1970, 1, 1).timetuple())) | eb8b2a78f25be93d433489c9bc1bbd7b3e93ba80 | 40,957 |
def get_stream_inventory_report_link_for_region(point: Point):
""" Returns Fish Inventory Data Query (FIDQ) links for streams within this
watershed area.
"""
point_3005 = transform(transform_4326_3005, point)
# look up region that this point is in
cql_filter = f"""INTERSECTS(SHAPE, {point_3... | e96584aac8f70745244d342836f9f885de644889 | 40,958 |
def baymodel_data_with_missing_flavor():
"""Generates random baymodel data with missing flavor
:returns: BayModelEntity with generated data
"""
return baymodel_data(keypair_id=config.Config.keypair_id,
image_id=config.Config.image_id) | 094e3f1e24299275b33fadbe4f7566a62d2a624c | 40,959 |
def run_intcode(memory, input_list, instr_ptr=0, input_ptr=0, previous_output=None):
"""Run an Intcode program from memory"""
output = previous_output
while instr_ptr < len(memory):
instruction = memory[instr_ptr]
digits = list_digits(instruction)
# extract opcode
opcode_pai... | 5651ff72dd502145f45688425e4e952051eeb5e5 | 40,960 |
from typing import Optional
def get_engine_sampler(processor_id: str, gate_set_name: str,
project_id: Optional[str] = None) \
-> 'cirq.google.QuantumEngineSampler':
"""Get an EngineSampler assuming some sensible defaults.
This uses the environment variable GOOGLE_CLOUD_PROJECT ... | 3aa2fc89ee2c8800ae6d0e16331b6432cc5bd429 | 40,961 |
import random
def frequency_sampling_paragraph(thief_vocab, thief_probs, para_len=None):
"""Sample words according to a unigram frequency to build a paragraph."""
if para_len is None:
# randomly choose a length from 75 to 500
para_len = np.random.randint(75, 500)
assert len(thief_probs) == len(thief_voc... | de76270092d951b7c4aaeb0f999569b4e76e6978 | 40,962 |
import csv
def cast_cadastro_cliente():
"""
Função que acessa os itens do arquivo bd_cliente_rotativo em modo read e,
faz o append dos dados para a lista_cadastro para iteração.
:return: Condição que informa que não existe nenhum veiculo cadastrada para iterar
"""
try:
with open('bd_c... | 23ee1b504343eba1e2b0f775f6690ff919de9b99 | 40,963 |
def generate_pool_name(**kwargs):
"""Generate a pool name.
This function takes keyword arguments, usually the connection arguments and
tries to generate a name for the pool.
Args:
**kwargs: Arbitrary keyword arguments with the connection arguments.
Raises:
PoolError: If the name c... | e03d7daf92a4b810753cad9eb5943d58e68b6423 | 40,964 |
def cluster_domain_DBScan(
x: np.ndarray,
y: np.ndarray,
time: np.ndarray,
) -> np.ndarray:
"""
return the cluster ID based on the given data using DBScan
@param x: event position x vector
@param y: event position y vector
@param time: event TOA vector
@returns: clustering results
... | 29d3ad8ccad1189326b31ad33acfdfc1a84dcbeb | 40,965 |
def retrofit_neural(X, in_edges, out_edges, k=5, n_iter=100, alpha=None,
beta=None, tol=1e-2, lr=0.5, lam=1e-5, verbose=0,
lr_decay=0.9, batch_size=32, patience=20):
""" Retrofit according to the neural penalty function.
Parameters
----------
X : np.arra... | 1945c80390aedc0c5e94c41cd9eac89b1507f0c0 | 40,966 |
def fake_create_test_db(self, verbosity=1, autoclobber=False):
"""Simplified version of BaseDatabaseCreation.create_test_db."""
test_database_name = self._get_test_db_name()
if verbosity >= 1:
test_db_repr = ''
if verbosity >= 2:
test_db_repr = " ('%s')" % test_database_name
... | cc63a9e2075451cc314b4ef497299b2b7e490c4c | 40,967 |
def value_from_choices_label(label, choices):
"""
Return the choices value for a given label
"""
# Search choices by label
result = None
for choices_value, choices_label in choices:
if label == choices_label:
result = choices_value
# If search by label failed, check if we... | 52dee6ae49adb1e10a7453009fdf29e07dd1ab82 | 40,968 |
def find_nearest_kp_2d(pcl2d, kps2d):
"""
find nearest 2d distance keypoint for every point in pcl.
:param pcl2d: [N,2] N points' xyz
:param kps2d: [K,2] K points' xyz
:return: nearest_kps2d [N,2] Nearest keypoint coordinate of every points.
"""
N, _ = pcl2d.shape
K, _ = kps2d.shape
... | 8d0f0cae1157e2dacef79238077dbcef919f2892 | 40,969 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.