content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_flavors():
""" Get Nectar vm flavors in a dict with openstack_id as key """
fls = Flavor.query.all()
results = []
for fl in fls:
results.append(repack(fl.json(), {"name": "flavor_name"}, ["id"]))
return array_to_dict(results) | 005ce92fa46689ea639594fd5341f327dc04704d | 3,658,139 |
def _HasTrafficChanges(args):
"""True iff any of the traffic flags are set."""
traffic_flags = ['to_revision', 'to_latest']
return _HasChanges(args, traffic_flags) | 3d638195f86dc9f383c01c92d475ca90dc4fa60b | 3,658,140 |
def find_credentials(account):
"""
fumction that check if a credentials exists with that username and return true or false
"""
return Credentials.find_credentialls(account) | dc59eec797d606854fa8a668b234a5eb61f8a0f8 | 3,658,141 |
import tokenize
def enumerate_imports(tokens):
"""
Iterates over *tokens* and returns a list of all imported modules.
.. note:: This ignores imports using the 'as' and 'from' keywords.
"""
imported_modules = []
import_line = False
from_import = False
for index, tok in enumerate(tokens... | 0ee4921455899b036eb808262e183a6bc9017ccc | 3,658,142 |
import re
def safe_htcondor_attribute(attribute: str) -> str:
"""Convert input attribute name into a valid HTCondor attribute name
HTCondor ClassAd attribute names consist only of alphanumeric characters or
underscores. It is not clearly documented, but the alphanumeric characters
are probably restr... | 7a4dda539b2379120e68737d72a80226c45f5602 | 3,658,144 |
def focal_length_to_fov(focal_length, length):
"""Convert focal length to field-of-view (given length of screen)"""
fov = 2 * np.arctan(length / (2 * focal_length))
return fov | 2803de559943ce84620ac1130c099438ec1b4b12 | 3,658,145 |
def make_csv(headers, data):
"""
Creates a CSV given a set of headers and a list of database query results
:param headers: A list containg the first row of the CSV
:param data: The list of query results from the Database
:returns: A str containing a csv of the query results
"""
# Create a list where each entr... | 5101d53de8dd09d8ebe743d77d71bff9aeb26334 | 3,658,147 |
def draw_color_rect(buf,ix,iy,size,wrect,color):
"""
draw a square centerd on x,y filled with color
"""
code = """
int nd = %d;
int x, y, i, j;
int ny = 1 + 2 * nd;
int nx = ny;
y = iy - nd;
if (y < 0) {
ny += y;
y = 0;
} else
if ((y + ny) > dimy) ny -= y + ny - dimy;
x = ix - nd;
if (x < 0) {
... | 822bc77d1e6ccb4c802a4a3335c1bba55ba14f04 | 3,658,148 |
def _compute_focus_2d(image_2d, kernel_size):
"""Compute a pixel-wise focus metric for a 2-d image.
Parameters
----------
image_2d : np.ndarray, np.float
A 2-d image with shape (y, x).
kernel_size : int
The size of the square used to define the neighborhood of each pixel.
An... | 67b139fdef8b6501a64699344d80b19012876f86 | 3,658,149 |
from typing import Tuple
def extract_value_from_config(
config: dict,
keys: Tuple[str, ...],
):
"""
Traverse a config dictionary to get some hyper-parameter's value.
Parameters
----------
config
A config dictionary.
keys
The possible names of a hyper-parameter.... | d545d4c9298c74776ec52fb6b2c8d54d0e653489 | 3,658,150 |
import numpy
def boundaryStats(a):
"""
Returns the minimum and maximum values of a only on the boundaries of the array.
"""
amin = numpy.amin(a[0,:])
amin = min(amin, numpy.amin(a[1:,-1]))
amin = min(amin, numpy.amin(a[-1,:-1]))
amin = min(amin, numpy.amin(a[1:-1,0]))
amax = numpy.amax(a[0,:])
amax ... | 6c007c6cf2c7c5774ca74365be8f63094864d962 | 3,658,151 |
from operator import add
def offset_func(func, offset, *args):
""" Offsets inputs by offset
>>> double = lambda x: x * 2
>>> f = offset_func(double, (10,))
>>> f(1)
22
>>> f(300)
620
"""
def _offset(*args):
args2 = list(map(add, args, offset))
return func(*args2)
... | 16526bc8302444a97ea27eb6088fe15604d3cf9e | 3,658,152 |
def get_redshift_schemas(cursor, user):
"""
Get all the Amazon Redshift schemas on which the user has create permissions
"""
get_schemas_sql = "SELECT s.schemaname " \
"FROM pg_user u " \
"CROSS JOIN " \
"(SELECT DISTINCT schemaname FROM ... | 2833205f3e1b863fe8e5a18da723cf1676a65485 | 3,658,153 |
def window_features(idx, window_size=100, overlap=10):
""" Generate indexes for a sliding window with overlap
:param array idx: The indexes that need to be windowed.
:param int window_size: The size of the window.
:param int overlap: How much should each window overlap.
:return arr... | e10caae55424134a95c2085e5f54f73d81697e92 | 3,658,154 |
from datetime import datetime
def create_suburbans_answer(from_code, to_code, for_date, limit=3):
"""
Creates yandex suburbans answer for date by stations codes
:param from_code: `from` yandex station code
:type from_code: str
:param to_code: `to` yandex station code
:type to_code: str
:p... | 47b34617fdcd9fe83d1c0973c420363c05b9f70c | 3,658,156 |
def update_user(usr):
"""
Update user and return new data
:param usr:
:return object:
"""
user = session.query(User).filter_by(id=usr['uid']).first()
user.username = usr['username']
user.first_name = usr['first_name']
user.last_name = usr['last_name']
user.email = usr['email']
... | d6c078c966443c609c29bb4ee046612c748bb192 | 3,658,157 |
from datetime import datetime
def get_data(date_from=None, date_to=None, location=None):
"""Get covid data
Retrieve covid data in pandas dataframe format
with the time periods and countries provided.
Parameters
----------
date_from : str, optional
Start date of the data range with for... | 14067432e5b6d51b60312707cc817acbe904ef0b | 3,658,158 |
from typing import List
from typing import Dict
from typing import Any
def group_by_lambda(array: List[dict], func: GroupFunc) -> Dict[Any, List[dict]]:
"""
Convert list of objects to dict of list of object when key of dict is generated by func.
Example::
grouped = group_by_lambda(detections, lamb... | a92733a21b5e6e932be6d95ff79939ca26e3d429 | 3,658,159 |
def update(isamAppliance, is_primary, interface, remote, port, health_check_interval,
health_check_timeout, check_mode=False, force=False):
"""
Updating HA configuration
"""
# Call to check function to see if configuration already exist
update_required = _check_enable(isamAppliance, is_pr... | b4da64648a46e30e7220d308266e4c4cc68e25ff | 3,658,160 |
import scipy
import numpy
def compare_images(image_file_name1, image_file_name2, no_print=True):
""" Compare two images by calculating Manhattan and Zero norms """
# Source: http://stackoverflow.com/questions/189943/
# how-can-i-quantify-difference-between-two-images
img1 = imread(image_file_name1).as... | c554750ae94b5925d283e0a9d8ff198e51abe29b | 3,658,161 |
def prepare_update_mutation_classes():
"""
Here it's preparing actual mutation classes for each model.
:return: A tuple of all mutation classes
"""
_models = get_enabled_app_models()
_classes = []
for m in _models:
_attrs = prepare_update_mutation_class_attributes(model=m)
# ... | 27e450ea81000e81ebbf33db5d860c9a6b0adb23 | 3,658,162 |
def vision_matched_template_get_pose(template_match):
"""
Get the pose of a previously detected template match. Use list operations
to get specific entries, otherwise returns value of first entry.
Parameters:
template_match (List[MatchedTemplate3D] or MatchedTemplate3D): The template match(s)
... | b854da7a085934f4f3aba510e76852fb8c0a440a | 3,658,164 |
def create_rotor(model, ring_setting=0):
"""Factory function to create and return a rotor of the given model name."""
if model in ROTORS:
data = ROTORS[model]
return Rotor(model, data['wiring'], ring_setting, data['stepping'])
raise RotorError("Unknown rotor type: %s" % model) | 193ab444c8b5527360498cb1c8911194f04742a3 | 3,658,165 |
def compute_ess(samples):
"""Compute an estimate of the effective sample size (ESS).
See the [Stan
manual](https://mc-stan.org/docs/2_18/reference-manual/effective-sample-size-section.html)
for a definition of the effective sample size in the context of MCMC.
Args:
samples: Tensor, vector (n,), float32 ... | 8330c4f6efb4b23c5a25be18d29c07e946731716 | 3,658,167 |
import time
def uptime():
"""Returns uptime in milliseconds, starting at first call"""
if not hasattr(uptime, "t0") is None:
uptime.t0 = time.time()
return int((time.time() - uptime.t0)*1000) | ff8dbe459cf7f349741cc8ac85b12e4d1dd88135 | 3,658,168 |
def load_plot(axis, plot, x_vals, y1=None, y2=None, y3=None, y4=None,
title="", xlab="", ylab="", ltype=[1, 1, 1, 1],
marker=['g-', 'r-', 'b-', 'k--']):
"""
Function to load the matplotlib plots.
:param matplotlib.Axis axis: the matplotlib axis object.
:param matplotlib.Figu... | ad7499f357349fde12537c6ceeb061bf6163709d | 3,658,169 |
def _optimize_loop_axis(dim):
"""
Chooses kernel parameters including CUDA block size, grid size, and
number of elements to compute per thread for the loop axis. The loop
axis is the axis of the tensor for which a thread can compute multiple
outputs. Uses a simple heuristic which tries to get at lea... | 8f3e77cc772dcf848de76328832c0546a68c1f09 | 3,658,170 |
def no_zero(t):
"""
This function replaces all zeros in a tensor with ones.
This allows us to take the logarithm and then sum over all values in the matrix.
Args:
t: tensor to be replaced
returns:
t: tensor with ones instead of zeros.
"""
t[t==0] = 1.
return t | 8119d1859dc8b248f5bb09b7cc0fc3b492d9b7bd | 3,658,171 |
def php_implode(*args):
"""
>>> array = Array('lastname', 'email', 'phone')
>>> php_implode(",", array)
'lastname,email,phone'
>>> php_implode('hello', Array())
''
"""
if len(args) == 1:
assert isinstance(args, list)
return "".join(args)
assert len(args) == 2
as... | 6f7c49ed340610c290d534a0c0edccd920a1e46e | 3,658,172 |
import math
def make_incompressible(velocity: Grid,
domain: Domain,
obstacles: tuple or list = (),
solve_params: math.LinearSolve = math.LinearSolve(None, 1e-3),
pressure_guess: CenteredGrid = None):
"""
Projects t... | 73904675b5d0c5b74bd13c029b52f7a6592eddac | 3,658,173 |
def get_y_generator_method(x_axis, y_axis):
"""Return the y-value generator method for the given x-axis.
Arguments:
x_axis -- an instance of an XAxis class
y_axis -- an instance of a YAxis class
Returns:
A reference to the y-value generator if it was found, and otherwise None.
"""
try:
method_name = AXIS_... | ab0f43743c91cfe9f51e8da3fe976f8c554af5c8 | 3,658,177 |
def generate_filename(table_type, table_format):
"""Generate the table's filename given its type and file format."""
ext = TABLE_FORMATS[table_format]
return f'EIA_MER_{table_type}.{ext}' | 076ef1e77cf4ec3c1be4fb602e5a1972eb75e826 | 3,658,178 |
def rescale_coords(df,session_epochs,maze_size_cm):
"""
rescale xy coordinates of each epoch into cm
note: automatically detects linear track by x to y ratio
input:
df: [ts,x,y] pandas data frame
session_epochs: nelpy epoch class with epoch times
mazesize: list with size of ... | 49da12dca1e3b7e30bf909a73505a129941bd3db | 3,658,179 |
def get_vocabulary(query_tree):
"""Extracts the normalized search terms from the leaf nodes of a parsed
query to construct the vocabulary for the text vectorization.
Arguments
---------
query_tree: pythonds.trees.BinaryTree
The binary tree object representing a parsed search query. Each lea... | bd03f4894cd3f9a7964196bfb163335f84a048d7 | 3,658,181 |
def pubkey_to_address(pubkey):
"""Convert a public key (in hex) to a Bitcoin address"""
return bin_to_b58check(hash_160(changebase(pubkey, 16, 256))) | bbfbe40346681a12d8b71ce8df6ef8670eb3e424 | 3,658,182 |
def find_point_in_section_list(point, section_list):
"""Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 3... | 47d5cda15b140ba8505ee658fd46ab090b2fda8a | 3,658,184 |
def all_reduce_sum(t, dim):
"""Like reduce_sum, but broadcasts sum out to every entry in reduced dim."""
t_shape = t.get_shape()
rank = t.get_shape().ndims
return tf.tile(
tf.expand_dims(tf.reduce_sum(t, dim), dim),
[1] * dim + [t_shape[dim].value] + [1] * (rank - dim - 1)) | c4048c308ccf2b7550e125b63911183d097959f5 | 3,658,187 |
def get_deltas_from_bboxes_and_landmarks(prior_boxes, bboxes_and_landmarks):
"""Calculating bounding box and landmark deltas for given ground truth boxes and landmarks.
inputs:
prior_boxes = (total_bboxes, [center_x, center_y, width, height])
bboxes_and_landmarks = (batch_size, total_bboxes, [y1... | 4945723b431657b643ef8799eeabacf0a745b8d2 | 3,658,188 |
def choose(population, sample):
"""
Returns ``population`` choose ``sample``, given
by: n! / k!(n-k)!, where n == ``population`` and
k == ``sample``.
"""
if sample > population:
return 0
s = max(sample, population - sample)
assert s <= population
assert population > -1
i... | 659eac683cae737888df74c0db21aa3ece746b33 | 3,658,189 |
def _where_cross(data,threshold):
"""return a list of Is where the data first crosses above threshold."""
Is=np.where(data>threshold)[0]
Is=np.concatenate(([0],Is))
Ds=Is[:-1]-Is[1:]+1
return Is[np.where(Ds)[0]+1] | 85fe8da97210e2eb7e3c9bca7074f0b0b88c425a | 3,658,190 |
import csv
def TVD_to_MD(well,TVD):
"""It returns the measure depth position for a well based on a true vertical depth
Parameters
----------
well : str
Selected well
TVD : float
Desire true vertical depth
Returns
-------
float
MD : measure depth
Attention
---------
The input information comes ... | eadca9f9e5ae22fc7a6d9d31f7f0ee7ba4c26be4 | 3,658,191 |
def get_table_b_2_b():
"""表 B.2 居住人数 2 人における照明設備の使用時間率 (b) 休日在宅
Args:
Returns:
list: 表 B.2 居住人数 2 人における照明設備の使用時間率 (b) 休日在宅
"""
table_b_2_b = [
(0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00),
(0.00, 0.00, 0.0... | 06d29050c0bc61170eeddc75be76fe8bb8422edd | 3,658,192 |
def eea(m, n):
"""
Compute numbers a, b such that a*m + b*n = gcd(m, n)
using the Extended Euclidean algorithm.
"""
p, q, r, s = 1, 0, 0, 1
while n != 0:
k = m // n
m, n, p, q, r, s = n, m - k*n, q, p - k*q, s, r - k*s
return (p, r) | 56e1c59ac3a51e26d416fe5c65cf6612dbe56b8c | 3,658,193 |
def arcball_constrain_to_axis(point, axis):
"""Return sphere point perpendicular to axis."""
v = np.array(point, dtype=np.float64, copy=True)
a = np.array(axis, dtype=np.float64, copy=True)
v -= a * np.dot(a, v) # on plane
n = vector_norm(v)
if n > _EPS:
if v[2] < 0.0:
v *= ... | a58a80dd29ba785bd829b33ccb283e7c42993218 | 3,658,195 |
from typing import Mapping
from typing import Any
from typing import MutableMapping
def text(
node: "RenderTreeNode",
renderer_funcs: Mapping[str, RendererFunc],
options: Mapping[str, Any],
env: MutableMapping,
) -> str:
"""Process a text token.
Text should always be a child of an inline toke... | 21b39fcdd21cba692a185e4de2c6f648c210e54b | 3,658,196 |
def patch_importlib_util_find_spec(name,package=None):
"""
function used to temporarily redirect search for loaders
to hickle_loader directory in test directory for testing
loading of new loaders
"""
return find_spec("hickle.tests." + name.replace('.','_',1),package) | 7a0082c0af92b4d79a93ae6bbd6d1be6ec0ec357 | 3,658,197 |
def format_msg_controller(data):
"""Prints a formatted message from a controller
:param data: The bytes from the controller message
:type data: bytes
"""
return format_message(data, 13, "Controller") | 4d1f262fd673eb3948fbc46866931ab6bd7205ee | 3,658,198 |
def initialize_window(icon, title, width,
height, graphical): # pragma: no cover
"""
Initialise l'environnement graphique et la fenêtre.
Parameters
----------
icon : Surface
Icone de la fenêtre
title : str
Nom de la fenêtre
width : int
Largeur ... | dbc15729b0cb9548ff229ac69dd5d1f2e76c85e5 | 3,658,199 |
def get_contour_verts(cn):
"""unpack the SVM contour values"""
contours = []
# for each contour line
for cc in cn.collections:
paths = []
# for each separate section of the contour line
for pp in cc.get_paths():
xy = []
# for each segment of that section
... | 93dc98e758aca4390adf75afa7ef9bede2d2ac1a | 3,658,200 |
def _compute_covariances(precisions_chol):
"""Compute covariancess from Cholesky decomposition of the precision matrices.
Parameters
----------
precisions_chol : array-like, shape (n_components, n_features, n_features)
The Cholesky decomposition of the sample precisions.
Returns
------... | 4268a807ed2d6a61e69bd2f07ebbdbf332e030da | 3,658,202 |
def rad2deg(angle):
"""
Convert radian to degree.
Parameters
----------
angle : float
Angle in radians
Returns
-------
degree : float
Angle in degrees
"""
return (180./PI) * angle | dea3270a96cf82bb136ce4f6e873617245a4bac3 | 3,658,203 |
import csv
def parse_kinetics_splits(level):
"""Parse Kinetics-400 dataset into "train", "val", "test" splits.
Args:
level (int): Directory level of data. 1 for the single-level directory,
2 for the two-level directory.
Returns:
list: "train", "val", "test" splits of Kinetics... | ee2521919f9f9c3f499cd28bc6003528eb402d2b | 3,658,204 |
def rotateContoursAbout(contours, about, degrees=90, ccw=True):
"""\
Rotate the given contours the given number of degrees about the point about
in a clockwise or counter-clockwise direction.
"""
rt = Transform.rotationAbout(about, degrees, ccw)
return rt.applyToContours(contours) | c929a8c412f4b3fe9b70c21dde62b0672f575abc | 3,658,205 |
import torch
def coordinate_addition(v, b, h, w, A, B, psize):
"""
Shape:
Input: (b, H*W*A, B, P*P)
Output: (b, H*W*A, B, P*P)
"""
assert h == w
v = v.view(b, h, w, A, B, psize)
coor = torch.arange(h, dtype=torch.float32) / h
coor_h = torch.cuda.FloatTens... | 9eeb906539a61b887216c59faf3ac2928e999d6c | 3,658,206 |
import uuid
def ticket() -> str:
"""生成请求饿百接口所需的ticket参数"""
return str(uuid.uuid1()).upper() | aaf1135d6ef5e61aa65960c5c38007848cbd0b17 | 3,658,207 |
def create_WchainCNOT_layered_ansatz(qc: qiskit.QuantumCircuit,
thetas: np.ndarray,
num_layers: int = 1):
"""Create WchainCNOT layered ansatz
Args:
- qc (qiskit.QuantumCircuit): init circuit
- thetas (np.ndarray): parameters
... | 488950214a26cdcf1812524511561d19baa9dfc9 | 3,658,208 |
import itertools
def birth_brander():
""" This pipeline operator will add or update a "birth" attribute for
passing individuals.
If the individual already has a birth, just let it float by with the
original value. If it doesn't, assign the individual the current birth
ID, and then increment the ... | dd2c1ef2e9ac2f56436e10829ca9c0685439ce6d | 3,658,209 |
def random_fit_nonnegative(values, n):
"""
Generates n random values using a normal distribution fitted from values used as argument.
Returns only non-negative values.
:param values: array/list to use as model fot the random data
:param n: number of random elements to return
:returns: an array o... | 9591b87b36c668681873fda1969d1710e7a2dd8b | 3,658,211 |
def channel_values(channel_freqs, channel_samples, dt, t):
"""Computes value of channels with given frequencies, samples, sample size and current time.
Args:
channel_freqs (array): 1d array of channel frequencies
channel_samples (array): 2d array of channel samples, the first index being time s... | cdc555a5ab2d21c0dba71f2f24386144796898c1 | 3,658,213 |
def get_small_corpus(num=10000):
"""
获取小型文本库,用于调试网络模型
:param num: 文本库前n/2条对联
:return: 默认返回前500条对联(1000句话)的list
"""
list = getFile('/total_list.json')
return list[:num] | 032ea34eaa6b5e1478e3770c91fa3da3214d907b | 3,658,215 |
from tqdm import tqdm_notebook
def groupby_apply2(df_1, df_2, cols, f, tqdn=True):
"""Apply a function `f` that takes two dataframes and returns a dataframe.
Groups inputs by `cols`, evaluates for each group, and concatenates the result.
"""
d_1 = {k: v for k,v in df_1.groupby(cols)}
d_2 = {k: v ... | 082ce61477c116ac421ab086e68b040dfc04ffff | 3,658,216 |
from datetime import datetime
import pytz
def login(request):
"""Logs in the user if given credentials are valid"""
username = request.data['username']
password = request.data['password']
try:
user = User.objects.get(username=username)
except:
user = None
if user is not None:
... | 79add2a805a36cd3339aeecafb7d0af95e42d2e5 | 3,658,217 |
def replace_data_in_gbq_table(project_id, table_id, complete_dataset):
""" replacing data in Google Cloud Table """
complete_dataset.to_gbq(
destination_table=table_id,
project_id=project_id,
credentials=credentials,
if_exists="replace",
)
return None | 1de5464cdce77f94857abe46a93f7b64f5e2dd1e | 3,658,218 |
def default_pubkey_inner(ctx):
"""Default expression for "pubkey_inner": tap.inner_pubkey."""
return get(ctx, "tap").inner_pubkey | 9333a62c0111f28e71c202b5553d7f2a8c4f71ce | 3,658,219 |
def quantize_8(image):
"""Converts and quantizes an image to 2^8 discrete levels in [0, 1]."""
q8 = tf.image.convert_image_dtype(image, tf.uint8, saturate=True)
return tf.cast(q8, tf.float32) * (1.0 / 255.0) | d822ff34b9941c6a812a69766de3483c2348e7da | 3,658,220 |
def get_clients( wlc, *vargs, **kvargs ):
"""
create a single dictionary containing information
about all associated stations.
"""
rsp = wlc.rpc.get_stat_user_session_status()
ret_data = {}
for session in rsp.findall('.//USER-SESSION-STATUS'):
locs... | c4ab5941033632d7f2b95bc23878f0464d12adb7 | 3,658,221 |
def coalmine(eia923_dfs, eia923_transformed_dfs):
"""Transforms the coalmine_eia923 table.
Transformations include:
* Remove fields implicated elsewhere.
* Drop duplicates with MSHA ID.
Args:
eia923_dfs (dict): Each entry in this dictionary of DataFrame objects
corresponds to ... | eb420428dcb2dceeeab1c5bbdceee7c7da2e5c11 | 3,658,222 |
import random
def _throw_object_x_at_y():
"""
Interesting interactions:
* If anything is breakable
:return:
"""
all_pickupable_objects_x = env.all_objects_with_properties({'pickupable': True})
x_weights = [10.0 if (x['breakable'] or x['mass'] > 4.0) else 1.0 for x in all_pickupable_objec... | 03f6c6a99754d79d94df5a4f857ae358db663081 | 3,658,223 |
def plot(
X,
color_by=None,
color_map="Spectral",
colors=None,
edges=None,
axis_limits=None,
background_color=None,
marker_size=1.0,
figsize_inches=(8.0, 8.0),
savepath=None,
):
"""Plot an embedding, in one, two, or three dimensions.
This function plots embeddings. The i... | f6c5ef6084278bcd3eb81c9286af53594aca4a1e | 3,658,224 |
def CausalConvIntSingle(val, time, kernel):
"""
Computing convolution of time varying data with given kernel function.
"""
ntime = time.size
dt_temp = np.diff(time)
dt = np.r_[time[0], dt_temp]
out = np.zeros_like(val)
for i in range(1, ntime):
temp = 0.
if i==0:
temp += val[0]*kernel(time[i]-time[0])*dt... | a4e94bfe2213c428042df4e561f584ffede3f9ab | 3,658,225 |
def sbox1(v):
"""AES inverse S-Box."""
w = mpc.to_bits(v)
z = mpc.vector_add(w, B)
y = mpc.matrix_prod([z], A1, True)[0]
x = mpc.from_bits(y)**254
return x | c10e9d440e1c1149c8d2b0f9fbd3fd5d4868596c | 3,658,226 |
def _get_photon_info_COS(tag, x1d, traceloc='stsci'):
"""
Add spectral units (wavelength, cross dispersion distance, energy/area)
to the photon table in the fits data unit "tag".
For G230L, you will get several 'xdisp' columns -- one for each segment. This allows for the use of overlapping
backgrou... | d1f06d6b8b26894a3297471c74c291cd15b3cb22 | 3,658,227 |
def maximum_value(tab):
"""
brief: return maximum value of the list
args:
tab: a list of numeric value expects at leas one positive value
return:
the max value of the list
the index of the max value
raises:
ValueError if expected a list as input
ValueError if no positive value found
"""
if not(isinstan... | 1c31daf3a953a9d781bc48378ef53323313dc22a | 3,658,228 |
import mpmath
def pdf(x, k, loc, scale):
"""
Probability density function for the Weibull distribution (for minima).
This is a three-parameter version of the distribution. The more typical
two-parameter version has just the parameters k and scale.
"""
with mpmath.extradps(5):
x = mpm... | 77efc3f7ceda57377a412dc7641114cea3562953 | 3,658,229 |
def rescale_column_test(img, img_shape, gt_bboxes, gt_label, gt_num):
"""rescale operation for image of eval"""
img_data, scale_factor = mmcv.imrescale(img, (config.img_width, config.img_height), return_scale=True)
if img_data.shape[0] > config.img_height:
img_data, scale_factor2 = mmcv.imrescale(im... | 11c7be91988aba926e5d9934443545a5112d2525 | 3,658,231 |
def resolvability_query(m, walks_):
"""
:param m: cost matrix
:param walks_: list of 0-percolation followed by its index of redundancy
as returned by percolation_finder
:return: M again untouched, followed by the list of $0$-percolation with
minimal index of redundancy, and with a flag, True if ... | 968acb44a94952187cd91ed50ee2f7c1d1f0f54f | 3,658,233 |
import math
def dsh(
incidence1: float, solar_az1: float, incidence2: float, solar_az2: float
):
"""Returns the Shadow-Tip Distance (dsh) as detailed in
Becker et al.(2015).
The input angles are assumed to be in radians.
This is defined as the distance between the tips of the shadows
in the ... | 5aef1c9d7ffeb3e8534568a53cf537d26d97324a | 3,658,235 |
def similarity(vec1, vec2):
"""Cosine similarity."""
return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2)) | 22a97fc08b4a8d7b662d0ba38eb6338aad587ca2 | 3,658,236 |
import _warnings
def epv00(date1, date2):
""" Earth position and velocity, heliocentric and barycentric, with
respect to the Barycentric Celestial Reference System.
:param date1, date2: TDB as a two-part Julian date.
:type date1, date2: float
:returns: a tuple of two items:
* heliocentr... | bb2c97517966168beb07e1732231bb0388eca0f3 | 3,658,237 |
def algorithm_conflict(old_config, new_config):
"""Generate an algorithm configuration conflict"""
return conflicts.AlgorithmConflict(old_config, new_config) | 8f9a1dcbf90b38efd69e028a35591d4d424d72c4 | 3,658,238 |
def nin():
"""
:return:
"""
def nin_block(num_channels, kernel_size, strides, padding):
blk = nn.Sequential()
blk.add(nn.Conv2D(num_channels, kernel_size, strides, padding, activation='relu'),
nn.Conv2D(num_channels, kernel_size=1, activation='relu'),
nn... | 8641d6b34256168d09d2ab3c6fa0d4a0aff71410 | 3,658,239 |
def factorial(n):
"""
Return the product of the integers 1 through n.
n must be a nonnegative integer.
"""
return product(range(2, n + 1)) | 132b772d27e661816979ea9a5f2fa3b53114b55c | 3,658,240 |
def get_status_lines(frames, check_transposed=True):
"""
Extract status lines from the given frames.
`frames` can be 2D array (one frame), 3D array (stack of frames, first index is frame number), or list of array.
Automatically check if the status line is present; return ``None`` if it's not.
I... | 8bc68246b0c4987836414810a0308a2034b16368 | 3,658,241 |
def quote():
"""Get stock quote."""
if request.method == "POST":
quote = lookup(request.form.get("symbol"))
if quote == None:
return apology("invalid symbol", 400)
return render_template("quoted.html", quote=quote)
# User reached route via GET (as by clicking a link or... | fb9d4b54e97a4d7b104f3c0d361347b99db68195 | 3,658,242 |
import json
def stats(api, containers=None, stream=True):
"""Get container stats container
When stream is set to true, the raw HTTPResponse is returned.
"""
path = "/containers/stats"
params = {'stream': stream}
if containers is not None:
params['containers'] = containers
try:
... | 8e8da5ab96ab14871e3a5de363d8cae66fba5701 | 3,658,243 |
def add_engineered(features):
"""Add engineered features to features dict.
Args:
features: dict, dictionary of input features.
Returns:
features: dict, dictionary with engineered features added.
"""
features["londiff"] = features["dropofflon"] - features["pickuplon"]
features["... | 56efe3ad922f5068c91ac702366416210e95dd74 | 3,658,244 |
def test_3tris():
"""3 triangles"""
conv = ToPointsAndSegments()
polygons = [
[[(0, 0), (1, 0), (0.5, -0.5), (0, 0)]],
[[(1, 0.5), (2, 0.5), (1.5, 1), (1, 0.5)]],
[[(2, 0), (3, 0), (2.5, -0.5), (2, 0)]],
]
for polygon in polygons:
conv.add_polygon(polygon)
return ... | fc9504e9c3ca0ae251ed67f8c99530ac6a1de73c | 3,658,245 |
def program_modules_with_functions(module_type, function_templates):
""" list the programs implementing a given set of functions
"""
prog_lsts = [program_modules_with_function(module_type, function_template)
for function_template in function_templates]
# get the intersection of all of ... | c3cfd6ee6c9fdcca3926015016e5d28a2a1f599d | 3,658,246 |
def tasmax_below_tasmin(
tasmax: xarray.DataArray,
tasmin: xarray.DataArray,
) -> xarray.DataArray:
"""Check if tasmax values are below tasmin values for any given day.
Parameters
----------
tasmax : xarray.DataArray
tasmin : xarray.DataArray
Returns
-------
xarray.DataArray, [... | c112dcf5b1a89f20151daaea8d56ea8b08262886 | 3,658,247 |
import torch
def laplace_attention(q, k, v, scale, normalize):
"""
Laplace exponential attention
Parameters
----------
q : torch.Tensor
Shape (batch_size, m, k_dim)
k : torch.Tensor
Shape (batch_size, n, k_dim)
v : torch.Tensor
Shape (batch_size, n, v_dim)
s... | 600ac2f75e5396dfe6e169776425229ffedbc884 | 3,658,248 |
def instantiate(class_name, *args, **kwargs):
"""Helper to dynamically instantiate a class from a name."""
split_name = class_name.split(".")
module_name = split_name[0]
class_name = ".".join(split_name[1:])
module = __import__(module_name)
class_ = getattr(module, class_name)
return class_... | d5906c835de9c2e86fbe3c15a9236662d6c7815d | 3,658,249 |
def fawa(pv_or_state, grid=None, levels=None, interpolate=None):
"""Finite-Amplitude Wave Activity according to Nakamura and Zhu (2010).
- If the first parameter is not a `barotropic.State`, `grid` must be
specified.
- `levels` specifies the number of contours generated for the equivalent
latit... | 91ca98bcb5abf71100ec9716f11c5cd38688836d | 3,658,250 |
def bmm_update(context, bmm_id, values, session=None):
"""
Updates Bare Metal Machine record.
"""
if not session:
session = get_session_dodai()
session.begin()
bmm_ref = bmm_get(context, bmm_id, session=session)
bmm_ref.update(values)
bmm_ref.save(session=session)
return... | 71c73582c9f6b96ffc5021598c8ef017ccb5af83 | 3,658,251 |
from datetime import datetime
def to_unified(entry):
"""
Convert to a unified entry
"""
assert isinstance(entry, StatementEntry)
date = datetime.datetime.strptime(entry.Date, '%d/%m/%Y').date()
return UnifiedEntry(date, entry.Reference, method=entry.Transaction_Type, credit=entry.Money_In,
... | d6eca8cbd970931569a2ad740298578c1106e7c9 | 3,658,252 |
def edit_profile():
"""
POST endpoint that edits the student profile.
"""
user = get_current_user()
json = g.clean_json
user.majors = Major.objects.filter(id__in=json['majors'])
user.minors = Minor.objects.filter(id__in=json['minors'])
user.interests = Tag.objects.filter(id__in=json['i... | 4548c4621f31bbd159535b7ea0768167655b4f5b | 3,658,253 |
import six
def _stringcoll(coll):
"""
Predicate function to determine whether COLL is a non-empty
collection (list/tuple) containing only strings.
Arguments:
- `coll`:*
Return: bool
Exceptions: None
"""
if isinstance(coll, (list, tuple)) and coll:
return len([s for s in c... | 9490a973900e230f70fea112f250cfe29be3a8bc | 3,658,254 |
import contextlib
def create_user_db_context(
database=Database(),
*args, **kwargs):
"""
Create a context manager for an auto-configured :func:`msdss_users_api.tools.create_user_db_func` function.
Parameters
----------
database : :class:`msdss_base_database:msdss_base_database.core.Databa... | 2bafe1f31f19c2b115d54e61c124f06368694b6b | 3,658,255 |
from pathlib import Path
import textwrap
def config(base_config):
""":py:class:`nemo_nowcast.Config` instance from YAML fragment to use as config for unit tests."""
config_file = Path(base_config.file)
with config_file.open("at") as f:
f.write(
textwrap.dedent(
"""\
... | 3ed4253f660a87e8b24392b4eb926b387067010f | 3,658,256 |
def __check_complete_list(list_, nb_max, def_value):
"""
make sure the list is long enough
complete with default value if not
:param list_: list to check
:param nb_max: maximum length of the list
:param def_value: if list too small,
completes it with this value
:return: boolean,... | 9d439cd3eeea04e7a3e0e59aa4fe0bbb875bdfe4 | 3,658,257 |
import pickle
def _fill_function(func, globals, defaults, closure, dct):
""" Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func().
"""
func.func_globals.update(globals)
func.func_defaults = defaults
func.func_dict = dct
... | 7ac454b7d6c43f49da1adf32522c03d28d88e6b7 | 3,658,258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.