max_stars_repo_path
stringlengths 4
245
| max_stars_repo_name
stringlengths 7
115
| max_stars_count
int64 101
368k
| id
stringlengths 2
8
| content
stringlengths 6
1.03M
|
---|---|---|---|---|
modules/api/functional_test/live_tests/internal/health_test.py
|
slandry90/vinyldns
| 333 |
145616
|
<filename>modules/api/functional_test/live_tests/internal/health_test.py
import pytest
from hamcrest import *
from vinyldns_python import VinylDNSClient
def test_health(shared_zone_test_context):
"""
Tests that the health check endpoint works
"""
client = shared_zone_test_context.ok_vinyldns_client
client.health()
|
gtsfm/averaging/rotation/rotation_averaging_base.py
|
swershrimpy/gtsfm
| 122 |
145617
|
<filename>gtsfm/averaging/rotation/rotation_averaging_base.py
"""Base class for the rotation averaging component of the GTSFM pipeline.
Authors: <NAME>, <NAME>
"""
import abc
from typing import Dict, List, Optional, Tuple
import dask
from dask.delayed import Delayed
from gtsam import Rot3
class RotationAveragingBase(metaclass=abc.ABCMeta):
"""Base class for rotation averaging.
This class generates global rotation estimates from the pairwise relative
rotations.
"""
# ignored-abstractmethod
@abc.abstractmethod
def run(self, num_images: int, i2Ri1_dict: Dict[Tuple[int, int], Optional[Rot3]]) -> List[Optional[Rot3]]:
"""Run the rotation averaging.
Args:
num_images: number of poses.
i2Ri1_dict: relative rotations as dictionary (i1, i2): i2Ri1.
Returns:
Global rotations for each camera pose, i.e. wRi, as a list. The number of entries in the list is
`num_images`. The list may contain `None` where the global rotation could not be computed (either
underconstrained system or ill-constrained system).
"""
def create_computation_graph(self, num_images: int, i2Ri1_graph: Delayed) -> Delayed:
"""Create the computation graph for performing rotation averaging.
Args:
num_images: number of poses.
i2Ri1_graph: dictionary of relative rotations as a delayed task.
Returns:
global rotations wrapped using dask.delayed.
"""
return dask.delayed(self.run)(num_images, i2Ri1_graph)
|
utils/eval/geometry.py
|
wx-b/patch2pix
| 157 |
145623
|
<reponame>wx-b/patch2pix
import numpy as np
from transforms3d.quaternions import quat2mat, mat2quat
# The skew-symmetric matrix of vector
skew = lambda v: np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
# Essential matrix & fundamental matrix
ess2fund = lambda K1, K2, E: np.linalg.inv(K2).T @ E @ np.linalg.inv(K1)
ess2fund_inv = lambda K1_inv, K2_inv, E: K2_inv.T @ E @ K1_inv
fund2ess = lambda F, K2, K1: K2.T @ F @ K1
# Camera relative pose to fundamental matrix
pose2ess = lambda R, t: skew(t.reshape(3,)) @ R
pose2fund = lambda K1, K2, R, t: np.linalg.inv(K2).T @ R @ K1.T @ skew((K1 @ R.T).dot(t.reshape(3,)))
pose2fund_inv = lambda K1, K2_inv, R, t: K2_inv.T @ R @ K1.T @ skew((K1 @ R.T).dot(t))
# Normalize fundamental matrix
normF = lambda F: F / F[-1,-1] # Normalize F by the last value
normalize = lambda A: A / np.linalg.norm(A)
def compose_projection_matrix(R, t):
"""Construct projection matrix
Args:
- R: rotation matrix, size (3,3);
- t: translation vector, size (3,);
Return:
- projection matrix [R|t], size (3,4)
"""
return np.hstack([R, np.expand_dims(t, axis=1)])
def matches2relapose_cv(p1, p2, K1, K2, rthres=1):
import cv2
# Move back to image center based coordinates
f1, f2, = K1[0,0], K2[0, 0]
pc1 = np.array([K1[:2, 2]])
pc2 = np.array([K2[:2, 2]])
# Rescale to im2 's focal setting
p1 = (p1 - pc1) * f2 / f1
p2 = (p2 - pc2)
K = np.array([[f2, 0, 0],
[0, f2, 0],
[0, 0, 1]])
E, inls = cv2.findEssentialMat(p1, p2, cameraMatrix=K, method=cv2.FM_RANSAC, threshold=rthres)
inls = np.where(inls > 0)[0]
_, R, t, _ = cv2.recoverPose(E, p1[inls], p2[inls], K)
return E, inls, R, t
def matches2relapose_degensac(p1, p2, K1, K2, rthres=1):
import pydegensac
import cv2
# Move back to image center based coordinates
f1, f2 = K1[0,0], K2[0, 0]
pc1 = np.array([K1[:2, 2]])
pc2 = np.array([K2[:2, 2]])
# Rescale to im2 's focal setting
p1 = (p1 - pc1) * f2 / f1
p2 = (p2 - pc2)
K = np.array([[f2, 0, 0],
[0, f2, 0],
[0, 0, 1]])
K1 = K2 = K
F, inls = pydegensac.findFundamentalMatrix(p1, p2, rthres)
E = fund2ess(F, K1, K2)
inls = np.where(inls > 0)[0]
_, R, t, _ = cv2.recoverPose(E, p1[inls], p2[inls], K)
return E, inls, R, t
def abs2relapose(c1, c2, q1, q2):
"""Calculate relative pose between two cameras
Args:
- c1: absolute position of the first camera
- c2: absolute position of the second camera
- q1: orientation quaternion of the first camera
- q2: orientation quaternion of the second camera
Return:
- (t12, q12): relative pose giving the transformation from the 1st camera to the 2nd camera coordinates,
t12 is translation, q12 is relative rotation quaternion
"""
r1 = quat2mat(q1)
r2 = quat2mat(q2)
r12 = r2.dot(r1.T)
q12 = mat2quat(r12)
t12 = r2.dot(c1 - c2)
return (t12, q12)
|
onmt/train_single.py
|
memray/OpenNMT-kpg-release
| 152 |
145657
|
#!/usr/bin/env python
"""Training on a single process."""
import os
import shutil
import torch
from onmt.inputters.inputter import build_dataset_iter, \
load_old_vocab, old_style_vocab, build_dataset_iter_multiple, make_tgt, reload_news_fields
from onmt.inputters.news_dataset import load_pretrained_tokenizer
from onmt.model_builder import build_model
from onmt.utils.optimizers import Optimizer
from onmt.utils.misc import set_random_seed
from onmt.trainer import build_trainer
from onmt.models import build_model_saver
from onmt.utils.logging import init_logger, logger
from onmt.utils.parse import ArgumentParser
from torchtext.data import Field, RawField
def _check_save_model_path(opt):
if not hasattr(opt, 'save_model') or opt.save_model is None:
if hasattr(opt, 'exp_dir'):
setattr(opt, 'save_model', opt.exp_dir+'/models/model')
else:
raise Exception('Neither exp_dir nor save_model is not given!')
save_model_path = os.path.abspath(opt.save_model)
model_dirname = os.path.dirname(save_model_path)
if not os.path.exists(model_dirname):
os.makedirs(model_dirname)
if not hasattr(opt, 'log_file') or opt.log_file is None or opt.log_file=='':
if hasattr(opt, 'log_file'):
setattr(opt, 'log_file', opt.exp_dir+'/train.log')
else:
logger.warn("opt.log_file is not set")
if not hasattr(opt, 'tensorboard_log_dir') or opt.tensorboard_log_dir is None:
if hasattr(opt, 'exp_dir'):
setattr(opt, 'tensorboard_log_dir', opt.exp_dir+'/logs/tfevents/')
else:
logger.warn("opt.tensorboard_log_dir is not set")
if hasattr(opt, 'tensorboard_log_dir') and not os.path.exists(opt.tensorboard_log_dir):
os.makedirs(opt.tensorboard_log_dir)
if not hasattr(opt, 'wandb_log_dir') or opt.wandb_log_dir is None:
if hasattr(opt, 'exp_dir'):
# a `/wandb` will be appended by wandb
setattr(opt, 'wandb_log_dir', opt.exp_dir+'/logs/')
else:
logger.warn("opt.wandb_log_dir is not set")
if hasattr(opt, 'wandb_log_dir') and not os.path.exists(opt.wandb_log_dir):
os.makedirs(opt.wandb_log_dir)
def _tally_parameters(model):
enc = 0
dec = 0
for name, param in model.named_parameters():
if 'encoder' in name:
enc += param.nelement()
else:
dec += param.nelement()
return enc + dec, enc, dec
def configure_process(opt, device_id):
if device_id >= 0:
torch.cuda.set_device(device_id)
set_random_seed(opt.seed, device_id >= 0)
def main(opt, device_id, batch_queue=None, semaphore=None):
# NOTE: It's important that ``opt`` has been validated and updated
# at this point.
configure_process(opt, device_id)
init_logger(opt.log_file)
# save training settings
if opt.log_file:
shutil.copy2(opt.config, opt.exp_dir)
logger.info(vars(opt))
assert len(opt.accum_count) == len(opt.accum_steps), \
'Number of accum_count values must match number of accum_steps'
# Load checkpoint if we resume from a previous training.
if opt.train_from:
logger.info('Loading checkpoint from %s' % opt.train_from)
checkpoint = torch.load(opt.train_from,
map_location=lambda storage, loc: storage)
model_opt = ArgumentParser.ckpt_model_opts(checkpoint["opt"])
ArgumentParser.update_model_opts(model_opt)
ArgumentParser.validate_model_opts(model_opt)
logger.info('Loading vocab from checkpoint at %s.' % opt.train_from)
vocab = checkpoint['vocab']
else:
checkpoint = None
model_opt = opt
# added by @memray for multiple datasets
if opt.vocab and opt.vocab != 'none':
vocab = torch.load(opt.vocab)
elif opt.encoder_type == 'pretrained':
vocab = None
else:
vocab = None
# check for code where vocab is saved instead of fields
# (in the future this will be done in a smarter way)
if old_style_vocab(vocab):
fields = load_old_vocab(
vocab, opt.model_type, dynamic_dict=opt.copy_attn)
else:
fields = vocab
# @memray: a temporary workaround, as well as train.py line 43
if opt.model_type == "keyphrase":
if opt.tgt_type in ["one2one", "multiple"]:
if 'sep_indices' in fields:
del fields['sep_indices']
else:
if 'sep_indices' not in fields:
sep_indices = Field(
use_vocab=False, dtype=torch.long,
postprocessing=make_tgt, sequential=False)
fields["sep_indices"] = sep_indices
if 'src_ex_vocab' not in fields:
src_ex_vocab = RawField()
fields["src_ex_vocab"] = src_ex_vocab
tokenizer = None
if opt.pretrained_tokenizer:
tokenizer = load_pretrained_tokenizer(opt.pretrained_tokenizer, opt.cache_dir, opt.special_vocab_path)
setattr(opt, 'vocab_size', len(tokenizer))
if opt.data_type == 'news':
fields = reload_news_fields(fields, opt, tokenizer)
# Report src and tgt vocab sizes, including for features
for side in ['src', 'tgt']:
f = fields[side]
try:
f_iter = iter(f)
except TypeError:
f_iter = [(side, f)]
for sn, sf in f_iter:
if sf.use_vocab:
logger.info(' * %s vocab size = %d' % (sn, len(sf.vocab)))
# Build model.
model = build_model(model_opt, opt, fields, checkpoint)
n_params, enc, dec = _tally_parameters(model)
logger.info('encoder: %d' % enc)
logger.info('decoder: %d' % dec)
logger.info('* number of parameters: %d' % n_params)
# Build optimizer.
optim = Optimizer.from_opt(model, opt, checkpoint=checkpoint)
# Build model saver
model_saver = build_model_saver(model_opt, opt, model, fields, optim)
trainer = build_trainer(
opt, device_id, model, fields, optim, model_saver=model_saver)
if batch_queue is None:
if len(opt.data_ids) > 1:
# added by @memray, for loading multiple datasets
if opt.multi_dataset:
shard_base = "train"
train_iter = build_dataset_iter(shard_base, fields, opt, tokenizer=tokenizer)
else:
train_shards = []
for train_id in opt.data_ids:
shard_base = "train_" + train_id
train_shards.append(shard_base)
train_iter = build_dataset_iter_multiple(train_shards, fields, opt, tokenizer=tokenizer)
else:
shard_base = "train"
train_iter = build_dataset_iter(shard_base, fields, opt)
else:
assert semaphore is not None, \
"Using batch_queue requires semaphore as well"
def _train_iter():
while True:
batch = batch_queue.get()
semaphore.release()
yield batch
train_iter = _train_iter()
if opt.valid:
valid_iter = build_dataset_iter(
"valid", fields, opt, is_train=False)
else:
valid_iter = None
if len(opt.gpu_ranks):
logger.info('Starting training on GPU: %s' % opt.gpu_ranks)
else:
logger.info('Starting training on CPU, could be very slow')
train_steps = opt.train_steps
if opt.single_pass and train_steps > 0:
logger.warning("Option single_pass is enabled, ignoring train_steps.")
train_steps = 0
trainer.train(
train_iter,
train_steps,
save_checkpoint_steps=opt.save_checkpoint_steps,
valid_iter=valid_iter,
valid_steps=opt.valid_steps)
if trainer.report_manager.tensorboard_writer is not None:
trainer.report_manager.tensorboard_writer.close()
|
platform/coredb/coredb/migrations/0006_auto_20201020_1705.py
|
admariner/polyaxon
| 3,200 |
145667
|
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.db import migrations, models
def migrate_runtime(apps, schema_editor):
Run = apps.get_model("coredb", "Run")
runs = []
for r in Run.objects.all():
r.runtime = r.meta_info.pop("meta_kind", None)
runs.append(r)
Run.objects.bulk_update(runs, ["meta_info", "runtime"])
class Migration(migrations.Migration):
dependencies = [
("coredb", "0005_auto_20201005_0913"),
]
operations = [
migrations.AddField(
model_name="run",
name="runtime",
field=models.CharField(blank=True, db_index=True, max_length=12, null=True),
),
migrations.RunPython(migrate_runtime),
]
|
jupyter_book/utils.py
|
dlukes/jupyter-book
| 108 |
145679
|
from pathlib import Path
from textwrap import dedent
from jupyter_client.kernelspec import find_kernel_specs
SUPPORTED_FILE_SUFFIXES = [".ipynb", ".md", ".markdown", ".myst", ".Rmd", ".py"]
def _filename_to_title(filename, split_char="_"):
"""Convert a file path into a more readable title."""
filename = Path(filename).with_suffix("").name
filename_parts = filename.split(split_char)
try:
# If first part of the filename is a number for ordering, remove it
int(filename_parts[0])
if len(filename_parts) > 1:
filename_parts = filename_parts[1:]
except Exception:
pass
title = " ".join(ii.capitalize() for ii in filename_parts)
return title
##############################################################################
# CLI utilities
border = "=" * 79
endc = "\033[0m"
bcolors = dict(
blue="\033[94m",
green="\033[92m",
orange="\033[93m",
red="\033[91m",
bold="\033[1m",
underline="\033[4m",
)
def _color_message(msg, style):
return bcolors[style] + msg + endc
def _message_box(msg, color="green", doprint=True, print_func=print):
# Prepare the message so the indentation is the same as the box
msg = dedent(msg)
# Color and create the box
border_colored = _color_message(border, color)
box = """
{border_colored}
{msg}
{border_colored}
"""
box = dedent(box).format(msg=msg, border_colored=border_colored)
if doprint is True:
print_func(box)
return box
def _error(msg, kind=None):
if kind is None:
kind = RuntimeError
box = _message_box(msg, color="red", doprint=False)
raise kind(box)
##############################################################################
# MyST + Jupytext
def init_myst_file(path, kernel, verbose=True):
"""Initialize a file with a Jupytext header that marks it as MyST markdown.
Parameters
----------
path : string
A path to a markdown file to be initialized for Jupytext
kernel : string
A kernel name to add to the markdown file. See a list of kernel names with
`jupyter kernelspec list`.
"""
try:
from jupytext.cli import jupytext
except ImportError:
raise ImportError(
"In order to use myst markdown features, " "please install jupytext first."
)
if not Path(path).exists():
raise FileNotFoundError(f"Markdown file not found: {path}")
kernels = list(find_kernel_specs().keys())
kernels_text = "\n".join(kernels)
if kernel is None:
if len(kernels) > 1:
_error(
"There are multiple kernel options, so you must give one manually."
" with `--kernel`\nPlease specify one of the following kernels.\n\n"
f"{kernels_text}"
)
else:
kernel = kernels[0]
if kernel not in kernels:
raise ValueError(
f"Did not find kernel: {kernel}\nPlease specify one of the "
f"installed kernels:\n\n{kernels_text}"
)
args = (str(path), "-q", "--set-kernel", kernel, "--set-formats", "myst")
jupytext(args)
if verbose:
print(f"Initialized file: {path}\nWith kernel: {kernel}")
|
060_hair_segmentation/01_float32/01_hair_segmentation_tflite2h5_weight_int_fullint_float16_quant.py
|
IgiArdiyanto/PINTO_model_zoo
| 1,529 |
145690
|
### tensorflow==2.3.0
### https://ai.googleblog.com/2020/08/on-device-real-time-body-pose-tracking.html
### https://google.github.io/mediapipe/solutions/pose
### https://www.tensorflow.org/api_docs/python/tf/keras/Model
### https://www.tensorflow.org/lite/guide/ops_compatibility
### https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D
### https://www.tensorflow.org/api_docs/python/tf/keras/layers/DepthwiseConv2D
### https://www.tensorflow.org/api_docs/python/tf/keras/layers/Add
### https://www.tensorflow.org/api_docs/python/tf/keras/layers/ReLU
### https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D
### https://www.tensorflow.org/api_docs/python/tf/keras/layers/Reshape
### https://www.tensorflow.org/api_docs/python/tf/keras/layers/Concatenate
### https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer
### https://github.com/google/mediapipe/issues/245
### https://github.com/mvoelk/keras_layers
### How to initialize a convolution layer with an arbitrary kernel in Keras? https://stackoverrun.com/ja/q/12269118
### saved_model_cli show --dir saved_model/ --tag_set serve --signature_def serving_default
import tensorflow as tf
from tensorflow.python.keras import backend as K
from tensorflow.keras import Model, Input
from tensorflow.keras.layers import Conv2D, Conv2DTranspose, DepthwiseConv2D, Add, ReLU, PReLU, MaxPool2D, Reshape, Concatenate, Layer
from tensorflow.keras.initializers import Constant
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
from tensorflow.python.keras.utils import conv_utils
from tensorflow.python.ops import nn_ops
import numpy as np
import sys
import cv2
# tmp = np.load('weights/depthwise_conv2d_Kernel')
# print(tmp.shape)
# print(tmp)
# def init_f(shape, dtype=None):
# ker = np.load('weights/depthwise_conv2d_Kernel')
# print(shape)
# return ker
# sys.exit(0)
# class MaxPoolingWithArgmax2D(Layer):
# def __init__(self, pool_size=(2, 2), strides=(2, 2), padding='same', **kwargs):
# super(MaxPoolingWithArgmax2D, self).__init__(**kwargs)
# self.pool_size = conv_utils.normalize_tuple(pool_size, 2, 'pool_size')
# self.strides = conv_utils.normalize_tuple(strides, 2, 'strides')
# self.padding = conv_utils.normalize_padding(padding)
# def call(self, inputs, **kwargs):
# ksize = [1, self.pool_size[0], self.pool_size[1], 1]
# strides = [1, self.strides[0], self.strides[1], 1]
# padding = self.padding.upper()
# output, argmax = nn_ops.max_pool_with_argmax(inputs, ksize, strides, padding)
# # output, argmax = tf.raw_ops.MaxPoolWithArgmax(inputs, ksize, strides, padding)
# argmax = tf.cast(argmax, K.floatx())
# return [output, argmax]
# def compute_output_shape(self, input_shape):
# ratio = (1, 2, 2, 1)
# output_shape = [dim // ratio[idx] if dim is not None else None for idx, dim in enumerate(input_shape)]
# output_shape = tuple(output_shape)
# return [output_shape, output_shape]
# def compute_mask(self, inputs, mask=None):
# return 2 * [None]
# def get_config(self):
# config = super(MaxPoolingWithArgmax2D, self).get_config()
# config.update({
# 'pool_size': self.pool_size,
# 'strides': self.strides,
# 'padding': self.padding,
# })
# return config
def max_pooling_with_argmax2d(input):
net_main = tf.nn.max_pool(input,
ksize=[1,2,2,1],
strides=[1,2,2,1],
padding='SAME')
input_shape = input.get_shape().as_list()
mask_shape = [input_shape[0], input_shape [1]//2,input_shape[2]//2, input_shape[3]]
pooling_indices = tf.zeros(mask_shape, dtype=tf.int64)
for n in range(mask_shape[0]):
for i in range(mask_shape[1]):
for j in range(mask_shape[2]):
in_indices = [ [n, w, h] for w in range(i*2, i*2+2) for h in range(j*2, j*2+2)]
slice = tf.gather_nd(input, in_indices)
argmax = tf.argmax(slice, axis=0)
indices_location = [[n, i, j, d] for d in range(input_shape[3])]
sparse_indices = tf.SparseTensor(indices=indices_location, values=argmax, dense_shape=mask_shape)
pooling_indices = tf.compat.v1.sparse_add(pooling_indices, sparse_indices)
return [net_main, pooling_indices]
class MaxUnpooling2D(Layer):
def __init__(self, size=(2, 2), **kwargs):
super(MaxUnpooling2D, self).__init__(**kwargs)
self.size = conv_utils.normalize_tuple(size, 2, 'size')
def call(self, inputs, output_shape=None):
updates, mask = inputs[0], inputs[1]
mask = tf.cast(mask, 'int32')
input_shape = tf.shape(updates, out_type='int32')
# calculation new shape
if output_shape is None:
output_shape = (input_shape[0], input_shape[1] * self.size[0], input_shape[2] * self.size[1], input_shape[3])
# calculation indices for batch, height, width and feature maps
one_like_mask = K.ones_like(mask, dtype='int32')
batch_shape = K.concatenate([[input_shape[0]], [1], [1], [1]], axis=0)
batch_range = K.reshape(tf.range(output_shape[0], dtype='int32'), shape=batch_shape)
b = one_like_mask * batch_range
y = mask // (output_shape[2] * output_shape[3])
x = (mask // output_shape[3]) % output_shape[2]
feature_range = tf.range(output_shape[3], dtype='int32')
f = one_like_mask * feature_range
# transpose indices & reshape update values to one dimension
updates_size = tf.size(updates)
indices = K.transpose(K.reshape(K.stack([b, y, x, f]), [4, updates_size]))
values = K.reshape(updates, [updates_size])
ret = tf.scatter_nd(indices, values, output_shape)
return ret
def compute_output_shape(self, input_shape):
mask_shape = input_shape[1]
output_shape = [mask_shape[0], mask_shape[1] * self.size[0], mask_shape[2] * self.size[1], mask_shape[3]]
return tuple(output_shape)
def get_config(self):
config = super(MaxUnpooling2D, self).get_config()
config.update({
'size': self.size,
})
return config
height = 512
width = 512
inputs = Input(shape=(height, width, 4), batch_size=1, name='input')
# Block_01
conv1_1 = Conv2D(filters=8, kernel_size=[2, 2], strides=[2, 2], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_Bias')))(inputs)
prelu1_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_Alpha')), shared_axes=[1, 2])(conv1_1)
conv1_2 = Conv2D(filters=32, kernel_size=[2, 2], strides=[2, 2], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_1_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_1_Bias')))(prelu1_1)
prelu1_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_1_Alpha')), shared_axes=[1, 2])(conv1_2)
# Block_02
conv2_1 = Conv2D(filters=16, kernel_size=[2, 2], strides=[2, 2], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_2_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_2_Bias')))(prelu1_2)
prelu2_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_2_Alpha')), shared_axes=[1, 2])(conv2_1)
depthconv2_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_Bias')))(prelu2_1)
conv2_2 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_3_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_3_Bias')))(depthconv2_1)
prelu2_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_3_Alpha')), shared_axes=[1, 2])(conv2_2)
depthconv2_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_1_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_1_Bias')))(prelu2_2)
prelu2_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_4_Alpha')), shared_axes=[1, 2])(depthconv2_2)
conv2_3 = Conv2D(filters=64, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_4_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_4_Bias')))(prelu2_3)
maxpoolarg2_1 = tf.raw_ops.MaxPoolWithArgmax(input=prelu1_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# maxpoolarg2_1 = max_pooling_with_argmax2d(prelu1_2)
conv2_4 = Conv2D(filters=64, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_5_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_5_Bias')))(maxpoolarg2_1[0])
add2_1 = Add()([conv2_3, conv2_4])
prelu2_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_5_Alpha')), shared_axes=[1, 2])(add2_1)
# Block_03
conv3_1 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_6_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_6_Bias')))(prelu2_4)
prelu3_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_6_Alpha')), shared_axes=[1, 2])(conv3_1)
depthconv3_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_2_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_2_Bias')))(prelu3_1)
conv3_2 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_7_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_7_Bias')))(depthconv3_1)
prelu3_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_7_Alpha')), shared_axes=[1, 2])(conv3_2)
depthconv3_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_3_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_3_Bias')))(prelu3_2)
prelu3_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_8_Alpha')), shared_axes=[1, 2])(depthconv3_2)
conv3_3 = Conv2D(filters=64, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_8_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_8_Bias')))(prelu3_3)
add3_1 = Add()([conv3_3, prelu2_4])
prelu3_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_9_Alpha')), shared_axes=[1, 2])(add3_1)
# Block_04
conv4_1 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_9_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_9_Bias')))(prelu3_4)
prelu4_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_10_Alpha')), shared_axes=[1, 2])(conv4_1)
depthconv4_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_4_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_4_Bias')))(prelu4_1)
conv4_2 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_10_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_10_Bias')))(depthconv4_1)
prelu4_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_11_Alpha')), shared_axes=[1, 2])(conv4_2)
depthconv4_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_5_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_5_Bias')))(prelu4_2)
prelu4_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_12_Alpha')), shared_axes=[1, 2])(depthconv4_2)
conv4_3 = Conv2D(filters=64, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_11_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_11_Bias')))(prelu4_3)
add4_1 = Add()([conv4_3, prelu3_4])
prelu4_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_13_Alpha')), shared_axes=[1, 2])(add4_1)
# Block_05
conv5_1 = Conv2D(filters=32, kernel_size=[2, 2], strides=[2, 2], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_12_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_12_Bias')))(prelu4_4)
prelu5_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_14_Alpha')), shared_axes=[1, 2])(conv5_1)
depthconv5_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_6_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_6_Bias')))(prelu5_1)
conv5_2 = Conv2D(filters=32, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_13_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_13_Bias')))(depthconv5_1)
prelu5_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_15_Alpha')), shared_axes=[1, 2])(conv5_2)
depthconv5_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_7_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_7_Bias')))(prelu5_2)
prelu5_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_16_Alpha')), shared_axes=[1, 2])(depthconv5_2)
conv5_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_14_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_14_Bias')))(prelu5_3)
maxpoolarg5_1 = tf.raw_ops.MaxPoolWithArgmax(input=prelu4_4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# maxpoolarg5_1 = max_pooling_with_argmax2d(prelu4_4)
conv5_4 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_15_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_15_Bias')))(maxpoolarg5_1[0])
add5_1 = Add()([conv5_3, conv5_4])
prelu5_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_17_Alpha')), shared_axes=[1, 2])(add5_1)
# Block_06
conv6_1 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_16_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_16_Bias')))(prelu5_4)
prelu6_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_18_Alpha')), shared_axes=[1, 2])(conv6_1)
depthconv6_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_8_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_8_Bias')))(prelu6_1)
conv6_2 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_17_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_17_Bias')))(depthconv6_1)
prelu6_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_19_Alpha')), shared_axes=[1, 2])(conv6_2)
depthconv6_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_9_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_9_Bias')))(prelu6_2)
prelu6_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_20_Alpha')), shared_axes=[1, 2])(depthconv6_2)
conv6_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_18_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_18_Bias')))(prelu6_3)
add6_1 = Add()([conv6_3, prelu5_4])
prelu6_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_21_Alpha')), shared_axes=[1, 2])(add6_1)
# Block_07
conv7_1 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_19_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_19_Bias')))(prelu6_4)
prelu7_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_22_Alpha')), shared_axes=[1, 2])(conv7_1)
depthconv7_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_10_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_10_Bias')))(prelu7_1)
conv7_2 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_20_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_20_Bias')))(depthconv7_1)
prelu7_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_23_Alpha')), shared_axes=[1, 2])(conv7_2)
depthconv7_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_11_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_11_Bias')))(prelu7_2)
prelu7_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_24_Alpha')), shared_axes=[1, 2])(depthconv7_2)
conv7_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_21_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_21_Bias')))(prelu7_3)
add7_1 = Add()([conv7_3, prelu6_4])
prelu7_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_25_Alpha')), shared_axes=[1, 2])(add7_1)
# Block_08
conv8_1 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_22_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_22_Bias')))(prelu7_4)
prelu8_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_26_Alpha')), shared_axes=[1, 2])(conv8_1)
depthconv8_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_12_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_12_Bias')))(prelu8_1)
conv8_2 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_23_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_23_Bias')))(depthconv8_1)
prelu8_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_27_Alpha')), shared_axes=[1, 2])(conv8_2)
depthconv8_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_13_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_13_Bias')))(prelu8_2)
prelu8_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_28_Alpha')), shared_axes=[1, 2])(depthconv8_2)
conv8_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_24_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_24_Bias')))(prelu8_3)
add8_1 = Add()([conv8_3, prelu7_4])
prelu8_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_29_Alpha')), shared_axes=[1, 2])(add8_1)
# Block_09
conv9_1 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_25_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_25_Bias')))(prelu8_4)
prelu9_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_30_Alpha')), shared_axes=[1, 2])(conv9_1)
depthconv9_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_14_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_14_Bias')))(prelu9_1)
conv9_2 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_26_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_26_Bias')))(depthconv9_1)
prelu9_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_31_Alpha')), shared_axes=[1, 2])(conv9_2)
depthconv9_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_15_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_15_Bias')))(prelu9_2)
prelu9_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_32_Alpha')), shared_axes=[1, 2])(depthconv9_2)
conv9_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_27_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_27_Bias')))(prelu9_3)
add9_1 = Add()([conv9_3, prelu8_4])
prelu9_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_33_Alpha')), shared_axes=[1, 2])(add9_1)
# Block_10
conv10_1 = Conv2D(filters=16, kernel_size=[2, 2], strides=[2, 2], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_28_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_28_Bias')))(prelu9_4)
prelu10_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_34_Alpha')), shared_axes=[1, 2])(conv10_1)
depthconv10_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_16_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_16_Bias')))(prelu10_1)
conv10_2 = Conv2D(filters=16, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_29_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_29_Bias')))(depthconv10_1)
prelu10_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_35_Alpha')), shared_axes=[1, 2])(conv10_2)
depthconv10_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_17_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_17_Bias')))(prelu10_2)
prelu10_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_36_Alpha')), shared_axes=[1, 2])(depthconv10_2)
conv10_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_30_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_30_Bias')))(prelu10_3)
maxpoolarg10_1 = tf.raw_ops.MaxPoolWithArgmax(input=prelu9_4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# maxpoolarg10_1 = max_pooling_with_argmax2d(prelu9_4)
add10_1 = Add()([conv10_3, maxpoolarg10_1[0]])
prelu10_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_37_Alpha')), shared_axes=[1, 2])(add10_1)
# Block_11
conv11_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_31_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_31_Bias')))(prelu10_4)
prelu11_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_38_Alpha')), shared_axes=[1, 2])(conv11_1)
depthconv11_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_18_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_18_Bias')))(prelu11_1)
conv11_2 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_32_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_32_Bias')))(depthconv11_1)
prelu11_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_39_Alpha')), shared_axes=[1, 2])(conv11_2)
depthconv11_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_19_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_19_Bias')))(prelu11_2)
prelu11_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_40_Alpha')), shared_axes=[1, 2])(depthconv11_2)
conv11_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_33_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_33_Bias')))(prelu11_3)
add11_1 = Add()([conv11_3, prelu10_4])
prelu11_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_41_Alpha')), shared_axes=[1, 2])(add11_1)
# Block_12
conv12_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_34_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_34_Bias')))(prelu11_4)
prelu12_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_42_Alpha')), shared_axes=[1, 2])(conv12_1)
conv12_2 = Conv2D(filters=8, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[2, 2],
kernel_initializer=Constant(np.load('weights/conv2d_35_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_35_Bias')))(prelu12_1)
prelu12_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_43_Alpha')), shared_axes=[1, 2])(conv12_2)
conv12_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_36_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_36_Bias')))(prelu12_2)
add12_1 = Add()([conv12_3, prelu11_4])
prelu12_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_44_Alpha')), shared_axes=[1, 2])(add12_1)
# Block_13
conv13_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_37_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_37_Bias')))(prelu12_3)
prelu13_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_45_Alpha')), shared_axes=[1, 2])(conv13_1)
depthconv13_1 = DepthwiseConv2D(kernel_size=[5, 5], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_20_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_20_Bias')))(prelu13_1)
conv13_2 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_38_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_38_Bias')))(depthconv13_1)
prelu13_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_46_Alpha')), shared_axes=[1, 2])(conv13_2)
conv13_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_39_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_39_Bias')))(prelu13_2)
add13_1 = Add()([conv13_3, prelu12_3])
prelu13_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_47_Alpha')), shared_axes=[1, 2])(add13_1)
# Block_14
conv14_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_40_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_40_Bias')))(prelu13_4)
prelu14_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_48_Alpha')), shared_axes=[1, 2])(conv14_1)
conv14_2 = Conv2D(filters=8, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[4, 4],
kernel_initializer=Constant(np.load('weights/conv2d_41_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_41_Bias')))(prelu14_1)
prelu14_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_49_Alpha')), shared_axes=[1, 2])(conv14_2)
conv14_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_42_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_42_Bias')))(prelu14_2)
add14_1 = Add()([conv14_3, prelu13_4])
prelu14_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_50_Alpha')), shared_axes=[1, 2])(add14_1)
# Block_15
conv15_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_43_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_43_Bias')))(prelu14_3)
prelu15_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_51_Alpha')), shared_axes=[1, 2])(conv15_1)
depthconv15_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_21_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_21_Bias')))(prelu15_1)
conv15_2 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_44_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_44_Bias')))(depthconv15_1)
prelu15_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_52_Alpha')), shared_axes=[1, 2])(conv15_2)
depthconv15_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_22_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_22_Bias')))(prelu15_2)
prelu15_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_53_Alpha')), shared_axes=[1, 2])(depthconv15_2)
conv15_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_45_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_45_Bias')))(prelu15_3)
add15_1 = Add()([conv15_3, prelu14_3])
prelu15_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_54_Alpha')), shared_axes=[1, 2])(add15_1)
# Block_16
conv16_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_46_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_46_Bias')))(prelu15_4)
prelu16_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_55_Alpha')), shared_axes=[1, 2])(conv16_1)
conv16_2 = Conv2D(filters=8, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[8, 8],
kernel_initializer=Constant(np.load('weights/conv2d_47_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_47_Bias')))(prelu16_1)
prelu16_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_56_Alpha')), shared_axes=[1, 2])(conv16_2)
conv16_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_48_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_48_Bias')))(prelu16_2)
add16_1 = Add()([conv16_3, prelu15_4])
prelu16_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_57_Alpha')), shared_axes=[1, 2])(add16_1)
# Block_17
conv17_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_49_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_49_Bias')))(prelu16_3)
prelu17_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_58_Alpha')), shared_axes=[1, 2])(conv17_1)
depthconv17_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_23_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_23_Bias')))(prelu17_1)
conv17_2 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_50_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_50_Bias')))(depthconv17_1)
prelu17_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_59_Alpha')), shared_axes=[1, 2])(conv17_2)
depthconv17_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_24_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_24_Bias')))(prelu17_2)
prelu17_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_60_Alpha')), shared_axes=[1, 2])(depthconv17_2)
conv17_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_51_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_51_Bias')))(prelu17_3)
add17_1 = Add()([conv17_3, prelu16_3])
prelu17_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_61_Alpha')), shared_axes=[1, 2])(add17_1)
# Block_18
conv18_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_46_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_46_Bias')))(prelu17_4)
prelu18_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_55_Alpha')), shared_axes=[1, 2])(conv18_1)
conv18_2 = Conv2D(filters=8, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[2, 2],
kernel_initializer=Constant(np.load('weights/conv2d_47_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_47_Bias')))(prelu18_1)
prelu18_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_56_Alpha')), shared_axes=[1, 2])(conv18_2)
conv18_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_48_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_48_Bias')))(prelu18_2)
add18_1 = Add()([conv18_3, prelu17_4])
prelu18_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_57_Alpha')), shared_axes=[1, 2])(add18_1)
# Block_19
conv19_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_55_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_55_Bias')))(prelu18_3)
prelu19_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_65_Alpha')), shared_axes=[1, 2])(conv19_1)
depthconv19_1 = DepthwiseConv2D(kernel_size=[5, 5], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_25_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_25_Bias')))(prelu19_1)
conv19_2 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_56_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_56_Bias')))(depthconv19_1)
prelu19_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_66_Alpha')), shared_axes=[1, 2])(conv19_2)
conv19_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_57_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_57_Bias')))(prelu19_2)
add19_1 = Add()([conv19_3, prelu18_3])
prelu19_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_67_Alpha')), shared_axes=[1, 2])(add19_1)
# Block_20
conv20_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_58_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_58_Bias')))(prelu19_4)
prelu20_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_68_Alpha')), shared_axes=[1, 2])(conv20_1)
conv20_2 = Conv2D(filters=8, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[4, 4],
kernel_initializer=Constant(np.load('weights/conv2d_59_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_59_Bias')))(prelu20_1)
prelu20_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_69_Alpha')), shared_axes=[1, 2])(conv20_2)
conv20_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_60_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_60_Bias')))(prelu20_2)
add20_1 = Add()([conv20_3, prelu19_4])
prelu20_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_70_Alpha')), shared_axes=[1, 2])(add20_1)
# Block_21
conv21_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_61_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_61_Bias')))(prelu20_3)
prelu21_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_71_Alpha')), shared_axes=[1, 2])(conv21_1)
depthconv21_1 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_26_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_26_Bias')))(prelu21_1)
conv21_2 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_62_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_62_Bias')))(depthconv21_1)
prelu21_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_72_Alpha')), shared_axes=[1, 2])(conv21_2)
depthconv21_2 = DepthwiseConv2D(kernel_size=[3, 3], strides=[1, 1], padding="same", depth_multiplier=1, dilation_rate=[1, 1],
depthwise_initializer=Constant(np.load('weights/depthwise_conv2d_27_Kernel')),
bias_initializer=Constant(np.load('weights/depthwise_conv2d_27_Bias')))(prelu21_2)
prelu21_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_73_Alpha')), shared_axes=[1, 2])(depthconv21_2)
conv21_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_63_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_63_Bias')))(prelu21_3)
add21_1 = Add()([conv21_3, prelu20_3])
prelu21_4 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_74_Alpha')), shared_axes=[1, 2])(add21_1)
# Block_22
conv22_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_64_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_64_Bias')))(prelu21_4)
prelu22_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_75_Alpha')), shared_axes=[1, 2])(conv22_1)
conv22_2 = Conv2D(filters=8, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[8, 8],
kernel_initializer=Constant(np.load('weights/conv2d_65_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_65_Bias')))(prelu22_1)
prelu22_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_76_Alpha')), shared_axes=[1, 2])(conv22_2)
conv22_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='valid', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_66_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_66_Bias')))(prelu22_2)
add22_1 = Add()([conv22_3, prelu21_4])
prelu22_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_77_Alpha')), shared_axes=[1, 2])(add22_1)
# Block_23
conv23_1 = Conv2D(filters=4, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_67_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_67_Bias')))(prelu22_3)
prelu23_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_78_Alpha')), shared_axes=[1, 2])(conv23_1)
conv23_2 = Conv2D(filters=4, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[8, 8],
kernel_initializer=Constant(np.load('weights/conv2d_68_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_68_Bias')))(prelu23_1)
prelu23_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_79_Alpha')), shared_axes=[1, 2])(conv23_2)
conv23_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_69_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_69_Bias')))(prelu23_2)
add23_1 = Add()([conv23_3, prelu22_3])
prelu23_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_80_Alpha')), shared_axes=[1, 2])(add23_1)
# Block_24
conv24_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_70_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_70_Bias')))(prelu23_3)
prelu24_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_81_Alpha')), shared_axes=[1, 2])(conv24_1)
convtransbias24_1 = Conv2DTranspose(filters=8, kernel_size=(3, 3), strides=(2, 2), padding='same',
kernel_initializer=Constant(np.load('weights/conv2d_transpose_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_transpose_Bias')))(prelu24_1)
prelu24_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_82_Alpha')), shared_axes=[1, 2])(convtransbias24_1)
conv24_2 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_71_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_71_Bias')))(prelu24_2)
conv24_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_72_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_72_Bias')))(prelu23_3)
maxunpool24_1 = MaxUnpooling2D(size=[2, 2])([conv24_3, maxpoolarg10_1[1]])
add24_1 = Add()([conv24_2, maxunpool24_1])
prelu24_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_77_Alpha')), shared_axes=[1, 2])(add24_1)
concat24_1 = Concatenate()([prelu24_3, prelu5_4])
# Block_25
conv25_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_73_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_73_Bias')))(concat24_1)
prelu25_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_84_Alpha')), shared_axes=[1, 2])(conv25_1)
conv25_2 = Conv2D(filters=8, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[8, 8],
kernel_initializer=Constant(np.load('weights/conv2d_74_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_74_Bias')))(prelu25_1)
prelu25_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_85_Alpha')), shared_axes=[1, 2])(conv25_2)
conv25_3 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_75_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_75_Bias')))(prelu25_2)
conv25_4 = Conv2D(filters=128, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_76_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_76_Bias')))(concat24_1)
add25_1 = Add()([conv25_3, conv25_4])
prelu25_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_86_Alpha')), shared_axes=[1, 2])(add25_1)
# Block_26
conv26_1 = Conv2D(filters=8, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_77_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_77_Bias')))(prelu25_3)
prelu26_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_87_Alpha')), shared_axes=[1, 2])(conv26_1)
convtransbias26_1 = Conv2DTranspose(filters=8, kernel_size=(3, 3), strides=(2, 2), padding='same',
kernel_initializer=Constant(np.load('weights/conv2d_transpose_1_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_transpose_1_Bias')))(prelu26_1)
prelu26_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_88_Alpha')), shared_axes=[1, 2])(convtransbias26_1)
conv26_2 = Conv2D(filters=64, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_78_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_78_Bias')))(prelu26_2)
conv26_3 = Conv2D(filters=64, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_79_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_79_Bias')))(prelu25_3)
maxunpool26_1 = MaxUnpooling2D(size=[2, 2])([conv26_3, maxpoolarg5_1[1]])
add26_1 = Add()([conv26_2, maxunpool26_1])
prelu26_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_89_Alpha')), shared_axes=[1, 2])(add26_1)
concat26_1 = Concatenate()([prelu26_3, prelu2_4])
# Block_27
conv27_1 = Conv2D(filters=4, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_80_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_80_Bias')))(concat26_1)
prelu27_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_90_Alpha')), shared_axes=[1, 2])(conv27_1)
conv27_2 = Conv2D(filters=4, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[8, 8],
kernel_initializer=Constant(np.load('weights/conv2d_81_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_81_Bias')))(prelu27_1)
prelu27_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_91_Alpha')), shared_axes=[1, 2])(conv27_2)
conv27_3 = Conv2D(filters=64, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_82_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_82_Bias')))(prelu27_2)
conv27_4 = Conv2D(filters=64, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_83_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_83_Bias')))(concat26_1)
add27_1 = Add()([conv27_3, conv27_4])
prelu27_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_92_Alpha')), shared_axes=[1, 2])(add27_1)
# Block_28
conv28_1 = Conv2D(filters=4, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_84_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_84_Bias')))(prelu27_3)
prelu28_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_93_Alpha')), shared_axes=[1, 2])(conv28_1)
convtransbias28_1 = Conv2DTranspose(filters=4, kernel_size=(3, 3), strides=(2, 2), padding='same',
kernel_initializer=Constant(np.load('weights/conv2d_transpose_2_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_transpose_2_Bias')))(prelu28_1)
prelu28_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_94_Alpha')), shared_axes=[1, 2])(convtransbias28_1)
conv28_2 = Conv2D(filters=32, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_85_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_85_Bias')))(prelu28_2)
conv28_3 = Conv2D(filters=32, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_86_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_86_Bias')))(prelu27_3)
maxunpool28_1 = MaxUnpooling2D(size=[2, 2])([conv28_3, maxpoolarg2_1[1]])
add28_1 = Add()([conv28_2, maxunpool28_1])
prelu28_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_95_Alpha')), shared_axes=[1, 2])(add28_1)
# Block_29
conv29_1 = Conv2D(filters=4, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_87_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_87_Bias')))(prelu28_3)
prelu29_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_96_Alpha')), shared_axes=[1, 2])(conv29_1)
conv29_2 = Conv2D(filters=4, kernel_size=[3, 3], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_88_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_88_Bias')))(prelu29_1)
prelu29_2 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_97_Alpha')), shared_axes=[1, 2])(conv29_2)
conv29_3 = Conv2D(filters=32, kernel_size=[1, 1], strides=[1, 1], padding='same', dilation_rate=[1, 1],
kernel_initializer=Constant(np.load('weights/conv2d_89_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_89_Bias')))(prelu29_2)
add29_1 = Add()([conv29_3, prelu28_3])
prelu29_3 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_98_Alpha')), shared_axes=[1, 2])(add29_1)
# Block_30
convtransbias30_1 = Conv2DTranspose(filters=8, kernel_size=(2, 2), strides=(2, 2), padding='same',
kernel_initializer=Constant(np.load('weights/conv2d_transpose_3_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_transpose_3_Bias')))(prelu29_3)
prelu30_1 = PReLU(alpha_initializer=Constant(np.load('weights/p_re_lu_99_Alpha')), shared_axes=[1, 2])(convtransbias30_1)
convtransbias30_2 = Conv2DTranspose(filters=2, kernel_size=(2, 2), strides=(2, 2), padding='same',
kernel_initializer=Constant(np.load('weights/conv2d_transpose_4_Kernel').transpose(1,2,3,0)),
bias_initializer=Constant(np.load('weights/conv2d_transpose_4_Bias')), name='conv2d_transpose_4')(prelu30_1)
# model = Model(inputs=inputs, outputs=[prelu2_4])
model = Model(inputs=inputs, outputs=[convtransbias30_2])
model.summary()
tf.saved_model.save(model, 'saved_model_{}x{}'.format(height, width))
model.save('hair_segmentation_{}x{}.h5'.format(height, width))
full_model = tf.function(lambda inputs: model(inputs))
full_model = full_model.get_concrete_function(inputs = (tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype)))
frozen_func = convert_variables_to_constants_v2(full_model, lower_control_flow=False)
frozen_func.graph.as_graph_def()
tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
logdir=".",
name="hair_segmentation_{}x{}_float32.pb".format(height, width),
as_text=False)
# No Quantization - Input/Output=float32
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
tflite_model = converter.convert()
with open('hair_segmentation_{}x{}_float32.tflite'.format(height, width), 'wb') as w:
w.write(tflite_model)
print("tflite convert complete! - hair_segmentation_{}x{}_float32.tflite".format(height, width))
# Weight Quantization - Input/Output=float32
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
tflite_model = converter.convert()
with open('hair_segmentation_{}x{}_weight_quant.tflite'.format(height, width), 'wb') as w:
w.write(tflite_model)
print("Weight Quantization complete! - hair_segmentation_{}x{}_weight_quant.tflite".format(height, width))
# def representative_dataset_gen():
# for image in raw_test_data:
# image = cv2.cvtColor(image, cv2.COLOR_RGB2RGBA)
# image = tf.image.resize(image, (height, width))
# image = image[np.newaxis,:,:,:]
# print('image.shape:', image.shape)
# yield [image]
# raw_test_data = np.load('calibration_data_img_person.npy', allow_pickle=True)
# # Integer Quantization - Input/Output=float32
# converter = tf.lite.TFLiteConverter.from_keras_model(model)
# converter.optimizations = [tf.lite.Optimize.DEFAULT]
# converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS]
# converter.representative_dataset = representative_dataset_gen
# tflite_quant_model = converter.convert()
# with open('hair_segmentation_{}x{}_integer_quant.tflite'.format(height, width), 'wb') as w:
# w.write(tflite_quant_model)
# print("Integer Quantization complete! - hair_segmentation_{}x{}_integer_quant.tflite".format(height, width))
# # Full Integer Quantization - Input/Output=int8
# converter = tf.lite.TFLiteConverter.from_keras_model(model)
# converter.optimizations = [tf.lite.Optimize.DEFAULT]
# converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS]
# converter.inference_input_type = tf.uint8
# converter.inference_output_type = tf.uint8
# converter.representative_dataset = representative_dataset_gen
# tflite_quant_model = converter.convert()
# with open('hair_segmentation_{}x{}_full_integer_quant.tflite'.format(height, width), 'wb') as w:
# w.write(tflite_quant_model)
# print("Full Integer Quantization complete! - hair_segmentation_{}x{}_full_integer_quant.tflite".format(height, width))
# # Float16 Quantization - Input/Output=float32
# converter = tf.lite.TFLiteConverter.from_keras_model(model)
# converter.optimizations = [tf.lite.Optimize.DEFAULT]
# converter.target_spec.supported_types = [tf.float16, tf.lite.OpsSet.SELECT_TF_OPS]
# tflite_quant_model = converter.convert()
# with open('hair_segmentation_{}x{}_float16_quant.tflite'.format(height, width), 'wb') as w:
# w.write(tflite_quant_model)
# print("Float16 Quantization complete! - hair_segmentation_{}x{}_float16_quant.tflite".format(height, width))
# # EdgeTPU
# import subprocess
# result = subprocess.check_output(["edgetpu_compiler", "-s", "hair_segmentation_{}x{}_full_integer_quant.tflite".format(height, width)])
# print(result)
|
enteletaor_lib/modules/brute/cmd_list_wordlists.py
|
Seabreg/enteletaor
| 159 |
145694
|
# -*- coding: utf-8 -*-
import os
import logging
log = logging.getLogger()
# ----------------------------------------------------------------------
def cmd_list_wordlists(config):
"""
Get all internal wordlist
"""
base_wordlists = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "resources", "wordlist"))
log.error(" - Available wordlists:")
for w in os.listdir(base_wordlists):
if "readme" not in w.lower():
log.error(" > %s" % w[:w.find(".txt")])
|
moneywagon/services/exchange_services.py
|
Detrous/moneywagon
| 147 |
145762
|
import json
import os
from requests.auth import HTTPBasicAuth
from moneywagon.core import (
Service, NoService, NoData, ServiceError, SkipThisService, currency_to_protocol,
decompile_scriptPubKey
)
from bitcoin import deserialize
import arrow
from bs4 import BeautifulSoup
import re
import hmac, hashlib, time, requests, base64
from requests.auth import AuthBase
try:
from urllib import urlencode, quote_plus
except ImportError:
from urllib.parse import urlencode, quote_plus
def make_standard_nonce(small=False):
num = int(time.time() * 1000)
if small:
return str(num - 1506215312123)
return str(num)
def make_stateful_nonce(exchange):
path = os.path.expanduser('~/.moneywagon_state')
if not os.path.exists(path):
# make
with open(path, "w+") as f:
f.write('{}')
with open(path) as f:
j = json.loads(f.read())
if exchange not in j:
j[exchange] = {'last_used_nonce': 0}
nonce = j[exchange].get('last_used_nonce', 0) + 1
j[exchange]['last_used_nonce'] = nonce
with open(path, "w") as f:
f.write(json.dumps(j))
return nonce
def eight_decimal_places(amount, format="str"):
"""
>>> eight_decimal_places(3.12345678912345)
"3.12345679"
>>> eight_decimal_places("3.12345678912345")
"3.12345679"
>>> eight_decimal_places(3.12345678912345, format='float')
3.12345679
>>> eight_decimal_places("3.12345678912345", format='float')
3.12345679
"""
if type(amount) == str:
return amount
if format == 'str':
return "%.8f" % amount
if format == 'float':
return float("%.8f" % amount)
class Bitstamp(Service):
service_id = 1
supported_cryptos = ['btc']
api_homepage = "https://www.bitstamp.net/api/"
name = "Bitstamp"
exchange_fee_rate = 0.0025
def __init__(self, customer_id=None, **kwargs):
self.customer_id = customer_id
super(Bitstamp, self).__init__(**kwargs)
def make_market(self, crypto, fiat):
return ("%s%s" % (crypto, fiat)).lower()
def get_current_price(self, crypto, fiat):
url = "https://www.bitstamp.net/api/v2/ticker/%s" % (
self.make_market(crypto, fiat)
)
response = self.get_url(url).json()
return float(response['last'])
def get_pairs(self):
return ['btc-usd', 'btc-eur', 'bch-btc', 'bch-usd', 'xrp-usd', 'xrp-eur', 'xrp-btc']
def get_orderbook(self, crypto, fiat):
url = "https://www.bitstamp.net/api/v2/order_book/%s/" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'bids': [(float(x[0]), float(x[1])) for x in resp['bids']],
'asks': [(float(x[0]), float(x[1])) for x in resp['asks']]
}
def _make_signature(self, nonce):
message = nonce + self.customer_id + self.api_key
return hmac.new(
self.api_secret,
msg=message,
digestmod=hashlib.sha256
).hexdigest().upper()
def _auth_request(self, url, params):
nonce = make_standard_nonce()
params.update({
'nonce': nonce,
'signature': self._make_signature(nonce),
'key': self.api_key,
})
return self.post_url(url, params)
def get_exchange_balance(self, currency, type="available"):
url = "https://www.bitstamp.net/api/balance/"
resp = self._auth_request(url, {}).json()
try:
return float(resp["%s_%s" % (currency.lower(), type)])
except KeyError:
return 0
def get_total_exchange_balances(self):
url = "https://www.bitstamp.net/api/balance/"
resp = self._auth_request(url, {}).json()
return {
code[:-8]: float(bal) for code, bal in resp.items()
if code.endswith("balance") and float(bal) > 0
}
def get_deposit_address(self, currency):
if currency.lower() == 'btc':
url = "https://www.bitstamp.net/api/bitcoin_deposit_address/"
return self._auth_request(url, {}).json()
if currency.lower() == 'xrp':
url = "https://www.bitstamp.net/api/ripple_address/"
return self._auth_request(url, {}).json()['address']
if currency.lower() in ['eth', 'ltc']:
url = "https://www.bitstamp.net/api/v2/%s_address/" % currency.lower()
return self._auth_request(url, {}).json()['address']
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
if type == 'limit':
url = "https://www.bitstamp.net/api/v2/%s/%s/" % (
side, self.make_market(crypto, fiat)
)
resp = self._auth_request(url, {
'amount': eight_decimal_places(amount),
'price': price,
})
if type == 'market':
url = "https://www.bitstamp.net/api/v2/%s/market/%s/" % (
side, self.make_market(crypto, fiat)
)
resp = self._auth_request(url, {
'amount': eight_decimal_places(amount),
})
return resp.json()
make_order.supported_types = ['limit', 'market']
make_order.minimums = {}
class CoinbaseExchangeAuth(AuthBase):
def __init__(self, api_key, secret_key, passphrase):
self.api_key = api_key
self.secret_key = secret_key
self.passphrase = passphrase
def __call__(self, request):
timestamp = str(time.time())
message = timestamp + request.method + request.path_url + (request.body or '')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'CB-ACCESS-PASSPHRASE': self.passphrase,
'Content-Type': 'application/json'
})
return request
class GDAX(Service):
service_id = 59
name = "GDAX"
base_url = "https://api.gdax.com"
api_homepage = "https://docs.gdax.com/"
supported_cryptos = ['btc', 'ltc', 'eth', 'bch']
exchange_fee_rate = 0.0025
def __init__(self, api_pass=None, **kwargs):
self.auth = None
self.api_pass = api_pass
super(GDAX, self).__init__(**kwargs)
if self.api_key and self.api_secret and self.api_pass:
self.auth = CoinbaseExchangeAuth(self.api_key, self.api_secret, self.api_pass)
def check_error(self, response):
if response.status_code != 200:
j = response.json()
raise ServiceError("GDAX returned %s error: %s" % (
response.status_code, j['message'])
)
super(GDAX, self).check_error(response)
def make_market(self, crypto, fiat):
return ("%s-%s" % (crypto, fiat)).upper()
def get_current_price(self, crypto, fiat):
url = "%s/products/%s/ticker" % (self.base_url, self.make_market(crypto, fiat))
response = self.get_url(url).json()
return float(response['price'])
def get_pairs(self):
url = "%s/products" % self.base_url
r = self.get_url(url).json()
return [x['id'].lower() for x in r]
def get_orderbook(self, crypto, fiat):
url = "%s/products/%s/book?level=3" % (self.base_url, self.make_market(crypto, fiat))
r = self.get_url(url).json()
return {
'bids': [(float(x[0]), float(x[1])) for x in r['bids']],
'asks': [(float(x[0]), float(x[1])) for x in r['asks']]
}
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
time_in_force = 'GTC'
if type == 'fill-or-kill':
type = 'limit'
time_in_force = 'FOK'
url = "%s/orders" % self.base_url
data = {
"size": eight_decimal_places(amount),
"type": type,
"price": price,
"side": side,
"time_in_force": time_in_force,
"product_id": self.make_market(crypto, fiat)
}
response = self.post_url(url, json=data, auth=self.auth).json()
return response['id']
make_order.supported_types = ['fill-or-kill', 'limit', 'market', 'stop']
make_order.minimums = {'btc': 0.0001, 'eth': 0.001, 'ltc': 0.01, 'usd': 1, 'eur': 1, 'gbp': 1}
def list_orders(self, status="open"):
url = "%s/orders" % self.base_url
response = self.get_url(url, auth=self.auth)
return response.json()
def cancel_order(self, order_id):
url = "%s/orders/%s" % (self.base_url, order_id)
response = self.delete_url(url, auth=self.auth)
return response.json()
def get_exchange_balance(self, currency, type="available"):
url = "%s/accounts" % self.base_url
resp = self.get_url(url, auth=self.auth).json()
try:
match = [x for x in resp if currency.upper() == x['currency']][0]
except IndexError:
return 0
return float(match[type])
def get_total_exchange_balances(self):
url = "%s/accounts" % self.base_url
resp = self.get_url(url, auth=self.auth).json()
return {
x['currency'].lower(): float(x['balance']) for x in resp
}
def initiate_withdraw(self, currency, amount, address):
url = "%s/withdrawals/crypto" % self.base_url
resp = self.post_url(url, auth=self.auth, json={
'crypto_address': address,
'currency': currency.upper(),
'amount': eight_decimal_places(amount)
})
return resp.json()
class BitFinex(Service):
service_id = 120
api_homepage = "https://bitfinex.readme.io/v2/reference"
exchange_fee_rate = 0.002
def check_error(self, response):
j = response.json()
if j and type(j) is list and j[0] == 'error':
raise SkipThisService(
"BitFinex returned Error: %s (%s)" % (j[2], j[1])
)
super(BitFinex, self).check_error(response)
def parse_market(self, market):
crypto = market[:3]
fiat = market[3:]
if crypto == 'dsh':
crypto = 'dash'
if crypto == 'iot':
crypto = 'miota'
return crypto, fiat
def fix_symbol(self, symbol):
if symbol == 'dash':
return 'dsh'
if symbol == 'miota':
return 'iot'
return symbol
def make_market(self, crypto, fiat):
return "%s%s" % (
self.fix_symbol(crypto).lower(), self.fix_symbol(fiat).lower()
)
def get_pairs(self):
url = "https://api.bitfinex.com/v1/symbols"
r = self.get_url(url).json()
return ["%s-%s" % self.parse_market(x) for x in r]
def get_current_price(self, crypto, fiat):
url = "https://api.bitfinex.com/v2/ticker/t%s" % self.make_market(crypto, fiat).upper()
r = self.get_url(url).json()
return r[6]
def get_orderbook(self, crypto, fiat):
url = "https://api.bitfinex.com/v1/book/%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'bids': [(float(x['price']), float(x['amount'])) for x in resp['bids']],
'asks': [(float(x['price']), float(x['amount'])) for x in resp['asks']]
}
def _make_signature(self, path, args, nonce, version=2):
if version == 2:
msg = '/api/' + path + nonce + json.dumps(args)
elif version == 1:
msg = nonce # actually payload, but passed in as nonce
return hmac.new(self.api_secret, msg, hashlib.sha384).hexdigest()
def _auth_request(self, path, params):
url = "https://api.bitfinex.com"
nonce = make_standard_nonce()
if path.startswith("/v2/"):
headers = {
'bfx-nonce': nonce,
'bfx-apikey': self.api_key,
'bfx-signature': self._make_signature(path, params, nonce, version=2)
}
elif path.startswith("/v1/"):
params['request'] = path
params['nonce'] = nonce
payload = base64.b64encode(json.dumps(params))
headers = {
'X-BFX-PAYLOAD': payload,
'X-BFX-APIKEY': self.api_key,
'X-BFX-SIGNATURE': self._make_signature(path, params, payload, version=1)
}
return self.post_url(url + path, json=params, headers=headers)
def get_deposit_address(self, crypto):
resp = self._auth_request("/v2/auth/r/wallets", {})
filt = [x[2] for x in resp.json() if x[1] == crypto.upper()]
return filt[0] if filt else 0
def get_exchange_balance(self, currency, type="available"):
curr = self.fix_symbol(currency)
resp = self._auth_request("/v1/balances", {}).json()
for item in resp:
if item['currency'] == curr.lower():
return float(item[type])
return 0
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
url = "/v1/order/new"
resp = self._auth_request(url, {
'symbol': self.make_market(crypto, fiat),
'amount': eight_decimal_places(amount),
'price': str(price),
'side': side,
'type': 'exchange %s' % type,
})
return resp.json()
make_order.supported_types = ['fill-or-kill', 'market', 'limit', 'stop', 'trailing-stop']
make_order.minimums = {}
def initiate_withdraw(self, crypto, amount, address):
from moneywagon.crypto_data import crypto_data
if crypto == 'etc':
type = "ethereumc"
else:
type = crypto_data[crypto.lower()]['name'].lower()
resp = self._auth_request("/v1/withdraw", {
"withdraw_type": type,
"walletselected": "exchange",
"amount": eight_decimal_places(amount),
"address": address,
}).json()
return resp
class NovaExchange(Service):
service_id = 89
name = "NovaExchange"
api_homepage = "https://novaexchange.com/remote/faq/"
def make_market(self, crypto, fiat):
return "%s_%s" % (fiat, crypto)
def check_error(self, response):
if response.json()['status'] == 'error':
raise ServiceError("NovaExchange returned error: %s" % response.json()['message'])
super(NovaExchange, self).check_error(response)
def get_current_price(self, crypto, fiat):
url = "https://novaexchange.com/remote/v2/market/info/%s" % self.make_market(crypto, fiat)
r = self.get_url(url).json()
return float(r['markets'][0]['last_price'])
def get_pairs(self):
url = "https://novaexchange.com/remote/v2/markets/"
r = self.get_url(url).json()
ret = []
for pair in r['markets']:
fiat = pair['basecurrency'].lower()
crypto = pair['currency'].lower()
ret.append("%s-%s" % (crypto, fiat))
return ret
def get_orderbook(self, crypto, fiat):
url = "https://novaexchange.com/remote/v2/market/openorders/%s/both/" % (
self.make_market(crypto, fiat)
)
r = self.get_url(url).json()
return {
'bids': [(float(x['price']), float(x['amount'])) for x in r['buyorders']],
'asks': [(float(x['price']), float(x['amount'])) for x in r['sellorders']],
}
def _make_signature(self, url):
return base64.b64encode(
hmac.new(self.api_secret, url, hashlib.sha512).digest()
)
def _auth_request(self, url, params):
url += '?nonce=' + make_standard_nonce()
params['apikey'] = self.api_key
params['signature'] = self._make_signature(url)
headers = {'content-type': 'application/x-www-form-urlencoded'}
return self.post_url(url, data=params, headers=headers, timeout=60)
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
url = "https://novaexchange.com/remote/v2/private/trade/%s/" % (
self.make_market(crypto, fiat)
)
params = {
'tradetype': side.upper(),
'tradeamount': eight_decimal_places(amount),
'tradeprice': price,
'tradebase': 0, # indicates "amount" is in crypto units, not fiat units
}
resp = self._auth_request(url, params)
return resp.json()['tradeitems'][0]['orderid']
make_order.minimums = {}
def cancel_order(self, order_id):
url = "https://novaexchange.com/remote/v2/private/cancelorder/%s/" % order_id
resp = self._auth_request(url, {})
return resp.json()['status'] == 'ok'
def list_orders(self, status="open"):
if status == 'open':
url = "https://novaexchange.com/remote/v2/private/myopenorders/"
else:
NotImplementedError("getting orders by status=%s not implemented yet" % status)
resp = self._auth_request(url, {})
return resp.json()['items']
def get_deposit_address(self, crypto):
url = "https://novaexchange.com/remote/v2/private/getdepositaddress/%s/" % crypto
resp = self._auth_request(url, {})
return resp.json()['address']
def initiate_withdraw(self, crypto, amount, address):
url = "https://novaexchange.com/remote/v2/private/withdraw/%s/" % crypto
params = {'currency': crypto, 'amount': eight_decimal_places(amount), 'address': address}
resp = self._auth_request(url, params)
return resp.json()
class xBTCe(Service):
service_id = 90
name = "xBTCe"
api_homepage = "https://www.xbtce.com/tradeapi"
def get_current_price(self, crypto, fiat):
if crypto.lower() == 'dash':
crypto = "dsh"
if fiat.lower() == 'rur':
fiat = 'rub'
if fiat.lower() == 'cny':
fiat = 'cnh'
pair = "%s%s" % (crypto.upper(), fiat.upper())
url = "https://cryptottlivewebapi.xbtce.net:8443/api/v1/public/ticker/%s" % pair
r = self.get_url(url).json()
try:
return r[0]['LastSellPrice']
except IndexError:
raise ServiceError("Pair not found")
def get_pairs(self):
url = "https://cryptottlivewebapi.xbtce.net:8443/api/v1/public/symbol"
r = self.get_url(url).json()
ret = []
for pair in r:
crypto = pair['MarginCurrency'].lower()
fiat = pair['ProfitCurrency'].lower()
if crypto.lower() == 'dsh':
crypto = "dash"
if fiat.lower() == 'rub':
fiat = 'rur'
if fiat == 'cnh':
fiat = 'cny'
ret.append(("%s-%s" % (crypto, fiat)))
return list(set(ret))
class OKcoin(Service):
service_id = 60
name = "OKcoin"
exchange_base_url = "https://www.okcoin.cn"
block_base_url = "http://block.okcoin.cn"
supported_cryptos = ['btc', 'ltc']
api_homepage = "https://www.okcoin.cn/rest_getStarted.html"
def get_current_price(self, crypto, fiat):
if not fiat == 'cny':
raise SkipThisService("Only fiat=CNY supported")
url = "%s/api/v1/ticker.do?symbol=%s_%s" % (
self.exchange_base_url, crypto.lower(), fiat.lower()
)
response = self.get_url(url).json()
return float(response['ticker']['last'])
def check_error(self, response):
j = response.json()
if 'error_code' in j:
raise ServiceError("OKcoin returned error code %s" % j['error_code'])
super(OKcoin, self).check_error(response)
def get_pairs(self):
return ['btc-cny', 'ltc-cny']
def get_block(self, crypto, block_hash=None, block_number=None, latest=False):
if latest:
args = 'latest_block.do?'
if block_number or block_number == 0:
args = "block_height.do?block_height=%s&" % block_number
if block_hash:
raise SkipThisService("Block by hash not supported")
url = "%s/api/v1/%ssymbol=%s" % (
self.block_base_url, args, crypto.upper()
)
r = self.get_url(url).json()
ret = dict(
block_number=r['height'],
size=r['size'],
time=arrow.get(r['time'] / 1000).datetime,
hash=r['hash'],
txids=r['txid'],
tx_count=r['txcount'],
version=r['version'],
mining_difficulty=r['difficulty'],
total_fees=r['fee'],
sent_value=r['totalOut']
)
if r.get('relayed_by'):
ret['miner'] = r['relayed_by']
if r.get('previousblockhash'):
ret['previous_hash'] = r['previousblockhash']
if r.get('nextblockhash'):
ret['next_hash'] = r['nextblockhash']
return ret
class FreeCurrencyConverter(Service):
service_id = 61
base_url = "http://free.currencyconverterapi.com"
api_homepage = "http://www.currencyconverterapi.com/docs"
def get_fiat_exchange_rate(self, from_fiat, to_fiat):
pair = "%s_%s" % (to_fiat.upper(), from_fiat.upper())
url = "%s/api/v3/convert?q=%s&compact=y" % (
self.base_url, pair
)
response = self.get_url(url).json()
return response[pair]['val']
class BTCChina(Service):
service_id = 62
api_homepage = "https://www.btcc.com/apidocs/spot-exchange-market-data-rest-api#ticker"
name = "BTCChina"
def get_current_price(self, crypto, fiat):
if fiat == 'usd':
url = "https://spotusd-data.btcc.com/data/pro/ticker?symbol=%sUSD" % crypto.upper()
key = "Last"
else:
url = "https://data.btcchina.com/data/ticker?market=%s%s" % (
crypto.lower(), fiat.lower()
)
key = "last"
response = self.get_url(url).json()
if not response:
raise ServiceError("Pair not supported (blank response)")
return float(response['ticker'][key])
class Gemini(Service):
service_id = 63
api_homepage = "https://docs.gemini.com/rest-api/"
name = "Gemini"
exchange_fee_rate = 0.0025
def check_error(self, response):
j = response.json()
if 'result' in j and j['result'] == 'error':
raise ServiceError("Gemini returned error: %s" % j['reason'])
super(Gemini, self).check_error(response)
def make_market(self, crypto, fiat):
return "%s%s" % (crypto.lower(), fiat.lower())
def get_current_price(self, crypto, fiat):
url = "https://api.gemini.com/v1/pubticker/%s" % self.make_market(crypto, fiat)
response = self.get_url(url).json()
return float(response['last'])
def get_orderbook(self, crypto, fiat):
url = "https://api.gemini.com/v1/book/%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'bids': [(float(x['price']), float(x['amount'])) for x in resp['bids']],
'asks': [(float(x['price']), float(x['amount'])) for x in resp['asks']]
}
def _make_signature(self, payload):
return hmac.new(self.api_secret, payload, hashlib.sha384).hexdigest()
def _auth_request(self, path, params):
params['nonce'] = make_standard_nonce()
params['request'] = path
payload = base64.b64encode(json.dumps(params))
headers = {
'X-GEMINI-APIKEY': self.api_key,
'X-GEMINI-PAYLOAD': payload,
'X-GEMINI-SIGNATURE': self._make_signature(payload)
}
return self.post_url("https://api.gemini.com" + path, headers=headers)
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
path = "/v1/order/new"
#order_token = "" % datetime.datetime.now()
opts = []
if type == 'fill-or-kill':
opts = ['immediate-or-cancel']
type = "limit"
if type == 'post-only':
opts = ["maker-or-cancel"]
type = 'limit'
if type != "limit":
raise NotImplementedError("Only limit orders currently supported")
params = {
#"client_order_id": order_token, # A client-specified order token
"symbol": self.make_market(crypto, fiat), # Or any symbol from the /symbols api
"amount": eight_decimal_places(amount), # Once again, a quoted number
"price": str(price),
"side": side, # must be "buy" or "sell"
"type": "exchange %s" % type, # the order type; only "exchange limit" supported
"options": opts # execution options; may be omitted for a standard limit order
}
resp = self._auth_request(path, params).json()
return resp
make_order.supported_types = ['post-only', 'limit', 'fill-or-kill']
make_order.minimums = {}
def get_deposit_address(self, currency):
path = "/v1/deposit/%s/newAddress" % currency.lower()
resp = self._auth_request(path, {})
return resp.json()['address']
def get_exchange_balance(self, currency, type="available"):
path = "/v1/balances"
resp = self._auth_request(path, {})
try:
match = [x for x in resp.json() if x['currency'] == currency.upper()][0]
except IndexError:
return 0
return float(match[type])
def get_total_exchange_balances(self):
path = "/v1/balances"
resp = self._auth_request(path, {})
return {
x['currency'].lower(): float(x['amount']) for x in resp.json()
if float(x['amount']) > 0
}
class CexIO(Service):
service_id = 64
api_homepage = "https://cex.io/rest-api"
name = "Cex.io"
exchange_fee_rate = 0.002
def __init__(self, user_id=None, **kwargs):
self.user_id = user_id
super(CexIO, self).__init__(**kwargs)
def check_error(self, response):
super(CexIO, self).check_error(response)
j = response.json()
if 'error' in j:
raise ServiceError("CexIO returned error: %s" % j['error'])
def get_current_price(self, crypto, fiat):
url = "https://cex.io/api/ticker/%s/%s" % (crypto.upper(), fiat.upper())
response = self.get_url(url).json()
return float(response['last'])
def get_pairs(self):
url = "https://cex.io/api/currency_limits"
r = self.get_url(url).json()['data']['pairs']
return [("%s-%s" % (x['symbol1'], x['symbol2'])).lower() for x in r]
def get_orderbook(self, crypto, fiat):
url = "https://cex.io/api/order_book/%s/%s/" % (crypto.upper(), fiat.upper())
resp = self.get_url(url).json()
return {
'bids': [(x[0], x[1]) for x in resp['bids']],
'asks': [(x[0], x[1]) for x in resp['asks']]
}
def _make_signature(self, nonce):
message = nonce + self.user_id + self.api_key
return hmac.new(self.api_secret, message, hashlib.sha256).hexdigest().upper()
def _auth_request(self, url, params):
nonce = make_standard_nonce()
params['nonce'] = nonce
params['signature'] = self._make_signature(nonce)
params['key'] = self.api_key
return self.post_url(url, params)
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
url = "https://cex.io/api/place_order/%s/%s" % (crypto.upper(), fiat.upper())
if type in ('limit', 'market'):
print("about to send amount to cex:", eight_decimal_places(amount))
params = {
'type': side,
'amount': eight_decimal_places(amount),
}
if type == 'market':
params['order_type'] = 'market'
if type == 'limit':
params['price'] = price
else:
raise Exception("Order with type=%s not yet supported" % type)
resp = self._auth_request(url, params).json()
return resp['id']
make_order.supported_types = ['limit', 'market']
make_order.minimums = {'btc': 0.01}
def list_orders(self):
url = "https://cex.io/api/open_orders/"
resp = self._auth_request(url, {})
return resp.json()
def cancel_order(self, order_id):
url = "https://cex.io/api/cancel_order/"
resp = self._auth_request(url, {'id': order_id})
return resp.content == 'true'
def get_deposit_address(self, crypto):
url = "https://cex.io/api/get_address"
resp = self._auth_request(url, {'currency': crypto.upper()})
return resp.json()['data']
def get_exchange_balance(self, currency, type="available"):
url = "https://cex.io/api/balance/"
resp = self._auth_request(url, {})
try:
return float(resp.json()[currency.upper()]['available'])
except KeyError:
return 0
def get_total_exchange_balances(self):
url = "https://cex.io/api/balance/"
resp = self._auth_request(url, {})
return {
code.lower(): float(data['available']) for code, data in resp.json().items()
if code not in ['timestamp', 'username'] and float(data['available']) > 0
}
class Poloniex(Service):
service_id = 65
api_homepage = "https://poloniex.com/support/api/"
name = "Poloniex"
exchange_fee_rate = 0.0025
def check_error(self, response):
j = response.json()
if 'error' in j:
raise ServiceError("Poloniex returned error: %s" % j['error'])
super(Poloniex, self).check_error(response)
def fix_symbol(self, symbol):
symbol = symbol.lower()
if symbol == 'usd':
return 'usdt'
if symbol == 'xlm':
return 'str'
return symbol
def reverse_fix_symbol(self, symbol):
symbol = symbol.lower()
if symbol == 'usdt':
return 'usd'
if symbol == 'str':
return 'xlm'
return symbol
def get_current_price(self, crypto, fiat):
url = "https://poloniex.com/public?command=returnTicker"
response = self.get_url(url).json()
is_usd = False
if fiat.lower() == 'usd':
fiat = 'usdt'
is_usd = True
find_pair = "%s_%s" % (fiat.upper(), crypto.upper())
for pair, data in response.items():
if pair == find_pair:
return float(data['last'])
reverse_pair = "%s_%s" % (crypto.upper(), fiat.upper())
for pair, data in response.items():
if pair == reverse_pair:
return 1 / float(data['last'])
btc_pair = "BTC_%s" % crypto.upper()
if is_usd and btc_pair in response:
btc_rate = float(response['USDT_BTC']['last'])
fiat_exchange = float(response[btc_pair]['last'])
return fiat_exchange * btc_rate
raise SkipThisService("Pair %s not supported" % find_pair)
def get_pairs(self):
url = "https://poloniex.com/public?command=returnTicker"
r = self.get_url(url).json()
ret = []
for pair in r.keys():
fiat, crypto = pair.lower().split('_')
ret.append("%s-%s" % (self.reverse_fix_symbol(crypto), self.reverse_fix_symbol(fiat)))
return ret
def get_orderbook(self, crypto, fiat):
url = "https://poloniex.com/public?command=returnOrderBook¤cyPair=%s" % (
self.make_market(crypto, fiat)
)
resp = self.get_url(url).json()
return {
'asks': [(float(x[0]), x[1]) for x in resp['asks']],
'bids': [(float(x[0]), x[1]) for x in resp['bids']]
}
def make_market(self, crypto, fiat):
return ("%s_%s" % (self.fix_symbol(fiat), self.fix_symbol(crypto))).upper()
def _make_signature(self, args):
str_args = urlencode(args)
return hmac.new(self.api_secret, str_args, hashlib.sha512).hexdigest()
def _auth_request(self, args):
url = "https://poloniex.com/tradingApi"
args["nonce"] = make_standard_nonce()
headers = {
'Sign': self._make_signature(args),
'Key': self.api_key
}
return self.post_url(url, args, headers=headers)
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
params = {}
if type == "fill-or-kill":
params = {'fillOrKill': 1}
if type == 'post-only':
params = {'postOnly': 1}
params.update({
"command": side,
"currencyPair": self.make_market(crypto, fiat),
"rate": price,
"amount": eight_decimal_places(amount)
})
r = self._auth_request(params)
return r.json()['orderNumber']
make_order.supported_types = ['limit', 'fill-or-kill', 'post-only']
make_order.minimums = {}
def cancel_order(self, order_id):
r = self._auth_request({
"command": "cancelOrder",
"orderNumber": order_id
})
return r['success'] == 1
def list_orders(self, crypto=None, fiat=None):
if not crypto and not fiat:
pair = "all"
else:
self.make_market(crypto, fiat)
resp = self._auth_request({
"command": "returnOpenOrders",
"currencyPair": pair,
})
return resp.json()
def initiate_withdraw(self, crypto, amount, address):
resp = self._auth_request({
"command": "withdrawl",
"currency": crypto,
"amount": eight_decimal_places(amount),
"address": address
})
return resp.json()
def get_deposit_address(self, currency):
c = self.fix_symbol(currency)
resp = self._auth_request({"command": "returnDepositAddresses"})
address = resp.json().get(c.upper())
if not address:
return self.generate_new_deposit_address(c)
return address
def generate_new_deposit_address(self, crypto):
resp = self._auth_request({
"command": "generateNewAddress",
"currency": crypto.upper()
})
return resp.json()['response']
def get_exchange_balance(self, currency, type="available"):
resp = self._auth_request({"command": "returnBalances"})
return float(resp.json().get(self.reverse_fix_symbol(currency).upper()))
def get_total_exchange_balances(self):
resp = self._auth_request({"command": "returnBalances"})
return {
self.reverse_fix_symbol(code): float(bal) for code, bal in resp.json().items()
if float(bal) > 0
}
class Bittrex(Service):
service_id = 66
api_homepage = "https://bittrex.com/home/api"
exchange_fee_rate = 0.0025
def check_error(self, response):
j = response.json()
if not j['success']:
raise ServiceError("Bittrex returned error: %s" % j['message'])
super(Bittrex, self).check_error(response)
def fix_symbol(self, symbol):
if symbol.lower() == 'usd':
return 'usdt'
if symbol == 'xmy':
return 'myr'
if symbol == 'bcc':
raise SkipThisService("BCC not supported (maybe you want BCH?)")
if symbol == 'bch':
return 'bcc'
return symbol.lower()
def reverse_fix_symbol(self, symbol):
symbol = symbol.lower()
if symbol == 'usdt':
return 'usd'
if symbol == 'bcc':
return 'bch'
return symbol
def make_market(self, crypto, fiat):
return "%s-%s" % (
self.fix_symbol(fiat).upper(),
self.fix_symbol(crypto).upper()
)
def get_current_price(self, crypto, fiat):
url = "https://bittrex.com/api/v1.1/public/getticker?market=%s" % (
self.make_market(crypto, fiat)
)
r = self.get_url(url).json()
return r['result']['Last']
def get_orderbook(self, crypto, fiat):
url = "https://bittrex.com/api/v1.1/public/getorderbook?market=%s&type=both" % (
self.make_market(crypto, fiat)
)
r = self.get_url(url).json()['result']
return {
'bids': [(x['Rate'], x['Quantity']) for x in r['buy']],
'asks': [(x['Rate'], x['Quantity']) for x in r['sell']],
}
def get_pairs(self):
url = "https://bittrex.com/api/v1.1/public/getmarkets"
r = self.get_url(url).json()['result']
ret = []
for x in r:
crypto = x['MarketCurrency'].lower()
fiat = x['BaseCurrency'].lower()
if fiat == 'usdt':
fiat = 'usd'
ret.append("%s-%s" % (crypto, fiat))
return ret
def _make_signature(self, url):
return hmac.new(
self.api_secret.encode(), url.encode(), hashlib.sha512
).hexdigest()
def _auth_request(self, path, params):
if not self.api_key or not self.api_secret:
raise Exception("Trade API requires an API key and secret.")
params["apikey"] = self.api_key
params["nonce"] = make_standard_nonce()
url = "https://bittrex.com/api" + path + "?" + urlencode(params)
return self.get_url(url, headers={"apisign": self._make_signature(url)})
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
path = "/v1.1/market/%slimit" % side
r = self._auth_request(path, {
'market': self.make_market(crypto, fiat),
'quantity': eight_decimal_places(amount),
'rate': price
})
return r.json()['result']['uuid']
make_order.supported_types = ['limit']
make_order.minimums = {}
def cancel_order(self, order_id):
path = "/v1.1/market/cancel"
r = self._auth_request(path, {'uuid': order_id})
return r['success']
def get_exchange_balance(self, currency, type="available"):
currency = self.fix_symbol(currency)
path = "/v1.1/account/getbalance"
resp = self._auth_request(path, {'currency': self.fix_symbol(currency)}).json()['result']
return resp[type.capitalize()] or 0
def get_total_exchange_balances(self):
path = "/v1.1/account/getbalances"
resp = self._auth_request(path, {}).json()['result']
return {
self.reverse_fix_symbol(x['Currency']): x['Balance'] for x in resp
if x['Balance'] > 0
}
def get_deposit_address(self, crypto):
path = "/v1.1/account/getdepositaddress"
resp = self._auth_request(path, {'currency': self.fix_symbol(crypto)})
return resp.json()['result']['Address']
def initiate_withdraw(self, crypto, amount, address):
path = "/v1.1/account/withdraw"
resp = self._auth_request(path, {
'currency': self.fix_symbol(crypto),
'quantity': eight_decimal_places(amount),
'address': address
})
return resp.json()
class Huobi(Service):
service_id = 67
api_homepage = "https://github.com/huobiapi/API_Docs_en/wiki"
name = "Huobi"
def check_error(self, response):
if response.status_code != 200:
j = response.json()
raise ServiceError("Huobi returned error: %s" % j['error'])
super(Huobi, self).check_error(response)
def get_current_price(self, crypto, fiat):
if fiat.lower() == "cny":
fiat = 'static'
elif fiat.lower() == 'usd':
pass
else:
raise SkipThisService("CNY and USD only fiat supported")
url = "http://api.huobi.com/%smarket/detail_%s_json.js" % (
fiat.lower(), crypto.lower()
)
r = self.get_url(url).json()
return r['p_last']
class BTER(Service):
service_id = 25
api_homepage = "https://bter.com/api"
name = "BTER"
def fix_symbol(self, symbol):
if symbol == 'bch':
return 'bcc'
return symbol
def make_market(self, crypto, fiat):
return ("%s_%s" % (self.fix_symbol(crypto), fiat)).lower()
def get_current_price(self, crypto, fiat):
url = "http://data.bter.com/api/1/ticker/%s" % self.make_market(crypto, fiat)
response = self.get_url(url).json()
if response.get('result', '') == 'false':
raise ServiceError("BTER returned error: " + r['message'])
return float(response['last'] or 0)
def get_pairs(self):
url = "http://data.bter.com/api/1/pairs"
r = self.get_url(url).json()
return [x.replace("_", "-") for x in r]
def get_orderbook(self, crypto, fiat):
url = "http://data.bter.com/api2/1/orderBook/%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'bids': [(float(x[0]), float(x[1])) for x in resp['bids']],
'asks': [(float(x[0]), float(x[1])) for x in resp['asks']],
}
def _make_signature(self, params):
return hmac.new(
self.api_secret, urlencode(params), hashlib.sha512
).hexdigest()
def _auth_request(self, url, params):
raise Exception("Not tested")
return self.post_url(url, headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Key': self.api_key,
'Sign': self._make_signature(params)
})
def get_exchange_balance(self, currency, type="available"):
url = "https://api.bter.com/api2/1/private/balances"
resp = self._auth_request(url, {})
for curr, bal in resp.json()[type].items():
if curr == currency.upper():
return float(bal)
def get_deposit_address(self, currency):
url = "https://bter.com/api2/1/private/depositAddress"
resp = self._auth_request(url, {'currency': currency.upper()})
return resp.json()['addr']
class Wex(Service):
service_id = 7
api_homepage = "https://wex.nz/api/documentation"
name = "Wex"
exchange_fee_rate = 0.002
def check_error(self, response):
try:
j = response.json()
except:
raise ServiceError("Wex returned error: %s" % response.content)
if 'error' in j:
raise ServiceError("Wex returned error: %s" % j['error'])
super(Wex, self).check_error(response)
def make_market(self, crypto, fiat):
return "%s_%s" % (
self.fix_symbol(crypto).lower(),
self.fix_symbol(fiat).lower()
)
def fix_symbol(self, symbol):
if symbol == 'dash':
return 'dsh'
return symbol
def reverse_fix_symbol(self, symbol):
if symbol == 'dsh':
return 'dash'
return symbol
def _fix_fiat_symbol(self, fiat):
return fiat
def get_current_price(self, crypto, fiat):
pair = self.make_market(crypto, fiat)
url = "https://wex.nz/api/3/ticker/" + pair
response = self.get_url(url).json()
return response[pair]['last']
def get_pairs(self):
url = "https://wex.nz/api/3/info"
r = self.get_url(url).json()
return [x.replace('_', '-') for x in r['pairs'].keys()]
def get_orderbook(self, crypto, fiat):
m = self.make_market(crypto, fiat)
url = "https://wex.nz/api/3/depth/%s" % m
resp = self.get_url(url).json()
return {
'bids': [(x[0], x[1]) for x in resp[m]['bids']],
'asks': [(x[0], x[1]) for x in resp[m]['asks']]
}
def _make_signature(self, params):
return hmac.new(
self.api_secret, urlencode(params), hashlib.sha512
).hexdigest()
def _auth_request(self, params):
# max nonce wex will accept is 4294967294
params['nonce'] = make_stateful_nonce(self.name)
headers = {"Key": self.api_key, "Sign": self._make_signature(params)}
return self.post_url("https://wex.nz/tapi", params, headers=headers)
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
params = {
'method': 'Trade',
'pair': self.make_market(crypto, fiat),
'type': side,
'rate': price,
'amount': eight_decimal_places(amount),
}
return self._auth_request(params)
make_order.supported_types = ['limit']
make_order.minimums = {'btc': 0.001, 'ltc': 0.1}
def get_deposit_address(self, crypto):
params = {'coinName': crypto.lower(), 'method': 'CoinDepositAddress'}
resp = self._auth_request(params).json()
return resp['return']['address']
def get_exchange_balance(self, currency, type="available"):
resp = self._auth_request({'method': 'getInfo'}).json()
try:
return resp['return']['funds'][self.fix_symbol(currency).lower()]
except IndexError:
return 0
def get_total_exchange_balances(self):
resp = self._auth_request({'method': 'getInfo'}).json()['return']['funds']
return {
self.reverse_fix_symbol(code): bal for code, bal in resp.items()
if not code.endswith("et") and bal > 0
}
def initiate_withdraw(self, currency, amount, address):
resp = self._auth_request({
'method': 'WithdrawCoin',
'coinName': self.fix_symbol(currency),
'amount': amount,
'address': address,
})
return resp.json()
class ViaBTC(Service):
service_id = 116
def get_current_price(self, crypto, fiat):
url = "https://www.viabtc.com/api/v1/market/ticker?market=%s%s" % (
crypto.upper(), fiat.upper()
)
return float(self.get_url(url).json()['data']['ticker']['last'])
class CryptoDao(Service):
service_id = 115
api_homepage = "https://cryptodao.com/doc/api"
def get_current_price(self, crypto, fiat):
url = "https://cryptodao.com/api/ticker?source=%s&target=%s" % (
fiat.upper(), crypto.upper()
)
r = self.get_url(url).json()
return r['last']
def get_orderbook(self, crypto, fiat):
url = "https://cryptodao.com/api/depth?source=%s&target=%s" % (
fiat.upper(), crypto.upper()
)
resp = self.get_url(url).json()
return resp
class HitBTC(Service):
service_id = 109
api_homepage = "https://hitbtc.com/api"
exchange_fee_rate = 0.001
def check_error(self, response):
j = response.json()
if response.status_code in (400, 401) and 'error' in j:
e = j['error']
raise SkipThisService("HitBTC returned %s %s: %s" % (
e['code'], e['message'], e['description']
))
if 'code' in j:
raise SkipThisService("HitBTC returned %s: %s" % (j['code'], j['message']))
super(HitBTC, self).check_error(response)
def fix_symbol(self, symbol):
return symbol.lower()
def make_market(self, crypto, fiat):
return ("%s%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper()
def get_pairs(self):
url = 'https://api.hitbtc.com/api/1/public/symbols'
r = self.get_url(url).json()['symbols']
return [("%s-%s" % (x['commodity'], x['currency'])).lower() for x in r]
def get_current_price(self, crypto, fiat):
url = "https://api.hitbtc.com/api/1/public/%s/ticker" % self.make_market(crypto, fiat)
r = self.get_url(url).json()
return float(r['last'])
def get_orderbook(self, crypto, fiat):
url = "https://api.hitbtc.com/api/1/public/%s/orderbook" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'asks': [(float(x[0]), float(x[1])) for x in resp['asks']],
'bids': [(float(x[0]), float(x[1])) for x in resp['bids']]
}
def _auth_request(self, path, params, method="post"):
path = path + "?" + urlencode({
'nonce': make_standard_nonce(),
'apikey': self.api_key
})
headers = {"X-Signature": self._make_signature(path, params)}
return self._external_request(
method, "https://api.hitbtc.com" + path,
params, headers=headers
)
def _make_signature(self, path, params):
msg = path + urlencode(params)
return hmac.new(self.api_secret, msg, hashlib.sha512).hexdigest()
def get_exchange_balance(self, currency, type="available"):
resp = self._auth_request("/api/1/trading/balance", {}, method="get").json()
c = self.fix_symbol(currency).upper()
try:
matched = [x for x in resp['balance'] if x['currency_code'] == c][0]
except IndexError:
return 0
if type == 'available':
return float(matched['cash'])
raise NotImplemented()
def get_total_exchange_balances(self):
resp = self._auth_request("/api/1/trading/balance", {}, method="get")
return {
self.fix_symbol(x['currency_code']): float(x['cash'])
for x in resp.json()['balance'] if float(x['cash']) > 0
}
def get_deposit_address(self, currency):
path = "/api/1/payment/address/%s" % self.fix_symbol(currency).upper()
resp = self._auth_request(path, {}, method="get").json()
return resp['address']
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
path = "/api/1/trading/new_order"
import random, string
clientOrderId = "".join(random.choice(string.digits + string.ascii_lowercase) for _ in range(30))
params = {
'symbol': self.make_market(crypto, fiat),
'side': side,
'price': price,
'quantity': eight_decimal_places(amount),
'clientOrderId': clientOrderId
}
if type == 'fill-or-kill':
params['timeInForce'] = 'FOK'
resp = self._auth_request(path, params).json()
return resp
make_order.minimums = {}
make_order.supported_types = ['fill-or-kill', 'limit']
class Liqui(Service):
service_id = 106
def parse_market(self, market):
crypto, fiat = market.split("_")
if fiat == 'usdt':
fiat = 'usd'
return crypto, fiat
def get_pairs(self):
url = "https://api.liqui.io/api/3/info"
r = self.get_url(url).json()['pairs']
return ["%s-%s" % self.parse_market(x) for x in r.keys()]
def make_market(self, crypto, fiat):
return "%s_%s" % (
self.fix_symbol(crypto).lower(), self.fix_symbol(fiat).lower()
)
def fix_symbol(self, symbol):
if symbol == 'usd':
return 'usdt'
return symbol
def get_current_price(self, crypto, fiat):
pair = self.make_market(crypto, fiat)
url = "https://api.liqui.io/api/3/ticker/%s" % pair
return self.get_url(url).json()[pair]['last']
def get_orderbook(self, crypto, fiat):
pair = self.make_market(crypto, fiat)
url = "https://api.liqui.io/api/3/depth/%s" % pair
return self.get_url(url).json()[pair]
def _make_signature(self, params):
return hmac.new(
self.api_secret, "?" + urlencode(params), hashlib.sha512
).hexdigest()
def _auth_request(self, params):
params['nonce'] = make_standard_nonce(small=True)
headers = {
'Key':self.api_key,
'Sign': self._make_signature(params)
}
return self.post_url('https://api.liqui.io', params, headers=headers)
def get_exchange_balance(self, currency):
resp = self._auth_request({'method': 'getInfo'}).json()
return resp
def list_orders(self, crypto=None, fiat=None):
resp = self._auth_request({'method': 'ActiveOrders'}).json()
return resp
class CoinOne(Service):
service_id = 105
def get_pairs(self):
return ['btc-krw', 'eth-krw', 'xrp-krw', 'etc-krw']
def get_current_price(self, crypto, fiat):
url = "https://api.coinone.co.kr/ticker?currency=%s" % crypto.lower()
return float(self.get_url(url).json()['last'])
class CryptoBG(Service):
service_id = 102
def get_current_price(self, crypto, fiat):
url = "https://crypto.bg/api/v1/public_rates"
if crypto != 'btc' or fiat != 'bgn':
raise SkipThisService("Only btc-bgn supported")
return float(self.get_url(url).json()['rates']['bitcoin']['bid'])
class Bitso(Service):
service_id = 101
def get_current_price(self, crypto, fiat):
url = "https://api.bitso.com/v3/ticker/?book=%s_%s" % (crypto, fiat)
r = self.get_url(url.lower()).json()
return float(['payload']['last'])
def get_pairs(self):
url = "https://api.bitso.com/v3/available_books/"
r = self.get_url(url).json()['payload']
return [x['book'].replace("_", '-') for x in r]
class TradeSatoshi(Service):
service_id = 96
def get_pairs(self):
url = "https://tradesatoshi.com/api/public/getmarketsummaries"
r = self.get_url(url).json()
return [x['market'].replace("_", '-').lower() for x in r['result']]
def get_current_price(self, crypto, fiat):
url = "https://tradesatoshi.com/api/public/getticker?market=%s_%s" % (
crypto.upper(), fiat.upper()
)
return self.get_url(url).json()['result']['last']
class UseCryptos(Service):
service_id = 95
def get_pairs(self):
url = "https://usecryptos.com/jsonapi/pairs"
r = self.get_url(url).json()
return r
def get_current_price(self, crypto, fiat):
pair = "%s-%s" % (crypto.lower(), fiat.lower())
url = "https://usecryptos.com/jsonapi/ticker/%s" % pair
return self.get_url(url).json()['lastPrice']
class BitcoinIndonesia(Service):
service_id = 94
api_homepage = "https://blog.bitcoin.co.id/wp-content/uploads/2014/03/API-Documentation-Bitcoin.co_.id_.pdf"
def get_current_price(self, crypto, fiat):
url = "https://vip.bitcoin.co.id/api/%s_%s/ticker" % (crypto.lower(), fiat.lower())
return float(self.get_url(url).json()['ticker']['last'])
class Kraken(Service):
service_id = 93
def check_error(self, response):
if response.json()['error']:
raise ServiceError("Kraken returned error: %s" % response.json()['error'][0])
super(Kraken, self).check_error(response)
def get_pairs(self):
url = "https://api.kraken.com/0/public/AssetPairs"
r = self.get_url(url).json()['result']
ret = []
for name, data in r.items():
crypto = data['base'].lower()
if len(crypto) == 4 and crypto.startswith('x'):
crypto = crypto[1:]
fiat = data['quote'].lower()
if fiat.startswith("z"):
fiat = fiat[1:]
if crypto == 'xbt':
crypto = 'btc'
if fiat == 'xxbt':
fiat = 'btc'
if fiat == 'xeth':
fiat = 'eth'
ret.append("%s-%s" % (crypto, fiat))
return list(set(ret))
def get_current_price(self, crypto, fiat):
if crypto != 'bch':
crypto = "x" + crypto.lower()
if crypto == 'xbtc':
crypto = 'xxbt'
fiat = "z" + fiat.lower()
if fiat == 'zbtc':
fiat = 'xxbt'
else:
# bch pairs have completely different format for some reason
# my god kraken's api is terrible
if fiat.lower() == 'btc':
fiat = 'xbt'
pair = "%s%s" % (crypto.upper(), fiat.upper())
url = "https://api.kraken.com/0/public/Ticker?pair=%s" % pair
r = self.get_url(url).json()['result']
return float(r[pair]['c'][0])
class BTC38(Service):
service_id = 92
api_homepage = "http://www.btc38.com/help/document/2581.html"
def get_current_price(self, crypto, fiat):
url = 'http://api.btc38.com/v1/ticker.php?c=%s&mk_type=%s' % (crypto, fiat)
return self.get_url(url).json()['ticker']['last']
def get_pairs(self):
url = "http://api.btc38.com/v1/ticker.php?c=all&mk_type=cny"
cny_bases = self.get_url(url).json().keys()
url = "http://api.btc38.com/v1/ticker.php?c=all&mk_type=btc"
btc_bases = self.get_url(url).json().keys()
return ["%s-cny" % x for x in cny_bases] + ["%s-btc" % x for x in btc_bases]
class BleuTrade(Service):
service_id = 91
api_homepage = 'https://bleutrade.com/help/API'
def get_pairs(self):
url = 'https://bleutrade.com/api/v2/public/getmarkets'
r = self.get_url(url).json()['result']
return [x['MarketName'].lower().replace("_", '-') for x in r]
def get_current_price(self, crypto, fiat):
url = "https://bleutrade.com/api/v2/public/getticker?market=%s_%s" % (
crypto.upper(), fiat.upper()
)
r = self.get_url(url).json()
return float(r['result'][0]['Last'])
class xBTCe(Service):
service_id = 90
name = "xBTCe"
api_homepage = "https://www.xbtce.com/tradeapi"
def get_current_price(self, crypto, fiat):
if crypto.lower() == 'dash':
crypto = "dsh"
if fiat.lower() == 'rur':
fiat = 'rub'
if fiat.lower() == 'cny':
fiat = 'cnh'
pair = "%s%s" % (crypto.upper(), fiat.upper())
url = "https://cryptottlivewebapi.xbtce.net:8443/api/v1/public/ticker/%s" % pair
r = self.get_url(url).json()
try:
return r[0]['LastSellPrice']
except IndexError:
raise ServiceError("Pair not found")
def get_pairs(self):
url = "https://cryptottlivewebapi.xbtce.net:8443/api/v1/public/symbol"
r = self.get_url(url).json()
ret = []
for pair in r:
crypto = pair['MarginCurrency'].lower()
fiat = pair['ProfitCurrency'].lower()
if crypto.lower() == 'dsh':
crypto = "dash"
if fiat.lower() == 'rub':
fiat = 'rur'
if fiat == 'cnh':
fiat = 'cny'
ret.append(("%s-%s" % (crypto, fiat)))
return list(set(ret))
class Cryptopia(Service):
service_id = 82
api_homepage = "https://www.cryptopia.co.nz/Forum/Thread/255"
exchange_fee_rate = 0.002
def check_error(self, response):
r = response.json()
error = r.get('Error', False)
if error is not None:
raise ServiceError("Cryptopia returned error: %s" % r['Error'])
super(Cryptopia, self).check_error(response)
def fix_symbol(self, symbol):
if symbol.lower() in ['nzd', 'usd']:
symbol += "t"
return symbol
def reverse_fix_symbol(self, symbol):
symbol = symbol.lower()
if symbol in ['nzdt', 'usdt']:
symbol = symbol[:-1]
return symbol
def make_market(self, crypto, fiat):
return "%s_%s" % (
self.fix_symbol(crypto).upper(), self.fix_symbol(fiat).upper()
)
def get_current_price(self, crypto, fiat):
url = "https://www.cryptopia.co.nz/api/GetMarket/%s" % self.make_market(crypto, fiat)
r = self.get_url(url).json()
return r['Data']['LastPrice']
def get_pairs(self):
url = "https://www.cryptopia.co.nz/api/GetTradePairs"
r = self.get_url(url).json()['Data']
ret = []
for pair in r:
crypto = pair['Symbol']
fiat = pair['BaseSymbol']
if fiat.lower() == 'usdt':
fiat = 'usd'
ret.append(("%s-%s" % (crypto, fiat)).lower())
return ret
def get_orderbook(self, crypto, fiat):
url = "https://www.cryptopia.co.nz/api/GetMarketOrders/%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'bids': [(x['Price'], x['Total']) for x in resp['Data']['Buy']],
'asks': [(x['Price'], x['Total']) for x in resp['Data']['Sell']]
}
def _make_signature_header(self, url, params):
nonce = str(int(time.time()))
post_data = json.dumps(params);
m = hashlib.md5()
m.update(post_data)
requestContentBase64String = base64.b64encode(m.digest())
signature = self.api_key + "POST" + quote_plus(url).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(
hmac.new(base64.b64decode(self.api_secret), signature, hashlib.sha256).digest()
)
header_value = "amx " + self.api_key + ":" + hmacsignature + ":" + nonce
return {'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
def _auth_request(self, method, args):
url = "https://www.cryptopia.co.nz/Api/" + method
return self.post_url(url, json=args, headers=self._make_signature_header(url, args))
def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"):
args = {
'Market': ("%s/%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper(),
'Type': side,
'Rate': price,
'Amount': eight_decimal_places(amount)
}
resp = self._auth_request("SubmitTrade", args).json()
return resp['Data']['OrderId']
make_order.minimums = {}
make_order.supported_types = ['limit']
def get_exchange_balance(self, currency):
curr = self.fix_symbol(currency).upper()
try:
resp = self._auth_request('GetBalance', {'Currency': curr})
except ServiceError:
return 0
for item in resp.json()['Data']:
if item['Symbol'] == curr:
return item['Total']
def get_total_exchange_balances(self):
resp = self._auth_request('GetBalance', {}).json()
#return resp.json()
return {
self.reverse_fix_symbol(x['Symbol']): x['Total'] for x in resp['Data']
if x['Total'] > 0
}
def get_deposit_address(self, currency):
curr = self.fix_symbol(currency).upper()
resp = self._auth_request('GetDepositAddress', {'Currency': curr})
return resp.json()['Data']['Address']
def initiate_withdraw(self, currency, amount, address):
curr = self.fix_symbol(currency).upper()
resp = self._auth_request('SubmitWithdraw', {
'Currency': curr,
'Address': address,
'Amount': amount
})
return resp.json()
class YoBit(Service):
service_id = 77
api_homepage = "https://www.yobit.net/en/api/"
def get_current_price(self, crypto, fiat):
pair = "%s_%s" % (crypto.lower(), fiat.lower())
url = "https://yobit.net/api/3/ticker/%s" % pair
r = self.get_url(url).json()
if 'error' in r:
raise SkipThisService(r['error'])
return r[pair]['last']
def get_pairs(self):
url = 'https://yobit.net/api/3/info'
r = self.get_url(url).json()
return [x.replace("_", '-') for x in r['pairs'].keys()]
class Yunbi(Service):
service_id = 78
api_homepage = "https://yunbi.com/swagger"
def get_current_price(self, crypto, fiat):
if fiat.lower() != "cny":
raise SkipThisService("Only CNY markets supported")
url = "https://yunbi.com/api/v2/tickers/%s%s.json" % (crypto.lower(), fiat.lower())
r = self.get_url(url, headers={"Accept": "application/json"}).json()
return float(r['ticker']['last'])
def get_pairs(self):
url = "https://yunbi.com/api/v2/markets.json"
r = self.get_url(url).json()
ret = []
for pair in r:
ret.append(pair['name'].replace("/", '-').lower())
return ret
class Vircurex(Service):
service_id = 70
base_url = "https://api.vircurex.com/api"
api_homepage = "https://vircurex.com/welcome/api"
def check_error(self, response):
j = response.json()
if j['status'] != 0:
raise ServiceError("Vircurex returned error: %s" % j['status_text'])
super(Vircurex, self).check_error(response)
def get_current_price(self, crypto, fiat):
if crypto == 'blk':
crypto = 'bc'
url = "%s/get_last_trade.json?base=%s&alt=%s" % (
self.base_url, crypto.upper(), fiat.upper()
)
r = self.get_url(url).json()
return float(r['value'])
def get_pairs(self):
url = "%s/get_info_for_currency.json" % self.base_url
r = self.get_url(url).json()
ret = []
for fiat, data in r.items():
if fiat == 'status':
continue
for crypto, exchange_data in data.items():
pair = "%s-%s" % (crypto.lower(), fiat.lower())
ret.append(pair)
return ret
class LiveCoin(Service):
service_id = 110
base_url = "https://api.livecoin.net"
api_homepage = "https://www.livecoin.net/api/public"
def get_pairs(self):
url = "%s/exchange/ticker" % (self.base_url)
r = self.get_url(url).json()
return [x['symbol'].replace('/', '-').lower() for x in r]
def get_current_price(self, crypto, fiat):
url = "%s/exchange/ticker/?currencyPair=%s/%s" % (
self.base_url, crypto.upper(), fiat.upper()
)
return self.get_url(url).json()['last']
class Bithumb(Service):
service_id = 129
def get_current_price(self, crypto, fiat):
if fiat != 'krw':
raise SkipThisService("Only KRW supported")
url = "https://api.bithumb.com/public/ticker/%s" % crypto.upper()
resp = self.get_url(url).json()
return float(resp['data']['average_price'])
def get_orderbook(self, crypto, fiat):
if fiat != 'krw':
raise SkipThisService("Only KRW supported")
url = "https://api.bithumb.com/public/orderbook/%s" % crypto
resp = self.get_url(url).json()['data']
return {
'bids': [(float(x['price']), float(x['quantity'])) for x in resp['bids']],
'asks': [(float(x['price']), float(x['quantity'])) for x in resp['asks']]
}
class Binance(Service):
service_id = 130
def check_error(self, response):
j = response.json()
if 'code' in j:
raise ServiceError("Binance returned error: %s %s" % (j['code'], j['msg']))
super(Binance, self).check_error(response)
def make_market(self, crypto, fiat):
return ("%s%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper()
def parse_market(self, market):
market = market.lower()
if market.endswith("usdt"):
crypto, fiat = market[:-4], "usd"
elif market.endswith("eth"):
crypto, fiat = market[:-3], "eth"
elif market.endswith("btc"):
crypto, fiat = market[:-3], "btc"
else:
crypto, fiat = market[:-3], market[-3:]
if crypto == 'iota':
crypto = 'miota'
if crypto == 'bcc':
crypto = 'bch'
return "%s-%s" % (crypto, fiat)
def fix_symbol(self, symbol):
if symbol.lower() == 'usd':
return 'usdt'
if symbol == 'miota':
return 'iota'
if symbol == 'bch':
return "bcc"
return symbol
def get_current_price(self, crypto, fiat):
url = "https://www.binance.com/api/v1/ticker/allPrices"
resp = self.get_url(url).json()
for data in resp:
if data['symbol'] == self.make_market(crypto, fiat):
return float(data['price'])
raise SkipThisService("Market not found")
def get_pairs(self):
url = "https://www.binance.com/api/v1/ticker/allPrices"
resp = self.get_url(url).json()
symbols = []
for data in resp:
symbols.append(self.parse_market(data['symbol']))
return symbols
def get_orderbook(self, crypto, fiat):
url = "https://www.binance.com/api/v1/depth"
resp = self.get_url(url, {'symbol': self.make_market(crypto, fiat)}).json()
return {
'bids': [(float(x[1]), float(x[0])) for x in resp['bids']],
'asks': [(float(x[1]), float(x[0])) for x in resp['asks']]
}
def _auth_request(self, path, params, method="post"):
params['timestamp'] = make_standard_nonce()
params['signature'] = self._make_signature(params)
headers = {"X-MBX-APIKEY": self.api_key}
return self._external_request(
method, "https://www.binance.com" + path, params, headers=headers
)
def _make_signature(self, params):
return hmac.new(
self.api_secret, urlencode(params), hashlib.sha256
).hexdigest()
def get_exchange_balance(self, currency, type="available"):
if type == 'available':
type = 'free'
else:
type == 'locked'
path = "/api/v3/account"
resp = self._auth_request(path, {}, method="get").json()
for data in resp['balances']:
if data['asset'].lower() == currency.lower():
return float(data[type])
return 0
class BitFlyer(Service):
service_id = 111
api_homepage = "https://bitflyer.jp/API?top_link&footer"
def get_current_price(self, crypto, fiat):
url = "https://api.bitflyer.jp/v1/getticker?product_code=%s" % (
self.make_market(crypto, fiat)
)
r = self.get_url(url).json()
return r['ltp']
def get_pairs(self):
return ['btc-jpy', 'eth-btc', 'btc-usd']
def make_market(self, crypto, fiat):
return ("%s_%s" % (crypto, fiat)).upper()
def get_orderbook(self, crypto, fiat):
if fiat.lower() == 'jpy':
domain = "api.bitflyer.jp"
elif fiat.lower() == 'usd':
domain = "api.bitflyer.com"
else:
raise SkipThisService("Only jpy and usd suppported")
url = "https://%s/v1/getboard?product_code=%s" % (
domain, self.make_market(crypto, fiat)
)
resp = self.get_url(url).json()
return {
'bids': [(x['price'], x['size']) for x in resp['bids']],
'asks': [(x['price'], x['size']) for x in resp['asks']],
}
def get_block(self, crypto, block_number=None, block_hash=None, latest=False):
url = "https://chainflyer.bitflyer.jp/v1/block/%s" % (
block_hash or
('height/%s' % block_number if block_number else None) or
('latest' if latest else 'None')
)
r = self.get_url(url).json()
return dict(
block_number=r['height'],
time=arrow.get(r['timestamp']).datetime,
#mining_difficulty=r['difficulty'],
hash=r['block_hash'],
next_hash=r.get('nextblockhash', None),
previous_hash=r.get('prev_block'),
txids=r['tx_hashes'],
version=r['version']
)
class BitX(Service):
service_id = 131
api_homepage = "https://www.luno.com/en/api"
def parse_market(self, market):
if market.startswith("XBT"):
crypto = "BTC"
fiat = market[3:]
return crypto, fiat
def fix_symbol(self, symbol):
if symbol.lower() == 'btc':
return 'XBT'
return symbol
def make_market(self, crypto, fiat):
return ("%s%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper()
def get_current_price(self, crypto, fiat):
url = "https://api.mybitx.com/api/1/ticker?pair=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return float(resp['last_trade'])
def get_pairs(self):
url = "https://api.mybitx.com/api/1/tickers"
resp = self.get_url(url).json()['tickers']
return [
("%s-%s" % self.parse_market(x['pair'])).lower() for x in resp
]
def get_orderbook(self, crypto, fiat):
url = "https://api.mybitx.com/api/1/orderbook?pair=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'bids': [(float(x['price']), float(x['volume'])) for x in resp['bids']],
'asks': [(float(x['price']), float(x['volume'])) for x in resp['asks']]
}
class ItBit(Service):
service_id = 132
def fix_symbol(self, symbol):
if symbol.lower() == 'btc':
return 'XBT'
return symbol
def make_market(self, crypto, fiat):
return ("%s%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper()
def get_current_price(self, crypto, fiat):
url = "https://api.itbit.com/v1/markets/%s/ticker" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return float(resp['lastPrice'])
def get_pairs(self):
return ['btc-usd', 'btc-sgd', 'btc-eur']
def get_orderbook(self, crypto, fiat):
url = "https://api.itbit.com/v1/markets/%s/order_book" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'bids': [(float(x[0]), float(x[1])) for x in resp['bids']],
'asks': [(float(x[0]), float(x[1])) for x in resp['asks']]
}
def _make_signature(self):
pass # https://github.com/itbit/itbit-restapi-python/blob/master/itbit_api.py
class KuCoin(Service):
service_id = 133
symbol_mapping = (
('usd', 'usdt'),
)
def make_market(self, crypto, fiat):
return ("%s-%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper()
def parse_market(self, market):
return super(KuCoin, self).parse_market(market.lower(), '-')
def get_pairs(self):
url = "https://api.kucoin.com/v1/market/open/symbols"
resp = self.get_url(url).json()
pairs = []
for pair in resp['data']:
crypto, fiat = self.parse_market(pair['symbol'])
pairs.append("%s-%s" % (crypto, fiat))
return pairs
def get_orderbook(self, crypto, fiat):
url = "https://api.kucoin.com/v1/open/orders?symbol=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()['data']
return {
'bids': [(x[0], x[1]) for x in resp['BUY']],
'asks': [(x[0], x[1]) for x in resp['SELL']]
}
def get_current_price(self, crypto, fiat):
url = "https://api.kucoin.com/v1/open/tick?symbol=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()['data']
return resp['lastDealPrice']
class CCex(Service):
service_id = 134
api_homepage = "https://c-cex.com/?id=api"
base_url = "https://c-cex.com/t/api_pub.html"
def check_error(self, response):
if response.content == "Maintenance...":
raise ServiceError("C-Cex is down for maintenance")
super(CCex, self).check_error(response)
def make_market(self, crypto, fiat):
return "%s-%s" % (crypto.lower(), fiat.lower())
def get_current_price(self, crypto, fiat):
url = "https://c-cex.com/t/%s.json" % (
self.make_market(crypto, fiat)
)
response = self.get_url(url).json()
return float(response['ticker']['lastprice'])
def get_pairs(self):
url = "https://c-cex.com/t/pairs.json"
r = self.get_url(url).json()
return r['pairs']
def get_orderbook(self, crypto, fiat):
url = "%s?a=getorderbook&market=%s&type=both" % (
self.base_url, self.make_market(crypto, fiat)
)
resp = self.get_url(url).json()['result']
return {
'bids': [(x["Rate"], x["Quantity"]) for x in resp['buy']],
'asks': [(x["Rate"], x["Quantity"]) for x in resp['sell']]
}
def _auth_request(self, params):
params['nonce'] = make_standard_nonce()
params['apikey'] = self.api_key
url = "%s?%s" % (self.base_url, urlencode(params))
headers = {'apisign': self._make_signature(url)}
return self.get_url(url, headers=headers)
def _make_signature(self, url):
return hmac.new(
self.api_secret,
msg=url,
digestmod=hashlib.sha512
).hexdigest()
def get_exchange_balance(self, currency, type="available"):
resp = self._auth_request({'a': 'getbalance', 'currency': currency})
if type == 'available':
return resp.json()['Available']
def get_deposit_address(self, currency):
resp = self._auth_request({'a': 'getbalance', 'currency': currency})
return resp.json()['CryptoAddress']
class CoinEx(Service):
service_id = 138
def __init__(self, access_id=None, **kwargs):
self.access_id = access_id
return super(CoinEx, self).__init__(**kwargs)
def get_pairs(self):
url = "https://api.coinex.com/v1/market/list"
resp = self.get_url(url).json()['data']
return [("%s-%s" % (x[:-3], x[-3:])).lower() for x in resp]
def make_market(self, crypto, fiat):
return ("%s%s" % (crypto, fiat)).upper()
def get_current_price(self, crypto, fiat):
url = "https://api.coinex.com/v1/market/ticker?market=%s" % (
self.make_market(crypto, fiat)
)
resp = self.get_url(url).json()
return float(resp['data']['ticker']['last'])
def _auth_request(self, url, params=None):
params['tonce'] = make_standard_nonce()
params['access_id'] = self.access_id
str_params = urlencode(sorted(params.items(), key=lambda x: x[0]))
to_sign = str_params + "&secret_key=%s" % self.api_secret
digest = hashlib.md5(to_sign).hexdigest().upper()
return self.get_url(url + "?" + str_params, headers={
'Content-Type': 'application/json',
'authorization': digest
})
def get_exchange_balance(self, crypto):
url = "https://api.coinex.com/v1/balance/"
resp = self._auth_request(url, {}).json()
return resp
class OKEX(Service):
service_id = 139
api_homepage = 'https://www.okex.com/rest_api.html'
symbol_mapping = (
('usd', 'usdt'),
)
def check_error(self, response):
j = response.json()
if 'error_code' in j:
raise ServiceError("OKEX returned error: %s" % j['error_code'])
super(OKEX, self).check_error(response)
def get_current_price(self, crypto, fiat):
url = "https://www.okex.com/api/v1/ticker.do?symbol=%s" % (
self.make_market(crypto, fiat)
)
resp = self.get_url(url).json()
return float(resp['ticker']['last'])
class BitZ(Service):
service_id = 140
def check_error(self, response):
j = response.json()
if not j['code'] == 0:
raise ServiceError("BitZ returned error: %s: %s" % (
j['code'], j['msg']
))
super(BitZ, self).check_error(response)
def get_current_price(self, crypto, fiat):
url = "https://www.bit-z.com/api_v1/ticker?coin=%s" % (self.make_market(crypto, fiat))
resp = self.get_url(url).json()
return float(resp['data']['last'])
class Zaif(Service):
service_id = 141
def check_error(self, response):
j = response.json()
if 'error' in j:
raise ServiceError("Zaif returned error: %s" % (j['error']))
super(Zaif, self).check_error(response)
def get_current_price(self, crypto, fiat):
url = "https://api.zaif.jp/api/1/ticker/%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return resp['last']
class Korbit(Service):
service_id = 142
api_homepage = "https://apidocs.korbit.co.kr/"
def get_current_price(self, crypto, fiat):
url = "https://api.korbit.co.kr/v1/ticker?currency_pair=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return float(resp['last'])
def get_orderbook(self, crypto, fiat):
url = "https://api.korbit.co.kr/v1/orderbook?currency_pair=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'asks': [(float(x[0]), float(x[1])) for x in resp['asks']],
'bids': [(float(x[0]), float(x[1])) for x in resp['bids']]
}
class CoinEgg(Service):
service_id = 143
api_homepage = "https://www.coinegg.com/explain.api.html#partone"
def get_current_price(self, crypto, fiat):
if fiat.lower() != 'btc':
raise SkipThisService("Only BTC markets supported")
url = "https://api.coinegg.com/api/v1/ticker/?coin=%s" % crypto
resp = self.get_url(url).json()
return float(resp['last'])
def get_orderbook(self, crypto, fiat):
if fiat.lower() != 'btc':
raise SkipThisService("Only BTC markets supported")
url = "https://api.coinegg.com/api/v1/depth/"
resp = self.get_url(url).json()
return {
'bids': [(float(x[0]), float(x[1])) for x in resp['bids']],
'asks': [(float(x[0]), float(x[1])) for x in resp['asks']]
}
class ZB(Service):
service_id = 144
api_homepage = "https://www.zb.com/i/developer"
symbol_mapping = (
('usd', 'usdt'),
('bch', 'bcc')
)
def get_pairs(self):
url = "http://api.zb.com/data/v1/markets"
resp = self.get_url(url).json()
pairs = []
for pair in resp.keys():
pairs.append("%s-%s" % self.parse_market(pair))
return pairs
def get_current_price(self, crypto, fiat):
url = "http://api.zb.com/data/v1/ticker?market=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return float(resp['ticker']['last'])
def get_orderbook(self, crypto, fiat):
url = "http://api.zb.com/data/v1/depth?market=%s&size=3" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
del resp['timestamp']
return resp
class CoinNest(Service):
service_id = 145
api_homepage = "https://www.coinnest.co.kr/doc/intro.html"
def get_current_price(self, crypto, fiat):
if fiat.lower() != 'krw':
raise SkipThisService("Only KRW markets supported")
url = "https://api.coinnest.co.kr/api/pub/ticker?coin=%s" % crypto
resp = self.get_url(url).json()
return resp['last']
def get_orderbook(self, crypto, fiat):
if fiat.lower() != 'krw':
raise SkipThisService("Only KRW markets supported")
url = "https://api.coinnest.co.kr/api/pub/depth?coin=%s" % crypto
resp = self.get_url(url).json()
del resp['result']
return resp
class BitBank(Service):
service_id = 147
api_homepage = "https://docs.bitbank.cc/"
symbol_mapping = (
('bch', 'bcc'),
)
def get_current_price(self, crypto, fiat):
url = "https://public.bitbank.cc/%s/ticker" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return float(resp['data']['last'])
def get_orderbook(self, crypto, fiat):
url = "https://public.bitbank.cc/%s/depth" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'asks': [(float(x[0]), float(x[1])) for x in resp['data']['asks']],
'bids': [(float(x[0]), float(x[1])) for x in resp['data']['bids']]
}
class EXX(Service):
service_id = 148
symbol_mapping = (
('usd', 'usdt'),
('bch', 'bcc')
)
def get_pairs(self):
url = "https://api.exx.com/data/v1/markets"
resp = self.get_url(url).json()
pairs = []
for pair in resp.keys():
pairs.append("%s-%s" % self.parse_market(pair))
return pairs
def get_current_price(self, crypto, fiat):
url = "https://api.exx.com/data/v1/ticker?currency=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return float(resp['ticker']['last'])
def get_orderbook(self, crypto, fiat):
url = "https://api.exx.com/data/v1/depth?currency=%s" % self.make_market(crypto, fiat)
resp = self.get_url(url).json()
return {
'asks': [(float(x[0]), float(x[1])) for x in resp['asks']],
'bids': [(float(x[0]), float(x[1])) for x in resp['bids']]
}
class BL3P(Service):
service_id = 150
def check_error(self, response):
j = response.json()
if j['result'] == 'error':
d = j['data']
raise ServiceError("BL3P returned error: %s, %s" % (d['code'], d['message']))
super(BL3P, self).check_error(response)
def get_current_price(self, crypto, fiat):
url = "https://api.bl3p.eu/1/%s/ticker" % self.make_market(crypto, fiat, '-')
return self.get_url(url).json()
class BTCbox(Service):
service_id = 151
def get_current_price(self, crypto, fiat):
if fiat.lower() != 'jpy':
raise SkipThisService("Only JPY trading pairs supported")
url = "https://www.btcbox.co.jp/api/v1/ticker/?coin=%s" % crypto
r = self.get_url(url).json()
return r['last']
class Bibox(Service):
service_id = 152
api_homepage = "https://github.com/Biboxcom/api_reference/wiki/api_reference"
symbol_mapping = (
('usd', 'usdt'),
)
def get_current_price(self, crypto, fiat):
url = "https://api.bibox.com/v1/mdata?cmd=ticker&pair=%s" % (
self.make_market(crypto, fiat).upper()
)
r = self.get_url(url).json()
return float(r['result']['last'])
def get_pairs(self):
url ="https://api.bibox.com/v1/mdata?cmd=pairList"
r = self.get_url(url).json()
markets = []
for data in r['result']:
pair = data['pair']
crypto, fiat = self.parse_market(pair)
markets.append("%s-%s" % (crypto, fiat))
return markets
def get_orderbook(self, crypto, fiat):
url = "https://api.bibox.com/v1/mdata?cmd=depth&pair=%s&size=200" % (
self.make_market(crypto, fiat).upper()
)
resp = self.get_url(url).json()['result']
return {
'asks': [(float(x['price']), float(x['volume'])) for x in resp['asks']],
'bids': [(float(x['price']), float(x['volume'])) for x in resp['bids']]
}
|
cocos/symbolic/__init__.py
|
michaelnowotny/cocos
| 101 |
145820
|
from ._lambdification import (
DUMMY_TIME_SYMBOL,
lambdify,
LambdifiedArrayExpressions,
LambdifiedMatrixExpressions,
LambdifiedVectorExpressions,
LambdifiedArrayExpression,
LambdifiedMatrixExpression,
LambdifiedVectorExpression,
LambdifiedScalarExpression
)
from .utilities import find_length_of_state_vectors
|
recipes/Python/578973_Easy_attribute_setting_pretty/recipe-578973.py
|
tdiprima/code
| 2,023 |
145821
|
"""Mix-in classes for easy attribute setting and pretty representation
>>> class T(HasInitableAttributes, HasTypedAttributes, IsCallable):
... spam = str
... def __init__(self, eggs, ham = 'ham'): pass
...
>>> t = T('bacon'); t(ham = 'eggs'); t.spam += 'sausage'; t
__main__.T('bacon', ham = 'eggs', spam = 'sausage')
>>>
"""
from inspect import getargspec
from itertools import chain
class HasInitableAttributes(object):
"""Initializes attributes automatically
>>> class T(HasInitableAttributes):
... z = 0
... def __init__(self, x, y=0, **opts): pass
...
>>> t = T(0, a = 1); t
__main__.T(0, a = 1)
>>> t.x, t.y, t.z = 1, 2, 3; t
__main__.T(1, y = 2, a = 1, z = 3)
>>>
"""
def __new__(cls, *pars, **opts):
"Initialize all attributes in the signature and any other options supplied"
try:
self = super().__new__(cls, *pars, **opts)
except:
self = super().__new__(cls)
self._argspec = names, parsname, optsname, defaults = getargspec(self.__init__)
if not defaults: defaults = []
n = len(names) - len(defaults) - 1
if n - len(pars) > 0:
_s, _to = ('s', '-%d' % (n-1)) if n - len(pars) > 1 else ('', '')
missing = "%s %s (pos %d%s)" % (_s, ", ".join(names[1:n+1]), len(pars), _to)
raise TypeError("Required argument%s not found." % missing)
for n, v in chain(zip(names[-len(defaults):], defaults), zip(names[1:], pars), opts.items()):
setattr(self, n, v)
return self
def __repr__(self):
"Show all attributes in the signature and any other public attributes that are changed"
names, parsname, optsname, defaults = self._argspec
if not defaults: defaults = []
optnames = names[-len(defaults):] if defaults else []
optvalues = (getattr(self, name) for name in optnames)
othernames = sorted(set((n for n in self.__dict__ if n[0] != '_')) - set(names))
othervalues = list((getattr(self, name, None) for name in othernames))
otherdefaults = list((getattr(self.__class__, name, None) for name in othernames))
return "%s.%s(%s)" % (self.__module__, self.__class__.__name__, ", ".join(chain(
(repr(getattr(self, name)) for name in names[1:len(names)-len(defaults)]),
("%s = %r" % (name, value) for name, value, default in zip(optnames, optvalues, defaults) if value != default),
("%s = %r" % (name, value) for name, value, default in zip(othernames, othervalues, otherdefaults) if value != default))))
class HasTypedAttributes(object):
"""Objectifies class attributes automatically
>>> class T(HasTypedAttributes):
... spam = str
... class C(HasTypedAttributes):
... eggs = list
...
>>> a, b = T(), T(); a.spam += 'ham'; a.C.eggs.append('bacon'); a.spam, b.spam, a.C.eggs, b.C.eggs
('ham', '', ['bacon'], [])
>>>
"""
def __new__(cls, *pars, **opts):
try:
self = super().__new__(cls, *pars, **opts)
except:
self = super().__new__(cls)
for name in dir(self):
if name[0] != '_':
value = getattr(self, name)
if isinstance(value, type):
setattr(self, name, value(opts.pop(name)) if name in opts else value())
if opts:
raise TypeError("__init__() got%s unexpected keyword argument%s %r" %
(" an", "", opts.keys()[0]) if len(opts) == 1 else ("", "s", opts.keys()))
return self
class IsCallable(object):
"""Update attributes by calling
>>> class T(IsCallable):
... x = 0
...
>>> t = T(); t(x=1, y=2); t.x, t.y
(1, 2)
"""
def __call__(self, *pars, **opts):
self.__dict__.update(*pars, **opts)
if __name__ == '__main__':
from doctest import testmod
testmod()
class T(HasInitableAttributes, HasTypedAttributes, IsCallable):
spam = str
t = T()
assert t.spam != str
|
lightnion/consensus.py
|
pthevenet/lightnion
| 120 |
145831
|
<gh_stars>100-1000
from base64 import b64encode, b64decode
import datetime
import binascii
import time
import os
import re
import urllib.request
import lightnion as lnn
from tools.keys import get_signing_keys_info
# TODO: remove extra (useless) checks/exceptions within this file
def scrap(consensus, end_of_field):
"""
Consume lines upon matching a criterion.
Returns (consensus-without-first-line, first-line)
if end_of_field(first-line) returns True,
else returns (consensus-with-first-line, None)
:param bytes consensus: input which first line may be consumed
:param function end_of_field: passed a line, returns True when no match
:returns: a tuple (updated-consensus, next-field-or-None)
"""
if b'\n' not in consensus:
return consensus, None
line, remaining = consensus.split(b'\n', 1)
if end_of_field(line):
return consensus, None
return remaining, line
def scrap_signature(consensus, fix=b'SIGNATURE'):
"""
Consume a signature field if there is one to consume.
:param bytes consensus: input which may start with a signature.
:returns: a tuple (updated-consensus, signature-or-None)
"""
if not consensus.startswith(b'-----BEGIN ' + fix + b'-----'):
return consensus, None
lines = consensus.split(b'\n', 22) # fits 0-1024o (for 256o sig)
try:
idx_endsig = lines.index(b'-----END ' + fix + b'-----')
except ValueError:
return consensus, None
remaining = b'\n'.join(lines[idx_endsig + 1:])
content = b''.join(lines[1:idx_endsig])
return remaining, content
def parse_address(address):
"""
Take a Tor-formatted v4 or v6 IP address with a port, returns a
cleaned-up version.
:param str address: input address to be processed
:returns: a tuple (address, port, guessed-type) where port is an
integer and guessed-type is 4 or 6 (IPv4 or IPv6).
"""
address = address.split(':')
address, port = ':'.join(address[:-1]), address[-1]
guessed_type = 4
if address.startswith('['):
address = address[1:]
guessed_type = 6
if address.endswith(']') or guessed_type == 6:
if not address.endswith(']'):
raise RuntimeError(
'Seems like an invalid IPv6: {}'.format(address))
address = address[:-1]
guessed_type = 6
if address.count(':') > 3:
if not guessed_type == 6:
raise RuntimeError(
'Seems like an very odd IPv6: {}'.format(address))
guessed_type = 6
return address, int(port), guessed_type
def parse_range_once(value, expand=True):
"""
Take Tor-formatted ranges, then returns it as a list of integers if
expanded or a mix of integers and ranges as [low, high] tuples.
For example, we use it to parse "p" fields:
https://github.com/plcp/tor-scripts/blob/master/torspec/dir-spec-4d0d42f.txt#L2322
:param str value: input value to be processed
:param bool expand: do we expand a range as integers? (default: True)
:returns: a list of integers or a mix of integers and range list/tuples
"""
value = value.split(',')
subvalues = []
for subvalue in value:
if '-' in subvalue:
low, high = [int(v) for v in subvalue.split('-')]
if expand:
subvalues += list(range(low, high + 1))
elif low == high - 1:
subvalues += [low, high]
else:
subvalues += [[low, high]]
else:
subvalues += [int(subvalue)]
return subvalues
def parse_ranges(ranges, expand=True):
"""
Take Tor-formatted named ranges, then returns a keyword-based
dictionary of list of integers or mix of integers and range tuples (as
returned by parse_range_once), expanded or not.
For example, we use it to parse "recommended-client-protocols" fields:
https://github.com/plcp/tor-scripts/blob/master/torspec/dir-spec-4d0d42f.txt#L780
:param str ranges: input ranges to be processed
:param bool expand: do we expand ranges as integers? (default: True)
:returns: a dictionary with (range-name, range-content) items
"""
pairs = ranges.split(' ')
content = {}
for key, value in [pair.split('=') for pair in pairs if '=' in pair]:
content[key] = parse_range_once(value, expand)
return content
def parse_params(params):
"""
Take Tor-formatted parameters, then returns a keyword-based dictionary
of integers.
For example, we use it to parse "params" fields:
https://github.com/plcp/tor-scripts/blob/master/torspec/dir-spec-4d0d42f.txt#L1820
:param str params: input params to be processed
:returns: a dictionary with (param-name, param-integer-value) items
"""
pairs = params.split(' ')
content = dict()
for key, value in [pair.split('=') for pair in pairs]:
content[key] = int(value)
return content
def parse_fingerprint(payload):
asbytes = bytes.fromhex(payload)
fingers = asbytes.hex().upper()
fingers = ' '.join([fingers[i:i + 4] for i in range(0, len(fingers), 4)])
if not fingers == payload:
raise RuntimeError(
'Fingerprint not conform: {} vs {}'.format(fingers, payload))
return fingers
def parse_base64(payload, decode=False):
"""
Take an input base64 string, decode it, re-encode it.
For example, we use it to parse "shared-rand-current-value" fields:
https://github.com/plcp/tor-scripts/blob/master/torspec/dir-spec-4d0d42f.txt#L2069
:param str payload: input base64-encoded data
:param bool decode: return raw bytes (default: False)
:returns: a base64-encoded string equivalent to the input
"""
decoded = b64decode(payload + '====')
value = str(b64encode(decoded), 'utf8')
if not payload[-2:].count('=') == value[-2:].count('='):
value = value.rstrip('=') + '=' * payload[-2:].count('=')
if not value == payload:
raise RuntimeError('Invalid base64 encoding: {} vs {}'.format(
value, payload))
if decode:
return decoded
return value
def parse_time(timedate):
"""
Take a Tor-formatted (Y-m-d H:M:S) time, parse it, then returns the
corresponding date, time and datetime object. This function assumes
that the given time uses the UTC timezone – as it's the timezone used
into Tor consensuses.
:param str timedate: input time and date to be parsed
:returns: a tuple (date-str, time-str, datetime-object)
"""
when = datetime.datetime.strptime(timedate, '%Y-%m-%d %H:%M:%S')
# convert to UTC-aware datetime object
when = datetime.datetime(*when.timetuple()[:6],
tzinfo=datetime.timezone.utc)
return (when.strftime('%Y-%m-%d'), when.strftime('%H:%M:%S'), when)
def consume_http(consensus):
"""
Consume HTTP headers if present, then returns the remaining input to be
further processed and a set of headers (or None, if none present).
:param str consensus: input to be processed
:returns: a tuple (remaining-input, headers-or-None)
"""
def end_of_field(line):
return line[-1:] != b'\r'
fields = dict(headers=dict())
valid = False
while True:
consensus, header = scrap(consensus, end_of_field)
if header is None:
return consensus, fields if valid else None
valid = True
if b' ' not in header:
continue
header = header[:-1]
try:
header = str(header, 'utf8')
except Exception:
continue
if header.startswith('HTTP/'):
version, fields['code'], _ = header.split(' ', 2)
fields['version'] = float(version.split('/', 1)[1])
keyword, content = header.split(' ', 1)
if keyword[-1:] == ':':
fields['headers'][keyword[:-1]] = content
def consume_headers(consensus, flavor='unflavored'):
"""
Consume consensus headers if present, then returns the remaining input
to be further processed and a set of headers (or None, if none
present).
Will consume the following fields:
- network-status-version
- vote-status
- consensus-method
- valid-after
- fresh-until
- valid-until
- voting-delay
- client-versions
- server-versions
- known-flags
- recommended-client-protocols
- recommended-relay-protocols
- required-client-protocols
- required-relay-protocols
- params
- shared-rand-previous-value
- shared-rand-current-value
:param str consensus: input to be processed
:param str flavor: consensus flavor ('unflavored' or 'microdesc')
:returns: a tuple (remaining-input, headers-or-None)
"""
if flavor not in ['unflavored', 'microdesc']:
raise NotImplementedError(
'Consensus flavor "{}" not supported.'.format(flavor))
whitelist = [
b'network-status-version', b'vote-status', b'consensus-method',
b'valid-after', b'fresh-until', b'valid-until', b'voting-delay',
b'client-versions', b'server-versions', b'known-flags',
b'recommended-client-protocols', b'recommended-relay-protocols',
b'required-client-protocols', b'required-relay-protocols', b'params',
b'shared-rand-previous-value', b'shared-rand-current-value']
def end_of_field(line):
if b' ' not in line:
return True
keyword, _ = line.split(b' ', 1)
return keyword not in whitelist
fields = dict()
valid = False
while True:
consensus, header = scrap(consensus, end_of_field)
if header is None:
return consensus, fields if valid else None
valid = True
if b' ' not in header:
continue
try:
header = str(header, 'utf8')
except:
continue
keyword, content = header.split(' ', 1)
if keyword == 'network-status-version':
content = content.split(' ', 1)
if len(content) == 1:
content.append('unflavored')
version, variant = content
content = dict(version=int(version), flavor=variant)
if not len(fields) == 0:
raise RuntimeError('Expecting {} as first field: {}'.format(
keyword, content))
if not content['version'] >= 3:
raise RuntimeError('Expecting {} version >= 3 here: {}'.format(
keyword, content))
if not content['flavor'] == flavor:
raise RuntimeError('Unmatched {} flavor {} here: {}'.format(
keyword, flavor, content))
if keyword == 'consensus-method':
content = int(content)
if not content >= 26:
raise RuntimeError(
'Consensus version >= 26 required: {}'.format(content))
if keyword in ['valid-after', 'fresh-until', 'valid-until']:
date, time_parsed, when = parse_time(content)
content = dict(date=date, time=time_parsed, stamp=when.timestamp())
if keyword == 'valid-after':
if not time.time() > content['stamp']:
raise RuntimeError('{} not yet valid! {}'.format(
keyword, content)) # valid-after
if keyword == 'fresh-until':
if not content['stamp'] > fields['valid-after']['stamp']:
raise RuntimeError('{} not fresh! {}'.format(
keyword, content)) # fresh-until
if keyword == 'valid-until':
if not time.time() < content['stamp']:
raise RuntimeError('{} no more valid! {}'.format(
keyword, content)) # valid-until
if keyword == 'voting-delay':
vote, dist = content.split(' ', 1)
content = dict(vote=int(vote), dist=int(dist))
if keyword in ['client-versions', 'server-versions']:
content = content.split(',')
if keyword == 'known-flags':
content = content.split(' ')
if keyword.startswith(('recommended', 'required')):
content = parse_ranges(content)
if keyword == 'params':
content = parse_params(content)
if keyword.startswith('shared-rand'):
reveals, value = content.split(' ')
value = parse_base64(value)
content = {'NumReveals': int(reveals), 'Value': value}
if not content['NumReveals'] >= 0:
raise RuntimeError('{} must be >= 0 here: {}'.format(
keyword, content))
fields[keyword] = content
def consume_dir_sources(consensus):
"""
Consume directory source listing if present, then returns the remaining
input to be further processed and a set of directory sources (or None,
if none present).
Will consume the following fields:
- dir-source
- contact
- vote-digest
:param str consensus: input to be processed
:returns: a tuple (remaining-input, headers-or-None)
"""
whitelist = [b'dir-source', b'contact', b'vote-digest']
def end_of_field(line):
if b' ' not in line:
return True
keyword, _ = line.split(b' ', 1)
return keyword not in whitelist
fields = []
valid = False
while True:
consensus, header = scrap(consensus, end_of_field)
if header is None:
if not valid:
return consensus, None
break
valid = True
if b' ' not in header:
continue
try:
header = str(header, 'utf8')
except:
continue
keyword, content = header.split(' ', 1)
if keyword == 'vote-digest':
value = bytes.fromhex(content).hex()
if not value.lower() == content.lower():
raise RuntimeError('Unmatched {} here: {} {}'.format(
keyword, value, content))
content = value
if keyword == 'dir-source':
nickname, identity, hostname, address, dirport, orport = (
content.split(' ', 5))
value = bytes.fromhex(identity).hex()
if not value.lower() == identity.lower():
raise RuntimeError('Unmatched {} here: {} {}'.format(
keyword, value, content))
identity = value
content = dict(nickname=nickname, identity=identity,
hostname=hostname, address=address, dirport=int(dirport),
orport=int(orport))
if not 0 < content['dirport'] < 65536:
raise RuntimeError('Invalid dirport here: {}'.format(content))
if not 0 < content['orport'] < 65536:
raise RuntimeError('Invalid orport here: {}'.format(content))
if keyword != 'dir-source' and fields[-1][0] == 'dir-source':
if not (keyword not in fields[-1][1]):
raise RuntimeError(
'Unexpected {} with: {}'.format(keyword, fields[-1]))
assert keyword not in fields[-1][1]
fields[-1][1][keyword] = content
continue
fields.append((keyword, content))
full_entries_count = len([v for k, v in fields if k == 'dir-source'])
if not full_entries_count == len(fields):
raise RuntimeError('Incomplete entry or corrupted?')
if full_entries_count == len(fields):
fields = [v for k, v in fields]
return consensus, fields
def consume_routers(consensus, flavor='unflavored'):
"""
Consume router listing if present, then returns the remaining input to
be further processed and a set of routers (or None, if none present).
Will consume the following fields:
- r
- m
- s
- v
- pr
- w
- p (unflavored only)
- a (unflavored only)
:param str consensus: input to be processed
:param str flavor: consensus flavor ('unflavored' or 'microdesc')
:returns: a tuple (remaining-input, headers-or-None)
"""
if flavor not in ['unflavored', 'microdesc']:
raise NotImplementedError(
'Consensus flavor "{}" not supported.'.format(flavor))
# TODO: check if 'a' fields in microdesc consensus are still a thing
if flavor == 'unflavored':
whitelist = [b'r', b'm', b's', b'v', b'pr', b'w', b'p', b'a']
elif flavor == 'microdesc':
whitelist = [b'r', b'm', b's', b'v', b'pr', b'w', b'a']
aliases = dict(m='micro-digest', pr='protocols', s='flags', v='version',
p='exit-policy', a='or-address')
def end_of_field(line):
if b' ' not in line:
return True
keyword, _ = line.split(b' ', 1)
return keyword not in whitelist
fields = []
valid = False
while True:
consensus, header = scrap(consensus, end_of_field)
if header is None:
if not valid:
return consensus, None
break
valid = True
if b' ' not in header:
continue
try:
header = str(header, 'utf8')
except:
continue
keyword, content = header.split(' ', 1)
if keyword == 'm':
content = parse_base64(content)
if keyword == 's':
content = content.split(' ')
if keyword == 'pr':
content = parse_ranges(content)
if keyword == 'w':
content = parse_params(content)
if keyword == 'p':
policy_type, portlist = content.split(' ')
if not policy_type in ['accept', 'reject']:
raise RuntimeError('Unknown policy: {}'.format(policy_type))
portlist = parse_range_once(portlist, expand=False)
content = {'type': policy_type, 'PortList': portlist}
if keyword == 'a':
address, port, guessed_type = parse_address(content)
content = [{'ip': address, 'port': port, 'type': guessed_type}]
if keyword == 'r' and flavor == 'unflavored':
(nickname, identity, digest, date, time, address, orport,
dirport) = content.split(' ', 7)
digest = parse_base64(digest)
identity = parse_base64(identity)
date, time, when = parse_time(' '.join([date, time]))
content = dict(nickname=nickname, identity=identity, digest=digest,
date=date, time=time, stamp=when.timestamp(), address=address,
dirport=int(dirport), orport=int(orport))
if not 0 <= content['dirport'] < 65536:
raise RuntimeError('Invalid dirport here: {}'.format(content))
if not 0 < content['orport'] < 65536:
raise RuntimeError('Invalid orport here: {}'.format(content))
if keyword == 'r' and flavor == 'microdesc':
nickname, identity, date, time, address, orport, dirport = (
content.split(' ', 6))
identity = parse_base64(identity)
date, time, when = parse_time(date + ' ' + time)
content = dict(nickname=nickname, identity=identity, date=date,
time=time, stamp=when.timestamp(), address=address,
dirport=int(dirport), orport=int(orport))
if not 0 <= content['dirport'] < 65536:
raise RuntimeError('Invalid dirport here: {}'.format(content))
if not 0 < content['orport'] < 65536:
raise RuntimeError('Invalid orport here: {}'.format(content))
if keyword != 'r' and fields[-1][0] == 'r':
if keyword in aliases:
keyword = aliases[keyword]
if keyword == 'or-address' and keyword in fields[-1][1]:
content[0]['ignored'] = True
fields[-1][1]['or-address'] += content
continue
if not (keyword not in fields[-1][1]):
raise RuntimeError('Unexpected {} with: {}'.format(keyword,
fields[-1]))
fields[-1][1][keyword] = content
continue
fields.append((keyword, content))
full_entries_count = len([v for k, v in fields if k == 'r'])
if not full_entries_count == len(fields):
raise RuntimeError('Invalid or corrupted entry?')
if full_entries_count == len(fields):
fields = [v for k, v in fields]
return consensus, fields
def consume_footer(consensus, flavor='unflavored'):
"""
Consume consensus footer if present, then returns the remaining input
to be further processed and a set of footers (or None, if none
present).
Will consume the following fields:
- directory-footer
- bandwidth-weights
- directory-signature
:param str consensus: input to be processed
:param str flavor: consensus flavor ('unflavored' or 'microdesc')
:returns: a tuple (remaining-input, headers-or-None)
"""
if flavor not in ['unflavored', 'microdesc']:
raise NotImplementedError(
'Consensus flavor "{}" not supported.'.format(flavor))
whitelist = [
b'directory-footer', b'bandwidth-weights', b'directory-signature']
def end_of_field(line):
if b'directory-footer' == line:
return False
if b' ' not in line:
return True
keyword, _ = line.split(b' ', 1)
return keyword not in whitelist
fields = dict()
valid = False
while True:
consensus, header = scrap(consensus, end_of_field)
if header is None:
return consensus, fields if valid else None
valid = True
if b' ' not in header:
continue
try:
header = str(header, 'utf8')
except:
continue
keyword, content = header.split(' ', 1)
if keyword == 'directory-footer' and not len(fields) == 0:
raise RuntimeError('Expect {} as first field!'.format(keyword))
if keyword == 'bandwidth-weights':
content = parse_params(content)
if keyword == 'directory-signature':
content = content.split(' ', 2)
if len(content) == 3:
algorithm, identity, signing_key_digest = content
elif len(content) == 2:
algorithm = 'sha1'
identity, signing_key_digest = content
content = {
'Algorithm': algorithm,
'identity': identity,
'signing-key-digest': signing_key_digest}
consensus, signature = scrap_signature(consensus)
if signature is not None:
signature = parse_base64(str(signature, 'utf8'))
content['signature'] = signature
if keyword + 's' not in fields:
fields[keyword + 's'] = []
fields[keyword + 's'].append(content)
continue
fields[keyword] = content
return consensus, fields
def parse(consensus, flavor='unflavored'):
"""
Parse a raw consensus with the given flavor, then returns sanitized
entries as a python dictionary.
:param str consensus: input to be processed
:param str flavor: consensus flavor ('unflavored' or 'microdesc')
:returns: a python dictionary
"""
fields = dict(flavor=flavor)
consensus, http = consume_http(consensus)
if http is not None:
fields['http'] = http
consensus, headers = consume_headers(consensus, flavor)
if headers is not None:
fields['headers'] = headers
consensus, dir_sources = consume_dir_sources(consensus)
if dir_sources is not None:
fields['dir-sources'] = dir_sources
consensus, routers = consume_routers(consensus, flavor)
if routers is not None:
fields['routers'] = routers
consensus, footer = consume_footer(consensus, flavor)
if footer is not None:
fields['footer'] = footer
if not ('headers' in fields
and 'dir-sources' in fields
and 'routers' in fields
and 'footer' in fields):
raise RuntimeError('Missing entry: {}'.format(list(fields)))
return fields, consensus
def extract_date(consensus, field):
"""
Retrieve the value from a date field as a datetime object.
"""
pattern = re.compile('{} [^\n]+'.format(field))
found = pattern.search(consensus)
if found is None:
raise RuntimeError('Field {} not found in consensus.'.format(field))
date_s = consensus[found.start():found.end()]
date = datetime.datetime.strptime(date_s, '{} %Y-%m-%d %H:%M:%S'.format(field))
date.replace(tzinfo=datetime.timezone.utc)
return date
def extract_nodes_digests_unflavored(consensus_raw):
"""Retrieve a list of the digests of all routers in the consensus.
"""
# We retrieve the third fields of the lines looking like that:
#r VSIFskylab AD14gl4Llgnuz/Xk4FKXF3cuU8c 3VZwLdY0Et7vqUbqDdXg3WGGHCw 2020-01-12 23:47:04 192.168.3.11 443 80
digests_raw = re.findall(r'^r [^ ]+ [^ ]+ ([^ ]+)', consensus_raw, re.MULTILINE)
digests_bytes = [b64decode(digest + '====') for digest in digests_raw]
return digests_bytes
def extract_nodes_digests_micro(consensus_raw):
"""Retrieve a list of the digests of all routers in the consensus.
"""
# We retrieve the third fields of the lines looking like that:
#m v7E0VcMnwVepVUh+j193lrbqbWOg26g9hXOBwSYv32I
digests_raw = re.findall(r'^m ([^\n]+)', consensus_raw, re.MULTILINE)
digests_bytes = [digest for digest in digests_raw]
return digests_bytes
def download(state, flavor='microdesc', cache=True):
if flavor not in ['unflavored', 'microdesc']:
raise NotImplementedError(
'Consensus flavor "{}" not supported.'.format(flavor))
if cache:
try:
return state, lnn.cache.consensus.get(flavor)
except BaseException:
pass
endpoint = '/tor/status-vote/current/consensus'
if flavor == 'microdesc':
endpoint += '-microdesc'
ip = '%s:%d'%('127.0.0.1',7000) #for real tor, change to 9051
keys = get_signing_keys_info(ip)
state, cons = lnn.hop.directory_query(state, endpoint)
cons_original = cons
cons, http = consume_http(cons)
if flavor != 'microdesc':
if not lnn.signature.verify(cons.decode('utf-8'), keys):
raise RuntimeError('Consensus Verification Failed')
consensus, remaining = parse(cons_original, flavor=flavor)
if consensus is None or remaining is None or not len(remaining) == 0:
raise RuntimeError('Unable to parse downloaded consensus!')
if cache:
lnn.cache.consensus.put(consensus)
return state, consensus
def download_direct(hostname, port, flavor='microdesc'):
"""Retrieve consensus via a direct HTTP connection.
:param hostname: host name of the node from which to retrieve the consensus.
:param port: port of the node from which to retrieve the consensus.
:param flavor: flavour of the consensus to retrieve.
:param cache: if the retrieved consensus should put in the cache.
"""
if flavor not in ['unflavored', 'microdesc']:
raise NotImplementedError(
'Consensus flavor "{}" not supported.'.format(flavor))
endpoint = 'consensus-microdesc' if flavor == 'microdesc' else 'consensus'
uri = 'http://%s:%d/tor/status-vote/current/%s' % (hostname, port, endpoint)
res = urllib.request.urlopen(uri)
cons = res.read()
ip = '%s:%d'%(hostname,port)
keys = get_signing_keys_info(ip)
if flavor != 'microdesc':
if not lnn.signature.verify(cons.decode('utf-8'), keys):
raise RuntimeError('Consensus Verification Failed')
consensus, remaining = parse(cons, flavor=flavor)
if consensus is None or remaining is None or not len(remaining) == 0:
raise RuntimeError('Unable to parse downloaded consensus!')
return consensus, keys
def download_raw(hostname, port, flavor='unflavored'):
"""Retrieve raw consensus via a direct HTTP connection.
:param hostname: host name of the node from which to retrieve the consensus.
:param port: port of the node from which to retrieve the consensus.
:param flavor: flavour of the consensus to retrieve.
"""
if flavor not in ['unflavored', 'microdesc']:
raise NotImplementedError(
'Consensus flavor "{}" not supported.'.format(flavor))
endpoint = 'consensus-microdesc' if flavor == 'microdesc' else 'consensus'
uri = 'http://%s:%d/tor/status-vote/current/%s' % (hostname, port, endpoint)
res = urllib.request.urlopen(uri)
cons = res.read().decode('utf-8')
return cons
def load(file_name, cache=True):
"""Load the consensus from a file
:param file_name: the name of the file in consensus_file
:param cache: if we cache the newly downloaded consensus
:return: the parsed consensus"""
abs_path = "/vagrant/consensus_files/"+file_name
if not os.path.exists(abs_path):
raise FileNotFoundError()
if cache:
try:
return lnn.cache.consensus.get("unflavored")
except BaseException:
pass
with open(abs_path, "r") as file:
answer = file.read()
consensus, remaining = consume_routers(answer)
if consensus is None or remaining is None or not len(remaining) == 0:
raise RuntimeError('Unable to parse downloaded consensus!')
if cache:
lnn.cache.consensus.put(consensus)
return consensus
|
volttron/platform/keystore.py
|
cloudcomputingabc/volttron
| 406 |
145836
|
<filename>volttron/platform/keystore.py
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2020, Battelle Memorial Institute.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This material was prepared as an account of work sponsored by an agency of
# the United States Government. Neither the United States Government nor the
# United States Department of Energy, nor Battelle, nor any of their
# employees, nor any jurisdiction or organization that has cooperated in the
# development of these materials, makes any warranty, express or
# implied, or assumes any legal liability or responsibility for the accuracy,
# completeness, or usefulness or any information, apparatus, product,
# software, or process disclosed, or represents that its use would not infringe
# privately owned rights. Reference herein to any specific commercial product,
# process, or service by trade name, trademark, manufacturer, or otherwise
# does not necessarily constitute or imply its endorsement, recommendation, or
# favoring by the United States Government or any agency thereof, or
# Battelle Memorial Institute. The views and opinions of authors expressed
# herein do not necessarily state or reflect those of the
# United States Government or any agency thereof.
#
# PACIFIC NORTHWEST NATIONAL LABORATORY operated by
# BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY
# under Contract DE-AC05-76RL01830
# }}}
#}}}
"""Module for storing local public and secret keys and remote public keys"""
from volttron.platform import jsonapi
import logging
import os
import urllib.parse
from zmq import curve_keypair
from .agent.utils import create_file_if_missing
from .vip.socket import encode_key
from volttron.platform import get_home
_log = logging.getLogger(__name__)
class BaseJSONStore(object):
"""JSON-file-backed store for dictionaries"""
def __init__(self, filename, permissions=0o600):
self.filename = filename
self.permissions = permissions
try:
created = create_file_if_missing(filename, contents='{}')
if created:
# remove access to group
os.chmod(filename, permissions)
except Exception as e:
import traceback
_log.error(traceback.print_exc())
raise RuntimeError("Failed to access KeyStore: {}".format(filename))
def store(self, data):
fd = os.open(self.filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
self.permissions)
try:
os.write(fd, jsonapi.dumpb(data, indent=4))
finally:
os.close(fd)
def load(self):
try:
with open(self.filename, 'r') as json_file:
return jsonapi.load(json_file)
except ValueError:
# If the file is empty jsonapi.load will raise ValueError
return {}
def remove(self, key):
data = self.load()
try:
del data[key]
except KeyError as e:
msg = 'Key "{}" is not present in {}'.format(key, self.filename)
raise KeyError(msg)
else:
self.store(data)
def update(self, new_data):
data = self.load()
data.update(new_data)
self.store(data)
class KeyStore(BaseJSONStore):
"""Handle generation, storage, and retrival of CURVE key pairs"""
def __init__(self, filename=None, encoded_public=None, encoded_secret=None):
if filename is None:
filename = self.get_default_path()
super(KeyStore, self).__init__(filename)
if not self.isvalid():
if encoded_public and encoded_secret:
self.store({'public': encoded_public,
'secret': encode_key(encoded_secret)})
else:
_log.debug("calling generate from keystore")
self.generate()
@staticmethod
def get_default_path():
return os.path.join(get_home(), 'keystore')
@staticmethod
def get_agent_keystore_path(identity=None):
if identity is None:
raise AttributeError("invalid identity")
return os.path.join(get_home(), f"keystores/{identity}/keystore.json")
@staticmethod
def generate_keypair_dict():
"""Generate and return new keypair as dictionary"""
public, secret = curve_keypair()
encoded_public = encode_key(public)
encoded_secret = encode_key(secret)
attempts = 0
max_attempts = 3
done = False
while not done and attempts < max_attempts:
# Keys that start with '-' are hard to use and cause issues with the platform
if encoded_secret.startswith('-') or encoded_public.startswith('-'):
# try generating public and secret key again
public, secret = curve_keypair()
encoded_public = encode_key(public)
encoded_secret = encode_key(secret)
else:
done = True
return {'public': encoded_public,
'secret': encoded_secret}
def generate(self):
"""Generate and store new key pair"""
self.store(self.generate_keypair_dict())
def _get_key(self, keyname):
"""Get key and make sure it's type is str (not unicode)
The json module returns all strings as unicode type, but base64
decode expects byte type as input. The conversion from unicode
type to str type is safe in this case, because encode_key
returns str type (ASCII characters only).
"""
key = self.load().get(keyname, None)
if key:
try:
key.encode('ascii')
except UnicodeEncodeError:
_log.warning(
'Non-ASCII character found for key {} in {}'
.format(keyname, self.filename))
key = None
return key
@property
def public(self):
"""Return encoded public key"""
return self._get_key('public')
@property
def secret(self):
"""Return encoded secret key"""
return self._get_key('secret')
def isvalid(self):
"""Check if key pair is valid"""
return self.public and self.secret
class KnownHostsStore(BaseJSONStore):
"""Handle storage and retrival of known hosts"""
def __init__(self, filename=None):
if filename is None:
filename = os.path.join(get_home(), 'known_hosts')
# all agents need read access to known_hosts file
super(KnownHostsStore, self).__init__(filename, permissions=0o644)
def add(self, addr, server_key):
self.update({self._parse_addr(addr): server_key})
def serverkey(self, addr):
return self.load().get(self._parse_addr(addr), None)
@staticmethod
def _parse_addr(addr):
url = urllib.parse.urlparse(addr)
if url.netloc:
return url.netloc
return url.path
|
python/my-widget-service/my_widget_service/my_widget_service_stack.py
|
marclyo/aws-cdk-examples
| 2,941 |
145837
|
<filename>python/my-widget-service/my_widget_service/my_widget_service_stack.py
from aws_cdk import (
core,
aws_apigateway as apigw,
aws_s3 as s3,
aws_iam as iam
)
class MyWidgetServiceStack(core.Stack):
def __init__(self, app: core.App, id: str, **kwargs) -> None:
super().__init__(app, id)
bucket: s3.Bucket = s3.Bucket(self, "WidgetStore")
api: apigw.RestApi = apigw.RestApi(
self,
"widgets-api",
rest_api_name="Widget Service",
description="This service serves widgets."
)
rest_api_role: iam.Role = iam.Role(
self,
"RestAPIRole",
assumed_by=iam.ServicePrincipal("apigateway.amazonaws.com"),
managed_policies=[iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3FullAccess")]
)
list_objects_response: apigw.IntegrationResponse = apigw.IntegrationResponse(status_code="200")
list_objects_integration_options: apigw.IntegrationOptions = apigw.IntegrationOptions(
credentials_role=rest_api_role,
integration_responses=[list_objects_response],
)
get_widget_integration_options: apigw.IntegrationOptions = apigw.IntegrationOptions(
credentials_role=rest_api_role,
integration_responses=[list_objects_response],
request_templates={"application/json": "#set($context.requestOverride.path.object = $input.params('id'))"}
)
put_widget_integration_options: apigw.IntegrationOptions = apigw.IntegrationOptions(
credentials_role=rest_api_role,
integration_responses=[list_objects_response],
passthrough_behavior=apigw.PassthroughBehavior.NEVER,
request_parameters={"integration.request.path.object": "method.request.path.id"},
request_templates={
"application/json": "#set($now=$context.requestTimeEpoch)\n"
"#set($body=\"$input.params('id') created $now\")"
"\n$util.base64Encode($body)"}
)
get_widgets_integration: apigw.AwsIntegration = apigw.AwsIntegration(
service="s3",
integration_http_method="GET",
path=bucket.bucket_name,
options=list_objects_integration_options
)
get_widget_integration: apigw.AwsIntegration = apigw.AwsIntegration(
service="s3",
integration_http_method="GET",
path="{}/{{object}}".format(bucket.bucket_name),
options=get_widget_integration_options
)
put_widget_integration: apigw.AwsIntegration = apigw.AwsIntegration(
service="s3",
integration_http_method="PUT",
path="{}/{{object}}".format(bucket.bucket_name),
options=put_widget_integration_options
)
delete_widget_integration: apigw.AwsIntegration = apigw.AwsIntegration(
service="s3",
integration_http_method="DELETE",
path="{}/{{object}}".format(bucket.bucket_name),
options=get_widget_integration_options
)
method_response: apigw.MethodResponse = apigw.MethodResponse(status_code="200")
api.root.add_method(
"GET",
get_widgets_integration,
method_responses=[method_response]
)
widget = api.root.add_resource('{id}')
widget.add_method(
"GET",
get_widget_integration,
method_responses=[method_response]
)
widget.add_method(
"POST",
put_widget_integration,
method_responses=[method_response],
request_parameters={"method.request.path.id": True}
)
widget.add_method(
"DELETE",
delete_widget_integration,
method_responses=[method_response]
)
|
histoqc/tests/test_data_cli.py
|
kaczmarj/HistoQC
| 140 |
145859
|
<reponame>kaczmarj/HistoQC
import os
from histoqc.data.__main__ import main
def test_data_cli_write_output(tmp_path):
assert main([os.fspath(tmp_path)]) == 0
assert set(x.name for x in tmp_path.iterdir()) == {'templates', 'models', 'pen'}
def test_data_cli_incorrect_output(capsys):
assert main(['does-not-exist']) == -1
captured = capsys.readouterr()
assert 'does-not-exist' in captured.err
|
test/make_sln.py
|
j123123/llilc
| 1,712 |
145871
|
#!/usr/bin/env python
#
# title : make_sln.py
# description : Make a Visual Studio solution to debug a managed
# application using LLILC jit.
#
# This script has been tested running on both Python 2.7 and Python 3.4.
#
# usage: make_sln.py [-h] [-d {summary,verbose}] [-x [EXTRA [EXTRA ...]]] [-n]
# [-p] [-v] [-r [CORERUN_ARGS [CORERUN_ARGS ...]]]
# [-j JIT_PATH] [-s SLN_PATH] [-i] [-f] -a APP_PATH -c
# CORECLR_RUNTIME_PATH
#
# Make a solution to debug a managed application with LLILC as the JIT. If the
# application has any arguments, they must be appended to the end of the command
# line, preceded by "--".
#
# optional arguments:
# -h, --help show this help message and exit
# -d {summary,verbose}, --dump-level {summary,verbose}
# the dump level: summary, or verbose
# -x [EXTRA [EXTRA ...]], --extra [EXTRA [EXTRA ...]]
# list of extra COMPlus settings. Each item is
# Name=Value, where Name does not have the
# COMPlus_AltJit prefix.
# -n, --ngen use ngened mscorlib
# -p, --precise-gc test with precise gc
# -v, --verbose echo commands
# -r [CORERUN_ARGS [CORERUN_ARGS ...]], --corerun-args [CORERUN_ARGS [CORERUN_ARGS ...]]
# The command arguments to pass to CoreRun, e.g. /v for
# verbose.
# -j JIT_PATH, --jit-path JIT_PATH
# full path to jit .dll. If given it is copied to
# coreclr directory. If not given we check that it
# exists in the coreclr directory.
# -s SLN_PATH, --sln-path SLN_PATH
# full path to use for the solution that will be
# written. If not given solution is written to the same
# directory as the application and has the same name
# with '.sln' substituted for '.exe'.
# -i, --invoke-vs Invoke Visual Studio on the solution
# -f, --force Force overwrite existing solution
#
# required arguments:
# -a APP_PATH, --app-path APP_PATH
# full path to application to run with llilc.
# -c CORECLR_RUNTIME_PATH, --coreclr-runtime-path CORECLR_RUNTIME_PATH
# full path to CoreCLR run-time binary directory
import argparse
import const
import os
import platform
import shutil
from string import Template
import subprocess
import sys
llilcverbose = False
def QuoteArg(arg):
'''Strip off any enclosing single quotes and enclose in double quotes'''
arg = '"' + arg.strip("'").strip('"') + '"'
return arg
def UnquoteArg(arg):
''' Remove single and double quotes from front and back of arg'''
return arg.strip("'").strip('"')
def GetPrintString(*args):
return ' '.join(map(str, args))
def Print(*args):
print (GetPrintString(*args))
def PrintError(*args):
''' Mimic the python 3.x print statement (should the community ever go to 3.4, we would not need to change much.)'''
sys.stderr.write(GetPrintString(*args) + '\n')
def log(*objs):
'''Print log message to both stdout and stderr'''
Print("llilc_run\stdout: ", *objs)
PrintError("llilc_run\stderr: ", *objs)
def RunCommand(command):
''' Run a command and return its exit code, optionally echoing it.'''
global llilcverbose
if llilcverbose:
log ('About to execute: ', command)
error_level = subprocess.call(command, shell=True)
return error_level
def main(argv):
'''
main method of script. arguments are script path and remaining arguments.
'''
global llilcverbose
const.Success = 0
const.GeneralError = -1
const.VS2015Missing = -2
const.SolutionAlreadyExists = -3
const.BadSolutionPath = -4
parser = argparse.ArgumentParser(description='''Make a solution to debug a managed
application with LLILC as the JIT.
If the application has any arguments, they must be
appended to the end of the command line, preceded by "--".
'''
)
parser.add_argument('-d', '--dump-level', type=str, choices={'summary', 'verbose'},
help='the dump level: summary, or verbose')
parser.add_argument('-x', '--extra', type=str, default=[], nargs='*',
help='''list of extra COMPlus settings. Each item is Name=Value, where
Name does not have the COMPlus_AltJit prefix.
''')
parser.add_argument('-n', '--ngen', help='use ngened mscorlib', default=False, action="store_true")
parser.add_argument('-p', '--precise-gc', help='test with precise gc', default=False, action="store_true")
parser.add_argument('-v', '--verbose', help='echo commands', default=False, action="store_true")
parser.add_argument('-r', '--corerun-args', type=str, nargs='*', default=[],
help='''The command arguments to pass to CoreRun, e.g. /v for verbose.
''')
parser.add_argument('-j', '--jit-path', type=str,
help='''full path to jit .dll. If given it is copied to coreclr directory.
If not given we check that it exists in the coreclr directory.
''')
parser.add_argument('-s', '--sln-path', type=str,
help='''full path to use for the solution that will be written.
If not given solution is written to the same directory
as the application and has the same name with '.sln'
substituted for '.exe'.
''')
parser.add_argument('-i', '--invoke-vs', default=False, action="store_true",
help='Invoke Visual Studio on the solution')
parser.add_argument('-f', '--force', default=False, action="store_true",
help='Force overwrite existing solution')
required = parser.add_argument_group('required arguments')
required.add_argument('-a', '--app-path', type=str, required=True,
help='full path to application to run with llilc.')
required.add_argument('-c', '--coreclr-runtime-path', required=True,
help='full path to CoreCLR run-time binary directory')
sln_template = Template('''
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.23107.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{911E67C6-3D85-4FCE-B560-20A9C3E3FF48}") = "$project", "$app_exe", "{3BE0C1EC-A093-408F-982D-6D50F5D9146C}"
ProjectSection(DebuggerProjectSystem) = preProject
PortSupplier = 00000000-0000-0000-0000-000000000000
Executable = $corerun
RemoteMachine = $current_machine
StartingDirectory = $app_dir
Arguments = $arguments
Environment = $tabbed_app_environment
LaunchingEngine = 2e36f1d4-b23c-435d-ab41-18e608940038
UseLegacyDebugEngines = No
LaunchSQLEngine = No
AttachLaunchAction = No
EndProjectSection
EndProject
''')
current_machine = platform.node()
args, unknown = parser.parse_known_args(argv)
llilcverbose = args.verbose
if llilcverbose:
log('Starting make_sln.py')
log(' argv=', argv)
# Skip separating '--', if any.
if unknown and (unknown[0] == '--'):
unknown = unknown[1:]
app_path = args.app_path
(app_dir, app_exe) = os.path.split(app_path)
(project, extension) = os.path.splitext(app_exe)
if args.sln_path:
sln_path = os.path.abspath(args.sln_path)
(sln_base, sln_ext) = os.path.splitext(sln_path)
if sln_ext != '.sln':
log('Specified solution file: ', args.sln_path, ' does not end with .sln')
return const.BadSolutionPath
else:
sln_path= os.path.join(app_dir, (project + ".sln"))
if os.path.exists(sln_path):
if not args.force:
log("File ", sln_path, " already exists, use --force to overwrite")
return const.SolutionAlreadyExists
corerun = os.path.join(args.coreclr_runtime_path, "CoreRun.exe")
jit_name = "llilcjit.dll"
# jit_path is the path to where the jit would be in the CoreClr directory in order
# to be used as the alternate jit.
jit_path = os.path.join(args.coreclr_runtime_path, jit_name)
if args.jit_path:
# User specified a source path to the LLILC JIT. Copy it even if there
# already is one, as it may be a revised version.
shutil.copy2(args.jit_path, jit_path)
elif not os.path.exists(jit_path):
log("llilc jit not found at ", jit_path)
return 1
# Compute desired environment.
# First initialize empty values for variables known to LLILC.
env = {}
env["complus_altjit"] = ""
env["complus_altjitname"] = ""
env["complus_gcconservative"] = ""
env["complus_insertstatepoints"] = ""
env["complus_zapdisable"] = ""
env["complus_dumpllvmir"] = ""
env["complus_jitgcinfologging"] = ""
env["complus_altjitexclude"] = ""
env["complus_altjitbreakatjitstart"] = ""
env["complus_altjitmsildump"] = ""
env["complus_altjitllvmdump"] = ""
env["complus_altjitcoderangedump"] = ""
env["complus_simdintrinc"] = ""
env["complus_altjitoptions"] = ""
# Now initialized based on desired values and options.
env["complus_altjit"]="*"
env["complus_altjitname"]=jit_name
if (args.precise_gc):
env["complus_insertstatepoints"]="1"
else:
env["complus_gcconservative"]="1"
if not args.ngen:
env["complus_zapdisable"]="1"
if args.dump_level:
env["complus_dumpllvmir"]=args.dump_level
for arg in args.extra:
pair = UnquoteArg(arg).split('=', 1)
name = 'complus_altjit' + pair[0]
name = name.lower()
value = pair[1]
env[name] = value
env["core_root"]=args.coreclr_runtime_path
env["core_libraries"]=app_dir
# Convert environment into tab-separated string.
tabbed_app_environment = ''
keys = list(env.keys())
keys.sort()
for key in keys:
value = env[key]
tabbed_app_environment += (key + '=' + value + "\t")
arguments = ''
if args.corerun_args:
for arg in args.corerun_args:
arg = QuoteArg(arg)
arguments += ' ' + arg
if arguments != '':
arguments += ' '
arguments += QuoteArg(args.app_path)
for arg in unknown:
arg = QuoteArg(arg)
arguments += ' ' + arg
sln = sln_template.substitute(locals())
try:
with open(sln_path, 'w') as sln_file:
sln_file.writelines(sln)
except:
e = sys.exc_info()[0]
print('Error: make_sln.py failed due to ', e)
return const.GeneralError
error_level = const.Success
if args.invoke_vs:
vstools = os.environ['VS140COMNTOOLS']
if not vstools:
log ("make_sln.py requires Visual Studio 2015")
return const.VS2015Missing
vspath = os.path.abspath(os.path.join(vstools, "..", "IDE", "devenv.exe"))
command = "start"
command += ' '
command += QuoteArg(vspath)
command += ' '
command += QuoteArg(sln_path)
error_level = RunCommand(command)
if llilcverbose:
log ('Exiting make_sln.py with exit code ', error_level)
return error_level
if __name__ == '__main__':
return_code = main(sys.argv[1:])
sys.exit(return_code)
|
misc/find-cids.py
|
S-YOU/quicly
| 8,657 |
145891
|
#!/usr/bin/env python
import sys
import json
if len(sys.argv) != 2:
print "Usage: find-cids.py inTrace.jsonl"
sys.exit(1)
cids = {}
f = open(sys.argv[1], 'r')
for line in f:
event = json.loads(line)
if event["type"] != "" and event["type"] == "accept":
cids[event["conn"]] = None
print "Connection IDs:", cids.keys()
f.close()
|
mock_data_generators/channel_program_name_gen.py
|
tzooming/bigquery-ml-templates
| 154 |
145896
|
<reponame>tzooming/bigquery-ml-templates
'''
Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This script generates the CRM account data's Channel Program Name.
'''
import numpy as np
from itertools import groupby
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv("crm_account.csv")
mu = 3
sigma = 0.4
lv = np.random.normal(mu, sigma, 2500)
lv = [int(i) for i in lv]
print(min(lv))
print(max(lv))
data['Channel Program Name'] = lv
count, bins, ignored = plt.hist(lv, 30, normed=True)
plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2)), linewidth=2, color='r')
plt.show()
data.to_csv("crm_account_temp.csv")
|
home/museum.py
|
pwqbot/eoj3
| 107 |
145897
|
<gh_stars>100-1000
from datetime import datetime, timedelta
from django.db.models import Count
from django.db.models.functions import TruncDate, TruncYear
from django.shortcuts import render
from account.models import User
from dispatcher.manage import ping
from dispatcher.models import Server
from problem.models import Problem
from submission.models import Submission
def museum_view(request):
def convert_timedelta(td):
return {
'year': td.days // 365,
'day': td.days % 365,
'hour': td.seconds // 3600,
'minute': (td.seconds % 3600) // 60,
'second': td.seconds % 60
}
ctx = {}
ctx['total_problem_count'] = Problem.objects.count()
ctx['total_submission_count'] = Submission.objects.count()
ctx['total_user_count'] = User.objects.filter(is_active=True).count()
# NOTE: this will break if there is no submission at all
first_submission = Submission.objects.last()
ctx['first_submission_time'] = first_submission.create_time
ctx['first_submission_duration'] = convert_timedelta(datetime.now() - ctx['first_submission_time'])
ctx['first_submission_author'] = first_submission.author
from uptime import uptime
ctx['uptime'] = convert_timedelta(timedelta(seconds=uptime()))
ctx['server_time'] = datetime.now()
ctx['eoj3_create_duration'] = convert_timedelta(datetime.now() - datetime(2017, 3, 11, 18, 32))
ctx['submission_count_1'] = Submission.objects.filter(create_time__gt=datetime.now() - timedelta(days=1)).count()
ctx['submission_count_7'] = Submission.objects.filter(create_time__gt=datetime.now() - timedelta(days=7)).count()
ctx['submission_count_30'] = Submission.objects.filter(create_time__gt=datetime.now() - timedelta(days=30)).count()
ctx['submission_stat'] = Submission.objects.filter(create_time__gt=datetime.today() - timedelta(days=30)). \
annotate(date=TruncDate('create_time')).values('date'). \
annotate(count=Count('id')).values('date', 'count').order_by()
ctx['user_stat'] = User.objects.filter(is_active=True).annotate(date=TruncYear('date_joined')).values('date'). \
annotate(count=Count('id')).values('date', 'count').order_by("date")
for idx, user in enumerate(ctx['user_stat']):
if idx == 0:
continue
user['count'] += ctx['user_stat'][idx - 1]['count']
ctx['problem_stat'] = Problem.objects.annotate(date=TruncYear('create_time')).values('date'). \
annotate(count=Count('id')).values('date', 'count').order_by("date")
for idx, user in enumerate(ctx['problem_stat']):
if idx == 0:
continue
user['count'] += ctx['problem_stat'][idx - 1]['count']
ctx['servers'] = servers = Server.objects.filter(enabled=True)
for server in servers:
server.status = ping(server)
return render(request, 'museum.jinja2', context=ctx)
|
vertx-web/src/test/sockjs-protocol/websocket/tests/test_cookiejar.py
|
yeikel/vertx-web
| 1,553 |
145916
|
<filename>vertx-web/src/test/sockjs-protocol/websocket/tests/test_cookiejar.py<gh_stars>1000+
import unittest
from websocket._cookiejar import SimpleCookieJar
try:
import Cookie
except:
import http.cookies as Cookie
class CookieJarTest(unittest.TestCase):
def testAdd(self):
cookie_jar = SimpleCookieJar()
cookie_jar.add("")
self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b")
self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; domain=.abc")
self.assertTrue(".abc" in cookie_jar.jar)
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; domain=abc")
self.assertTrue(".abc" in cookie_jar.jar)
self.assertTrue("abc" not in cookie_jar.jar)
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; c=d; domain=abc")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; c=d; domain=abc")
cookie_jar.add("e=f; domain=abc")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d; e=f")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; c=d; domain=abc")
cookie_jar.add("e=f; domain=.abc")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d; e=f")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; c=d; domain=abc")
cookie_jar.add("e=f; domain=xyz")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
self.assertEquals(cookie_jar.get("xyz"), "e=f")
self.assertEquals(cookie_jar.get("something"), "")
def testSet(self):
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b")
self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; domain=.abc")
self.assertTrue(".abc" in cookie_jar.jar)
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; domain=abc")
self.assertTrue(".abc" in cookie_jar.jar)
self.assertTrue("abc" not in cookie_jar.jar)
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc")
cookie_jar.set("e=f; domain=abc")
self.assertEquals(cookie_jar.get("abc"), "e=f")
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc")
cookie_jar.set("e=f; domain=.abc")
self.assertEquals(cookie_jar.get("abc"), "e=f")
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc")
cookie_jar.set("e=f; domain=xyz")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
self.assertEquals(cookie_jar.get("xyz"), "e=f")
self.assertEquals(cookie_jar.get("something"), "")
def testGet(self):
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc.com")
self.assertEquals(cookie_jar.get("abc.com"), "a=b; c=d")
self.assertEquals(cookie_jar.get("x.abc.com"), "a=b; c=d")
self.assertEquals(cookie_jar.get("abc.com.es"), "")
self.assertEquals(cookie_jar.get("xabc.com"), "")
cookie_jar.set("a=b; c=d; domain=.abc.com")
self.assertEquals(cookie_jar.get("abc.com"), "a=b; c=d")
self.assertEquals(cookie_jar.get("x.abc.com"), "a=b; c=d")
self.assertEquals(cookie_jar.get("abc.com.es"), "")
self.assertEquals(cookie_jar.get("xabc.com"), "")
|
terrascript/provider/Mongey/hellosign.py
|
mjuenema/python-terrascript
| 507 |
145932
|
# terrascript/provider/Mongey/hellosign.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:18:22 UTC)
import terrascript
class hellosign(terrascript.Provider):
""""""
__description__ = ""
__namespace__ = "Mongey"
__name__ = "hellosign"
__source__ = "https://github.com/Mongey/terraform-provider-hellosign"
__version__ = "0.0.2"
__published__ = "2021-02-08T22:16:56Z"
__tier__ = "community"
__all__ = ["hellosign"]
|
vh-nginx/__init__.py
|
rEinve/ajenti-v
| 150 |
145940
|
import ajenti
from ajenti.api import *
from ajenti.plugins import *
info = PluginInfo(
title='Ajenti VH - NGINX Support',
icon='globe',
dependencies=[
PluginDependency('vh'),
PluginDependency('services'),
#BinaryDependency('nginx'),
],
)
def init():
from ajenti.plugins.vh import destroyed_configs
destroyed_configs.append('nginx')
import nginx
import nginx_templates
from ajenti.plugins import manager
from ajenti.plugins.nginx.main import Nginx
#from ajenti.plugins.apache.main import Apache
manager.blacklist.append(Nginx)
#manager.blacklist.append(Apache)
|
tests/test_flask_kvsession.py
|
ldruschk/flask-kvsession
| 102 |
145951
|
#!/usr/bin/env python
# coding=utf8
from datetime import timedelta
import json
import time
from itsdangerous import Signer
from six import b
import pytest
def json_dec(bs):
return json.loads(bs.decode('ascii'))
def split_cookie(app, rv):
signer = Signer(app.secret_key)
cookie_data = rv.headers['Set-Cookie'].split(';', 1)[0]
for cookie in cookie_data.split('&'):
name, value = cookie_data.split('=')
if name == app.session_cookie_name:
unsigned_value = signer.unsign(value)
sid, created = unsigned_value.split(b('_'))
return sid.decode('ascii'), int(created, 16)
def test_app_request_no_extras(client):
rv = client.get('/')
assert b('move along') in rv.data
def test_no_session_usage_uses_no_storage(store, client):
client.get('/')
client.get('/')
assert not store.keys()
def test_session_usage(store, client):
client.get('/store-in-session/foo/bar/')
assert store.keys()
def test_proper_cookie_received(store, app, client):
rv = client.get('/store-in-session/bar/baz/')
sid, created = split_cookie(app, rv)
assert created != 0
# check sid in store
key = '%s_%x' % (sid, created)
assert key in store
def test_session_restores_properly(client):
client.get('/store-in-session/k1/value1/')
client.get('/store-in-session/k2/value2/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
assert s['k2'] == 'value2'
def test_manipulation_caught(client):
client.get('/store-in-session/k1/value1/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
# now manipulate the cookie
cookie = client.get_session_cookie()
v_orig = cookie.value
# FIXME: this seems to break (i.e. not detect manipulation) if the
# last character of v_orig is changed. possibly padding?
for i in range(len(v_orig)-1):
broken_value = (v_orig[:i] +
('a' if v_orig[i] != 'a' else 'b') +
v_orig[i + 1:])
cookie.value = broken_value
assert broken_value != v_orig
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s == {}, 'manipulation check failed: %s / %s / %d' % (
v_orig, broken_value, i
)
# sanity check: ensure original value still works
cookie.value = v_orig
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
def test_can_change_values(client):
client.get('/store-in-session/k1/value1/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
client.get('/store-in-session/k1/value2/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value2'
def test_can_delete_values(client):
client.get('/store-in-session/k1/value1/')
client.get('/store-in-session/k2/value2/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
assert s['k2'] == 'value2'
client.get('/delete-from-session/k1/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert 'k1' not in s
assert s['k2'] == 'value2'
def test_can_destroy_sessions(client):
client.get('/store-in-session/k1/value1/')
client.get('/store-in-session/k2/value2/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
assert s['k2'] == 'value2'
# destroy session
rv = client.get('/destroy-session/')
assert b('session destroyed') in rv.data
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s == {}
def test_session_expires_without_backend_support(app, client):
# set expiration to 1 second
app.permanent_session_lifetime = timedelta(seconds=1)
client.get('/store-in-session/k1/value1/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
rv = client.get('/make-session-permanent/')
# assert that the session has a non-zero timestamp
sid, created = split_cookie(app, rv)
assert created != 0
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
# sleep two seconds
time.sleep(2)
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s == {}
def test_session_cleanup_works(store, app, client):
# set expiration to 1 second
app.permanent_session_lifetime = timedelta(seconds=1)
client.get('/store-in-session/k1/value1/')
client.get('/make-session-permanent/')
# assume there is a valid session, even after cleanup
assert list(store.keys())
app.kvsession.cleanup_sessions(app)
assert list(store.keys())
time.sleep(2)
app.kvsession.cleanup_sessions(app)
assert not list(store.keys())
def test_can_regenerate_session(store, client):
client.get('/store-in-session/k1/value1/')
assert len(store.keys()) == 1
key = store.keys()[0]
# now regenerate
client.get('/regenerate-session/')
assert len(store.keys()) == 1
new_key = store.keys()[0]
assert new_key != key
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
def test_works_without_secret_key_if_session_not_used(app):
app.config['SECRET_KEY'] = None
client = app.test_client()
client.get('/')
def test_correct_error_reporting_with_no_secret_key(app, client):
app.config['SECRET_KEY'] = None
with pytest.raises(RuntimeError):
client.get('/store-in-session/k1/value1/')
def test_can_store_datetime(client):
client.get('/store-datetime/')
rv = client.get('/dump-datetime/')
assert rv.data == b('2011-08-10 15:46:00')
def test_missing_session_causes_new_empty_session(store, client):
client.get('/store-in-session/k1/value1/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
store.delete(store.keys()[0])
rv = client.get('/dump-session/')
assert rv.data == b('{}')
rv = client.get('/is-kvsession/')
assert rv.data == b('True')
def test_manipulated_session_causes_new_empty_session(client):
client.get('/store-in-session/k1/value1/')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
cookie = client.get_session_cookie()
cookie.value += 'x'
rv = client.get('/dump-session/')
assert rv.data == b('{}')
rv = client.get('/is-kvsession/')
assert rv.data == b('True')
def test_expired_session_causes_new_empty_session(app, client):
app.permanent_session_lifetime = timedelta(seconds=1)
client.get('/store-in-session/k1/value1/')
rv = client.get('/make-session-permanent/')
# assert that the session has a non-zero timestamp
sid, created = split_cookie(app, rv)
assert created != 0
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s['k1'] == 'value1'
# sleep two seconds
time.sleep(2)
# we should have a new session now
rv = client.get('/is-new-session/')
assert rv.data == b('True')
rv = client.get('/dump-session/')
s = json_dec(rv.data)
assert s == {}
def test_expired_made_permanent_causes_no_exception(app, client):
app.permanent_session_lifetime = timedelta(seconds=1)
client.get('/store-in-session/k1/value1/')
# sleep two seconds
time.sleep(2)
client.get('/make-session-permanent/')
def test_permanent_session_cookies_are_permanent(app, client):
client.get('/store-in-session/k1/value1/')
# session cookie
assert client.get_session_cookie().expires is None
client.get('/make-session-permanent/')
# now it needs to be permanent
assert client.get_session_cookie().expires is not None
def test_regenerate_before_session(client):
client.get('/regenerate-session/')
def test_destroying_session_does_not_immediately_create_new(client, store):
client.get('/store-in-session/k1/value1/')
client.get('/make-session-permanent/')
assert list(store.keys())
client.get('/destroy-session/')
# now the store should be empty
assert not list(store.keys())
def test_destroying_session_immediately(client):
client.get('/destroy-immediately/')
def test_new_session_not_modified(client):
rv = client.get('/is-modified-session/')
assert rv.data == b('False')
def test_existing_session_not_modified(client):
client.get('/store-in-session/k1/value1/')
rv = client.get('/is-modified-session/')
assert rv.data == b('False')
def test_path_app_root(app, client):
app.config['APPLICATION_ROOT'] = '/foo'
client.get('/store-in-session/k1/value1/')
cookie = client.get_session_cookie('/foo')
assert cookie.path == '/foo'
def test_path_session_path(app, client):
app.config['APPLICATION_ROOT'] = '/foo'
app.config['SESSION_COOKIE_PATH'] = '/bar'
client.get('/store-in-session/k1/value1/')
cookie = client.get_session_cookie('/bar')
assert cookie.path == '/bar'
|
insights/combiners/x86_page_branch.py
|
lhuett/insights-core
| 121 |
145956
|
"""
X86PageBranch - combiner for x86 kernel features:
=================================================
x86 kernel features includes:
* PTI (Page Table Isolation)
* IBPB (Indirect Branch Prediction Barrier)
* IBRS (Indirect Branch Restricted Speculation)
This combiner reads information from debugfs:
Examples:
>>> type(dv)
<class 'insights.combiners.x86_page_branch.X86PageBranch'>
>>> dv.pti
1
>>> dv.ibpb
3
>>> dv.ibrs
2
>>> dv.retp
0
Attributes:
pti (int): The result parsed of '/sys/kernel/debug/x86/pti_enabled'
ibpb (int): The result parsed of '/sys/kernel/debug/x86/ibpb_enabled'
ibrs (int): The result parsed of '/sys/kernel/debug/x86/ibrs_enabled'
retp (int): The result parsed of '/sys/kernel/debug/x86/retp_enabled'
"""
from insights.core.plugins import combiner
from insights.parsers.x86_debug import X86PTIEnabled, X86IBPBEnabled, X86IBRSEnabled, X86RETPEnabled
@combiner(X86PTIEnabled, X86IBPBEnabled, X86IBRSEnabled, optional=[X86RETPEnabled])
class X86PageBranch(object):
"""
This combiner provides an interface to the three X86 Page Table/Branch Prediction parsers.
If retp_enabled is not available, self.retp is None.
"""
def __init__(self, pti_enabled, ibpb_enabled, ibrs_enabled, retp_enabled):
self.pti = pti_enabled.value
self.ibpb = ibpb_enabled.value
self.ibrs = ibrs_enabled.value
self.retp = None
if retp_enabled:
self.retp = retp_enabled.value
|
dsgn/layers/smooth_l1_loss.py
|
fangchengji/DSGN
| 192 |
145961
|
<gh_stars>100-1000
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import numpy as np
# TODO maybe push this to nn?
def smooth_l1_loss(input, target, beta=1. / 9, size_average=True):
"""
very similar to the smooth_l1_loss from pytorch, but with
the extra beta parameter
"""
n = torch.abs(input - target)
cond = n < beta
loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta)
if size_average:
return loss.mean()
return loss.sum()
def l1_loss(input, target, beta=1., sum_last_dim=False):
n = torch.abs(input - target)
loss = n * beta
if sum_last_dim:
loss = loss.sum(dim=-1)
return loss.mean()
def l2_loss(input, target, beta=1., sum_last_dim=False):
diff = input - target
n = diff * diff
loss = n * beta
if sum_last_dim:
loss = loss.sum(dim=-1)
return loss.mean()
def ordinal_loss(input, target):
N, C = input.shape
ranges = torch.arange(C, dtype=torch.int32).cuda()
mask = ranges[None, :] < target[:, None]
loss = -(torch.sum(torch.log( input[mask] + 1e-6 )) \
+ torch.sum(torch.log( 1. - input[1 - mask] + 1e-6 )))
loss = loss / N / C
return loss
def dorn_decode(cls, reg, alpha, beta):
dorn_dim = cls.shape[1]
depth_discretization = torch.sum((cls > 0.5), dim=1, keepdim=True)
if reg is not None:
depth_residual = torch.gather(reg, dim=1, index=depth_discretization)
depth_continuity = depth_discretization.float() + 0.5 + depth_residual
else:
depth_continuity = depth_discretization.float()
depth = alpha * (beta / alpha) ** (depth_continuity / dorn_dim)
return depth
def dorn_encode(depth, alpha, beta, dorn_dim):
depth = dorn_dim * torch.log(depth / alpha + 1e-6) / np.log(beta / alpha + 1e-6)
depth = depth.clamp(0, dorn_dim)
return depth.int(), depth - depth.int().float() - 0.5
def bce_loss(score, target):
loss = - (target * torch.log(score + 1e-6) + (1 - target) * torch.log( 1 - score + 1e-6))
return loss.mean()
|
tests/test_sampler.py
|
nylas/stackcollector
| 592 |
145976
|
import time
from stacksampler import Sampler
def slp():
time.sleep(0.00001)
def fn():
for i in range(50000):
slp()
s = Sampler()
def test_foo():
s.start()
fn()
print s.output_stats()
if __name__ == '__main__':
test_foo()
|
chapter13/ShortCorridor.py
|
zhaoletian/reinforcement-learning-an-introduction
| 220 |
146012
|
#######################################################################
# Copyright (C) #
# 2018 <NAME> (<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
#######################################################################
#
# This is a reproduction of the plot shown in Example 13.1
# in Chapter 13, "Policy Gradient Methods". Book draft May 27, 2018.
#
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
def f(p):
""" True value of the first state
Args:
p (float): probability of the action 'right'.
Returns:
True value of the first state.
The expression is obtained by manually solving the easy linear system
of Bellman equations using known dynamics.
"""
return (2 * p - 4) / (p * (1 - p))
epsilon = 0.05
fig, ax = plt.subplots(1, 1)
# Plot a graph
p = np.linspace(0.01, 0.99, 100)
y = f(p)
ax.plot(p, y, color='red')
# Find a maximum point, can also be done analytically by taking a derivative
imax = np.argmax(y)
pmax = p[imax]
ymax = y[imax]
ax.plot(pmax, ymax, color='green', marker="*", label="optimal point: f({0:.2f}) = {1:.2f}".format(pmax, ymax))
# Plot points of two epsilon-greedy policies
ax.plot(epsilon, f(epsilon), color='magenta', marker="o", label="epsilon-greedy left")
ax.plot(1 - epsilon, f(1 - epsilon), color='blue', marker="o", label="epsilon-greedy right")
ax.set_ylabel("Value of the first state")
ax.set_xlabel("Probability of the action 'right'")
ax.set_title("Short corridor with switched actions")
ax.set_ylim(ymin=-105.0, ymax=5)
ax.legend()
fig.tight_layout()
plt.show()
|
coordinator/SwitchOracles/oracle.py
|
TotalKnob/muse
| 122 |
146016
|
<filename>coordinator/SwitchOracles/oracle.py
from switch_oracle import *
def get_switch_oracle(config, proj_dir):
return SwitchOracles(config, proj_dir)
|
modules/dbnd/src/dbnd/_vendor/pygtrie.py
|
ipattarapong/dbnd
| 224 |
146029
|
<reponame>ipattarapong/dbnd<filename>modules/dbnd/src/dbnd/_vendor/pygtrie.py
# -*- coding: utf-8 -*-
"""Implementation of a trie data structure.
`Trie data structure <http://en.wikipedia.org/wiki/Trie>`_, also known as radix
or prefix tree, is a tree associating keys to values where all the descendants
of a node have a common prefix (associated with that node).
The trie module contains :class:`pygtrie.Trie`, :class:`pygtrie.CharTrie` and
:class:`pygtrie.StringTrie` classes each implementing a mutable mapping
interface, i.e. :class:`dict` interface. As such, in most circumstances,
:class:`pygtrie.Trie` could be used as a drop-in replacement for
a :class:`dict`, but the prefix nature of the data structure is trie’s real
strength.
The module also contains :class:`pygtrie.PrefixSet` class which uses a trie to
store a set of prefixes such that a key is contained in the set if it or its
prefix is stored in the set.
Features
--------
- A full mutable mapping implementation.
- Supports iterating over as well as deleting a subtrie.
- Supports prefix checking as well as shortest and longest prefix
look-up.
- Extensible for any kind of user-defined keys.
- A PrefixSet supports “all keys starting with given prefix” logic.
- Can store any value including None.
For some simple examples see ``example.py`` file.
"""
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright 2014 Google Inc.'
import collections as _collections
# Python 2.x and 3.x compatibility stuff
if hasattr(dict, 'iteritems'):
# pylint: disable=invalid-name
_iteritems = lambda d: d.iteritems()
_iterkeys = lambda d: d.iterkeys()
def _sorted_iteritems(d):
"""Returns d's items in sorted order."""
items = d.items()
items.sort()
return iter(items)
else:
_sorted_iteritems = lambda d: sorted(d.items()) # pylint: disable=invalid-name
_iteritems = lambda d: iter(d.items()) # pylint: disable=invalid-name
_iterkeys = lambda d: iter(d.keys()) # pylint: disable=invalid-name
try:
_basestring = basestring
except NameError:
_basestring = str
class ShortKeyError(KeyError):
"""Raised when given key is a prefix of a longer key."""
pass
_SENTINEL = object()
class _Node(object):
"""A single node of a trie.
Stores value associated with the node and dictionary of children.
"""
__slots__ = ('children', 'value')
def __init__(self):
self.children = {}
self.value = _SENTINEL
def iterate(self, path, shallow, iteritems):
"""Yields all the nodes with values associated to them in the trie.
Args:
path: Path leading to this node. Used to construct the key when
returning value of this node and as a prefix for children.
shallow: Perform a shallow traversal, i.e. do not yield nodes if
their prefix has been yielded.
iteritems: A function taking dictionary as argument and returning
iterator over its items. Something other than dict.iteritems
may be given to enable sorting.
Yields:
``(path, value)`` tuples.
"""
# Use iterative function with stack on the heap so we don't hit Python's
# recursion depth limits.
node = self
stack = []
while True:
if node.value is not _SENTINEL:
yield path, node.value
if (not shallow or node.value is _SENTINEL) and node.children:
stack.append(iter(iteritems(node.children)))
path.append(None)
while True:
try:
step, node = next(stack[-1])
path[-1] = step
break
except StopIteration:
stack.pop()
path.pop()
except IndexError:
return
def traverse(self, node_factory, path_conv, path, iteritems):
"""Traverses the node and returns another type of node from factory.
Args:
node_factory: Callable function to construct new nodes.
path_conv: Callable function to convert node path to a key.
path: Current path for this node.
iteritems: A function taking dictionary as argument and returning
iterator over its items. Something other than dict.iteritems
may be given to enable sorting.
Returns:
An object constructed by calling node_factory(path_conv, path,
children, value=...), where children are constructed by node_factory
from the children of this node. There doesn't need to be 1:1
correspondence between original nodes in the trie and constructed
nodes (see make_test_node_and_compress in test.py).
"""
def children():
"""Recursively traverses all of node's children."""
for step, node in iteritems(self.children):
yield node.traverse(node_factory, path_conv, path + [step],
iteritems)
args = [path_conv, tuple(path), children()]
if self.value is not _SENTINEL:
args.append(self.value)
return node_factory(*args)
def __eq__(self, other):
# Like iterate, we don't recurse so this works on deep tries.
a, b = self, other
stack = []
while True:
if a.value != b.value or len(a.children) != len(b.children):
return False
if a.children:
stack.append((_iteritems(a.children), b.children))
while True:
try:
key, a = next(stack[-1][0])
b = stack[-1][1].get(key)
if b is None:
return False
break
except StopIteration:
stack.pop()
except IndexError:
return True
return self.value == other.value and self.children == other.children
def __ne__(self, other):
return not self.__eq__(other)
def __bool__(self):
return bool(self.value is not _SENTINEL or self.children)
__nonzero__ = __bool__
__hash__ = None
def __getstate__(self):
"""Get state used for pickling.
The state is encoded as a list of simple commands which consist of an
integer and some command-dependent number of arguments. The commands
modify what the current node is by navigating the trie up and down and
setting node values. Possible commands are:
* [n, step0, step1, ..., stepn-1, value], for n >= 0, specifies step
needed to reach the next current node as well as its new value. There
is no way to create a child node without setting its (or its
descendant's) value.
* [-n], for -n < 0, specifies to go up n steps in the trie.
When encoded as a state, the commands are flattened into a single list.
For example::
[ 0, 'Root',
2, 'Foo', 'Bar', 'Root/Foo/Bar Node',
-1,
1, 'Baz', 'Root/Foo/Baz Node',
-2,
1, 'Qux', 'Root/Qux Node' ]
Creates the following hierarchy::
-* value: Root
+-- Foo --* no value
| +-- Bar -- * value: Root/Foo/Bar Node
| +-- Baz -- * value: Root/Foo/Baz Node
+-- Qux -- * value: Root/Qux Node
Returns:
A pickable state which can be passed to :func:`_Node.__setstate__`
to reconstruct the node and its full hierarchy.
"""
# Like iterate, we don't recurse so pickling works on deep tries.
state = [] if self.value is _SENTINEL else [0]
last_cmd = 0
node = self
stack = []
while True:
if node.value is not _SENTINEL:
last_cmd = 0
state.append(node.value)
stack.append(_iteritems(node.children))
while True:
try:
step, node = next(stack[-1])
except StopIteration:
if last_cmd < 0:
state[-1] -= 1
else:
last_cmd = -1
state.append(-1)
stack.pop()
continue
except IndexError:
if last_cmd < 0:
state.pop()
return state
if last_cmd > 0:
last_cmd += 1
state[-last_cmd] += 1
else:
last_cmd = 1
state.append(1)
state.append(step)
break
def __setstate__(self, state):
"""Unpickles node. See :func:`_Node.__getstate__`."""
self.__init__()
state = iter(state)
stack = [self]
for cmd in state:
if cmd < 0:
del stack[cmd:]
else:
while cmd > 0:
stack.append(type(self)())
stack[-2].children[next(state)] = stack[-1]
cmd -= 1
stack[-1].value = next(state)
_NONE_PAIR = type('NonePair', (tuple,), {
'__nonzero__': lambda _: False,
'__bool__': lambda _: False,
'__slots__': (),
})((None, None))
class Trie(_collections.MutableMapping):
"""A trie implementation with dict interface plus some extensions.
Keys used with the :class:`pygtrie.Trie` must be iterable, yielding hashable
objects. In other words, for a given key, ``dict.fromkeys(key)`` must be
valid.
In particular, strings work fine as trie keys, however when getting keys
back from iterkeys() method for example, instead of strings, tuples of
characters are produced. For that reason, :class:`pygtrie.CharTrie` or
:class:`pygtrie.StringTrie` may be preferred when using
:class:`pygtrie.Trie` with string keys.
"""
def __init__(self, *args, **kwargs):
"""Initialises the trie.
Arguments are interpreted the same way :func:`Trie.update` interprets
them.
"""
self._root = _Node()
self._sorted = False
self.update(*args, **kwargs)
@property
def _iteritems(self):
"""Returns function yielding over dict's items possibly in sorted order.
Returns:
A function iterating over items of a dictionary given as an
argument. If child nodes sorting has been enabled (via
:func:`Trie.enable_sorting` method), returned function will go
through the items in sorted order..
"""
return _sorted_iteritems if self._sorted else _iteritems
def enable_sorting(self, enable=True):
"""Enables sorting of child nodes when iterating and traversing.
Normally, child nodes are not sorted when iterating or traversing over
the trie (just like dict elements are not sorted). This method allows
sorting to be enabled (which was the behaviour prior to pygtrie 2.0
release).
For Trie class, enabling sorting of children is identical to simply
sorting the list of items since Trie returns keys as tuples. However,
for other implementations such as StringTrie the two may behove subtly
different. For example, sorting items might produce::
root/foo-bar
root/foo/baz
even though foo comes before foo-bar.
Args:
enable: Whether to enable sorting of child nodes.
"""
self._sorted = enable
def clear(self):
"""Removes all the values from the trie."""
self._root = _Node()
def update(self, *args, **kwargs):
"""Updates stored values. Works like :func:`dict.update`."""
if len(args) > 1:
raise ValueError('update() takes at most one positional argument, '
'%d given.' % len(args))
# We have this here instead of just letting MutableMapping.update()
# handle things because it will iterate over keys and for each key
# retrieve the value. With Trie, this may be expensive since the path
# to the node would have to be walked twice. Instead, we have our own
# implementation where iteritems() is used avoiding the unnecessary
# value look-up.
if args and isinstance(args[0], Trie):
for key, value in _iteritems(args[0]):
self[key] = value
args = ()
super(Trie, self).update(*args, **kwargs)
def copy(self):
"""Returns a shallow copy of the trie."""
return self.__class__(self)
@classmethod
def fromkeys(cls, keys, value=None):
"""Creates a new trie with given keys set.
This is roughly equivalent to calling the constructor with a ``(key,
value) for key in keys`` generator.
Args:
keys: An iterable of keys that should be set in the new trie.
value: Value to associate with given keys.
Returns:
A new trie where each key from ``keys`` has been set to the given
value.
"""
trie = cls()
for key in keys:
trie[key] = value
return trie
def _get_node(self, key, create=False):
"""Returns node for given key. Creates it if requested.
Args:
key: A key to look for.
create: Whether to create the node if it does not exist.
Returns:
``(node, trace)`` tuple where ``node`` is the node for given key and
``trace`` is a list specifying path to reach the node including all
the encountered nodes. Each element of trace is a ``(step, node)``
tuple where ``step`` is a step from parent node to given node and
``node`` is node on the path. The first element of the path is
always ``(None, self._root)``.
Raises:
KeyError: If there is no node for the key and ``create`` is
``False``.
"""
node = self._root
trace = [(None, node)]
for step in self.__path_from_key(key):
if create:
node = node.children.setdefault(step, _Node())
else:
node = node.children.get(step)
if not node:
raise KeyError(key)
trace.append((step, node))
return node, trace
def __iter__(self):
return self.iterkeys()
# pylint: disable=arguments-differ
def iteritems(self, prefix=_SENTINEL, shallow=False):
"""Yields all nodes with associated values with given prefix.
Only nodes with values are output. For example::
>>> import pygtrie
>>> t = pygtrie.StringTrie()
>>> t['foo'] = 'Foo'
>>> t['foo/bar/baz'] = 'Baz'
>>> t['qux'] = 'Qux'
>>> t.items()
[('qux', 'Qux'), ('foo', 'Foo'), ('foo/bar/baz', 'Baz')]
Items are generated in topological order but the order of siblings is
unspecified by default. In other words, in the above example, the
``('qux', 'Qux')`` pair might have been at the end of the list. At an
expense of efficiency, this can be changed via
:func:`Trie.enable_sorting`.
With ``prefix`` argument, only items with specified prefix are generated
(i.e. only given subtrie is traversed) as demonstrated by::
>>> t.items(prefix='foo/bar')
[('foo/bar/baz', 'Baz')]
With ``shallow`` argument, if a node has value associated with it, it's
children are not traversed even if they exist which can be seen in::
>>> t.items(shallow=True)
[('qux', 'Qux'), ('foo', 'Foo')]
Args:
prefix: Prefix to limit iteration to.
shallow: Perform a shallow traversal, i.e. do not yield items if
their prefix has been yielded.
Yields:
``(key, value)`` tuples.
Raises:
KeyError: If ``prefix`` does not match any node.
"""
node, _ = self._get_node(prefix)
for path, value in node.iterate(list(self.__path_from_key(prefix)),
shallow, self._iteritems):
yield (self._key_from_path(path), value)
def iterkeys(self, prefix=_SENTINEL, shallow=False):
"""Yields all keys having associated values with given prefix.
This is equivalent to taking first element of tuples generated by
:func:`Trie.iteritems` which see for more detailed documentation.
Args:
prefix: Prefix to limit iteration to.
shallow: Perform a shallow traversal, i.e. do not yield keys if
their prefix has been yielded.
Yields:
All the keys (with given prefix) with associated values in the trie.
Raises:
KeyError: If ``prefix`` does not match any node.
"""
for key, _ in self.iteritems(prefix=prefix, shallow=shallow):
yield key
def itervalues(self, prefix=_SENTINEL, shallow=False):
"""Yields all values associated with keys with given prefix.
This is equivalent to taking second element of tuples generated by
:func:`Trie.iteritems` which see for more detailed documentation.
Args:
prefix: Prefix to limit iteration to.
shallow: Perform a shallow traversal, i.e. do not yield values if
their prefix has been yielded.
Yields:
All the values associated with keys (with given prefix) in the trie.
Raises:
KeyError: If ``prefix`` does not match any node.
"""
node, _ = self._get_node(prefix)
for _, value in node.iterate(list(self.__path_from_key(prefix)),
shallow, self._iteritems):
yield value
def items(self, prefix=_SENTINEL, shallow=False):
"""Returns a list of ``(key, value)`` pairs in given subtrie.
This is equivalent to constructing a list from generator returned by
:func:`Trie.iteritems` which see for more detailed documentation.
"""
return list(self.iteritems(prefix=prefix, shallow=shallow))
def keys(self, prefix=_SENTINEL, shallow=False):
"""Returns a list of all the keys, with given prefix, in the trie.
This is equivalent to constructing a list from generator returned by
:func:`Trie.iterkeys` which see for more detailed documentation.
"""
return list(self.iterkeys(prefix=prefix, shallow=shallow))
def values(self, prefix=_SENTINEL, shallow=False):
"""Returns a list of values in given subtrie.
This is equivalent to constructing a list from generator returned by
:func:`Trie.iterivalues` which see for more detailed documentation.
"""
return list(self.itervalues(prefix=prefix, shallow=shallow))
# pylint: enable=arguments-differ
def __len__(self):
"""Returns number of values in a trie.
Note that this method is expensive as it iterates over the whole trie.
"""
return sum(1 for _ in self.itervalues())
def __nonzero__(self):
return bool(self._root)
HAS_VALUE = 1
HAS_SUBTRIE = 2
def has_node(self, key):
"""Returns whether given node is in the trie.
Return value is a bitwise or of ``HAS_VALUE`` and ``HAS_SUBTRIE``
constants indicating node has a value associated with it and that it is
a prefix of another existing key respectively. Both of those are
independent of each other and all of the four combinations are possible.
For example::
>>> import pygtrie
>>> t = pygtrie.StringTrie()
>>> t['foo/bar'] = 'Bar'
>>> t['foo/bar/baz'] = 'Baz'
>>> t.has_node('qux') == 0
True
>>> t.has_node('foo/bar/baz') == pygtrie.Trie.HAS_VALUE
True
>>> t.has_node('foo') == pygtrie.Trie.HAS_SUBTRIE
True
>>> t.has_node('foo/bar') == (pygtrie.Trie.HAS_VALUE |
... pygtrie.Trie.HAS_SUBTRIE)
True
There are two higher level methods built on top of this one which give
easier interface for the information. :func:`Trie.has_key` and returns
whether node has a value associated with it and :func:`Trie.has_subtrie`
checks whether node is a prefix. Continuing previous example::
>>> t.has_key('qux'), t.has_subtrie('qux')
False, False
>>> t.has_key('foo/bar/baz'), t.has_subtrie('foo/bar/baz')
True, False
>>> t.has_key('foo'), t.has_subtrie('foo')
False, True
>>> t.has_key('foo/bar'), t.has_subtrie('foo/bar')
True, True
Args:
key: A key to look for.
Returns:
Non-zero if node exists and if it does a bit-field denoting whether
it has a value associated with it and whether it has a subtrie.
"""
try:
node, _ = self._get_node(key)
except KeyError:
return 0
return ((self.HAS_VALUE * int(node.value is not _SENTINEL)) |
(self.HAS_SUBTRIE * int(bool(node.children))))
def has_key(self, key):
"""Indicates whether given key has value associated with it.
See :func:`Trie.has_node` for more detailed documentation.
"""
return bool(self.has_node(key) & self.HAS_VALUE)
def has_subtrie(self, key):
"""Returns whether given key is a prefix of another key in the trie.
See :func:`Trie.has_node` for more detailed documentation.
"""
return bool(self.has_node(key) & self.HAS_SUBTRIE)
@staticmethod
def _slice_maybe(key_or_slice):
"""Checks whether argument is a slice or a plain key.
Args:
key_or_slice: A key or a slice to test.
Returns:
``(key, is_slice)`` tuple. ``is_slice`` indicates whether
``key_or_slice`` is a slice and ``key`` is either ``key_or_slice``
itself (if it's not a slice) or slice's start position.
Raises:
TypeError: If ``key_or_slice`` is a slice whose stop or step are not
``None`` In other words, only ``[key:]`` slices are valid.
"""
if isinstance(key_or_slice, slice):
if key_or_slice.stop is not None or key_or_slice.step is not None:
raise TypeError(key_or_slice)
return key_or_slice.start, True
return key_or_slice, False
def __getitem__(self, key_or_slice):
"""Returns value associated with given key or raises KeyError.
When argument is a single key, value for that key is returned (or
:class:`KeyError` exception is thrown if the node does not exist or has
no value associated with it).
When argument is a slice, it must be one with only `start` set in which
case the access is identical to :func:`Trie.itervalues` invocation with
prefix argument.
Example:
>>> import pygtrie
>>> t = pygtrie.StringTrie()
>>> t['foo/bar'] = 'Bar'
>>> t['foo/baz'] = 'Baz'
>>> t['qux'] = 'Qux'
>>> t['foo/bar']
'Bar'
>>> list(t['foo':])
['Baz', 'Bar']
>>> t['foo']
Traceback (most recent call last):
...
pygtrie.ShortKeyError: 'foo'
Args:
key_or_slice: A key or a slice to look for.
Returns:
If a single key is passed, a value associated with given key. If
a slice is passed, a generator of values in specified subtrie.
Raises:
ShortKeyError: If the key has no value associated with it but is
a prefix of some key with a value. Note that
:class:`ShortKeyError` is subclass of :class:`KeyError`.
KeyError: If key has no value associated with it nor is a prefix of
an existing key.
TypeError: If ``key_or_slice`` is a slice but it's stop or step are
not ``None``.
"""
if self._slice_maybe(key_or_slice)[1]:
return self.itervalues(key_or_slice.start)
node, _ = self._get_node(key_or_slice)
if node.value is _SENTINEL:
raise ShortKeyError(key_or_slice)
return node.value
def _set(self, key, value, only_if_missing=False, clear_children=False):
"""Sets value for a given key.
Args:
key: Key to set value of.
value: Value to set to.
only_if_missing: If ``True``, value won't be changed if the key is
already associated with a value.
clear_children: If ``True``, all children of the node, if any, will
be removed.
Returns:
Value of the node.
"""
node, _ = self._get_node(key, create=True)
if not only_if_missing or node.value is _SENTINEL:
node.value = value
if clear_children:
node.children.clear()
return node.value
def __setitem__(self, key_or_slice, value):
"""Sets value associated with given key.
If `key_or_slice` is a key, simply associate it with given value. If it
is a slice (which must have `start` set only), it in addition clears any
subtrie that might have been attached to particular key. For example::
>>> import pygtrie
>>> t = pygtrie.StringTrie()
>>> t['foo/bar'] = 'Bar'
>>> t['foo/baz'] = 'Baz'
>>> t.keys()
['foo/baz', 'foo/bar']
>>> t['foo':] = 'Foo'
>>> t.keys()
['foo']
Args:
key_or_slice: A key to look for or a slice. If it is a slice, the
whole subtrie (if present) will be replaced by a single node
with given value set.
value: Value to set.
Raises:
TypeError: If key is a slice whose stop or step are not None.
"""
key, is_slice = self._slice_maybe(key_or_slice)
self._set(key, value, clear_children=is_slice)
def setdefault(self, key, value=None):
"""Sets value of a given node if not set already. Also returns it.
In contrast to :func:`Trie.__setitem__`, this method does not accept
slice as a key.
"""
return self._set(key, value, only_if_missing=True)
@staticmethod
def _cleanup_trace(trace):
"""Removes empty nodes present on specified trace.
Args:
trace: Trace to the node to cleanup as returned by
:func:`Trie._get_node`.
"""
i = len(trace) - 1 # len(path) >= 1 since root is always there
step, node = trace[i]
while i and not node:
i -= 1
parent_step, parent = trace[i]
del parent.children[step]
step, node = parent_step, parent
def _pop_from_node(self, node, trace, default=_SENTINEL):
"""Removes a value from given node.
Args:
node: Node to get value of.
trace: Trace to that node as returned by :func:`Trie._get_node`.
default: A default value to return if node has no value set.
Returns:
Value of the node or ``default``.
Raises:
ShortKeyError: If the node has no value associated with it and
``default`` has not been given.
"""
if node.value is not _SENTINEL:
value = node.value
node.value = _SENTINEL
self._cleanup_trace(trace)
return value
elif default is _SENTINEL:
raise ShortKeyError()
else:
return default
def pop(self, key, default=_SENTINEL):
"""Deletes value associated with given key and returns it.
Args:
key: A key to look for.
default: If specified, value that will be returned if given key has
no value associated with it. If not specified, method will
throw KeyError in such cases.
Returns:
Removed value, if key had value associated with it, or ``default``
(if given).
Raises:
ShortKeyError: If ``default`` has not been specified and the key has
no value associated with it but is a prefix of some key with
a value. Note that :class:`ShortKeyError` is subclass of
:class:`KeyError`.
KeyError: If default has not been specified and key has no value
associated with it nor is a prefix of an existing key.
"""
try:
return self._pop_from_node(*self._get_node(key))
except KeyError:
if default is not _SENTINEL:
return default
raise
def popitem(self):
"""Deletes an arbitrary value from the trie and returns it.
There is no guarantee as to which item is deleted and returned. Neither
in respect to its lexicographical nor topological order.
Returns:
``(key, value)`` tuple indicating deleted key.
Raises:
KeyError: If the trie is empty.
"""
if not self:
raise KeyError()
node = self._root
trace = [(None, node)]
while node.value is _SENTINEL:
step = next(_iterkeys(node.children))
node = node.children[step]
trace.append((step, node))
return (self._key_from_path((step for step, _ in trace[1:])),
self._pop_from_node(node, trace))
def __delitem__(self, key_or_slice):
"""Deletes value associated with given key or raises KeyError.
If argument is a key, value associated with it is deleted. If the key
is also a prefix, its descendents are not affected. On the other hand,
if the argument is a slice (in which case it must have only start set),
the whole subtrie is removed. For example::
>>> import pygtrie
>>> t = pygtrie.StringTrie()
>>> t['foo'] = 'Foo'
>>> t['foo/bar'] = 'Bar'
>>> t['foo/bar/baz'] = 'Baz'
>>> del t['foo/bar']
>>> t.keys()
['foo', 'foo/bar/baz']
>>> del t['foo':]
>>> t.keys()
[]
Args:
key_or_slice: A key to look for or a slice. If key is a slice, the
whole subtrie will be removed.
Raises:
ShortKeyError: If the key has no value associated with it but is
a prefix of some key with a value. This is not thrown is
key_or_slice is a slice -- in such cases, the whole subtrie is
removed. Note that :class:`ShortKeyError` is subclass of
:class:`KeyError`.
KeyError: If key has no value associated with it nor is a prefix of
an existing key.
TypeError: If key is a slice whose stop or step are not ``None``.
"""
key, is_slice = self._slice_maybe(key_or_slice)
node, trace = self._get_node(key)
if is_slice:
node.children.clear()
elif node.value is _SENTINEL:
raise ShortKeyError(key)
node.value = _SENTINEL
self._cleanup_trace(trace)
def prefixes(self, key):
"""Walks towards the node specified by key and yields all found items.
Example:
>>> import pygtrie
>>> t = pygtrie.StringTrie()
>>> t['foo'] = 'Foo'
>>> t['foo/bar/baz'] = 'Baz'
>>> list(t.prefixes('foo/bar/baz/qux'))
[('foo', 'Foo'), ('foo/bar/baz', 'Baz')]
>>> list(t.prefixes('does/not/exist'))
[]
Args:
key: Key to look for.
Yields:
``(k, value)`` pairs denoting keys with associated values
encountered on the way towards the specified key.
"""
node = self._root
path = self.__path_from_key(key)
pos = 0
while True:
if node.value is not _SENTINEL:
yield self._key_from_path(path[:pos]), node.value
if pos == len(path):
break
node = node.children.get(path[pos])
if not node:
break
pos += 1
def shortest_prefix(self, key):
"""Finds the shortest prefix of a key with a value.
This is equivalent to taking the first object yielded by
:func:`Trie.prefixes` with a default of `(None, None)` if said method
yields no items. As an added bonus, the pair in that case will be
a falsy value (as opposed to regular two-element tuple of ``None``
values).
Example:
>>> import pygtrie
>>> t = pygtrie.StringTrie()
>>> t['foo'] = 'Foo'
>>> t['foo/bar/baz'] = 'Baz'
>>> t.shortest_prefix('foo/bar/baz/qux')
('foo', 'Foo')
>>> t.shortest_prefix('does/not/exist')
(None, None)
>>> bool(t.shortest_prefix('does/not/exist'))
False
Args:
key: Key to look for.
Returns:
``(k, value)`` where ``k`` is the shortest prefix of ``key`` (it may
equal ``key``) and ``value`` is a value associated with that key.
If no node is found, ``(None, None)`` is returned.
"""
return next(self.prefixes(key), _NONE_PAIR)
def longest_prefix(self, key):
"""Finds the longest prefix of a key with a value.
This is equivalent to taking the last object yielded by
:func:`Trie.prefixes` with a default of `(None, None)` if said method
yields no items. As an added bonus, the pair in that case will be
a falsy value (as opposed to regular two-element tuple of ``None``
values).
Example:
>>> import pygtrie
>>> t = pygtrie.StringTrie()
>>> t['foo'] = 'Foo'
>>> t['foo/bar/baz'] = 'Baz'
>>> t.longest_prefix('foo/bar/baz/qux')
('foo/bar/baz', 'Baz')
>>> t.longest_prefix('does/not/exist')
(None, None)
>>> bool(t.longest_prefix('does/not/exist'))
False
Args:
key: Key to look for.
Returns:
``(k, value)`` where ``k`` is the longest prefix of ``key`` (it may
equal ``key``) and ``value`` is a value associated with that key.
If no node is found, ``(None, None)`` is returned.
"""
ret = _NONE_PAIR
for ret in self.prefixes(key):
pass
return ret
def __eq__(self, other):
return self._root == other._root # pylint: disable=protected-access
def __ne__(self, other):
return self._root != other._root # pylint: disable=protected-access
def __str__(self):
return 'Trie(%s)' % (
', '.join('%s: %s' % item for item in self.iteritems()))
def __repr__(self):
if self:
return 'Trie((%s,))' % (
', '.join('(%r, %r)' % item for item in self.iteritems()))
else:
return 'Trie()'
def __path_from_key(self, key):
"""Converts a user visible key object to internal path representation.
Args:
key: User supplied key or ``_SENTINEL``.
Returns:
An empty tuple if ``key`` was ``_SENTINEL``, otherwise whatever
:func:`Trie._path_from_key` returns.
Raises:
TypeError: If ``key`` is of invalid type.
"""
return () if key is _SENTINEL else self._path_from_key(key)
def _path_from_key(self, key): # pylint: disable=no-self-use
"""Converts a user visible key object to internal path representation.
The default implementation simply returns key.
Args:
key: User supplied key.
Returns:
A path, which is an iterable of steps. Each step must be hashable.
Raises:
TypeError: If key is of invalid type.
"""
return key
def _key_from_path(self, path): # pylint: disable=no-self-use
"""Converts an internal path into a user visible key object.
The default implementation creates a tuple from the path.
Args:
path: Internal path representation.
Returns:
A user visible key object.
"""
return tuple(path)
def traverse(self, node_factory, prefix=_SENTINEL):
"""Traverses the tree using node_factory object.
node_factory is a callable function which accepts (path_conv, path,
children, value=...) arguments, where path_conv is a lambda converting
path representation to key, path is the path to this node, children is
an iterable of children nodes constructed by node_factory, optional
value is the value associated with the path.
node_factory's children argument is a generator which has a few
consequences:
* To traverse into node's children, the generator must be iterated over.
This can by accomplished by a simple "children = list(children)"
statement.
* Ignoring the argument allows node_factory to stop the traversal from
going into the children of the node. In other words, whole subtrie
can be removed from traversal if node_factory chooses so.
* If children is stored as is (i.e. as a generator) when it is iterated
over later on it will see state of the trie as it is during the
iteration and not when traverse method was called.
:func:`Trie.traverse` has two advantages over :func:`Trie.iteritems` and
similar methods:
1. it allows subtries to be skipped completely when going through the
list of nodes based on the property of the parent node; and
2. it represents structure of the trie directly making it easy to
convert structure into a different representation.
For example, the below snippet prints all files in current directory
counting how many HTML files were found but ignores hidden files and
directories (i.e. those whose names start with a dot)::
import os
import pygtrie
t = pygtrie.StringTrie(separator=os.sep)
# Construct a trie with all files in current directory and all
# of its sub-directories. Files get set a True value.
# Directories are represented implicitly by being prefixes of
# files.
for root, _, files in os.walk('.'):
for name in files: t[os.path.join(root, name)] = True
def traverse_callback(path_conv, path, children, is_file=False):
if path and path[-1] != '.' and path[-1][0] == '.':
# Ignore hidden directory (but accept root node and '.')
return 0
elif is_file:
print path_conv(path)
return int(path[-1].endswith('.html'))
else:
# Otherwise, it's a directory. Traverse into children.
return sum(int(is_html) for is_html in children)
print t.traverse(traverse_callback)
As documented, ignoring the children argument causes subtrie to be
omitted and not walked into.
In the next example, the trie is converted to a tree representation
where child nodes include a pointer to their parent. As before, hidden
files and directories are ignored::
import os
import pygtrie
t = pygtrie.StringTrie(separator=os.sep)
for root, _, files in os.walk('.'):
for name in files: t[os.path.join(root, name)] = True
class File(object):
def __init__(self, name):
self.name = name
self.parent = None
class Directory(File):
def __init__(self, name, children):
super(Directory, self).__init__(name)
self._children = children
for child in children:
child.parent = self
def traverse_callback(path_conv, path, children, is_file=False):
if not path or path[-1] == '.' or path[-1][0] != '.':
if is_file:
return File(path[-1])
children = filter(None, children)
return Directory(path[-1] if path else '', children)
root = t.traverse(traverse_callback)
Note: Unlike iterators, traverse method uses stack recursion which means
that using it on deep tries may lead to a RuntimeError exception thrown
once Python's maximum recursion depth is reached.
Args:
node_factory: Makes opaque objects from the keys and values of the
trie.
prefix: Prefix for node to start traversal, by default starts at
root.
Returns:
Node object constructed by node_factory corresponding to the root
node.
"""
node, _ = self._get_node(prefix)
return node.traverse(node_factory, self._key_from_path,
list(self.__path_from_key(prefix)),
self._iteritems)
class CharTrie(Trie):
"""A variant of a :class:`pygtrie.Trie` which accepts strings as keys.
The only difference between :class:`pygtrie.CharTrie` and
:class:`pygtrie.Trie` is that when :class:`pygtrie.CharTrie` returns keys
back to the client (for instance in keys() method is called), those keys are
returned as strings.
Canonical example where this class can be used is a dictionary of words in
a natural language. For example::
>>> import pygtrie
>>> t = pygtrie.CharTrie()
>>> t['wombat'] = True
>>> t['woman'] = True
>>> t['man'] = True
>>> t['manhole'] = True
>>> t.has_subtrie('wo')
True
>>> t.has_key('man')
True
>>> t.has_subtrie('man')
True
>>> t.has_subtrie('manhole')
False
"""
def _key_from_path(self, path):
return ''.join(path)
class StringTrie(Trie):
""":class:`pygtrie.Trie` variant accepting strings with a separator as keys.
The trie accepts strings as keys which are split into components using
a separator specified during initialisation ("/" by default).
Canonical example where this class can be used is when keys are paths. For
example, it could map from a path to a request handler::
import pygtrie
def handle_root(): pass
def handle_admin(): pass
def handle_admin_images(): pass
handlers = pygtrie.StringTrie()
handlers[''] = handle_root
handlers['/admin'] = handle_admin
handlers['/admin/images'] = handle_admin_images
request_path = '/admin/images/foo'
handler = handlers.longest_prefix(request_path)
"""
def __init__(self, *args, **kwargs):
"""Initialises the trie.
Except for a ``separator`` named argument, all other arguments are
interpreted the same way :func:`Trie.update` interprets them.
Args:
*args: Passed to super class initialiser.
**kwargs: Passed to super class initialiser.
separator: A separator to use when splitting keys into paths used by
the trie. "/" is used if this argument is not specified. This
named argument is not specified on the function's prototype
because of Python's limitations.
"""
separator = kwargs.pop('separator', '/')
if not isinstance(separator, _basestring):
raise TypeError('separator must be a string')
if not separator:
raise ValueError('separator can not be empty')
self._separator = separator
super(StringTrie, self).__init__(*args, **kwargs)
@classmethod
def fromkeys(cls, keys, value=None, separator='/'): # pylint: disable=arguments-differ
trie = cls(separator=separator)
for key in keys:
trie[key] = value
return trie
def _path_from_key(self, key):
return key.split(self._separator)
def _key_from_path(self, path):
return self._separator.join(path)
class PrefixSet(_collections.MutableSet): # pylint: disable=abstract-class-not-used
"""A set of prefixes.
:class:`pygtrie.PrefixSet` works similar to a normal set except it is said
to contain a key if the key or it's prefix is stored in the set. For
instance, if "foo" is added to the set, the set contains "foo" as well as
"foobar".
The set supports addition of elements but does *not* support removal of
elements. This is because there's no obvious consistent and intuitive
behaviour for element deletion.
"""
def __init__(self, iterable=None, factory=Trie, **kwargs):
"""Initialises the prefix set.
Args:
iterable: A sequence of keys to add to the set.
factory: A function used to create a trie used by the
:class:`pygtrie.PrefixSet`.
kwargs: Additional keyword arguments passed to the factory function.
"""
super(PrefixSet, self).__init__()
trie = factory(**kwargs)
if iterable:
trie.update((key, True) for key in iterable)
self._trie = trie
def copy(self):
"""Returns a copy of the prefix set."""
return self.__class__(self._trie)
def clear(self):
"""Removes all keys from the set."""
self._trie.clear()
def __contains__(self, key):
"""Checks whether set contains key or its prefix."""
return bool(self._trie.shortest_prefix(key)[1])
def __iter__(self):
"""Return iterator over all prefixes in the set.
See :func:`PrefixSet.iter` method for more info.
"""
return self._trie.iterkeys()
def iter(self, prefix=_SENTINEL):
"""Iterates over all keys in the set optionally starting with a prefix.
Since a key does not have to be explicitly added to the set to be an
element of the set, this method does not iterate over all possible keys
that the set contains, but only over the shortest set of prefixes of all
the keys the set contains.
For example, if "foo" has been added to the set, the set contains also
"foobar", but this method will *not* iterate over "foobar".
If ``prefix`` argument is given, method will iterate over keys with
given prefix only. The keys yielded from the function if prefix is
given does not have to be a subset (in mathematical sense) of the keys
yielded when there is not prefix. This happens, if the set contains
a prefix of the given prefix.
For example, if only "foo" has been added to the set, iter method called
with no arguments will yield "foo" only. However, when called with
"foobar" argument, it will yield "foobar" only.
"""
if prefix is _SENTINEL:
return iter(self)
elif self._trie.has_node(prefix):
return self._trie.iterkeys(prefix=prefix)
elif prefix in self:
# Make sure the type of returned keys is consistent.
# pylint: disable=protected-access
return self._trie._key_from_path(self._trie._path_from_key(prefix)),
else:
return ()
def __len__(self):
"""Returns number of keys stored in the set.
Since a key does not have to be explicitly added to the set to be an
element of the set, this method does not count over all possible keys
that the set contains (since that would be infinity), but only over the
shortest set of prefixes of all the keys the set contains.
For example, if "foo" has been added to the set, the set contains also
"foobar", but this method will *not* count "foobar".
"""
return len(self._trie)
def add(self, key):
"""Adds given key to the set.
If the set already contains prefix of the key being added, this
operation has no effect. If the key being added is a prefix of some
existing keys in the set, those keys are deleted and replaced by
a single entry for the key being added.
For example, if the set contains key "foo" adding a key "foobar" does
not change anything. On the other hand, if the set contains keys
"foobar" and "foobaz", adding a key "foo" will replace those two keys
with a single key "foo".
This makes a difference when iterating over the keys or counting number
of keys. Counter intuitively, adding of a key can *decrease* size of
the set.
Args:
key: Key to add.
"""
if key not in self:
self._trie[key:] = True
def discard(self, key):
raise NotImplementedError(
'Removing keys from PrefixSet is not implemented.')
def remove(self, key):
raise NotImplementedError(
'Removing keys from PrefixSet is not implemented.')
def pop(self):
raise NotImplementedError(
'Removing keys from PrefixSet is not implemented.')
|
examples/basic.py
|
SamiAlsubhi/fastapi-jwt-auth
| 357 |
146030
|
from fastapi import FastAPI, HTTPException, Depends, Request
from fastapi.responses import JSONResponse
from fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.exceptions import AuthJWTException
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
password: str
# in production you can use Settings management
# from pydantic to get secret key from .env
class Settings(BaseModel):
authjwt_secret_key: str = "secret"
# callback to get your configuration
@AuthJWT.load_config
def get_config():
return Settings()
# exception handler for authjwt
# in production, you can tweak performance using orjson response
@app.exception_handler(AuthJWTException)
def authjwt_exception_handler(request: Request, exc: AuthJWTException):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.message}
)
# provide a method to create access tokens. The create_access_token()
# function is used to actually generate the token to use authorization
# later in endpoint protected
@app.post('/login')
def login(user: User, Authorize: AuthJWT = Depends()):
if user.username != "test" or user.password != "<PASSWORD>":
raise HTTPException(status_code=401,detail="Bad username or password")
# subject identifier for who this token is for example id or username from database
access_token = Authorize.create_access_token(subject=user.username)
return {"access_token": access_token}
# protect endpoint with function jwt_required(), which requires
# a valid access token in the request headers to access.
@app.get('/user')
def user(Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
current_user = Authorize.get_jwt_subject()
return {"user": current_user}
|
PyInstaller/building/splash.py
|
hawkhai/pyinstaller
| 9,267 |
146049
|
<filename>PyInstaller/building/splash.py
# -----------------------------------------------------------------------------
# Copyright (c) 2005-2021, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#
# SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
# -----------------------------------------------------------------------------
import io
import os
import re
import struct
from PyInstaller import log as logging
from PyInstaller.archive.writers import SplashWriter
from PyInstaller.building import splash_templates
from PyInstaller.building.datastruct import TOC, Target
from PyInstaller.building.utils import _check_guts_eq, _check_guts_toc, misc
from PyInstaller.compat import is_darwin
from PyInstaller.utils.hooks import exec_statement
from PyInstaller.utils.hooks.tcl_tk import (TK_ROOTNAME, collect_tcl_tk_files, find_tcl_tk_shared_libs)
try:
from PIL import Image as PILImage
except ImportError:
PILImage = None
logger = logging.getLogger(__name__)
# These requirement files are checked against the current splash screen script. If you wish to modify the splash screen
# and run into tcl errors/bad behavior, this is a good place to start and add components your implementation of the
# splash screen might use.
splash_requirements = [
# prepended tcl/tk binaries
os.path.join(TK_ROOTNAME, "license.terms"),
os.path.join(TK_ROOTNAME, "text.tcl"),
os.path.join(TK_ROOTNAME, "tk.tcl"),
# Used for customizable font
os.path.join(TK_ROOTNAME, "ttk", "ttk.tcl"),
os.path.join(TK_ROOTNAME, "ttk", "fonts.tcl"),
os.path.join(TK_ROOTNAME, "ttk", "cursors.tcl"),
os.path.join(TK_ROOTNAME, "ttk", "utils.tcl"),
]
class Splash(Target):
"""
Bundles the required resources for the splash screen into a file, which will be included in the CArchive.
A Splash has two outputs, one is itself and one is sored in splash.binaries. Both need to be passed to other
build targets in order to enable the splash screen.
"""
typ = 'SPLASH'
def __init__(self, image_file, binaries, datas, **kwargs):
"""
:param str image_file:
A path-like object to the image to be used. Only the PNG file format is supported.
.. note:: If a different file format is supplied and PIL (Pillow) is installed, the file will be converted
automatically.
.. note:: *Windows*: Due to the implementation, the color Magenta/ RGB(255, 0, 255) must not be used in the
image or text.
.. note:: If PIL (Pillow) is installed and the image is bigger than max_img_size, the image will be resized
to fit into the specified area.
:param TOC binaries:
The TOC of binaries the Analysis build target found. This TOC includes all extensionmodules and their
dependencies. This is required to figure out, if the users program uses tkinter.
:param TOC datas:
The TOC of data the Analysis build target found. This TOC includes all data-file dependencies of the
modules. This is required to check if all splash screen requirements can be bundled.
:keyword text_pos:
An optional 2x integer tuple that represents the origin of the text on the splash screen image. The
origin of the text is its lower left corner. A unit in the respective coordinate system is a pixel of the
image, its origin lies in the top left corner of the image. This parameter also acts like a switch for
the text feature. If omitted, no text will be displayed on the splash screen. This text will be used to
show textual progress in onefile mode.
:type text_pos: Tuple[int, int]
:keyword text_size:
The desired size of the font. If the size argument is a positive number, it is interpreted as a size in
points. If size is a negative number, its absolute value is interpreted as a size in pixels. Default: ``12``
:type text_size: int
:keyword text_font:
An optional name of a font for the text. This font must be installed on the user system, otherwise the
system default font is used. If this parameter is omitted, the default font is also used.
:keyword text_color:
An optional color for the text. Either RGB HTML notation or color names are supported. Default: black
(Windows: Due to a implementation issue the color magenta/ rgb(255, 0, 255) is forbidden)
:type text_color: str
:keyword text_default:
The default text which will be displayed before the extraction starts. Default: "Initializing"
:type text_default: str
:keyword full_tk:
By default Splash bundles only the necessary files for the splash screen (some tk components). This
options enables adding full tk and making it a requirement, meaning all tk files will be unpacked before
the splash screen can be started. This is useful during development of the splash screen script.
Default: ``False``
:type full_tk: bool
:keyword minify_script:
The splash screen is created by executing an Tcl/Tk script. This option enables minimizing the script,
meaning removing all non essential parts from the script. Default: True
:keyword rundir:
The folder name in which tcl/tk will be extracted at runtime. There should be no matching folder in your
application to avoid conflicts. Default: ``__splash``
:type rundir: str
:keyword name:
An optional alternative filename for the .res file. If not specified, a name is generated.
:type name: str
:keyword script_name:
An optional alternative filename for the Tcl script, that will be generated. If not specified, a name is
generated.
:type script_name: str
:keyword max_img_size:
Maximum size of the splash screen image as a tuple. If the supplied image exceeds this limit, it will be
resized to fit the maximum width (to keep the original aspect ratio). This option can be disabled by
setting it to None. Default: (760, 480)
:type max_img_size: Tuple[int, int]
"""
from ..config import CONF
Target.__init__(self)
# Splash screen is not supported on macOS. It operates in a secondary thread and macOS disallows UI operations
# in any thread other than main.
if is_darwin:
raise SystemExit("Splash screen is not supported on macOS.")
# Make image path relative to .spec file
if not os.path.isabs(image_file):
image_file = os.path.join(CONF['specpath'], image_file)
image_file = os.path.normpath(image_file)
if not os.path.exists(image_file):
raise ValueError("Image file '%s' not found" % image_file)
# Copy all arguments
self.image_file = image_file
self.full_tk = kwargs.get("full_tk", False)
self.name = kwargs.get("name", None)
self.script_name = kwargs.get("script_name", None)
self.minify_script = kwargs.get("minify_script", True)
self.rundir = kwargs.get("rundir", None)
self.max_img_size = kwargs.get("max_img_size", (760, 480))
# text options
self.text_pos = kwargs.get("text_pos", None)
self.text_size = kwargs.get("text_size", 12)
self.text_font = kwargs.get("text_font", "TkDefaultFont")
self.text_color = kwargs.get("text_color", "black")
self.text_default = kwargs.get("text_default", "Initializing")
# Save the generated file separately so that it is not necessary to generate the data again and again
root = os.path.splitext(self.tocfilename)[0]
if self.name is None:
self.name = root + '.res'
if self.script_name is None:
self.script_name = root + '_script.tcl'
if self.rundir is None:
self.rundir = self._find_rundir(binaries + datas)
# Internal variables
try:
# Do not import _tkinter at the toplevel, because on some systems _tkinter will fail to load, since it is
# not installed. This would cause a runtime error in PyInstaller, since this module is imported from
# build_main.py, instead we just want to inform the user that the splash screen feature is not supported on
# his platform
import _tkinter
self._tkinter_module = _tkinter
self._tkinter_file = self._tkinter_module.__file__
except ModuleNotFoundError:
raise SystemExit(
"You platform does not support the splash screen feature, since tkinter is not installed. Please "
"install tkinter and try again."
)
# Calculated / analysed values
self.uses_tkinter = self._uses_tkinter(binaries)
self.script = self.generate_script()
self.tcl_lib, self.tk_lib = find_tcl_tk_shared_libs(self._tkinter_file)
if is_darwin:
# Outdated Tcl/Tk 8.5 system framework is not supported. Depending on macOS version, the library path will
# come up empty (hidden system libraries on Big Sur), or will be
# [/System]/Library/Frameworks/Tcl.framework/Tcl
if self.tcl_lib[1] is None or 'Library/Frameworks/Tcl.framework' in self.tcl_lib[1]:
raise SystemExit("The splash screen feature does not support macOS system framework version of Tcl/Tk.")
# Check if tcl/tk was found
assert all(self.tcl_lib)
assert all(self.tk_lib)
logger.debug("Use Tcl Library from %s and Tk From %s" % (self.tcl_lib, self.tk_lib))
self.splash_requirements = set([self.tcl_lib[0], self.tk_lib[0]] + splash_requirements)
logger.info("Collect tcl/tk binaries for the splash screen")
tcltk_tree = collect_tcl_tk_files(self._tkinter_file)
if self.full_tk:
# The user wants a full copy of tk, so make all tk files a requirement.
self.splash_requirements.update(toc[0] for toc in tcltk_tree)
self.binaries = TOC()
if not self.uses_tkinter:
# The user's script does not use tkinter, so we need to provide a TOC of all necessary files add the shared
# libraries to the binaries.
self.binaries.append((self.tcl_lib[0], self.tcl_lib[1], 'BINARY'))
self.binaries.append((self.tk_lib[0], self.tk_lib[1], 'BINARY'))
# Only add the intersection of the required and the collected resources, or add all entries if full_tk is
# true.
self.binaries.extend(toc for toc in tcltk_tree if toc[0] in self.splash_requirements)
# Check if all requirements were found.
fnames = [toc[0] for toc in (binaries + datas + self.binaries)]
def _filter(_item):
if _item not in fnames:
# Item is not bundled, so warn the user about it. This actually may happen on some tkinter installations
# that are missing the license.terms file.
logger.warning(
"The local Tcl/Tk installation is missing the file %s. The behavior of the splash screen is "
"therefore undefined and may be unsupported." % _item
)
return False
return True
# Remove all files which were not found.
self.splash_requirements = set(filter(_filter, self.splash_requirements))
# Test if the tcl/tk version is supported by the bootloader.
self.test_tk_version()
logger.debug("Splash Requirements: %s" % self.splash_requirements)
self.__postinit__()
_GUTS = (
# input parameters
('image_file', _check_guts_eq),
('name', _check_guts_eq),
('script_name', _check_guts_eq),
('text_pos', _check_guts_eq),
('text_size', _check_guts_eq),
('text_font', _check_guts_eq),
('text_color', _check_guts_eq),
('text_default', _check_guts_eq),
('full_tk', _check_guts_eq),
('minify_script', _check_guts_eq),
('rundir', _check_guts_eq),
('max_img_size', _check_guts_eq),
# calculated/analysed values
('uses_tkinter', _check_guts_eq),
('script', _check_guts_eq),
('tcl_lib', _check_guts_eq),
('tk_lib', _check_guts_eq),
('splash_requirements', _check_guts_eq),
('binaries', _check_guts_toc),
# internal value
# Check if the tkinter installation changed. This is theoretically possible if someone uses two different python
# installations of the same version.
('_tkinter_file', _check_guts_eq),
)
def _check_guts(self, data, last_build):
if Target._check_guts(self, data, last_build):
return True
# Check if the image has been modified.
if misc.mtime(self.image_file) > last_build:
logger.info("Building %s because file %s changed", self.tocbasename, self.image_file)
return True
return False
def assemble(self):
logger.info("Building Splash %s" % self.name)
# Function to resize a given image to fit into the area defined by max_img_size.
def _resize_image(_image, _orig_size):
if PILImage:
_w, _h = _orig_size
_ratio_w = self.max_img_size[0] / _w
if _ratio_w < 1:
# Image width exceeds limit
_h = int(_h * _ratio_w)
_w = self.max_img_size[0]
_ratio_h = self.max_img_size[1] / _h
if _ratio_h < 1:
# Image height exceeds limit
_w = int(_w * _ratio_h)
_h = self.max_img_size[1]
# If a file is given it will be open
if isinstance(_image, PILImage.Image):
_img = _image
else:
_img = PILImage.open(_image)
_img_resized = _img.resize((_w, _h))
# Save image into a stream
_image_stream = io.BytesIO()
_img_resized.save(_image_stream, format='PNG')
_img.close()
_img_resized.close()
_image_data = _image_stream.getvalue()
logger.info(
"Resized image %s from dimensions %s to (%d, %d)" % (self.image_file, str(_orig_size), _w, _h)
)
return _image_data
else:
raise ValueError(
"The splash image dimensions (w: %d, h: %d) exceed max_img_size (w: %d, h:%d), but the image "
"cannot be resized due to missing PIL.Image! Either install the Pillow package, adjust the "
"max_img_size, or use an image of compatible dimensions." %
(_orig_size[0], _orig_size[1], self.max_img_size[0], self.max_img_size[1])
)
# Open image file
image_file = open(self.image_file, 'rb')
# Check header of the file to identify it
if image_file.read(8) == b'\x89PNG\r\n\x1a\n':
# self.image_file is a PNG file
image_file.seek(16)
img_size = (struct.unpack("!I", image_file.read(4))[0], struct.unpack("!I", image_file.read(4))[0])
if img_size > self.max_img_size:
# The image exceeds the maximum image size, so resize it
image = _resize_image(self.image_file, img_size)
else:
image = os.path.abspath(self.image_file)
elif PILImage:
# Pillow is installed, meaning the image can be converted automatically
img = PILImage.open(self.image_file, mode='r')
if img.size > self.max_img_size:
image = _resize_image(img, img.size)
else:
image_data = io.BytesIO()
img.save(image_data, format='PNG')
img.close()
image = image_data.getvalue()
logger.info("Converted image %s to PNG format" % self.image_file)
else:
raise ValueError(
"The image %s needs to be converted to a PNG file, but PIL.Image is not available! Either install the "
"Pillow package, or use a PNG image for you splash screen." % self.image_file
)
image_file.close()
SplashWriter(
self.name,
self.splash_requirements,
self.tcl_lib[0], # tcl86t.dll
self.tk_lib[0], # tk86t.dll
TK_ROOTNAME,
self.rundir,
image,
self.script
)
def test_tk_version(self):
tcl_version = float(self._tkinter_module.TCL_VERSION)
tk_version = float(self._tkinter_module.TK_VERSION)
# Test if tcl/tk version is supported
if tcl_version < 8.6 or tk_version < 8.6:
logger.warning(
"The installed Tcl/Tk (%s/%s) version might not work with the splash screen feature of the bootloader. "
"The bootloader is tested against Tcl/Tk 8.6" %
(self._tkinter_module.TCL_VERSION, self._tkinter_module.TK_VERSION)
)
# This should be impossible, since tcl/tk is released together with the same version number, but just in case
if tcl_version != tk_version:
logger.warning(
"The installed version of Tcl (%s) and Tk (%s) do not match. PyInstaller is tested against matching "
"versions" % (self._tkinter_module.TCL_VERSION, self._tkinter_module.TK_VERSION)
)
# Test if tcl is threaded.
# If the variable tcl_platform(threaded) exist, the tcl interpreter was compiled with thread support.
threaded = bool(exec_statement(
"""
from tkinter import Tcl, TclError
try:
print(Tcl().getvar('tcl_platform(threaded)'))
except TclError:
pass
"""
)) # yapf: disable
if not threaded:
# This is a feature breaking problem, so exit.
raise SystemExit(
"The installed tcl version is not threaded. PyInstaller only supports the splash screen "
"using threaded tcl."
)
def generate_script(self):
"""
Generate the script for the splash screen.
If minify_script is True, all unnecessary parts will be removed.
"""
d = {}
if self.text_pos is not None:
logger.debug("Add text support to splash screen")
d.update({
'pad_x': self.text_pos[0],
'pad_y': self.text_pos[1],
'color': self.text_color,
'font': self.text_font,
'font_size': self.text_size,
'default_text': self.text_default,
})
script = splash_templates.build_script(text_options=d)
if self.minify_script:
# Remove any documentation, empty lines and unnecessary spaces
script = '\n'.join(
line for line in map(lambda l: l.strip(), script.splitlines())
if not line.startswith('#') # documentation
and line # empty lines
)
# Remove unnecessary spaces
script = re.sub(' +', ' ', script)
# Write script to disk, so that it is transparent to the user what script is executed.
with open(self.script_name, "w") as script_file:
script_file.write(script)
return script
@staticmethod
def _uses_tkinter(binaries):
# Test for _tkinter instead of tkinter, because a user might use a different wrapping library for tk.
return '_tkinter' in binaries.filenames
@staticmethod
def _find_rundir(structure):
# First try a name the user could understand, if one would find the directory.
rundir = '__splash%s'
candidate = rundir % ""
counter = 0
# Run this loop as long as a folder exist named like rundir. In most cases __splash will be sufficient and this
# loop wont enter.
while any(e[0].startswith(candidate + os.sep) for e in structure):
# just append to rundir a counter
candidate = rundir % str(counter)
counter += 1
# The SPLASH_DATA_HEADER structure limits the name to be 16 bytes at maximum. So if we exceed the limit
# raise an error. This will never happen, since there are 10^8 different possibilities, but just in case.
assert len(candidate) <= 16
return candidate
|
service_catalog/models/tower_server.py
|
Sispheor/squest
| 112 |
146070
|
<gh_stars>100-1000
from django.db import models
from towerlib import Tower
class TowerServer(models.Model):
name = models.CharField(max_length=100)
host = models.CharField(max_length=200, unique=True)
token = models.CharField(max_length=200)
secure = models.BooleanField(default=True)
ssl_verify = models.BooleanField(default=False)
def __str__(self):
return f"{self.name} ({self.host})"
def sync(self, job_template_id=None):
"""
Sync all job templates
:return:
"""
from .job_templates import JobTemplate as JobTemplateLocal
tower = self.get_tower_instance()
if job_template_id is None:
id_in_tower = []
for job_template_from_tower in tower.job_templates:
id_in_tower.append(job_template_from_tower.id)
self._update_job_template_from_tower(job_template_from_tower)
JobTemplateLocal.objects.filter(tower_server=self).exclude(tower_id__in=id_in_tower).delete()
else:
job_template = JobTemplateLocal.objects.get(id=job_template_id)
self._update_job_template_from_tower(tower.get_job_template_by_id(job_template.tower_id))
def get_tower_instance(self):
return Tower(self.host, None, None, secure=self.secure, ssl_verify=self.ssl_verify, token=self.token)
def _update_job_template_from_tower(self, job_template_from_tower):
from .job_templates import JobTemplate as JobTemplateLocal
job_template, _ = JobTemplateLocal.objects.get_or_create(tower_id=job_template_from_tower.id,
tower_server=self,
defaults={'name': job_template_from_tower.name})
# update data
job_template.name = job_template_from_tower.name
job_template.tower_job_template_data = job_template_from_tower._data
job_template.survey = job_template_from_tower.survey_spec
job_template.is_compliant = job_template.check_is_compliant()
job_template.save()
# update all operation that uses this template
from service_catalog.models import Operation
Operation.update_survey_after_job_template_update(job_template)
|
contrib/opencensus-ext-azure/examples/metrics/simple.py
|
Flared/opencensus-python
| 650 |
146082
|
# Copyright 2019, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
from opencensus.ext.azure import metrics_exporter
from opencensus.stats import aggregation as aggregation_module
from opencensus.stats import measure as measure_module
from opencensus.stats import stats as stats_module
from opencensus.stats import view as view_module
from opencensus.tags import tag_map as tag_map_module
stats = stats_module.stats
view_manager = stats.view_manager
stats_recorder = stats.stats_recorder
CARROTS_MEASURE = measure_module.MeasureInt("carrots",
"number of carrots",
"carrots")
CARROTS_VIEW = view_module.View("carrots_view",
"number of carrots",
[],
CARROTS_MEASURE,
aggregation_module.CountAggregation())
def main():
# Enable metrics
# Set the interval in seconds in which you want to send metrics
# TODO: you need to specify the instrumentation key in a connection string
# and place it in the APPLICATIONINSIGHTS_CONNECTION_STRING
# environment variable.
exporter = metrics_exporter.new_metrics_exporter()
view_manager.register_exporter(exporter)
view_manager.register_view(CARROTS_VIEW)
mmap = stats_recorder.new_measurement_map()
tmap = tag_map_module.TagMap()
mmap.measure_int_put(CARROTS_MEASURE, 1000)
mmap.record(tmap)
time.sleep(60)
print("Done recording metrics")
if __name__ == "__main__":
main()
|
gtfspy/import_loaders/route_loader.py
|
Leo-Ryu/gtfspy
| 118 |
146087
|
from gtfspy.import_loaders.table_loader import TableLoader, decode_six
class RouteLoader(TableLoader):
fname = 'routes.txt'
table = 'routes'
tabledef = '(route_I INTEGER PRIMARY KEY, ' \
'route_id TEXT UNIQUE NOT NULL, ' \
'agency_I INT, ' \
'name TEXT, ' \
'long_name TEXT, ' \
'desc TEXT, ' \
'type INT, ' \
'url TEXT, ' \
'color TEXT, ' \
'text_color TEXT' \
')'
extra_keys = ['agency_I', ]
extra_values = ['(SELECT agency_I FROM agencies WHERE agency_id=:_agency_id )',
]
# route_id,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url
# 1001,HSL,1,Kauppatori - Kapyla,0,http://aikataulut.hsl.fi/linjat/fi/h1_1a.html
def gen_rows(self, readers, prefixes):
from gtfspy import extended_route_types
for reader, prefix in zip(readers, prefixes):
for row in reader:
#print (row)
yield dict(
route_id = prefix + decode_six(row['route_id']),
_agency_id = prefix + decode_six(row['agency_id']) if 'agency_id' in row else None,
name = decode_six(row['route_short_name']),
long_name = decode_six(row['route_long_name']),
desc = decode_six(row['route_desc']) if 'route_desc' in row else None,
type = extended_route_types.ROUTE_TYPE_CONVERSION[int(row['route_type'])],
url = decode_six(row['route_url']) if 'route_url' in row else None,
color = decode_six(row['route_color']) if 'route_color' in row else None,
text_color = decode_six(row['route_text_color']) if 'route_text_color' in row else None,
)
@classmethod
def index(cls, cur):
# cur.execute('CREATE INDEX IF NOT EXISTS idx_rid ON route (route_id)')
cur.execute('CREATE INDEX IF NOT EXISTS idx_route_name ON routes (name)')
|
cyclegan/data/celeba_faceswap/paste_faces.py
|
dingyanna/DepthNets
| 114 |
146092
|
<filename>cyclegan/data/celeba_faceswap/paste_faces.py
from skimage.io import imread, imsave
import numpy as np
import glob
import os
import sys
dest_folder = "extracted_images_pasted"
if not os.path.exists(dest_folder):
os.makedirs(dest_folder)
for filename in glob.glob("extracted_images/*.png"):
print("Processing: %s" % filename)
src_file = os.path.basename(filename).split("_")[0] + "_crop.png"
tgt_file = os.path.basename(filename).split("_")[1].replace(".png","_crop.png")
#print(src_file, tgt_file)
src_img = imread(os.path.join("images", src_file))
tgt_img = imread(os.path.join("images", tgt_file))
normed_img = imread(filename)[:,:,0:3]
final_img = np.copy(tgt_img)
for i in range(final_img.shape[0]):
for j in range(final_img.shape[1]):
if normed_img[i,j].tolist() != [0,0,0]:
final_img[i,j] = normed_img[i,j]
imsave(arr=final_img,
fname="%s/%s" % (dest_folder, os.path.basename(filename)))
|
pythran/tests/test_math.py
|
davidbrochart/pythran
| 1,647 |
146117
|
from pythran.tests import TestEnv
@TestEnv.module
class TestMath(TestEnv):
def test_cos_(self):
self.run_test("def cos_(a):\n from math import cos\n return cos(a)", 1, cos_=[int])
def test_exp_(self):
self.run_test("def exp_(a):\n from math import exp\n return exp(a)", 1, exp_=[int])
def test_sqrt_(self):
self.run_test("def sqrt_(a):\n from math import sqrt\n return sqrt(a)", 1, sqrt_=[int])
def test_log10_(self):
self.run_test("def log10_(a):\n from math import log10\n return log10(a)", 1, log10_=[int])
def test_isnan_(self):
self.run_test("def isnan_(a):\n from math import isnan\n return isnan(a)", 1, isnan_=[int])
def test_pi_(self):
self.run_test("def pi_():\n from math import pi\n return pi", pi_=[])
def test_e_(self):
self.run_test("def e_():\n from math import e\n return e", e_=[])
def test_asinh_(self):
self.run_test("def asinh_(a):\n from math import asinh\n return asinh(a)",1., asinh_=[float])
def test_atanh_(self):
self.run_test("def atanh_(a):\n from math import atanh\n return atanh(a)",.1, atanh_=[float])
def test_acosh_(self):
self.run_test("def acosh_(a):\n from math import acosh\n return acosh(a)",1, acosh_=[int])
def test_radians_(self):
self.run_test("def radians_(a):\n from math import radians\n return radians(a)",1, radians_=[int])
def test_degrees_(self):
self.run_test("def degrees_(a):\n from math import degrees\n return degrees(a)",1, degrees_=[int])
def test_hypot_(self):
self.run_test("def hypot_(a,b):\n from math import hypot\n return hypot(a,b)",3,4, hypot_=[int,int])
def test_tanh_(self):
self.run_test("def tanh_(a):\n from math import tanh\n return tanh(a)",1, tanh_=[int])
def test_cosh_(self):
self.run_test("def cosh_(a):\n from math import cosh\n return cosh(a)",1., cosh_=[float])
def test_sinh_(self):
self.run_test("def sinh_(a):\n from math import sinh\n return sinh(a)",1, sinh_=[int])
def test_atan_(self):
self.run_test("def atan_(a):\n from math import atan\n return atan(a)",1, atan_=[int])
def test_atan2_(self):
self.run_test("def atan2_(a,b):\n from math import atan2\n return atan2(a,b)",2,4, atan2_=[int,int])
def test_asin_(self):
self.run_test("def asin_(a):\n from math import asin\n return asin(a)",1, asin_=[int])
def test_tan_(self):
self.run_test("def tan_(a):\n from math import tan\n return tan(a)",1, tan_=[int])
def test_log_(self):
self.run_test("def log_(a):\n from math import log\n return log(a)",1, log_=[int])
def test_log1p_(self):
self.run_test("def log1p_(a):\n from math import log1p\n return log1p(a)",1, log1p_=[int])
def test_expm1_(self):
self.run_test("def expm1_(a):\n from math import expm1\n return expm1(a)",1, expm1_=[int])
def test_ldexp_(self):
self.run_test("def ldexp_(a,b):\n from math import ldexp\n return ldexp(a,b)",3,4, ldexp_=[int,int])
def test_fmod_(self):
self.run_test("def fmod_(a,b):\n from math import fmod\n return fmod(a,b)",5.3,2, fmod_=[float,int])
def test_fabs_(self):
self.run_test("def fabs_(a):\n from math import fabs\n return fabs(a)",1, fabs_=[int])
def test_copysign_(self):
self.run_test("def copysign_(a,b):\n from math import copysign\n return copysign(a,b)",2,-2, copysign_=[int,int])
def test_acos_(self):
self.run_test("def acos_(a):\n from math import acos\n return acos(a)",1, acos_=[int])
def test_erf_(self):
self.run_test("def erf_(a):\n from math import erf\n return erf(a)",1, erf_=[int])
def test_erfc_(self):
self.run_test("def erfc_(a):\n from math import erfc\n return erfc(a)",1, erfc_=[int])
def test_gamma_(self):
self.run_test("def gamma_(a):\n from math import gamma\n return gamma(a)",1, gamma_=[int])
def test_lgamma_(self):
self.run_test("def lgamma_(a):\n from math import lgamma\n return lgamma(a)",1, lgamma_=[int])
def test_trunc_(self):
self.run_test("def trunc_(a):\n from math import trunc\n return trunc(a)",1, trunc_=[int])
def test_factorial_(self):
self.run_test("def factorial_(a):\n from math import factorial\n return factorial(a)",2, factorial_=[int])
def test_modf_(self):
self.run_test("def modf_(a):\n from math import modf\n return modf(a)",2, modf_=[int])
def test_frexp_(self):
self.run_test("def frexp_(a):\n from math import frexp\n return frexp(a)",2.2, frexp_=[float])
def test_isinf_(self):
self.run_test("def isinf_(a):\n from math import isinf\n n=1\n while not isinf(a):\n a=a*a\n n+=1\n return isinf(a)", 2., isinf_=[float])
def test_pow_accuracy(self):
code = '''
from math import factorial
def pow_accuracy(N, i):
N = N ** i
p = 0.0000001 * 1.0
binomial_coef = 1. * factorial(N) / factorial(i) / factorial(N-i)
pp = binomial_coef * p**i * (1-p)**(N-i)
return pp'''
self.run_test(code,
3, 2,
pow_accuracy=[int, int])
def test_pow_array_accuracy(self):
code = '''
import numpy as np
def pow_array_accuracy(N, i):
p = np.arange(N) * 0.0000001
pp = p**i * (1-p)**(N-i)
return pp'''
self.run_test(code,
3, 2,
pow_array_accuracy=[int, int])
|
datmo/cli/command/tests/test_workspace.py
|
dmh43/datmo
| 331 |
146157
|
<reponame>dmh43/datmo
"""
Tests for Project Commands
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# TODO: include builtin libraries for the appropriate Python
# try:
# import __builtin__
# except ImportError:
# # Python 3
# import builtins as __builtin__
try:
def to_bytes(val):
return bytes(val)
to_bytes("test")
except TypeError:
def to_bytes(val):
return bytes(val, "utf-8")
to_bytes("test")
import os
import uuid
import tempfile
import platform
import timeout_decorator
from datmo.config import Config
from datmo.cli.driver.helper import Helper
from datmo.cli.command.environment import EnvironmentCommand
from datmo.cli.command.project import ProjectCommand
from datmo.cli.command.workspace import WorkspaceCommand
from datmo.cli.command.run import RunCommand
from datmo.core.util.misc_functions import pytest_docker_environment_failed_instantiation
# provide mountable tmp directory for docker
tempfile.tempdir = "/tmp" if not platform.system() == "Windows" else None
test_datmo_dir = os.environ.get('TEST_DATMO_DIR', tempfile.gettempdir())
class TestWorkspace():
def setup_method(self):
self.temp_dir = tempfile.mkdtemp(dir=test_datmo_dir)
Config().set_home(self.temp_dir)
self.cli_helper = Helper()
def __set_variables(self):
self.project_command = ProjectCommand(self.cli_helper)
self.project_command.parse(
["init", "--name", "foobar", "--description", "test model"])
@self.project_command.cli_helper.input("\n")
def dummy(self):
return self.project_command.execute()
dummy(self)
self.environment_command = EnvironmentCommand(self.cli_helper)
self.workspace_command = WorkspaceCommand(self.cli_helper)
self.run_command = RunCommand(self.cli_helper)
# Create environment_driver definition
self.env_def_path = os.path.join(self.temp_dir, "Dockerfile")
with open(self.env_def_path, "wb") as f:
f.write(
to_bytes(
str("FROM datmo/python-base:cpu-py27%s" % os.linesep)))
def teardown_method(self):
pass
@pytest_docker_environment_failed_instantiation(test_datmo_dir)
def test_notebook(self):
self.__set_variables()
test_mem_limit = "4g"
# test single ports option before command
self.workspace_command.parse([
"notebook",
"--gpu",
"--environment-paths",
self.env_def_path,
"--mem-limit",
test_mem_limit,
])
# test for desired side effects
assert self.workspace_command.args.gpu == True
assert self.workspace_command.args.environment_paths == [
self.env_def_path
]
assert self.workspace_command.args.mem_limit == test_mem_limit
# test notebook command
self.workspace_command.parse(["notebook"])
assert self.workspace_command.args.gpu == False
@timeout_decorator.timeout(10, use_signals=False)
def timed_run(timed_run_result):
if self.workspace_command.execute():
return timed_run_result
timed_run_result = False
try:
timed_run_result = timed_run(timed_run_result)
except timeout_decorator.timeout_decorator.TimeoutError:
timed_run_result = True
assert timed_run_result
# Stop all running datmo task to not have any containers
self.run_command.parse(["stop", "--all"])
self.run_command.execute()
# creating and passing environment id
random_text = str(uuid.uuid1())
with open(self.env_def_path, "wb") as f:
f.write(
to_bytes(
str("FROM datmo/python-base:cpu-py27%s" % os.linesep)))
f.write(to_bytes(str("RUN echo " + random_text)))
self.environment_command.parse([
"environment", "create", "--name", "test", "--description",
"test description"
])
result = self.environment_command.execute()
# test notebook command
self.workspace_command.parse(
["notebook", "--environment-id", result.id])
@timeout_decorator.timeout(10, use_signals=False)
def timed_run(timed_run_result):
if self.workspace_command.execute():
return timed_run_result
timed_run_result = False
try:
timed_run_result = timed_run(timed_run_result)
except timeout_decorator.timeout_decorator.TimeoutError:
timed_run_result = True
assert timed_run_result
# Stop all running datmo task
self.run_command.parse(["stop", "--all"])
self.run_command.execute()
@pytest_docker_environment_failed_instantiation(test_datmo_dir)
def test_jupyterlab(self):
self.__set_variables()
test_mem_limit = "4g"
# test single ports option before command
self.workspace_command.parse([
"jupyterlab",
"--gpu",
"--environment-paths",
self.env_def_path,
"--mem-limit",
test_mem_limit,
])
# test for desired side effects
assert self.workspace_command.args.gpu == True
assert self.workspace_command.args.environment_paths == [
self.env_def_path
]
assert self.workspace_command.args.mem_limit == test_mem_limit
# test multiple ports option before command
self.workspace_command.parse(["jupyterlab"])
assert self.workspace_command.args.gpu == False
@timeout_decorator.timeout(10, use_signals=False)
def timed_run(timed_run_result):
if self.workspace_command.execute():
return timed_run_result
timed_run_result = False
try:
timed_run_result = timed_run(timed_run_result)
except timeout_decorator.timeout_decorator.TimeoutError:
timed_run_result = True
assert timed_run_result
# Stop all running datmo task to not have any containers
self.run_command.parse(["stop", "--all"])
self.run_command.execute()
# creating and passing environment id
random_text = str(uuid.uuid1())
with open(self.env_def_path, "wb") as f:
f.write(
to_bytes(
str("FROM datmo/python-base:cpu-py27%s" % os.linesep)))
f.write(to_bytes(str("RUN echo " + random_text)))
self.environment_command.parse([
"environment", "create", "--name", "test", "--description",
"test description"
])
result = self.environment_command.execute()
# test notebook command
self.workspace_command.parse(
["jupyterlab", "--environment-id", result.id])
@timeout_decorator.timeout(10, use_signals=False)
def timed_run(timed_run_result):
if self.workspace_command.execute():
return timed_run_result
timed_run_result = False
try:
timed_run_result = timed_run(timed_run_result)
except timeout_decorator.timeout_decorator.TimeoutError:
timed_run_result = True
assert timed_run_result
# Stop all running datmo task
self.run_command.parse(["stop", "--all"])
self.run_command.execute()
# Test doesn't take tty as True for docker
# @pytest_docker_environment_failed_instantiation(test_datmo_dir)
# def test_terminal(self):
# self.__set_variables()
# test_mem_limit = "4g"
# # test single ports option before command
# self.workspace_command.parse([
# "terminal",
# "--gpu",
# "--environment-paths",
# self.env_def_path,
# "--mem-limit",
# test_mem_limit,
# ])
#
# # test for desired side effects
# assert self.workspace_command.args.gpu == True
# assert self.workspace_command.args.environment_paths == [
# self.env_def_path
# ]
# assert self.workspace_command.args.mem_limit == test_mem_limit
#
# # test multiple ports option before command
# self.workspace_command.parse(["terminal"])
#
# assert self.workspace_command.args.gpu == False
# @timeout_decorator.timeout(10, use_signals=False)
# def timed_run(timed_run_result):
# if self.workspace_command.execute():
# return timed_run_result
#
# timed_run_result = False
# timed_run_result = timed_run(timed_run_result)
#
# assert timed_run_result
#
# # Stop all running datmo task
# self.run_command.parse(["stop", "--all"])
# self.run_command.execute()
@pytest_docker_environment_failed_instantiation(test_datmo_dir)
def test_rstudio(self):
self.__set_variables()
# Update environment_driver definition
self.env_def_path = os.path.join(self.temp_dir, "Dockerfile")
with open(self.env_def_path, "wb") as f:
f.write(to_bytes(str("FROM datmo/r-base:cpu%s" % os.linesep)))
test_mem_limit = "4g"
# test single ports option before command
self.workspace_command.parse([
"rstudio",
"--environment-paths",
self.env_def_path,
"--mem-limit",
test_mem_limit,
])
# test for desired side effects
assert self.workspace_command.args.environment_paths == [
self.env_def_path
]
assert self.workspace_command.args.mem_limit == test_mem_limit
# test multiple ports option before command
self.workspace_command.parse(["rstudio"])
@timeout_decorator.timeout(10, use_signals=False)
def timed_run(timed_run_result):
if self.workspace_command.execute():
return timed_run_result
timed_run_result = False
try:
timed_run_result = timed_run(timed_run_result)
except timeout_decorator.timeout_decorator.TimeoutError:
timed_run_result = True
assert timed_run_result
# Stop all running datmo task to not have any containers
self.run_command.parse(["stop", "--all"])
self.run_command.execute()
# creating and passing environment id
random_text = str(uuid.uuid1())
with open(self.env_def_path, "wb") as f:
f.write(to_bytes(str("FROM datmo/r-base:cpu%s" % os.linesep)))
f.write(to_bytes(str("RUN echo " + random_text)))
self.environment_command.parse([
"environment", "create", "--name", "test", "--description",
"test description"
])
result = self.environment_command.execute()
# test notebook command
self.workspace_command.parse(
["rstudio", "--environment-id", result.id])
@timeout_decorator.timeout(10, use_signals=False)
def timed_run(timed_run_result):
if self.workspace_command.execute():
return timed_run_result
timed_run_result = False
try:
timed_run_result = timed_run(timed_run_result)
except timeout_decorator.timeout_decorator.TimeoutError:
timed_run_result = True
assert timed_run_result
# Stop all running datmo task
self.run_command.parse(["stop", "--all"])
self.run_command.execute()
|
psonic/samples/misc.py
|
m-roberts/python-sonic
| 263 |
146177
|
<filename>psonic/samples/misc.py
"""Miscellaneous Sounds"""
from . import Sample
MISC_BURP = Sample('misc_burp', 0.7932879818594104)
MISC_CINEBOOM = Sample('misc_cineboom', 7.922675736961451)
MISC_CROW = Sample('misc_crow', 0.48063492063492064)
|
modules/dbnd/src/dbnd/_vendor/psutil/vendorized_psutil.py
|
ipattarapong/dbnd
| 224 |
146185
|
<reponame>ipattarapong/dbnd<gh_stars>100-1000
import errno
import os
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid == 0:
# According to "man 2 kill" PID 0 has a special meaning:
# it refers to <<every process in the process group of the
# calling process>> so we don't want to go any further.
# If we get here it means this UNIX platform *does* have
# a process with id 0.
return True
try:
os.kill(pid, 0)
except OSError as err:
if err.errno == errno.ESRCH:
# ESRCH == No such process
return False
elif err.errno == errno.EPERM:
# EPERM clearly means there's a process to deny access to
return True
else:
# According to "man 2 kill" possible error values are
# (EINVAL, EPERM, ESRCH) therefore we should never get
# here. If we do let's be explicit in considering this
# an error.
raise err
else:
return True
|
src/sagemaker/cli/compatibility/v2/modifiers/matching.py
|
LastRemote/sagemaker-python-sdk
| 1,690 |
146190
|
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
"""Functions for checking AST nodes for matches."""
from __future__ import absolute_import
import ast
from sagemaker.cli.compatibility.v2.modifiers import parsing
def matches_any(node, name_to_namespaces_dict):
"""Determines if the ``ast.Call`` node matches any of the provided names and namespaces.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
name_to_namespaces_dict (dict[str, tuple]): a mapping of names to appropriate namespaces.
Returns:
bool: if the node matches any of the names and namespaces.
"""
return any(
matches_name_or_namespaces(node, name, namespaces)
for name, namespaces in name_to_namespaces_dict.items()
)
def matches_name_or_namespaces(node, name, namespaces):
"""Determines if the ``ast.Call`` node matches the function name in the right namespace.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
name (str): the function name.
namespaces (tuple): the possible namespaces to match to.
Returns:
bool: if the node matches the name and any of the namespaces.
"""
if matches_name(node, name):
return True
if not matches_attr(node, name):
return False
return any(matches_namespace(node, namespace) for namespace in namespaces)
def matches_name(node, name):
"""Determines if the ``ast.Call`` node points to an ``ast.Name`` node with a matching name.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
name (str): the function name.
Returns:
bool: if ``node.func`` is an ``ast.Name`` node with a matching name.
"""
return isinstance(node.func, ast.Name) and node.func.id == name
def matches_attr(node, name):
"""Determines if the ``ast.Call`` node points to an ``ast.Attribute`` node with a matching name.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
name (str): the function name.
Returns:
bool: if ``node.func`` is an ``ast.Attribute`` node with a matching name.
"""
return isinstance(node.func, ast.Attribute) and node.func.attr == name
def matches_namespace(node, namespace):
"""Determines if the ``ast.Call`` node corresponds to a matching namespace.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
namespace (str): the namespace.
Returns:
bool: if the node's namespaces matches the given namespace.
"""
names = namespace.split(".")
name, value = names.pop(), node.func.value
while isinstance(value, ast.Attribute) and len(names) > 0:
if value.attr != name:
return False
name, value = names.pop(), value.value
return isinstance(value, ast.Name) and value.id == name
def has_arg(node, arg):
"""Checks if the call has the given argument.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
arg (str): the name of the argument.
Returns:
bool: if the node has the given argument.
"""
try:
return parsing.arg_value(node, arg) is not None
except KeyError:
return False
|
Giveme5W1H/extractor/tools/mapper.py
|
bkrrr/Giveme5W
| 410 |
146206
|
"""
Helper to get relation to extractors, questions and their weights
"""
def weight_to_string(extractor, weight_index, question: str = None):
"""
naming for a weight
:param extractor:
:param weight_index:
:return:
"""
if extractor == 'action':
if weight_index == 0:
return 'position'
elif weight_index == 1:
return 'frequency'
elif weight_index == 2:
return 'named_entity'
elif extractor == 'cause':
if weight_index == 0:
return 'position'
elif weight_index == 1:
return 'clausal conjunction'
elif weight_index == 2:
return 'adverbial indicator'
elif weight_index == 3:
return 'NP-VP-NP'
elif extractor == 'environment':
if question.startswith('where'):
if weight_index == 0:
return 'position'
elif weight_index == 1:
return 'frequency'
elif weight_index == 2:
return 'entailment'
elif weight_index == 3:
return 'accurate'
if question.startswith('when'):
if weight_index == 0:
return 'position'
elif weight_index == 1:
return 'frequency'
elif weight_index == 2:
return 'entailment'
elif weight_index == 3:
return 'distance_from_publisher_date'
elif weight_index == 4:
return 'accurate'
elif extractor == 'method':
if weight_index == 0:
return 'position'
elif weight_index == 1:
return 'frequency'
elif weight_index == 2:
return 'conjunction'
elif weight_index == 3:
return 'adjectives_adverbs'
else:
return 'no_mapping'
def question_to_extractor(question: str):
"""
extractor for a given question
:param question:
:return:
"""
if question == 'who' or question == 'what':
return 'action'
elif question == 'why':
return 'cause'
elif question == 'where' or question == 'when':
return 'environment'
elif question == 'how':
return 'method'
else:
return 'no_mapping'
def extractor_to_question(extractor: str):
"""
return questions for a extractor in a tuple
:param extractor:
:return:
"""
if extractor == 'action':
return ('who', 'what')
elif extractor == 'cause':
return ('why',)
elif extractor == 'environment':
return ('where', 'when')
elif extractor == 'method':
return ('how',)
else:
return ('no_mapping',)
|
tests/test_DumpCreds.py
|
sc979/jenkins-attack-framework
| 451 |
146211
|
<filename>tests/test_DumpCreds.py<gh_stars>100-1000
import unittest
import warnings
from libs.JAF.BaseCommandLineParser import BaseCommandLineParser
from libs.JAF.plugin_DumpCreds import DumpCreds, DumpCredsParser
from .configuration import (
server,
user_admin,
user_bad,
user_noaccess,
user_normal,
user_read_job_access,
user_read_no_job_access,
)
from .helpers import DummyWebServer, TestFramework
class DumpCredsTest(unittest.TestCase, TestFramework):
def setUp(self):
warnings.simplefilter("ignore", ResourceWarning)
self.testcommand = "DumpCreds"
self.TestParserClass = DumpCredsParser
self.TestClass = DumpCreds
def test_invalid_url(self):
"""Make sure that calling with invalid url fails gracefully"""
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", "https://127.0.0.1:59321/", "-a", user_bad],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_url_bad_protocol(self):
"""Make sure that calling with valid url (that isn't Jenkins or right protocol) fails gracefully"""
with DummyWebServer():
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", "https://127.0.0.1:59322/", "-a", user_bad],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_url_and_protocol(self):
"""Make sure that calling with valid url (that isn't Jenkins but right protocol) fails gracefully"""
with DummyWebServer():
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", "http://127.0.0.1:59322/", "-a", user_bad],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_jenkins_invalid_creds(self):
"""Make sure that calling with valid jenkins (but bad creds) fails gracefully"""
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", server, "-a", user_bad],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_jenkins_anonymous_creds(self):
"""Make sure that calling with valid jenkins (but no creds)"""
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", server],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_jenkins_valid_unprivileged_creds(self):
"""Make sure that calling with valid jenkins (unprivileged creds) returns expected results"""
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", server, "-a", user_noaccess],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_jenkins_valid_read_no_job_creds(self):
"""Make sure that calling with valid jenkins (read only [no job access] creds) returns expected results"""
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", server, "-a", user_read_no_job_access],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_jenkins_valid_read_job_creds(self):
"""Make sure that calling with valid jenkins (read only [job access] creds) returns expected results"""
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", server, "-a", user_read_job_access],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_jenkins_valid_normal_creds(self):
"""Make sure that calling with valid jenkins (normal creds) returns expected results"""
self.basic_test_harness(
["jaf.py", self.testcommand, "-s", server, "-a", user_normal],
[r"- \w+: Invalid Credentials or unable to access Jenkins server."],
1,
)
def test_valid_jenkins_valid_admin_creds(self):
"""Make sure that calling with valid jenkins (admin creds) returns expected results"""
self.basic_test_harness(["jaf.py", self.testcommand, "-s", server, "-a", user_admin])
class DumpCredsParserTest(unittest.TestCase, TestFramework):
def setUp(self):
self.testcommand = "DumpCreds"
self.TestClass = DumpCreds
self.TestParserClass = DumpCredsParser
def test_no_args(self):
"""Ensure that calling with no arguments results in help output and not an error"""
self.basic_test_harness(
["jaf.py", self.testcommand],
[
r"usage: jaf.py {0} \[-h\]".format(self.testcommand),
r"Jenkins Attack Framework",
r"positional arguments:",
],
)
if __name__ == "__main__":
unittest.main()
|
python/ql/src/Statements/SysExitUsed.py
|
vadi2/codeql
| 4,036 |
146221
|
<filename>python/ql/src/Statements/SysExitUsed.py
import sys
def main():
try:
process()
except Exception as ex:
print(ex)
sys.exit(1)
|
plugins/assets/__init__.py
|
qrilka/this-week-in-rust
| 533 |
146255
|
from .assets import *
|
tests/vcd_ext.py
|
gpooja3/pyvcloud
| 168 |
146257
|
<reponame>gpooja3/pyvcloud<gh_stars>100-1000
# VMware vCloud Director Python SDK
# Copyright (c) 2017-2018 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from pyvcloud.vcd.api_extension import APIExtension
from pyvcloud.vcd.test import TestCase
class TestExtension(TestCase):
def test_0001_create_extension(self):
extension = APIExtension(self.client)
extension.add_extension(self.config['vcd']['extension_name'],
self.config['vcd']['extension_namespace'],
self.config['vcd']['routing_key'],
self.config['vcd']['exchange'],
self.config['vcd']['patterns'].split(','))
def test_0002_get_extension(self):
extension = APIExtension(self.client)
ext_info = extension.get_extension_info(
self.config['vcd']['extension_name'],
self.config['vcd']['extension_namespace'])
assert ext_info
assert ext_info['name'] == self.config['vcd']['extension_name']
assert ext_info['namespace'] == \
self.config['vcd']['extension_namespace']
assert ext_info['filter_1'].startswith('/api/')
def test_0003_delete_extension(self):
extension = APIExtension(self.client)
extension.delete_extension(self.config['vcd']['extension_name'],
self.config['vcd']['extension_namespace'])
if __name__ == '__main__':
unittest.main()
|
Python/other/Wave_Array.py
|
Khushboo85277/NeoAlgo
| 897 |
146312
|
"""
Sorting the array into a wave-like array.
For eg: arr[] = {1,2,3,4,5}
Output: 2 1 4 3 5
"""
def convertToWave(length,array):
for i in range(0, length - length%2, 2): #swapping alternatively
temp=array[i]
array[i]=array[i+1]
array[i+1]=temp
return array
arr = list(map(int,input("Enter the elements of the array : ").split()))
N = len(arr) # length of the array
arr = convertToWave(N,arr)
print("Wave Array: ")
for el in arr:
print(el, end=" ")
"""
Time complexity : O(1)
Space complexity : O(1)
INPUT:-
Enter the elements of the array : 1 2 3 4 5 6 7
OUTPUT:-
Wave Array: 2 1 4 3 6 5 7
"""
|
setup.py
|
11010cy/airflow-client-python
| 115 |
146320
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Airflow API (Stable)
The version of the OpenAPI document: 1.0.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
from setuptools import setup, find_packages # noqa: H301
VERSION = "2.2.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = [
"urllib3 >= 1.25.3",
"python-dateutil",
]
setup(
version=VERSION,
keywords=["OpenAPI", "OpenAPI-Generator", "Apache Airflow API (Stable)"],
download_url=('https://archive.apache.org/dist/airflow/clients/python/' + VERSION),
install_requires=REQUIRES,
packages=find_packages(exclude=["test", "tests"])
)
|
tests/test_position.py
|
nervecell23/qstrader_c
| 113 |
146324
|
<reponame>nervecell23/qstrader_c
import unittest
from qstrader.position import Position
from qstrader.price_parser import PriceParser
class TestRoundTripXOMPosition(unittest.TestCase):
"""
Test a round-trip trade in Exxon-Mobil where the initial
trade is a buy/long of 100 shares of XOM, at a price of
$74.78, with $1.00 commission.
"""
def setUp(self):
"""
Set up the Position object that will store the PnL.
"""
self.position = Position(
"BOT", "XOM", 100,
PriceParser.parse(74.78), PriceParser.parse(1.00),
PriceParser.parse(74.78), PriceParser.parse(74.80)
)
def test_calculate_round_trip(self):
"""
After the subsequent purchase, carry out two more buys/longs
and then close the position out with two additional sells/shorts.
The following prices have been tested against those calculated
via Interactive Brokers' Trader Workstation (TWS).
"""
self.position.transact_shares(
"BOT", 100, PriceParser.parse(74.63), PriceParser.parse(1.00)
)
self.position.transact_shares(
"BOT", 250, PriceParser.parse(74.620), PriceParser.parse(1.25)
)
self.position.transact_shares(
"SLD", 200, PriceParser.parse(74.58), PriceParser.parse(1.00)
)
self.position.transact_shares(
"SLD", 250, PriceParser.parse(75.26), PriceParser.parse(1.25)
)
self.position.update_market_value(
PriceParser.parse(77.75), PriceParser.parse(77.77)
)
self.assertEqual(self.position.action, "BOT")
self.assertEqual(self.position.ticker, "XOM")
self.assertEqual(self.position.quantity, 0)
self.assertEqual(self.position.buys, 450)
self.assertEqual(self.position.sells, 450)
self.assertEqual(self.position.net, 0)
self.assertEqual(
PriceParser.display(self.position.avg_bot, 5), 74.65778
)
self.assertEqual(
PriceParser.display(self.position.avg_sld, 5), 74.95778
)
self.assertEqual(PriceParser.display(self.position.total_bot), 33596.00)
self.assertEqual(PriceParser.display(self.position.total_sld), 33731.00)
self.assertEqual(PriceParser.display(self.position.net_total), 135.00)
self.assertEqual(PriceParser.display(self.position.total_commission), 5.50)
self.assertEqual(PriceParser.display(self.position.net_incl_comm), 129.50)
self.assertEqual(
PriceParser.display(self.position.avg_price, 3), 74.665
)
self.assertEqual(PriceParser.display(self.position.cost_basis), 0.00)
self.assertEqual(PriceParser.display(self.position.market_value), 0.00)
self.assertEqual(PriceParser.display(self.position.unrealised_pnl), 0.00)
self.assertEqual(PriceParser.display(self.position.realised_pnl), 129.50)
class TestRoundTripPGPosition(unittest.TestCase):
"""
Test a round-trip trade in Proctor & Gamble where the initial
trade is a sell/short of 100 shares of PG, at a price of
$77.69, with $1.00 commission.
"""
def setUp(self):
self.position = Position(
"SLD", "PG", 100,
PriceParser.parse(77.69), PriceParser.parse(1.00),
PriceParser.parse(77.68), PriceParser.parse(77.70)
)
def test_calculate_round_trip(self):
"""
After the subsequent sale, carry out two more sells/shorts
and then close the position out with two additional buys/longs.
The following prices have been tested against those calculated
via Interactive Brokers' Trader Workstation (TWS).
"""
self.position.transact_shares(
"SLD", 100, PriceParser.parse(77.68), PriceParser.parse(1.00)
)
self.position.transact_shares(
"SLD", 50, PriceParser.parse(77.70), PriceParser.parse(1.00)
)
self.position.transact_shares(
"BOT", 100, PriceParser.parse(77.77), PriceParser.parse(1.00)
)
self.position.transact_shares(
"BOT", 150, PriceParser.parse(77.73), PriceParser.parse(1.00)
)
self.position.update_market_value(
PriceParser.parse(77.72), PriceParser.parse(77.72)
)
self.assertEqual(self.position.action, "SLD")
self.assertEqual(self.position.ticker, "PG")
self.assertEqual(self.position.quantity, 0)
self.assertEqual(self.position.buys, 250)
self.assertEqual(self.position.sells, 250)
self.assertEqual(self.position.net, 0)
self.assertEqual(
PriceParser.display(self.position.avg_bot, 3), 77.746
)
self.assertEqual(
PriceParser.display(self.position.avg_sld, 3), 77.688
)
self.assertEqual(PriceParser.display(self.position.total_bot), 19436.50)
self.assertEqual(PriceParser.display(self.position.total_sld), 19422.00)
self.assertEqual(PriceParser.display(self.position.net_total), -14.50)
self.assertEqual(PriceParser.display(self.position.total_commission), 5.00)
self.assertEqual(PriceParser.display(self.position.net_incl_comm), -19.50)
self.assertEqual(
PriceParser.display(self.position.avg_price, 5), 77.67600
)
self.assertEqual(PriceParser.display(self.position.cost_basis), 0.00)
self.assertEqual(PriceParser.display(self.position.market_value), 0.00)
self.assertEqual(PriceParser.display(self.position.unrealised_pnl), 0.00)
self.assertEqual(PriceParser.display(self.position.realised_pnl), -19.50)
class TestShortPosition(unittest.TestCase):
"""
Test a short position in Proctor & Gamble where the initial
trade is a sell/short of 100 shares of PG, at a price of
$77.69, with $1.00 commission.
"""
def setUp(self):
self.position = Position(
"SLD", "PG", 100,
PriceParser.parse(77.69), PriceParser.parse(1.00),
PriceParser.parse(77.68), PriceParser.parse(77.70)
)
def test_open_short_position(self):
self.assertEqual(PriceParser.display(self.position.cost_basis), -7768.00)
self.assertEqual(PriceParser.display(self.position.market_value), -7769.00)
self.assertEqual(PriceParser.display(self.position.unrealised_pnl), -1.00)
self.assertEqual(PriceParser.display(self.position.realised_pnl), 0.00)
self.position.update_market_value(
PriceParser.parse(77.72), PriceParser.parse(77.72)
)
self.assertEqual(PriceParser.display(self.position.cost_basis), -7768.00)
self.assertEqual(PriceParser.display(self.position.market_value), -7772.00)
self.assertEqual(PriceParser.display(self.position.unrealised_pnl), -4.00)
self.assertEqual(PriceParser.display(self.position.realised_pnl), 0.00)
class TestProfitLossBuying(unittest.TestCase):
"""
Tests that the unrealised and realised pnls are
working after position initialization, every
transaction, and every price update
"""
def setUp(self):
self.position = Position(
"BOT", "XOM", 100,
PriceParser.parse(74.78), PriceParser.parse(1.00),
PriceParser.parse(74.77), PriceParser.parse(74.79)
)
def test_realised_unrealised_calcs(self):
self.assertEqual(
PriceParser.display(self.position.unrealised_pnl), -1.00
)
self.assertEqual(
PriceParser.display(self.position.realised_pnl), 0.00
)
self.position.update_market_value(
PriceParser.parse(75.77), PriceParser.parse(75.79)
)
self.assertEqual(
PriceParser.display(self.position.unrealised_pnl), 99.00
)
self.position.transact_shares(
"SLD", 100,
PriceParser.parse(75.78), PriceParser.parse(1.00)
)
self.assertEqual(
PriceParser.display(self.position.unrealised_pnl), 99.00
) # still high
self.assertEqual(
PriceParser.display(self.position.realised_pnl), 98.00
)
self.position.update_market_value(
PriceParser.parse(75.77), PriceParser.parse(75.79)
)
self.assertEqual(
PriceParser.display(self.position.unrealised_pnl), 0.00
)
if __name__ == "__main__":
unittest.main()
|
whispers/plugins/traverse.py
|
nidogski/whispers
| 415 |
146381
|
from whispers.plugins.uri import Uri
from whispers.rules import WhisperRules
class StructuredDocument:
def __init__(self, rules: WhisperRules):
self.breadcrumbs = []
self.rules = rules
def traverse(self, code, key=None):
"""Recursively traverse YAML/JSON document"""
if isinstance(code, dict):
yield from self.cloudformation(code)
for k, v in code.items():
self.breadcrumbs.append(k)
yield k, v, self.breadcrumbs
yield from self.traverse(v, key=k)
self.breadcrumbs.pop()
# Special key/value format
elements = list(code.keys())
if "key" in elements and "value" in elements:
yield code["key"], code["value"], self.breadcrumbs
elif isinstance(code, list):
for item in code:
yield key, item, self.breadcrumbs
yield from self.traverse(item, key=key)
elif isinstance(code, str):
if "=" in code:
item = code.split("=", 1)
if len(item) == 2:
yield item[0], item[1], self.breadcrumbs
if self.rules.match("uri", code):
for k, v in Uri().pairs(code):
yield k, v, self.breadcrumbs
def cloudformation(self, code):
"""
AWS CloudFormation format
"""
if self.breadcrumbs:
return # Not tree root
if "AWSTemplateFormatVersion" not in code:
return # Not CF format
if "Parameters" not in code:
return # No parameters
for key, values in code["Parameters"].items():
if "Default" not in values:
continue # No default value
yield key, values["Default"]
|
grappelli/views/switch.py
|
browniebroke/django-grappelli
| 2,210 |
146383
|
# coding: utf-8
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import load_backend, login
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from django.shortcuts import redirect
from django.utils.html import escape
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import gettext_lazy as _
from grappelli.settings import SWITCH_USER_ORIGINAL, SWITCH_USER_TARGET
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
@staff_member_required
def switch_user(request, object_id):
# current/session user
current_user = request.user
session_user = request.session.get("original_user", {"id": current_user.id, "username": current_user.get_username()})
# check redirect
redirect_url = request.GET.get("redirect", None)
if redirect_url is None or not \
url_has_allowed_host_and_scheme(
url=redirect_url,
allowed_hosts={request.get_host()},
require_https=request.is_secure(),
):
raise Http404()
# check original_user
try:
original_user = User.objects.get(pk=session_user["id"], is_staff=True)
if not SWITCH_USER_ORIGINAL(original_user):
messages.add_message(request, messages.ERROR, _("Permission denied."))
return redirect(redirect_url)
except ObjectDoesNotExist:
msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])}
messages.add_message(request, messages.ERROR, msg)
return redirect(redirect_url)
# check new user
try:
target_user = User.objects.get(pk=object_id, is_staff=True)
if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user):
messages.add_message(request, messages.ERROR, _("Permission denied."))
return redirect(redirect_url)
except ObjectDoesNotExist:
msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)}
messages.add_message(request, messages.ERROR, msg)
return redirect(redirect_url)
# find backend
if not hasattr(target_user, 'backend'):
for backend in settings.AUTHENTICATION_BACKENDS:
if target_user == load_backend(backend).get_user(target_user.pk):
target_user.backend = backend
break
# target user login, set original as session
if hasattr(target_user, 'backend'):
login(request, target_user)
if original_user.id != target_user.id:
request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()}
return redirect(redirect_url)
|
hypergan/search/default_configurations.py
|
limberc/HyperGAN
| 889 |
146413
|
<filename>hypergan/search/default_configurations.py<gh_stars>100-1000
class DefaultConfigurations:
@staticmethod
def get():
return {}
|
filter_images.py
|
allendred/train-DeepLab
| 199 |
146417
|
<reponame>allendred/train-DeepLab
#!/usr/bin/env python
# <NAME>, <EMAIL>
# 2016/03/24
# TODO check if directories and file exist
from __future__ import print_function
import os
import sys
from skimage.io import imread, imsave
import numpy as np
from utils import get_id_classes, convert_from_color_segmentation, create_lut
def main():
##
ext = '.png'
class_names = ['bird', 'bottle', 'chair']
##
input_path, output_path, list_file, subset_data_file = process_arguments(sys.argv)
clear_subset_list_logs(subset_data_file)
class_ids = get_id_classes(class_names)
lut = create_lut(class_ids)
with open(list_file, 'rb') as f:
for img_name in f:
img_name = img_name.strip()
img = contain_class(os.path.join(input_path, img_name)+ext, class_ids, lut)
if img != None:
log_image(img_name, subset_data_file)
imsave(os.path.join(output_path, img_name)+ext, img)
def clear_subset_list_logs(file_name):
if os.path.isfile(file_name):
os.remove(file_name)
def log_image(img_name, list_file):
with open(list_file, 'ab') as f:
print(img_name, file=f)
def contain_class(img_name, class_ids, lut):
img = imread(img_name)
# If label is three-dimensional image we have to convert it to
# corresponding labels (0 - 20). Currently anticipated labels are from
# VOC pascal datasets.
if (len(img.shape) > 2):
img = convert_from_color_segmentation(img)
img_labels = np.unique(img)
if len(set(img_labels).intersection(class_ids)) >= 1:
return lut[img]
else:
return None
def process_arguments(argv):
if len(argv) != 5:
help()
input_path = argv[1]
output_path = argv[2]
list_file = argv[3]
subset_list_file = argv[4]
return input_path, output_path, list_file, subset_list_file
def help():
print('Usage: python filter_images.py INPUT_PATH OUTPUT_PATH LIST_FILE SUBSET_LIST_FILE\n'
'INPUT_PATH points to directory with segmentation ground truth labels.\n'
'OUTPUT_PATH point to directory where reindexed ground truth labels are going to be stored.\n'
'LIST_FILE denotes text file containing names of images in INPUT_PATH.\n'
'SUBSET_LIST_FILE denotes text file with remaining images that contain specified labels.\n'
'Names do not include extension of images.'
, file=sys.stderr)
exit()
if __name__ == '__main__':
main()
|
rlgraph/components/common/noise_components.py
|
RLGraph/RLGraph
| 290 |
146448
|
<filename>rlgraph/components/common/noise_components.py
# Copyright 2018/2019 The RLgraph authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from rlgraph import get_backend
from rlgraph.components.component import Component
from rlgraph.utils.decorators import rlgraph_api
from rlgraph.utils.util import convert_dtype
if get_backend() == "tf":
import tensorflow as tf
class NoiseComponent(Component):
"""
A base class Component that takes an action input and outputs some noise value.
API:
ins:
action (float): The action value input.
outs:
noise (float): The noise value to be added to the action.
"""
def __init__(self, scope="noise", **kwargs):
super(NoiseComponent, self).__init__(scope=scope, **kwargs)
@rlgraph_api
def _graph_fn_get_noise(self):
"""
The function that returns the DataOp to actually compute the noise.
Returns:
DataOp: The noise value.
"""
raise NotImplementedError
class ConstantNoise(NoiseComponent):
"""
Simple constant noise component.
"""
def __init__(self, value=0.0, scope="constant_noise", **kwargs):
super(ConstantNoise, self).__init__(scope=scope, **kwargs)
self.value = value
@rlgraph_api
def _graph_fn_get_noise(self):
if get_backend() == "tf":
return tf.constant(self.value)
class GaussianNoise(NoiseComponent):
"""
Simple Gaussian noise component.
"""
def __init__(self, mean=0.0, stddev=1.0, scope="gaussian_noise", **kwargs):
super(GaussianNoise, self).__init__(scope=scope, **kwargs)
self.mean = mean
self.stddev = stddev
self.action_space = None
def check_input_spaces(self, input_spaces, action_space=None):
assert action_space is not None
self.action_space = action_space
@rlgraph_api
def _graph_fn_get_noise(self):
if get_backend() == "tf":
return tf.random_normal(
shape=(1,) + self.action_space.shape,
mean=self.mean,
stddev=self.stddev,
dtype=convert_dtype(self.action_space.dtype)
)
class OrnsteinUhlenbeckNoise(NoiseComponent):
"""
Ornstein-Uhlenbeck noise component emitting a mean-reverting time-correlated stochastic noise.
"""
def __init__(self, sigma=0.3, mu=0.0, theta=0.15, scope="ornstein-uhlenbeck-noise", **kwargs):
"""
Args:
sigma (float): FixMe: missing documentation.
mu (float): The mean reversion level.
theta (float): The mean reversion rate.
"""
super(OrnsteinUhlenbeckNoise, self).__init__(scope=scope, **kwargs)
self.sigma = sigma
self.mu = mu
self.theta = theta
self.ou_state = None
self.action_space = None
def create_variables(self, input_spaces, action_space=None):
assert action_space is not None
self.action_space = action_space
self.ou_state = self.get_variable(
name="ou_state",
from_space=self.action_space,
add_batch_rank=False,
initializer=self.mu
)
@rlgraph_api
def _graph_fn_get_noise(self):
drift = self.theta * (self.mu - self.ou_state)
if get_backend() == "tf":
diffusion = self.sigma * tf.random_normal(
shape=self.action_space.shape, dtype=convert_dtype(self.action_space.dtype)
)
delta = drift + diffusion
return tf.assign_add(ref=self.ou_state, value=delta)
|
src/execution/execution_service.py
|
tomgilbertson/script-server-v1
| 833 |
146472
|
import logging
from collections import namedtuple
from typing import Optional, Dict, Callable, Any
from auth.authorization import Authorizer, is_same_user
from auth.user import User
from execution.executor import ScriptExecutor
from model import script_config
from model.model_helper import is_empty, AccessProhibitedException
from utils.exceptions.missing_arg_exception import MissingArgumentException
from utils.exceptions.not_found_exception import NotFoundException
LOGGER = logging.getLogger('script_server.execution_service')
_ExecutionInfo = namedtuple('_ExecutionInfo',
['execution_id', 'owner_user', 'audit_name', 'config', 'audit_command'])
class ExecutionService:
def __init__(self, authorizer, id_generator):
self._id_generator = id_generator
self._authorizer = authorizer # type: Authorizer
self._executors = {} # type: Dict[str, ScriptExecutor]
self._execution_infos = {} # type: Dict[str, _ExecutionInfo]
# active from user perspective:
# - either they are running
# - OR user haven't yet seen execution results
self._active_executor_ids = set()
self._finish_listeners = []
self._start_listeners = []
def get_active_executor(self, execution_id, user):
self.validate_execution_id(execution_id, user, only_active=False)
if execution_id not in self._active_executor_ids:
return None
return self._executors.get(execution_id)
def start_script(self, config, values, user: User):
audit_name = user.get_audit_name()
executor = ScriptExecutor(config, values)
execution_id = self._id_generator.next_id()
audit_command = executor.get_secure_command()
LOGGER.info('Calling script #%s: %s', execution_id, audit_command)
executor.start()
self._executors[execution_id] = executor
self._execution_infos[execution_id] = _ExecutionInfo(
execution_id=execution_id,
owner_user=user,
audit_name=audit_name,
audit_command=audit_command,
config=config)
self._active_executor_ids.add(execution_id)
self._add_post_finish_handling(execution_id, executor, user)
self._fire_execution_started(execution_id, user)
return execution_id
def stop_script(self, execution_id, user):
self.validate_execution_id(execution_id, user)
if execution_id in self._executors:
self._executors[execution_id].stop()
def kill_script(self, execution_id, user):
self.validate_execution_id(execution_id, user)
if execution_id in self._executors:
self._executors[execution_id].kill()
def kill_script_by_system(self, execution_id):
if execution_id in self._executors:
self._executors[execution_id].kill()
def get_exit_code(self, execution_id):
return self._get_for_executor(execution_id, lambda e: e.get_return_code())
def is_running(self, execution_id, user):
executor = self._executors.get(execution_id) # type: ScriptExecutor
if executor is None:
return False
self.validate_execution_id(execution_id, user, only_active=False, allow_when_history_access=True)
return not executor.is_finished()
def get_active_executions(self, user_id):
result = []
for id in self._active_executor_ids:
execution_info = self._execution_infos[id]
if self._can_access_execution(execution_info, user_id):
result.append(id)
return result
def get_running_executions(self):
result = []
for id, executor in self._executors.items():
if executor.is_finished():
continue
result.append(id)
return result
def get_config(self, execution_id, user) -> Optional[script_config.ConfigModel]:
self.validate_execution_id(execution_id, user)
return self._get_for_execution_info(execution_id,
lambda i: i.config)
def is_active(self, execution_id):
return execution_id in self._active_executor_ids
def can_access(self, execution_id, user_id):
execution_info = self._execution_infos.get(execution_id)
return self._can_access_execution(execution_info, user_id)
def validate_execution_id(self, execution_id, user, only_active=True, allow_when_history_access=False):
if is_empty(execution_id):
raise MissingArgumentException('Execution id is missing', 'execution_id')
if only_active and (not self.is_active(execution_id)):
raise NotFoundException('No (active) executor found for id ' + execution_id)
if not self.can_access(execution_id, user.user_id) \
and not (allow_when_history_access and self._has_full_history_rights(user.user_id)):
LOGGER.warning('Prohibited access to not owned execution #%s (user=%s)',
execution_id, str(user))
raise AccessProhibitedException('Prohibited access to not owned execution')
@staticmethod
def _can_access_execution(execution_info: _ExecutionInfo, user_id):
return (execution_info is not None) and (is_same_user(execution_info.owner_user.user_id, user_id))
def get_user_parameter_values(self, execution_id):
return self._get_for_executor(execution_id,
lambda e: e.get_user_parameter_values())
def get_script_parameter_values(self, execution_id):
return self._get_for_executor(execution_id,
lambda e: e.get_script_parameter_values())
def get_owner(self, execution_id):
return self._get_for_execution_info(execution_id,
lambda i: i.owner_user.user_id)
def get_audit_name(self, execution_id):
return self._get_for_execution_info(execution_id,
lambda i: i.owner_user.get_audit_name())
def get_audit_command(self, execution_id):
return self._get_for_execution_info(execution_id,
lambda i: i.audit_command)
def get_all_audit_names(self, execution_id):
return self._get_for_execution_info(execution_id,
lambda i: i.owner_user.audit_names)
def get_anonymized_output_stream(self, execution_id):
return self._get_for_executor(execution_id,
lambda e: e.get_anonymized_output_stream())
def get_raw_output_stream(self, execution_id, user_id):
owner = self.get_owner(execution_id)
def getter(executor):
if user_id != owner:
LOGGER.warning(user_id + ' tried to access execution #' + execution_id + ' with owner ' + owner)
return executor.get_raw_output_stream()
return self._get_for_executor(execution_id, getter)
def get_process_id(self, execution_id):
return self._get_for_executor(execution_id,
lambda e: e.get_process_id())
def _get_for_executor(self, execution_id, getter: Callable[[ScriptExecutor], Any]):
executor = self._executors.get(execution_id)
if executor is None:
return None
return getter(executor)
def _get_for_execution_info(self, execution_id, getter: Callable[[_ExecutionInfo], Any]):
info = self._execution_infos.get(execution_id)
if info is None:
return None
return getter(info)
def cleanup_execution(self, execution_id, user):
try:
self.validate_execution_id(execution_id, user)
except NotFoundException:
return
executor = self._executors.get(execution_id)
if not executor.is_finished():
raise Exception('Executor ' + execution_id + ' is not yet finished')
executor.cleanup()
self._active_executor_ids.remove(execution_id)
def add_finish_listener(self, callback, execution_id=None):
if execution_id is None:
self._finish_listeners.append(callback)
else:
executor = self._executors.get(execution_id)
if not executor:
LOGGER.error('Failed to find executor for id ' + execution_id)
return
class FinishListener:
def finished(self):
callback()
executor.add_finish_listener(FinishListener())
def _add_post_finish_handling(self, execution_id, executor, user):
self_service = self
class FinishListener:
def finished(self):
self_service._fire_execution_finished(execution_id, user)
executor.add_finish_listener(FinishListener())
def _fire_execution_finished(self, execution_id, user):
for callback in self._finish_listeners:
try:
callback(execution_id, user)
except:
LOGGER.exception('Could not notify finish listener (%s), execution: %s', str(callback), execution_id)
def add_start_listener(self, callback):
self._start_listeners.append(callback)
def _fire_execution_started(self, execution_id, user):
for callback in self._start_listeners:
try:
callback(execution_id, user)
except:
LOGGER.exception('Could not notify start listener (%s), execution: %s', str(callback), execution_id)
def _has_full_history_rights(self, user_id):
return self._authorizer.has_full_history_access(user_id)
|
example.py
|
aangelopoulos/conformal_classification
| 112 |
146480
|
<reponame>aangelopoulos/conformal_classification<filename>example.py
import argparse
import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
import time
from utils import *
from conformal import ConformalModel
import torch.backends.cudnn as cudnn
import random
parser = argparse.ArgumentParser(description='Conformalize Torchvision Model on Imagenet')
parser.add_argument('data', metavar='IMAGENETVALDIR', help='path to Imagenet Val')
parser.add_argument('--batch_size', metavar='BSZ', help='batch size', default=128)
parser.add_argument('--num_workers', metavar='NW', help='number of workers', default=0)
parser.add_argument('--num_calib', metavar='NCALIB', help='number of calibration points', default=10000)
parser.add_argument('--seed', metavar='SEED', help='random seed', default=0)
if __name__ == "__main__":
args = parser.parse_args()
### Fix randomness
np.random.seed(seed=args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
random.seed(args.seed)
# Transform as in https://github.com/pytorch/examples/blob/42e5b996718797e45c46a25c55b031e6768f8440/imagenet/main.py#L92
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std= [0.229, 0.224, 0.225])
])
# Get the conformal calibration dataset
imagenet_calib_data, imagenet_val_data = torch.utils.data.random_split(torchvision.datasets.ImageFolder(args.data, transform), [args.num_calib,50000-args.num_calib])
# Initialize loaders
calib_loader = torch.utils.data.DataLoader(imagenet_calib_data, batch_size=args.batch_size, shuffle=True, pin_memory=True)
val_loader = torch.utils.data.DataLoader(imagenet_val_data, batch_size=args.batch_size, shuffle=True, pin_memory=True)
cudnn.benchmark = True
# Get the model
model = torchvision.models.resnet152(pretrained=True,progress=True).cuda()
model = torch.nn.DataParallel(model)
model.eval()
# optimize for 'size' or 'adaptiveness'
lamda_criterion = 'size'
# allow sets of size zero
allow_zero_sets = False
# use the randomized version of conformal
randomized = True
# Conformalize model
model = ConformalModel(model, calib_loader, alpha=0.1, lamda=0, randomized=randomized, allow_zero_sets=allow_zero_sets)
print("Model calibrated and conformalized! Now evaluate over remaining data.")
validate(val_loader, model, print_bool=True)
print("Complete!")
|
examples/cls_svm_demo.py
|
msgi/nlp-tour
| 1,559 |
146506
|
from smartnlp.classfication.svm_classifier import SVMClassifier
if __name__ == '__main__':
svm_model = SVMClassifier('model/svm/model.pkl',
'./data/imdb/aclImdb.txt',
train=True)
# svm_model = SVMClassifier('model/svm/model.pkl')
svm_model.predict(['i like it ! its very interesting', 'I don\'t like it, it\'s boring'])
|
main.py
|
kant/open-solution-toxic-comments
| 119 |
146508
|
<gh_stars>100-1000
import os
import shutil
import subprocess
import click
import numpy as np
import pandas as pd
from deepsense import neptune
from sklearn.model_selection import StratifiedKFold
from pipeline_config import SOLUTION_CONFIG, Y_COLUMNS, CV_LABELS, ID_LABEL
from pipelines import PIPELINES
from preprocessing import split_train_data, translate_data
from utils import init_logger, get_logger, read_params, read_data, read_predictions, multi_roc_auc_score, \
create_submission, create_predictions_df, save_submission
RANDOM_STATE = 1234
logger = get_logger()
ctx = neptune.Context()
params = read_params(ctx)
@click.group()
def action():
pass
@action.command()
def translate_to_english():
logger.info('translating train')
translate_data(data_dir=params.data_dir, filename='train.csv', filename_translated='train_translated.csv')
logger.info('translating test')
translate_data(data_dir=params.data_dir, filename='test.csv', filename_translated='test_translated.csv')
@action.command()
def train_valid_split():
logger.info('preprocessing training data')
split_train_data(data_dir=params.data_dir, filename='train_translated.csv', target_columns=CV_LABELS,
n_splits=params.n_cv_splits)
@action.command()
@click.option('-p', '--pipeline_name', help='pipeline to be trained', required=True)
def train_pipeline(pipeline_name):
_train_pipeline(pipeline_name)
def _train_pipeline(pipeline_name):
if bool(params.overwrite) and os.path.isdir(params.experiment_dir):
shutil.rmtree(params.experiment_dir)
train = read_data(data_dir=params.data_dir, filename='train_split_translated.csv')
valid = read_data(data_dir=params.data_dir, filename='valid_split_translated.csv')
data = {'input': {'meta': train,
'meta_valid': valid,
'train_mode': True,
},
'input_ensemble': {'meta': valid,
'meta_valid': None,
'train_mode': True,
},
}
pipeline = PIPELINES[pipeline_name]['train'](SOLUTION_CONFIG)
_ = pipeline.fit_transform(data)
@action.command()
@click.option('-p', '--pipeline_name', help='pipeline to be trained', required=True)
def evaluate_pipeline(pipeline_name):
_evaluate_pipeline(pipeline_name)
def _evaluate_pipeline(pipeline_name):
valid = read_data(data_dir=params.data_dir, filename='valid_split_translated.csv')
data = {'input': {'meta': valid,
'meta_valid': None,
'train_mode': False,
},
'input_ensemble': {'meta': valid,
'meta_valid': None,
'train_mode': False,
},
}
pipeline = PIPELINES[pipeline_name]['inference'](SOLUTION_CONFIG)
output = pipeline.transform(data)
y_true = valid[Y_COLUMNS].values
y_pred = output['y_pred']
create_submission(params.experiment_dir, '{}_predictions_valid.csv'.format(pipeline_name), valid, y_pred, Y_COLUMNS,
logger)
score = multi_roc_auc_score(y_true, y_pred)
logger.info('Score on validation is {}'.format(score))
ctx.channel_send('Final Validation Score ROC_AUC', 0, score)
@action.command()
@click.option('-p', '--pipeline_name', help='pipeline to be trained', required=True)
def predict_pipeline(pipeline_name):
_predict_pipeline(pipeline_name)
def _predict_pipeline(pipeline_name):
test = read_data(data_dir=params.data_dir, filename='test_translated.csv')
data = {'input': {'meta': test,
'meta_valid': None,
'train_mode': False,
},
}
pipeline = PIPELINES[pipeline_name]['inference'](SOLUTION_CONFIG)
output = pipeline.transform(data)
y_pred = output['y_pred']
create_submission(params.experiment_dir, '{}_predictions_test.csv'.format(pipeline_name),
test, y_pred, Y_COLUMNS, logger)
@action.command()
@click.option('-p', '--pipeline_name', help='pipeline to be trained', required=True)
def train_evaluate_predict_pipeline(pipeline_name):
logger.info('training')
_train_pipeline(pipeline_name)
logger.info('evaluating')
_evaluate_pipeline(pipeline_name)
logger.info('predicting')
_predict_pipeline(pipeline_name)
@action.command()
@click.option('-p', '--pipeline_name', help='pipeline to be trained', required=True)
def train_evaluate_pipeline(pipeline_name):
logger.info('training')
_train_pipeline(pipeline_name)
logger.info('evaluating')
_evaluate_pipeline(pipeline_name)
@action.command()
@click.option('-p', '--pipeline_name', help='pipeline to be trained', required=True)
def evaluate_predict_pipeline(pipeline_name):
logger.info('evaluating')
_evaluate_pipeline(pipeline_name)
logger.info('predicting')
_predict_pipeline(pipeline_name)
@action.command()
@click.option('-p', '--pipeline_name', help='pipeline to be trained', required=True)
@click.option('-m', '--model_level', help='choices are "first" or "second"', default='second', required=False)
def train_evaluate_predict_cv_pipeline(pipeline_name, model_level):
if bool(params.overwrite) and os.path.isdir(params.experiment_dir):
shutil.rmtree(params.experiment_dir)
if model_level == 'first':
train = read_data(data_dir=params.data_dir, filename='train_translated.csv')
test = read_data(data_dir=params.data_dir, filename='test_translated.csv')
elif model_level == 'second':
train, test = read_predictions(prediction_dir=params.single_model_predictions_dir)
else:
raise NotImplementedError("""only 'first' or 'second' """)
train.reset_index(drop=True, inplace=True)
test.reset_index(drop=True, inplace=True)
fold_scores, valid_predictions_out_of_fold, test_predictions_by_fold = [], [], []
if model_level == 'first':
cv_label = train[CV_LABELS].values
cv = StratifiedKFold(n_splits=params.n_cv_splits, shuffle=True, random_state=RANDOM_STATE)
cv.get_n_splits(cv_label)
for i, (train_idx, valid_idx) in enumerate(cv.split(cv_label, cv_label)):
logger.info('Fold {} started'.format(i))
train_split = train.iloc[train_idx]
valid_split = train.iloc[valid_idx]
y_valid = valid_split[Y_COLUMNS].values
data_train = {'input': {'meta': train_split,
'meta_valid': valid_split,
'train_mode': True,
},
}
data_valid = {'input': {'meta': valid_split,
'meta_valid': None,
'train_mode': False,
}
}
data_test = {'input': {'meta': test,
'meta_valid': None,
'train_mode': False,
}
}
score, out_of_fold_predictions, test_submission = _fold_fit_loop(data_train, data_valid, data_test,
y_valid, valid_split,
test,
i,
pipeline_name)
_fold_save_loop(out_of_fold_predictions, test_submission, i, pipeline_name)
_dump_transformers(i, params.n_cv_splits)
fold_scores.append(score)
valid_predictions_out_of_fold.append(out_of_fold_predictions)
test_predictions_by_fold.append(test_submission)
(combined_oof_predictions, combined_test_predictions, mean_test_prediction) = _aggregate_fold_outputs(
fold_scores,
valid_predictions_out_of_fold,
test_predictions_by_fold)
_save_aggregate_fold_outputs(combined_oof_predictions, combined_test_predictions, mean_test_prediction,
pipeline_name)
elif model_level == 'second':
for i in range(params.n_cv_splits):
train_split = train[train['fold_id'] != i]
valid_split = train[train['fold_id'] == i]
test_split = test[test['fold_id'] == i]
y_train = train_split[Y_COLUMNS].values
y_valid = valid_split[Y_COLUMNS].values
columns_to_drop_train = Y_COLUMNS + ID_LABEL + ['fold_id']
X_train = train_split.drop(columns_to_drop_train, axis=1).values
X_valid = valid_split.drop(columns_to_drop_train, axis=1).values
columns_to_drop_test = ID_LABEL + ['fold_id']
X_test = test_split.drop(columns_to_drop_test, axis=1).values
data_train = {'input': {'X': X_train,
'y': y_train,
'X_valid': X_valid,
'y_valid': y_valid
},
}
data_valid = {'input': {'X': X_valid,
'y': y_valid,
}
}
data_test = {'input': {'X': X_test,
'y': None,
}
}
score, out_of_fold_predictions, test_submission = _fold_fit_loop(data_train, data_valid, data_test, y_valid,
valid_split, test_split,
i,
pipeline_name)
_fold_save_loop(out_of_fold_predictions, test_submission, i, pipeline_name)
_dump_transformers(i, params.n_cv_splits)
fold_scores.append(score)
valid_predictions_out_of_fold.append(out_of_fold_predictions)
test_predictions_by_fold.append(test_submission)
(combined_oof_predictions, combined_test_predictions, mean_test_prediction) = _aggregate_fold_outputs(
fold_scores,
valid_predictions_out_of_fold,
test_predictions_by_fold)
_save_aggregate_fold_outputs(combined_oof_predictions, combined_test_predictions, mean_test_prediction,
pipeline_name)
else:
raise NotImplementedError("""only 'first' and 'second' """)
@action.command()
@click.argument('pipeline_names', nargs=-1)
def prepare_single_model_predictions_dir(pipeline_names):
os.makedirs(params.single_model_predictions_dir, exist_ok=True)
train_labels_source = os.path.join(params.data_dir, 'train_translated.csv')
train_labels_destination = os.path.join(params.single_model_predictions_dir, 'labels.csv')
logger.info('copying train from {} to {}'.format(train_labels_source, train_labels_destination))
train = pd.read_csv(train_labels_source)
train_labels = train[ID_LABEL + Y_COLUMNS]
train_labels.to_csv(train_labels_destination, index=None)
sample_submit_source = os.path.join(params.data_dir, 'sample_submission.csv')
sample_submit_destination = os.path.join(params.single_model_predictions_dir, 'sample_submission.csv')
logger.info('copying valid_split from {} to {}'.format(sample_submit_source, sample_submit_destination))
shutil.copy(sample_submit_source, sample_submit_destination)
for pipeline_name in pipeline_names:
pipeline_dir = os.path.join(params.experiment_dir, pipeline_name)
train_predictions_filename = '{}_predictions_train_oof.csv'.format(pipeline_name)
test_predictions_filename = '{}_predictions_test_oof.csv'.format(pipeline_name)
for filename in [train_predictions_filename, test_predictions_filename]:
source_filepath = os.path.join(pipeline_dir, filename)
destination_filepath = os.path.join(params.single_model_predictions_dir, filename)
logger.info('copying from {} to {}'.format(source_filepath, destination_filepath))
shutil.copy(source_filepath, destination_filepath)
def _fold_fit_loop(data_train, data_valid, data_test, y_valid,
valid_split, test_split,
i, pipeline_name):
logger.info('Training...')
pipeline = PIPELINES[pipeline_name]['train'](SOLUTION_CONFIG)
_ = pipeline.fit_transform(data_train)
logger.info('Evaluating...')
pipeline = PIPELINES[pipeline_name]['inference'](SOLUTION_CONFIG)
output_valid = pipeline.transform(data_valid)
y_valid_pred = output_valid['y_pred']
out_of_fold_predictions = create_predictions_df(valid_split, y_valid_pred, Y_COLUMNS)
out_of_fold_predictions['fold_id'] = i
out_of_fold_predictions.reset_index(drop=True, inplace=True)
score = multi_roc_auc_score(y_valid, y_valid_pred)
logger.info('Score on fold {} is {}'.format(i, score))
logger.info('Predicting...')
output_test = pipeline.transform(data_test)
y_test_pred = output_test['y_pred']
test_submission = create_predictions_df(test_split, y_test_pred, Y_COLUMNS)
test_submission['fold_id'] = i
test_submission.reset_index(drop=True, inplace=True)
return score, out_of_fold_predictions, test_submission
def _dump_transformers(i, nr_splits):
if i + 1 != nr_splits:
subprocess.call('rm -rf {}/transformers'.format(params.experiment_dir), shell=True)
def _fold_save_loop(valid_oof_submission, test_submission, i, pipeline_name):
logger.info('Saving fold {} oof predictions'.format(i))
save_submission(valid_oof_submission, params.experiment_dir,
'{}_predictions_valid_fold{}.csv'.format(pipeline_name, i), logger)
logger.info('Saving fold {} test predictions'.format(i))
save_submission(test_submission, params.experiment_dir,
'{}_predictions_test_fold{}.csv'.format(pipeline_name, i), logger)
def _aggregate_fold_outputs(fold_scores, valid_predictions_out_of_fold, test_predictions_by_fold):
mean_score = np.mean(fold_scores)
logger.info('Score on validation is {}'.format(mean_score))
ctx.channel_send('Final Validation Score ROC_AUC', 0, mean_score)
logger.info('Concatenating out of fold valid predictions')
combined_oof_predictions = pd.concat(valid_predictions_out_of_fold, axis=0)
logger.info('Concatenating out of fold test predictions')
combined_test_predictions = pd.concat(test_predictions_by_fold, axis=0)
logger.info('Averaging out of fold test predictions')
mean_test_prediction = combined_test_predictions.groupby('id').mean().reset_index().drop('fold_id', axis=1)
return combined_oof_predictions, combined_test_predictions, mean_test_prediction
def _save_aggregate_fold_outputs(combined_oof_predictions, combined_test_predictions, mean_test_prediction,
pipeline_name):
logger.info('Saving out of fold valid predictions')
save_submission(combined_oof_predictions, params.experiment_dir,
'{}_predictions_train_oof.csv'.format(pipeline_name), logger)
logger.info('Saving out of fold test predictions')
save_submission(combined_test_predictions, params.experiment_dir,
'{}_predictions_test_oof.csv'.format(pipeline_name), logger)
logger.info('Saving averaged out of fold test predictions')
save_submission(mean_test_prediction, params.experiment_dir,
'{}_predictions_test_am.csv'.format(pipeline_name), logger)
if __name__ == "__main__":
init_logger()
action()
|
dataprofiler/labelers/__init__.py
|
gautomdas/DataProfiler
| 690 |
146514
|
<filename>dataprofiler/labelers/__init__.py<gh_stars>100-1000
"""
The following will list the built-in models, processors, and data labelers.
Models:
1. CharacterLevelCnnModel - character classification of text.
2. RegexModel - character classification of text.
Processors:
Preprocessors
1. CharPreprocessor
2. StructCharPreprocessor
3. DirectPassPreprocessor
PostProcessors
1. CharPreprocessor
2. StructCharPostprocessor
3. RegexPostProcessor
Data Labelers:
Classes
1. UnstructuredDataLabeler
2. StructuredDataLabeler
Files to load from disk using `BaseDataLabeler.load_from_library(<NAME>)`
1. unstructured_model
2. structured_model
3. regex_model
"""
# import models
from .base_data_labeler import BaseDataLabeler
# import data processors
from .data_processing import CharPreprocessor, CharPostprocessor, \
StructCharPreprocessor, StructCharPostprocessor, \
DirectPassPreprocessor, RegexPostProcessor
# import data labelers
from .base_data_labeler import BaseDataLabeler, TrainableDataLabeler
from .data_labelers import DataLabeler, StructuredDataLabeler, \
UnstructuredDataLabeler
|
tests/inferences/klpq_test.py
|
zhangyewu/edward
| 5,200 |
146523
|
<filename>tests/inferences/klpq_test.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import edward as ed
import numpy as np
import tensorflow as tf
from edward.models import Bernoulli, Normal
class test_klpq_class(tf.test.TestCase):
def _test_normal_normal(self, Inference, default, *args, **kwargs):
with self.test_session() as sess:
x_data = np.array([0.0] * 50, dtype=np.float32)
mu = Normal(loc=0.0, scale=1.0)
x = Normal(loc=mu, scale=1.0, sample_shape=50)
qmu_loc = tf.Variable(tf.random_normal([]))
qmu_scale = tf.nn.softplus(tf.Variable(tf.random_normal([])))
qmu = Normal(loc=qmu_loc, scale=qmu_scale)
if not default:
qmu_loc = tf.Variable(tf.random_normal([]))
qmu_scale = tf.nn.softplus(tf.Variable(tf.random_normal([])))
qmu = Normal(loc=qmu_loc, scale=qmu_scale)
# analytic solution: N(loc=0.0, scale=\sqrt{1/51}=0.140)
inference = Inference({mu: qmu}, data={x: x_data})
else:
inference = Inference([mu], data={x: x_data})
qmu = inference.latent_vars[mu]
inference.run(*args, **kwargs)
self.assertAllClose(qmu.mean().eval(), 0, rtol=1e-1, atol=1e-1)
self.assertAllClose(qmu.stddev().eval(), np.sqrt(1 / 51),
rtol=1e-1, atol=1e-1)
variables = tf.get_collection(
tf.GraphKeys.GLOBAL_VARIABLES, scope='optimizer')
old_t, old_variables = sess.run([inference.t, variables])
self.assertEqual(old_t, inference.n_iter)
sess.run(inference.reset)
new_t, new_variables = sess.run([inference.t, variables])
self.assertEqual(new_t, 0)
self.assertNotEqual(old_variables, new_variables)
def _test_model_parameter(self, Inference, *args, **kwargs):
with self.test_session() as sess:
x_data = np.array([0, 1, 0, 0, 0, 0, 0, 0, 0, 1])
p = tf.sigmoid(tf.Variable(0.5))
x = Bernoulli(probs=p, sample_shape=10)
inference = Inference({}, data={x: x_data})
inference.run(*args, **kwargs)
self.assertAllClose(p.eval(), 0.2, rtol=5e-2, atol=5e-2)
def test_klpq(self):
self._test_normal_normal(ed.KLpq, default=False, n_samples=25, n_iter=100)
self._test_normal_normal(ed.KLpq, default=True, n_samples=25, n_iter=100)
self._test_model_parameter(ed.KLpq, n_iter=50)
def test_klpq_nsamples_check(self):
with self.assertRaisesRegexp(ValueError,
"n_samples should be greater than zero: 0"):
self._test_normal_normal(ed.KLpq, default=True, n_samples=0, n_iter=10)
if __name__ == '__main__':
ed.set_seed(42)
tf.test.main()
|
predict.py
|
kisel4363/CountNet
| 131 |
146541
|
import numpy as np
import soundfile as sf
import argparse
import os
import keras
import sklearn
import librosa
from keras import backend as K
eps = np.finfo(np.float).eps
def class_mae(y_true, y_pred):
return K.mean(
K.abs(
K.argmax(y_pred, axis=-1) - K.argmax(y_true, axis=-1)
),
axis=-1
)
def count(audio, model, scaler):
# compute STFT
X = np.abs(librosa.stft(audio, n_fft=400, hop_length=160)).T
# apply global (featurewise) standardization to mean1, var0
X = scaler.transform(X)
# cut to input shape length (500 frames x 201 STFT bins)
X = X[:500, :]
# apply l2 normalization
Theta = np.linalg.norm(X, axis=1) + eps
X /= np.mean(Theta)
# add sample dimension
X = X[np.newaxis, ...]
if len(model.input_shape) == 4:
X = X[:, np.newaxis, ...]
ys = model.predict(X, verbose=0)
return np.argmax(ys, axis=1)[0]
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Load keras model and predict speaker count'
)
parser.add_argument(
'audio',
help='audio file (samplerate 16 kHz) of 5 seconds duration'
)
parser.add_argument(
'--model', default='CRNN',
help='model name'
)
args = parser.parse_args()
# load model
model = keras.models.load_model(
os.path.join('models', args.model + '.h5'),
custom_objects={
'class_mae': class_mae,
'exp': K.exp
}
)
# print model configuration
model.summary()
# save as svg file
# load standardisation parameters
scaler = sklearn.preprocessing.StandardScaler()
with np.load(os.path.join("models", 'scaler.npz')) as data:
scaler.mean_ = data['arr_0']
scaler.scale_ = data['arr_1']
# compute audio
audio, rate = sf.read(args.audio, always_2d=True)
# downmix to mono
audio = np.mean(audio, axis=1)
estimate = count(audio, model, scaler)
print("Speaker Count Estimate: ", estimate)
|
src/programy/dynamic/maps/roman.py
|
cdoebler1/AIML2
| 345 |
146550
|
<reponame>cdoebler1/AIML2<gh_stars>100-1000
"""
Copyright (c) 2016-2020 <NAME> http://www.keithsterling.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from programy.dynamic.maps.map import DynamicMap
# Code stolen from http://code.activestate.com/recipes/81611-roman-numerals/
class MapRomanToDecimal(DynamicMap):
NAME = "ROMANTODEC"
NUMS = ('M', 'D', 'C', 'L', 'X', 'V', 'I')
INTS = (1000, 500, 100, 50, 10, 5, 1)
def __init__(self, config):
DynamicMap.__init__(self, config)
def map_value(self, client_context, input_value):
if not isinstance(input_value, str):
raise TypeError("expected string, got %s" % type(input_value))
input_value = input_value.upper()
places = []
for char in input_value:
if char not in MapRomanToDecimal.NUMS:
raise ValueError("input_value is not a valid roman numeral: %s" % input_value)
charnum = 0
for char in input_value:
value = MapRomanToDecimal.INTS[MapRomanToDecimal.NUMS.index(char)]
# If the next place holds a larger number, this value is negative.
try:
nextvalue = MapRomanToDecimal.INTS[MapRomanToDecimal.NUMS.index(input_value[charnum + 1])]
if nextvalue > value:
value *= -1
except IndexError:
# there is no next place.
pass
places.append(value)
charnum += 1
total = 0
for num in places:
total += num
return str(total)
class MapDecimalToRoman(DynamicMap):
NAME = "DECTOROMAN"
INTS = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
NUMS = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')
def __init__(self, config):
DynamicMap.__init__(self, config)
def map_value(self, client_context, input_value):
input_value = int(input_value)
if not 0 < input_value < 4000:
raise ValueError("Argument must be between 1 and 3999")
result = ""
num = 0
for num_str in MapDecimalToRoman.NUMS:
# No need to check for div by 0 as the sets of ints does not contain 0
count = input_value // MapDecimalToRoman.INTS[num]
result += num_str * count
input_value -= MapDecimalToRoman.INTS[num] * count
num += 1
return result
|
finalists/yc14600/PyTorch-Encoding/encoding/datasets/imagenet.py
|
lrzpellegrini/cvpr_clvision_challenge
| 2,190 |
146578
|
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: <NAME>
## Email: <EMAIL>
## Copyright (c) 2018
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this source tree
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import os
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import warnings
warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning)
class ImageNetDataset(datasets.ImageFolder):
BASE_DIR = "ILSVRC2012"
def __init__(self, root=os.path.expanduser('~/.encoding/data'), transform=None,
target_transform=None, train=True, **kwargs):
split='train' if train == True else 'val'
root = os.path.join(root, self.BASE_DIR, split)
super(ImageNetDataset, self).__init__(
root, transform, target_transform)
|
Alignment/CommonAlignmentProducer/python/GlobalTrackerMuonAlignment_cfi.py
|
ckamtsikis/cmssw
| 852 |
146598
|
<reponame>ckamtsikis/cmssw<gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
GlobalTrackerMuonAlignment = cms.EDAnalyzer('GlobalTrackerMuonAlignment',
isolated = cms.bool(False),
cosmics = cms.bool(False),
refitmuon = cms.bool(False),
refittrack = cms.bool(False),
rootOutFile = cms.untracked.string('outfile.root'),
txtOutFile = cms.untracked.string('outglobal.txt'),
writeDB = cms.untracked.bool(False),
debug = cms.untracked.bool(False)
)
|
args.py
|
hujilin1229/P-GNN
| 352 |
146618
|
from argparse import ArgumentParser
def make_args():
parser = ArgumentParser()
# general
parser.add_argument('--comment', dest='comment', default='0', type=str,
help='comment')
parser.add_argument('--task', dest='task', default='link', type=str,
help='link; link_pair')
parser.add_argument('--model', dest='model', default='GCN', type=str,
help='model class name. E.g., GCN, PGNN, ...')
parser.add_argument('--dataset', dest='dataset', default='All', type=str,
help='All; Cora; grid; communities; ppi')
parser.add_argument('--gpu', dest='gpu', action='store_true',
help='whether use gpu')
parser.add_argument('--cache_no', dest='cache', action='store_false',
help='whether use cache')
parser.add_argument('--cpu', dest='gpu', action='store_false',
help='whether use cpu')
parser.add_argument('--cuda', dest='cuda', default='0', type=str)
# dataset
parser.add_argument('--remove_link_ratio', dest='remove_link_ratio', default=0.2, type=float)
parser.add_argument('--rm_feature', dest='rm_feature', action='store_true',
help='whether rm_feature')
parser.add_argument('--rm_feature_no', dest='rm_feature', action='store_false',
help='whether rm_feature')
parser.add_argument('--permute', dest='permute', action='store_true',
help='whether permute subsets')
parser.add_argument('--permute_no', dest='permute', action='store_false',
help='whether permute subsets')
parser.add_argument('--feature_pre', dest='feature_pre', action='store_true',
help='whether pre transform feature')
parser.add_argument('--feature_pre_no', dest='feature_pre', action='store_false',
help='whether pre transform feature')
parser.add_argument('--dropout', dest='dropout', action='store_true',
help='whether dropout, default 0.5')
parser.add_argument('--dropout_no', dest='dropout', action='store_false',
help='whether dropout, default 0.5')
parser.add_argument('--approximate', dest='approximate', default=-1, type=int,
help='k-hop shortest path distance. -1 means exact shortest path') # -1, 2
parser.add_argument('--batch_size', dest='batch_size', default=8, type=int) # implemented via accumulating gradient
parser.add_argument('--layer_num', dest='layer_num', default=2, type=int)
parser.add_argument('--feature_dim', dest='feature_dim', default=32, type=int)
parser.add_argument('--hidden_dim', dest='hidden_dim', default=32, type=int)
parser.add_argument('--output_dim', dest='output_dim', default=32, type=int)
parser.add_argument('--anchor_num', dest='anchor_num', default=64, type=int)
parser.add_argument('--normalize_adj', dest='normalize_adj', action='store_true',
help='whether normalize_adj')
parser.add_argument('--lr', dest='lr', default=1e-2, type=float)
parser.add_argument('--epoch_num', dest='epoch_num', default=2001, type=int)
parser.add_argument('--repeat_num', dest='repeat_num', default=2, type=int) # 10
parser.add_argument('--epoch_log', dest='epoch_log', default=10, type=int)
parser.set_defaults(gpu=True, task='link', model='GCN', dataset='All',
cache=False, rm_feature=False,
permute=True, feature_pre=True, dropout=True,
approximate=-1, normalize_adj=False)
args = parser.parse_args()
return args
|
haskell/private/cabal_wrapper.py
|
guibou/rules_haskell
| 222 |
146665
|
<reponame>guibou/rules_haskell
#!/usr/bin/env python3
# cabal_wrapper.py <FILE.JSON>
#
# This wrapper calls Cabal's configure/build/install steps one big
# action so that we don't have to track all inputs explicitly between
# steps. It receives the path to a json file with the following schema:
#
# { "component": string # Cabal component to build.
# , "pkg_name": string # Package ID of the resulting package.
# , "generate_haddock": boolean # Whether to generate haddock documentation.
# , "setup_path": string # Path to Setup.hs
# , "pkg_dir": string # Directory containing the Cabal file
# , "package_db_path": string # Output package DB path.
# , "runghc_args": list of string # Arguments for runghc
# , "extra_args": list of string # Additional args to Setup.hs configure.
# , "path_args": list of string # Additional args to Setup.hs configure where paths need to be prefixed with execroot.
# , "toolchain_info" :
# { "ghc": string # path to ghc
# , "ghc_pkg": string # path to ghc_pkg
# , "runghc": string # path to runghc
# , "ar": string # path to ar
# , "cc": string # path to cc
# , "strip": string # path to strip
# , "is_windows": boolean # this is a windows build
# , "workspace": string # workspace name
# , "ghc_cc_args": list of string # cc flags for ghc
# }
# , "generate_paths_module": boolean # whether to generate a paths_module
# , "ghc_version": List of int # version of ghc
# , "cabal_basename": basename of cabal binary
# , "cabal_dirname": dirname of cabal binary
# }
from __future__ import print_function
from contextlib import contextmanager
from glob import glob
import json
import os
import os.path
import re
import shutil
import subprocess
import sys
import tempfile
from generate_cabal_paths_module import generate_cabal_paths_module
debug = False
verbose = os.environ.get("CABAL_VERBOSE", "") == "True"
with open(sys.argv.pop(1)) as json_file:
json_args = json.load(json_file)
toolchain_info = json_args["toolchain_info"]
is_windows = toolchain_info["is_windows"]
def run(cmd, *args, **kwargs):
if debug:
print("+ " + " ".join(["'{}'".format(arg) for arg in cmd]), file=sys.stderr)
sys.stderr.flush()
if verbose:
subprocess.run(cmd, check=True, *args, **kwargs)
else:
try:
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, *args, **kwargs)
except subprocess.CalledProcessError as err:
sys.stdout.buffer.write(err.stdout)
sys.stderr.buffer.write(err.stderr)
raise
def find_exe(exe):
if os.path.isfile(exe):
path = os.path.abspath(exe)
elif is_windows and os.path.isfile(exe + ".exe"):
path = os.path.abspath(exe + ".exe")
else:
path = toolchain_info["workspace"] + "/" + exe
if not os.path.isfile(path) and is_windows:
path = toolchain_info["workspace"] + "/" + exe + ".exe"
return path
path_list_sep = ";" if is_windows else ":"
def canonicalize_path(path):
return path_list_sep.join([
os.path.abspath(entry)
for entry in path.split(path_list_sep)
if entry != ""
])
# Remove any relative entries, because we'll be changing CWD shortly.
os.environ["LD_LIBRARY_PATH"] = canonicalize_path(os.getenv("LD_LIBRARY_PATH", ""))
os.environ["LIBRARY_PATH"] = canonicalize_path(os.getenv("LIBRARY_PATH", ""))
os.environ["PATH"] = canonicalize_path(os.getenv("PATH", ""))
os.environ["RULES_HASKELL_GHC_PATH"] = canonicalize_path(os.getenv("RULES_HASKELL_GHC_PATH", ""))
os.environ["RULES_HASKELL_GHC_PKG_PATH"] = canonicalize_path(os.getenv("RULES_HASKELL_GHC_PKG_PATH", ""))
os.environ["RULES_HASKELL_LIBDIR_PATH"] = canonicalize_path(os.getenv("RULES_HASKELL_LIBDIR_PATH", ""))
os.environ["RULES_HASKELL_DOCDIR_PATH"] = canonicalize_path(os.getenv("RULES_HASKELL_DOCDIR_PATH", ""))
component = json_args["component"]
name = json_args["pkg_name"]
haddock = json_args["generate_haddock"]
execroot = os.getcwd()
setup = os.path.join(execroot, json_args["setup_path"])
srcdir = os.path.join(execroot, json_args["pkg_dir"])
# By definition (see ghc-pkg source code).
pkgroot = os.path.realpath(os.path.join(execroot, os.path.dirname(json_args["package_db_path"])))
libdir = os.path.join(pkgroot, "{}_iface".format(name))
dynlibdir = os.path.join(pkgroot, "lib")
bindir = os.path.join(pkgroot, "bin")
datadir = os.path.join(pkgroot, "{}_data".format(name))
package_database = os.path.join(pkgroot, "{}.conf.d".format(name))
haddockdir = os.path.join(pkgroot, "{}_haddock".format(name))
htmldir = os.path.join(pkgroot, "{}_haddock_html".format(name))
runghc_args = json_args["runghc_args"]
runghc = find_exe(toolchain_info["runghc"])
ghc = find_exe(toolchain_info["ghc"])
ghc_pkg = find_exe(toolchain_info["ghc_pkg"])
extra_args = json_args["extra_args"]
path_args = json_args["path_args"]
ar = find_exe(toolchain_info["ar"])
cc = find_exe(toolchain_info["cc"])
strip = find_exe(toolchain_info["strip"])
def recache_db():
run([ghc_pkg, "recache", "--package-db=" + package_database])
recache_db()
@contextmanager
def tmpdir():
"""This is a reimplementation of `tempfile.TemporaryDirectory` because
the latter isn't available in python2
"""
# Build into a sibling path of the final binary output location.
# This is to ensure that relative `RUNPATH`s are valid in the intermediate
# output in the `--builddir` as well as in the final output in `--bindir`.
# Executables are placed into `<distdir>/build/<package-name>/<binary>`.
# Libraries are placed into `<distdir>/build/<library>`. I.e. there is an
# extra subdirectory for libraries.
#
# On Windows we don't do dynamic linking and prefer shorter paths to avoid
# exceeding `MAX_PATH`.
if is_windows:
distdir = tempfile.mkdtemp()
else:
if component.startswith("exe:"):
distdir = tempfile.mkdtemp(dir=os.path.dirname(os.path.dirname(pkgroot)))
else:
distdir = tempfile.mkdtemp(dir=os.path.dirname(pkgroot))
try:
yield distdir
finally:
shutil.rmtree(distdir, ignore_errors = True)
with tmpdir() as distdir:
enable_relocatable_flags = ["--enable-relocatable"] \
if not is_windows else []
# Cabal really wants the current working directory to be directory
# where the .cabal file is located. So we have no choice but to chance
# cd into it, but then we have to rewrite all relative references into
# absolute ones before doing so (using $execroot).
old_cwd = os.getcwd()
os.chdir(srcdir)
os.putenv("RULES_HASKELL_EXEC_ROOT", old_cwd)
os.putenv("HOME", "/var/empty")
os.putenv("TMPDIR", os.path.join(distdir, "tmp"))
os.putenv("TMP", os.path.join(distdir, "tmp"))
os.putenv("TEMP", os.path.join(distdir, "tmp"))
os.makedirs(os.path.join(distdir, "tmp"))
# Create a Paths module that will be used instead of the cabal generated one.
# https://cabal.readthedocs.io/en/3.4/cabal-package.html#accessing-data-files-from-package-code
generated_paths_file = None
if json_args["generate_paths_module"]:
component_name = component.split(':')[1]
(paths_file, cabal_paths_file_content) = generate_cabal_paths_module(
component_name = component_name,
ghc_version = json_args["ghc_version"],
is_windows = is_windows,
cabal_basename = json_args["cabal_basename"],
cabal_dirname = json_args["cabal_dirname"],
ghc = ghc,
libdir = os.path.basename(libdir),
dynlibdir = os.path.basename(dynlibdir),
bindir = os.path.basename(bindir),
datadir = os.path.basename(datadir),
pkgroot = pkgroot,
workspace = toolchain_info["workspace"],
)
if not os.path.exists(paths_file):
with open(paths_file, 'w') as f:
f.write(cabal_paths_file_content)
generated_paths_file = paths_file
# XXX: Bazel hack
# When cabal_wrapper calls other tools with runfiles, the runfiles are
# searched in the runfile tree of cabal_wrapper unless we clear
# RUNFILES env vars. After clearing the env vars, each tool looks for
# runfiles in its own runfiles tree.
#
# Clearing RUNFILES_DIR is necessary in macos where a wrapper script
# cc-wrapper.sh is used from the cc toolchain.
#
# Clearing RUNFILES_MANIFEST_FILE is necessary in windows where we
# use a wrapper script cc-wrapper-bash.exe which has a different
# manifest file than cabal_wrapper.py.
if "RUNFILES_DIR" in os.environ:
del os.environ["RUNFILES_DIR"]
if "RUNFILES_MANIFEST_FILE" in os.environ:
del os.environ["RUNFILES_MANIFEST_FILE"]
runghc_args = [arg.replace("./", execroot + "/") for arg in runghc_args]
run([runghc] + runghc_args + [setup, "configure", \
component, \
"--verbose=0", \
"--user", \
"--with-compiler=" + ghc,
"--with-hc-pkg=" + ghc_pkg,
"--with-ar=" + ar,
"--with-gcc=" + cc,
"--with-strip=" + strip,
"--enable-deterministic", \
] +
[ "--ghc-option=" + flag.replace("$CC", cc) for flag in toolchain_info["ghc_cc_args"] ] +
enable_relocatable_flags + \
[ \
# Make `--builddir` a relative path. Using an absolute path would
# confuse the `RUNPATH` patching logic in `cc_wrapper`. It assumes that
# absolute paths refer the temporary directory that GHC uses for
# intermediate template Haskell outputs. `cc_wrapper` should improved
# in that regard.
"--builddir=" + (os.path.relpath(distdir) if not is_windows else distdir), \
"--prefix=" + pkgroot, \
"--libdir=" + libdir, \
"--dynlibdir=" + dynlibdir, \
"--libsubdir=", \
"--bindir=" + bindir, \
"--datadir=" + datadir, \
# Note, setting --datasubdir is required to work around
# https://github.com/haskell/cabal/issues/6235
"--datasubdir=", \
"--haddockdir=" + haddockdir, \
"--htmldir=" + htmldir, \
"--package-db=clear", \
"--package-db=global", \
] + \
extra_args + \
[ arg.replace("=", "=" + execroot + "/") for arg in path_args ] + \
[ "--package-db=" + package_database ], # This arg must come last.
)
run([runghc] + runghc_args + [setup, "build", "--verbose=0", "--builddir=" + distdir])
if haddock:
run([runghc] + runghc_args + [setup, "haddock", "--verbose=0", "--builddir=" + distdir])
run([runghc] + runghc_args + [setup, "install", "--verbose=0", "--builddir=" + distdir])
# Bazel builds are not sandboxed on Windows and can be non-sandboxed on
# other OSs. Operations like executing `configure` scripts can modify the
# source tree. If the `srcs` attribute uses a glob like `glob(["**"])`,
# then these modified files will enter `srcs` on the next execution and
# invalidate the cache. To avoid this we remove generated files.
run([runghc] + runghc_args + [setup, "clean", "--verbose=0", "--builddir=" + distdir])
if generated_paths_file: os.remove(generated_paths_file)
os.chdir(old_cwd)
# XXX Cabal has a bizarre layout that we can't control directly. It
# confounds the library-dir and the import-dir (but not the
# dynamic-library-dir). That's pretty annoying, because Bazel won't
# allow overlap in the path to the interface files directory and the
# path to the static library. So we move the static library elsewhere
# and patch the .conf file accordingly.
#
# There were plans for controlling this, but they died. See:
# https://github.com/haskell/cabal/pull/3982#issuecomment-254038734
libraries=glob(os.path.join(libdir, "libHS*.a"))
package_conf_file = os.path.join(package_database, name + ".conf")
def make_relocatable_paths(line):
line = re.sub("library-dirs:.*", "library-dirs: ${pkgroot}/lib", line)
def make_relative_to_pkgroot(matchobj):
abspath=matchobj.group(0)
return os.path.join("${pkgroot}", os.path.relpath(abspath, start=pkgroot))
# The $execroot is an absolute path and should not leak into the output.
# Replace each ocurrence of execroot by a path relative to ${pkgroot}.
line = re.sub(re.escape(execroot) + '\S*', make_relative_to_pkgroot, line)
return line
if libraries != [] and os.path.isfile(package_conf_file):
for lib in libraries:
os.rename(lib, os.path.join(dynlibdir, os.path.basename(lib)))
tmp_package_conf_file = package_conf_file + ".tmp"
with open(package_conf_file, 'r', errors='surrogateescape') as package_conf:
with open(tmp_package_conf_file, 'w', errors='surrogateescape') as tmp_package_conf:
for line in package_conf.readlines():
print(make_relocatable_paths(line), file=tmp_package_conf)
os.remove(package_conf_file)
os.rename(tmp_package_conf_file, package_conf_file)
recache_db()
|
src/convert_transforms.py
|
Shuhei-YOSHIDA/tagslam
| 210 |
146672
|
import tf
import numpy as np
""" convert multicam_calib transforms to tagslam format:
example session:
ipython
import numpy as np
from convert_transforms import multicam_to_tagslam
%load_ext autoreload
%autoreload 2
# copy T_cn_cnm1 from multicam_calibration file:
T=np.array([[0.99995273841, 0.00284628684, 0.00929621430, -0.20032164920], [-0.00285007802, 0.99999586067, 0.00039459796, -0.00109630102], [-0.00929505268, -0.00042107425, 0.99995671141, 0.00092501568], [ 0.00000000000, 0.00000000000, 0.00000000000, 1.00000000000]])
rvec,tvec = multicam_to_tagslam(T)
"""
def mat_to_rvec_tvec(T):
angle, direc, point = tf.transformations.rotation_from_matrix(T)
return angle*direc, T[0:3,3]
def multicam_to_tagslam(tf_matrix_4x4_cn_cnm1):
T_w_c = np.linalg.inv(tf_matrix_4x4_cn_cnm1)
return mat_to_rvec_tvec(T_w_c)
def rvec_tvec_to_mat(rvec, tvec):
l = np.linalg.norm(rvec)
n = rvec/l if l > 1e-8 else np.array([1.0, 0.0, 0.0])
T = tf.transformations.rotation_matrix(l, n)
T[0:3, 3] = tvec
return T
def as_yaml(rvec, tvec):
print " position:"
print " x: %12.8f" % tvec[0]
print " y: %12.8f" % tvec[1]
print " z: %12.8f" % tvec[2]
print " rotation:"
print " x: %11.8f" % rvec[0]
print " y: %11.8f" % rvec[1]
print " z: %11.8f" % rvec[2]
|
utils/box/__init__.py
|
pzheng2018/MutualGuide
| 124 |
146706
|
from .box_utils import *
from .seq_matcher import SeqBoxMatcher
from .detection import Detect
from .prior_box import PriorBox
|
source/models/mann_net.py
|
SizheWei/OpenCompoundDomainAdaptation-OCDA
| 136 |
146717
|
import numpy as np
import torch
import torch.nn as nn
from .utils import register_model, get_model
from . import cos_norm_classifier
@register_model('MannNet')
class MannNet(nn.Module):
"""Defines a Dynamic Meta-Embedding Network."""
def __init__(self, num_cls=10, model='LeNet', src_weights_init=None,
weights_init=None, use_domain_factor_selector=False, centroids_path=None, feat_dim=512):
super(MannNet, self).__init__()
self.name = 'MannNet'
self.base_model = model
self.num_cls = num_cls
self.feat_dim = feat_dim
self.use_domain_factor_selector = use_domain_factor_selector
self.cls_criterion = nn.CrossEntropyLoss()
self.gan_criterion = nn.CrossEntropyLoss()
self.centroids = torch.from_numpy(np.load(centroids_path)).float().cuda()
assert self.centroids is not None
self.centroids.requires_grad = False
self.setup_net()
if weights_init is not None:
self.load(weights_init)
elif src_weights_init is not None:
self.load_src_net(src_weights_init)
else:
raise Exception('MannNet must be initialized with weights.')
def forward(self, x_s, x_t):
"""Pass source and target images through their respective networks."""
score_s, x_s = self.src_net(x_s, with_ft=True)
score_t, x_t = self.tgt_net(x_t, with_ft=True)
if self.discrim_feat:
d_s = self.discriminator(x_s.clone())
d_t = self.discriminator(x_t.clone())
else:
d_s = self.discriminator(score_s.clone())
d_t = self.discriminator(score_t.clone())
return score_s, score_t, d_s, d_t
def setup_net(self):
"""Setup source, target and discriminator networks."""
self.src_net = get_model(self.base_model, num_cls=self.num_cls, feat_dim=self.feat_dim)
self.tgt_net = get_model(self.base_model, num_cls=self.num_cls, feat_dim=self.feat_dim)
input_dim = self.num_cls
self.discriminator = nn.Sequential(
nn.Linear(input_dim, 500),
nn.ReLU(),
nn.Linear(500, 500),
nn.ReLU(),
nn.Linear(500, 2),
)
self.fc_selector = nn.Linear(self.feat_dim, self.feat_dim)
if self.use_domain_factor_selector:
self.domain_factor_selector = nn.Linear(self.feat_dim, self.feat_dim)
self.classifier = cos_norm_classifier.create_model(self.feat_dim, self.num_cls)
self.image_size = self.src_net.image_size
self.num_channels = self.src_net.num_channels
def load(self, init_path):
"""Loads full src and tgt models."""
net_init_dict = torch.load(init_path)
self.load_state_dict(net_init_dict)
def load_src_net(self, init_path):
"""Initialize source and target with source weights."""
self.src_net.load(init_path)
self.tgt_net.load(init_path)
net_init_dict = torch.load(init_path)
classifier_weights = net_init_dict['classifier.weight']
self.classifier.weight.data = classifier_weights.data.clone()
def save(self, out_path):
torch.save(self.state_dict(), out_path)
def save_tgt_net(self, out_path):
torch.save(self.tgt_net.state_dict(), out_path)
|
parsifal/utils/test.py
|
ShivamPytho/parsifal
| 342 |
146722
|
<gh_stars>100-1000
from django.conf import settings
from django.shortcuts import resolve_url
from django.utils.http import urlencode
def login_redirect_url(url):
"""
Utility function to be used as the "expected_url" param of the
test case assertRedirects.
:param url: Model instance, url pattern, url
:return: String in the format "/login/?next=%2Fabout%2F"
"""
login_url = resolve_url(settings.LOGIN_URL)
next_url = urlencode({"next": resolve_url(url)})
return f"{login_url}?{next_url}"
|
src/pretix/base/migrations/0127_auto_20190711_0705.py
|
pajowu/pretix
| 1,248 |
146726
|
# Generated by Django 2.2.1 on 2019-07-11 07:05
from django.db import migrations
import pretix.base.models.fields
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0126_item_show_quota_left'),
]
operations = [
migrations.RenameField(
model_name='question',
old_name='dependency_value',
new_name='dependency_values',
),
migrations.AlterField(
model_name='question',
name='dependency_values',
field=pretix.base.models.fields.MultiStringField(default=['']),
),
]
|
tools/ipynb2md.py
|
xudong-sun/mxnet
| 399 |
146734
|
<reponame>xudong-sun/mxnet
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Convert jupyter notebook into the markdown format. The notebook outputs will be
removed.
It is heavily adapted from https://gist.github.com/decabyte/0ed87372774cf5d34d7e
"""
import sys
import io
import os
import argparse
import nbformat
def remove_outputs(nb):
"""Removes the outputs cells for a jupyter notebook."""
for cell in nb.cells:
if cell.cell_type == 'code':
cell.outputs = []
def clear_notebook(old_ipynb, new_ipynb):
with io.open(old_ipynb, 'r') as f:
nb = nbformat.read(f, nbformat.NO_CONVERT)
remove_outputs(nb)
with io.open(new_ipynb, 'w', encoding='utf8') as f:
nbformat.write(nb, f, nbformat.NO_CONVERT)
def main():
parser = argparse.ArgumentParser(
description="Jupyter Notebooks to markdown"
)
parser.add_argument("notebook", nargs=1, help="The notebook to be converted.")
parser.add_argument("-o", "--output", help="output markdown file")
args = parser.parse_args()
old_ipynb = args.notebook[0]
new_ipynb = 'tmp.ipynb'
md_file = args.output
print md_file
if not md_file:
md_file = os.path.splitext(old_ipynb)[0] + '.md'
clear_notebook(old_ipynb, new_ipynb)
os.system('jupyter nbconvert ' + new_ipynb + ' --to markdown --output ' + md_file)
with open(md_file, 'a') as f:
f.write('<!-- INSERT SOURCE DOWNLOAD BUTTONS -->')
os.system('rm ' + new_ipynb)
if __name__ == '__main__':
main()
|
src/aria_actions.py
|
Wildog/Ariafred
| 191 |
146741
|
<reponame>Wildog/Ariafred<filename>src/aria_actions.py
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import xmlrpclib
from workflow import Workflow3
def escape(s, char=' '):
return s.replace(char, '\\' + char)
def notify(msg, title='Ariafred', gid=''):
notifier = os.path.join(wf.workflowdir, 'Ariafred.app/Contents/MacOS/Ariafred')
notifier = escape(notifier)
msg = escape(msg, char='[')
os_command = '%s -title "%s" -message "%s"' % (notifier.encode('utf-8'),
title.encode('utf-8'),
msg.encode('utf-8'))
if gid:
dir = server.tellStatus(secret, gid, ['dir'])['dir']
filepath = server.getFiles(secret, gid)[0]['path'].encode('utf-8')
if os.path.exists(filepath):
click_command = 'open -R "%s"' % filepath
else:
click_command = 'open "%s" ' % dir
os_command = '%s -execute \'%s\'' % (os_command, click_command)
os.system(os_command)
def set_query(query):
alfred_2_cmd = 'if application "Alfred 2" is running then tell application "Alfred 2" to search "%s"' % query
alfred_3_cmd = 'if application "Alfred 3" is running then tell application "Alfred 3" to search "%s"' % query
os_command = "osascript -e '%s' & osascript -e '%s'" % (alfred_2_cmd, alfred_3_cmd)
os.system(os_command)
def run_aria():
os_command = 'export PATH=$PATH:/usr/local/bin:/usr/local/aria2/bin && aria2c --enable-rpc --rpc-listen-all=true --rpc-allow-origin-all -c -D'
if os.system(os_command) == 0:
notify('Aria2 has started successfully')
else:
notify('Failed to start Aria2, please run manually')
def get_task_name(gid):
bt = server.tellStatus(secret, gid, ['bittorrent'])
path = server.getFiles(secret, gid)[0]['path']
if bt:
file_num = len(server.getFiles(secret, gid))
if 'info' in bt:
bt_name = bt['bittorrent']['info']['name']
else:
bt_name = os.path.basename(os.path.dirname(path))
if not bt_name:
bt_name = 'Task name not obtained yet'
name = u'{bt_name} (BT: {file_num} files)'.format(bt_name=bt_name, file_num=file_num)
else:
name = os.path.basename(path)
if not name:
name = 'Task name not obtained yet'
return name
def reveal(gid, alfred=False):
dir = server.tellStatus(secret, gid, ['dir'])['dir']
filepath = server.getFiles(secret, gid)[0]['path'].encode('utf-8')
if os.path.exists(filepath):
if alfred:
alfred_2_cmd = 'if application "Alfred 2" is running then tell application "Alfred 2" to search "%s"' % filepath
alfred_3_cmd = 'if application "Alfred 3" is running then tell application "Alfred 3" to search "%s"' % filepath
os_command = "osascript -e '%s' & osascript -e '%s'" % (alfred_2_cmd, alfred_3_cmd)
else:
os_command = 'open -R "%s"' % filepath
else:
os_command = 'open "%s" ' % dir
os.system(os_command)
def pause_all():
server.pauseAll(secret)
notify('All active downloads paused')
def resume_all():
server.unpauseAll(secret)
notify('All paused downloads resumed')
def switch_task(gid):
name = get_task_name(gid)
status = server.tellStatus(secret, gid, ['status'])['status']
if status in ['active', 'waiting']:
server.pause(secret, gid)
notify(title='Download paused:', msg=name, gid=gid)
elif status == 'paused':
server.unpause(secret, gid)
notify(title='Download resumed:', msg=name, gid=gid)
elif status == 'complete':
pass
else:
urls = server.getFiles(secret, gid)[0]['uris']
if urls:
url = urls[0]['uri']
server.addUri(secret, [url])
server.removeDownloadResult(secret, gid)
notify(title='Download resumed:', msg=name, gid=gid)
else:
notify(title='Cannot resume download:', msg=name, gid=gid)
def get_url(gid):
urls = server.getFiles(secret, gid)[0]['uris']
if urls:
url = urls[0]['uri']
notify(title='URL has been copied to clipboard:', msg=url)
print(url, end='')
else:
notify('No URL found')
def add_task(url):
gid = server.addUri(secret, [url])
notify(title='Download added:', msg=url, gid=gid)
def add_bt_task(filepath):
gid = server.addTorrent(secret, xmlrpclib.Binary(open(filepath, mode='rb').read()))
notify(title='BT download added:', msg=os.path.basename(filepath), gid=gid)
def remove_task(gid):
name = get_task_name(gid)
status = server.tellStatus(secret, gid, ['status'])['status']
if status in ['active', 'waiting', 'paused']:
server.remove(secret, gid)
notify(title='Download removed:', msg=name, gid=gid)
server.removeDownloadResult(secret, gid)
def clear_stopped():
server.purgeDownloadResult(secret)
notify('All stopped downloads cleared')
def quit_aria():
server.shutdown(secret)
notify('Aria2 shutting down')
kill_notifier()
def speed_convert(s):
try:
speed = int(s)
m = speed / (1024 * 1024)
k = speed / 1024
if m != 0:
string = '%d MiB/s' % m
elif k != 0:
string = '%d KiB/s' % k
else:
string = '%d Byte/s' % speed
return (s, string)
except:
import re
m = re.match(r'\s*(\d+)\s*(\w+)\s*', s)
if m:
number = m.group(1)
unit = m.group(2)[0]
if unit == 'K' or unit == 'k':
exp = 1
unit = 'KiB/s'
elif unit == 'M' or unit == 'm':
exp = 2
unit = 'MiB/s'
elif unit == 'G' or unit == 'g':
exp = 3
unit = 'GiB/s'
else:
exp = 0
unit = 'Byte/s'
string = '%s %s' % (number, unit)
speed = int(number) * (1024 ** exp)
return (str(speed), string)
else:
return ('0', '0 Byte')
def limit_speed(type, speed):
option = 'max-overall-' + type + '-limit'
speed_value,speed_string = speed_convert(speed)
server.changeGlobalOption(secret, {option: speed_value})
notify('Limit ' + type + ' speed to: ' + speed_string)
def limit_num(num):
server.changeGlobalOption(secret, {'max-concurrent-downloads': num})
notify('Limit concurrent downloads to: ' + num)
def kill_notifier():
with open(wf.cachefile('notifier.pid'), 'r') as pid_file:
pid = pid_file.readline()
os_command = 'pkill -TERM -P ' + pid
os.system(os_command)
def set_rpc(path):
wf.settings['rpc_path'] = path
notify('Set RPC path to: ' + path)
kill_notifier()
def set_secret(str):
wf.settings['secret'] = str
notify('Set RPC secret to: ' + str)
kill_notifier()
def get_help():
os_command = 'open https://github.com/Wildog/Ariafred'
os.system(os_command)
def main(wf):
command = wf.args[0]
if command == '--reveal':
reveal(wf.args[1])
elif command == '--alfred':
reveal(wf.args[1], True)
elif command == '--rm':
remove_task(wf.args[1])
elif command == '--add':
add_task(wf.args[1])
elif command == '--bt':
add_bt_task(wf.args[1])
elif (command == '--pause'
or command == '--resume'
or command == '--switch'):
switch_task(wf.args[1])
elif command == '--pauseall':
pause_all()
elif command == '--resumeall':
resume_all()
elif command == '--clear':
clear_stopped()
elif command == '--url':
get_url(wf.args[1])
elif command == '--rpc-setting':
set_rpc(wf.args[1])
elif command == '--secret-setting':
set_secret(wf.args[1])
elif command == '--run-aria2':
run_aria()
elif command == '--quit':
quit_aria()
elif command == '--help':
get_help()
elif command == '--limit-download':
limit_speed('download', wf.args[1])
elif command == '--limit-upload':
limit_speed('upload', wf.args[1])
elif command == '--limit-num':
limit_num(wf.args[1])
elif command == '--go-rpc-setting':
set_query('aria rpc ')
elif command == '--go-secret-setting':
set_query('aria secret ')
elif command == '--go-active':
set_query('aria active ')
elif command == '--go-stopped':
set_query('aria stopped ')
elif command == '--go-waiting':
set_query('aria waiting ')
elif command == '--go-download-limit-setting':
set_query('aria limit ')
elif command == '--go-upload-limit-setting':
set_query('aria limitup ')
if __name__ == '__main__':
wf = Workflow3()
rpc_path = wf.settings['rpc_path']
server = xmlrpclib.ServerProxy(rpc_path).aria2
secret = 'token:' + wf.settings['secret']
sys.exit(wf.run(main))
|
extra_tests/snippets/name.py
|
dbrgn/RustPython
| 11,058 |
146783
|
#when name.py is run __name__ should equal to __main__
assert __name__ == "__main__"
from import_name import import_func
#__name__ should be set to import_func
import_func()
assert __name__ == "__main__"
|
tests/px_integration_test.py
|
walles/px
| 149 |
146815
|
import os
import sys
from px import px
def test_run_on_pid(capfd):
"""
Just run px on a PID.
The only verification done here is that it doesn't crash,
there is room for improvement...
"""
argv = [
sys.argv[0],
"--no-pager", # Paging causes problems on Travis CI
# Note that px hides our own PID by design, so we look for our
# parent PID in this test.
str(os.getppid()),
]
# Enable manual inspection of the output:
# https://docs.pytest.org/en/latest/capture.html
with capfd.disabled():
px._main(argv)
|
pysph/examples/sloshing/sloshing_tank_pitch.py
|
nauaneed/pysph
| 293 |
146823
|
<reponame>nauaneed/pysph
"""Dam break flow against a tall structure
The case is from "<NAME>, <NAME>,
Sloshing in a three-dimensional rectangular tank:
Numerical simulation and experimental validation,
Ocean Engineering, Volume 33, Issue 16,
2006, Pages 2135-2149, ISSN 0029-8018"
DOI: https://doi.org/10.1016/j.oceaneng.2005.11.001.
pitch angle = 4 deg, roll frequency = 2 rad/s, 75% filled
"""
from math import sin, pi, cos
import os
import numpy as np
# PySPH imports
from pysph.base.utils import get_particle_array
from pysph.base.kernels import CubicSpline
from pysph.solver.solver import Solver
from pysph.solver.application import Application
from pysph.sph.integrator_step import WCSPHStep, IntegratorStep
from pysph.sph.integrator import PECIntegrator
from pysph.sph.equation import Group, Equation
from pysph.sph.scheme import WCSPHScheme
from pysph.examples._db_geometry import DamBreak3DGeometry
Umax = np.sqrt(9.81*0.75*0.62)
c0 = 10.0 * Umax
dx = 0.02
hdx = 1.2
h0 = hdx * dx
tf = 10.0
rho = 1000.0
alpha = 0.1
beta = 0.0
gamma = 7.0
length = 0.92
width = 0.46
height = 0.62
n_layers = 3
theta_0 = 4 * pi/180
omega_r = 2
class PitchingMotion(Equation):
def __init__(self, dest, sources, theta_0, omega_r):
self.theta_0 = theta_0
self.omega_r = omega_r
super(PitchingMotion, self).__init__(dest, sources)
def initialize(self, d_idx, d_au, d_aw, t, d_z, d_x):
theta_0 = self.theta_0
omega_r = self.omega_r
omega = theta_0*omega_r*cos(omega_r*t)
alpha = -theta_0*omega_r*omega_r*sin(omega_r*t)
at_x = d_z[d_idx]*alpha
at_z = -d_x[d_idx]*alpha
ac_x = -d_x[d_idx]*omega*omega
ac_z = -d_z[d_idx]*omega*omega
d_au[d_idx] = at_x + ac_x
d_aw[d_idx] = at_z + ac_z
class OneStageRigidBodyStep(IntegratorStep):
def initialize(self, d_idx, d_x, d_y, d_z, d_x0, d_y0, d_z0,
d_u, d_v, d_w, d_u0, d_v0, d_w0, d_rho, d_rho0):
d_u0[d_idx] = d_u[d_idx]
d_v0[d_idx] = d_v[d_idx]
d_w0[d_idx] = d_w[d_idx]
d_x0[d_idx] = d_x[d_idx]
d_y0[d_idx] = d_y[d_idx]
d_z0[d_idx] = d_z[d_idx]
d_rho0[d_idx] = d_rho[d_idx]
def stage1(self, d_idx, d_x, d_y, d_z, d_x0, d_y0, d_z0,
d_u, d_v, d_w, d_u0, d_v0, d_w0, d_au, d_av, d_aw,
dt, d_rho0, d_arho, d_rho):
d_rho[d_idx] = d_rho0[d_idx] + dt * 0.5 * d_arho[d_idx]
def stage2(self, d_idx, d_x, d_y, d_z, d_x0, d_y0, d_z0,
d_u, d_v, d_w, d_u0, d_v0, d_w0, d_au, d_av, d_aw,
dt, d_rho0, d_arho, d_rho):
# update velocities
d_u[d_idx] += dt * d_au[d_idx]
d_v[d_idx] += dt * d_av[d_idx]
d_w[d_idx] += dt * d_aw[d_idx]
# update positions using time-centered velocity
d_x[d_idx] += dt * 0.5 * (d_u[d_idx] + d_u0[d_idx])
d_y[d_idx] += dt * 0.5 * (d_v[d_idx] + d_v0[d_idx])
d_z[d_idx] += dt * 0.5 * (d_w[d_idx] + d_w0[d_idx])
d_rho[d_idx] = d_rho0[d_idx] + dt * d_arho[d_idx]
class SloshingTankPitch(Application):
def add_user_options(self, group):
interp_methods = ['shepard', 'sph', 'order1']
group.add_argument(
'--dx', action='store', type=float, dest='dx', default=dx,
help='Particle spacing.'
)
group.add_argument(
'--hdx', action='store', type=float, dest='hdx', default=hdx,
help='Specify the hdx factor where h = hdx * dx.'
)
group.add_argument(
'--interp-method', action="store", type=str, dest='interp_method',
default='shepard', help="Specify the interpolation method.",
choices=interp_methods
)
def consume_user_options(self):
self.hdx = self.options.hdx
self.dx = self.options.dx
self.h0 = self.hdx * self.dx
self.interp_method = self.options.interp_method
def create_particles(self):
geom = DamBreak3DGeometry(
container_height=height, container_width=width,
container_length=length, fluid_column_height=height*0.75,
fluid_column_width=width, fluid_column_length=length,
nboundary_layers=n_layers, with_obstacle=False,
dx=self.dx, hdx=self.hdx, rho0=rho
)
[fluid, boundary] = geom.create_particles()
fluid.x = fluid.x - length*0.5
boundary.x = boundary.x - length*0.5
# Setting up intital velocity of the tank
omega0 = theta_0 * omega_r
boundary.u, boundary.w = boundary.z*omega0, -boundary.x*omega0
self.scheme.setup_properties([fluid, boundary])
particles = [fluid, boundary]
return particles
def create_solver(self):
kernel = CubicSpline(dim=3)
integrator = PECIntegrator(fluid=WCSPHStep(),
boundary=OneStageRigidBodyStep())
dt = 0.125 * self.h0 / c0
self.scheme.configure(h0=self.h0, hdx=self.hdx)
solver = Solver(kernel=kernel, dim=3, integrator=integrator,
tf=tf, dt=dt, adaptive_timestep=True,
fixed_h=False)
return solver
def create_scheme(self):
s = WCSPHScheme(
['fluid'], ['boundary'], dim=3, rho0=rho, c0=c0,
h0=h0, hdx=hdx, gz=-9.81, alpha=alpha,
beta=beta, gamma=gamma, hg_correction=True,
tensile_correction=False, delta_sph=True
)
return s
def create_equations(self):
eqns = self.scheme.get_equations()
equation_1 = Group(
equations=[
PitchingMotion(
dest='boundary', sources=None,
theta_0=theta_0, omega_r=omega_r),
], real=False
)
eqns.insert(0, equation_1)
return eqns
def create_tools(self):
tools = []
from pysph.solver.tools import DensityCorrection
rho_corr = DensityCorrection(self, ['fluid', 'boundary'],
corr="shepard", freq=10,
kernel=CubicSpline)
tools.append(rho_corr)
return tools
def post_process(self, info_fname):
self.read_info(info_fname)
if len(self.output_files) == 0:
return
from pysph.solver.utils import iter_output
import matplotlib.pyplot as plt
from pysph.examples import st_exp_data as st
from pysph.tools.interpolator import Interpolator
files = self.output_files
t = []
p0 = []
xc0 = 0.0
for sd, arrays1, arrays2 in iter_output(files, "fluid", "boundary"):
t.append(sd["t"])
xc = arrays2.x.mean()
if sd["t"] == 0:
xc0 = xc
# Point 1: Bottom right corner of the tank
# Point 2: Top right corner of the tank
# Point 3: Bottom left corner of the tank
if xc > xc0:
z1 = arrays2.z.min()
x2 = arrays2.x.max()
x1 = arrays2.x[np.where(arrays2.z == z1)[0][0]]
z2 = arrays2.x[np.where(arrays2.x == x2)[0][0]]
angle = np.arctan((z2-z1)/(x2-x1))
x3 = arrays2.x.min()
z3 = arrays2.z[np.where(arrays2.x == x3)[0][0]]
if xc <= xc0:
z2 = arrays2.z.max()
x1 = arrays2.x.max()
x2 = arrays2.x[np.where(arrays2.z == z2)[0][0]]
z1 = arrays2.z[np.where(arrays2.x == x1)[0][0]]
angle = np.arctan((z2-z1)/(x2-x1)) + pi
z3 = arrays2.z.min()
x3 = arrays2.x[np.where(arrays2.z == z3)[0][0]]
if x3-x1 == 0:
vec = np.array([-1, 0])
else:
vec = np.array([x3-x1, z3-z1])
vec = vec/np.linalg.norm(vec)
dx = self.dx
# Probes at 0.17 m above Point 1 and 0.45 m above Point 3
x_probe = [x1 + 0.17*cos(angle) + 3.25*dx*vec[0], x3 + 0.45*cos(angle) - 3.25*dx*vec[0]]
z_probe = [z1 + 0.17*sin(angle) + 3.25*dx*vec[1], z3 + 0.45*sin(angle) - 3.25*dx*vec[1]]
y_probe = [0, 0]
interp = Interpolator([arrays1, arrays2], x=x_probe,
y=y_probe, z=z_probe,
method=self.interp_method)
p0.append(interp.interpolate('p'))
p0 = np.array(p0)
p2 = p0.T[0]/1000
p8 = p0.T[1]/1000
p2_avg, p8_avg = p2, p8
fname = os.path.join(self.output_dir, 'results.npz')
t, p0 = list(map(np.asarray, (t, p0)))
np.savez(fname, t=t, p0=p0)
exp_t2, exp_p2, exp_t8, exp_p8 = st.get_au_pitch_data()
figure_1 = plt.figure()
# Probe 2
plt.plot(t[:-10], p2_avg[:-10], label="Computed", figure=figure_1)
plt.scatter(exp_t2, exp_p2, color=(0, 0, 0),
label="Experiment (Akyildiz and Unal, 2006)",
figure=figure_1)
plt.title("P2 v/s t")
plt.legend()
plt.ylabel("Pressue [KPa]")
plt.xlabel("Time [s]")
plt.xlim(3, 10)
plt.savefig(os.path.join(self.output_dir, 'p2_vs_t.png'))
plt.show()
figure_2 = plt.figure()
# Probe 8
plt.plot(t, p8_avg, label="Computed", figure=figure_2)
plt.scatter(exp_t8, exp_p8, color=(0, 0, 0),
label="Experiment (Akyildiz and Unal, 2006)",
figure=figure_2)
plt.title("P8 v/s t")
plt.legend()
plt.ylabel("Pressue [KPa]")
plt.xlabel("Time [s]")
plt.xlim(3, 10)
plt.savefig(os.path.join(self.output_dir, 'p8_vs_t.png'))
plt.show()
if __name__ == '__main__':
app = SloshingTankPitch()
app.run()
app.post_process(app.info_filename)
|
paperboy/resources/login.py
|
chris-aeviator/paperboy
| 233 |
146825
|
import falcon
import jinja2
from .base import BaseResource
from .html import read
class LoginResource(BaseResource):
'''Falcon resource for user authentication'''
auth_required = False
def __init__(self, *args, **kwargs):
super(LoginResource, self).__init__(*args, **kwargs)
def on_get(self, req, resp):
'''Get login page'''
resp.content_type = 'text/html'
file = read('login.html')
tpl = jinja2.Template(file).render(baseurl=self.config.baseurl,
apiurl=self.config.apiurl,
loginurl=self.config.loginurl,
include_register=self.config.include_register,
registerurl=self.config.registerurl,
include_password=self.config.include_password)
resp.body = tpl
def on_post(self, req, resp):
'''Log user in using authentication backend'''
token = self.db.users.login(None, req.params, self.session)
user = self.db.users.detail(token, req.params, self.session)
if token and user:
# setup token and set auth cookie
req.context['auth_token'] = token
req.context['user'] = user
resp.set_cookie('auth_token', token, max_age=self.config.token_timeout, path='/', secure=not self.config.http)
resp.status = falcon.HTTP_302
resp.set_header('Location', self.config.baseurl)
else:
# rerender login page
resp.content_type = 'text/html'
file = read('login.html')
tpl = jinja2.Template(file).render(baseurl=self.config.baseurl,
apiurl=self.config.apiurl,
loginurl=self.config.loginurl,
include_register=self.config.include_register,
registerurl=self.config.registerurl,
include_password=self.config.include_password)
resp.body = tpl
|
third_party/blink/tools/move_blink_source.py
|
zipated/src
| 2,151 |
146849
|
#!/usr/bin/env vpython
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tool to move Blink source from third_party/WebKit to third_party/blink.
See https://docs.google.com/document/d/1l3aPv1Wx__SpRkdOhvJz8ciEGigNT3wFKv78XiuW0Tw/edit?usp=sharing#heading=h.o225wrxp242h
for the details.
"""
import argparse
import logging
import os
import platform
import re
import sys
from functools import partial
sys.path.append(os.path.join(os.path.dirname(__file__),
'..', 'renderer', 'build', 'scripts'))
from blinkbuild.name_style_converter import NameStyleConverter
from blinkpy.common.checkout.git import Git
from blinkpy.common.path_finder import get_chromium_src_dir
from blinkpy.common.path_finder import get_blink_tools_dir
from blinkpy.common.system.executive import Executive
from blinkpy.common.system.executive import ScriptError
from blinkpy.common.system.filesystem import FileSystem
from blinkpy.common.system.platform_info import PlatformInfo
from plan_blink_move import plan_blink_move
from plan_blink_move import relative_dest
_log = logging.getLogger('move_blink_source')
class FileType(object):
NONE = 0
BUILD = 1
BLINK_BUILD = 2
OWNERS = 3
DEPS = 4
MOJOM = 5
TYPEMAP = 6
BLINK_BUILD_PY = 7
LAYOUT_TESTS_WITH_MOJOM = 8
BLINK_DEPS = 9
@staticmethod
def detect(path):
slash_dir, basename = os.path.split(path)
slash_dir = slash_dir.replace(os.path.sep, '/')
if basename == 'DEPS':
if 'third_party/WebKit' in path:
return FileType.BLINK_DEPS
return FileType.DEPS
if basename == 'OWNERS':
return FileType.OWNERS
if basename.endswith('.mojom'):
return FileType.MOJOM
if basename.endswith('.typemap'):
return FileType.TYPEMAP
if basename.endswith('.py') and 'third_party/WebKit/Source/build' in slash_dir:
return FileType.BLINK_BUILD_PY
if basename.endswith(('.gn', '.gni')):
if 'third_party/WebKit' in path or 'third_party/blink' in slash_dir:
return FileType.BLINK_BUILD
if 'third_party' in slash_dir:
return FileType.NONE
return FileType.BUILD
if basename.endswith('.html') and re.search(
r'third_party/WebKit/LayoutTests/('
r'fast/dom/shadow|'
r'fast/forms/color|'
r'geolocation-api|'
r'http/tests/budget|'
r'http/tests/credentialmanager|'
r'http/tests/security/powerfulFeatureRestrictions|'
r'installedapp|'
r'media/mediasession|'
r'payments|'
r'presentation|'
r'reporting-observer|'
r'webshare)', slash_dir):
return FileType.LAYOUT_TESTS_WITH_MOJOM
return FileType.NONE
class MoveBlinkSource(object):
def __init__(self, fs, options, repo_root):
self._fs = fs
self._platform = PlatformInfo(sys, platform, fs, Executive())
self._options = options
_log.debug(options)
self._repo_root = repo_root
# The following fields are initialized in _create_basename_maps.
self._basename_map = None
self._basename_re_list = None
self._idl_generated_impl_headers = None
# _checked_in_header_re_list is used to distinguish checked-in
# header files and generated header files.
self._checked_in_header_re_list = None
self._updated_files = []
def update(self, apply_only=None):
"""Updates contents of files affected by Blink source move.
Args:
apply_only: If it's None, updates all affected files. Otherwise,
it should be a set of file paths and this function updates
only the files in |apply_only|.
"""
_log.info('Planning renaming ...')
file_pairs = plan_blink_move(self._fs, [])
self._create_basename_maps(file_pairs)
dirs = self._update_file_content(apply_only)
# Updates #includes in files in directories with updated DEPS +
# third_party/WebKit/{Source,common,public}.
self._append_unless_upper_dir_exists(dirs, self._fs.join(self._repo_root, 'third_party', 'WebKit', 'Source'))
self._append_unless_upper_dir_exists(dirs, self._fs.join(self._repo_root, 'third_party', 'WebKit', 'common'))
self._append_unless_upper_dir_exists(dirs, self._fs.join(self._repo_root, 'third_party', 'WebKit', 'public'))
self._append_unless_upper_dir_exists(dirs, self._fs.join(self._repo_root, 'mojo', 'public', 'tools',
'bindings', 'generators', 'cpp_templates'))
self._update_cpp_includes_in_directories(dirs, apply_only)
# Content update for individual files.
# The following is a list of tuples.
# Tuple: (<file path relative to repo root>, [replacement commands])
# Command: a callable object, or
# a tuple of (<original string>, <new string>).
file_replacement_list = [
('DEPS',
[('src/third_party/WebKit/Source/devtools',
'src/third_party/blink/renderer/devtools')]),
('WATCHLISTS',
[('third_party/WebKit/Source', 'third_party/blink/renderer'),
('third_party/WebKit/public', 'third_party/blink/public')]),
('build/check_gn_headers_whitelist.txt',
[('third_party/WebKit/Source', 'third_party/blink/renderer'),
('third_party/WebKit/public', 'third_party/blink/public'),
self._update_basename]),
('chrome/browser/resources/chromeos/chromevox/tools/jsbundler.py',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('testing/buildbot/gn_isolate_map.pyl',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('third_party/WebKit/Source/BUILD.gn',
[('$root_gen_dir/third_party/WebKit',
'$root_gen_dir/third_party/blink')]),
('third_party/WebKit/Source/config.gni',
[('snake_case_source_files = false',
'snake_case_source_files = true')]),
('third_party/WebKit/Source/core/css/CSSProperties.json5',
[self._update_basename]),
('third_party/WebKit/Source/core/css/ComputedStyleExtraFields.json5',
[self._update_basename]),
('third_party/WebKit/Source/core/css/ComputedStyleFieldAliases.json5',
[self._update_basename]),
('third_party/WebKit/Source/core/html/parser/create-html-entity-table',
[self._update_basename]),
('third_party/WebKit/Source/core/inspector/inspector_protocol_config.json',
[self._update_basename]),
('third_party/WebKit/Source/core/probe/CoreProbes.json5',
[self._update_basename]),
('third_party/WebKit/Source/core/testing/InternalSettings.h',
[('InternalSettingsGenerated.h', 'internal_settings_generated.h')]),
('third_party/WebKit/Source/core/testing/Internals.cpp',
[('InternalRuntimeFlags.h', 'internal_runtime_flags.h')]),
('third_party/WebKit/Source/platform/probe/PlatformProbes.json5',
[self._update_basename]),
('third_party/WebKit/Tools/Scripts/audit-non-blink-usage.py',
[('third_party/WebKit/Source', 'third_party/blink/renderer'),
('ls-files third_party/WebKit', 'ls-files third_party/blink')]),
('third_party/WebKit/Tools/Scripts/webkitpy/style/checker.py',
[('Source/', 'renderer/')]),
('third_party/WebKit/public/BUILD.gn',
[('$root_gen_dir/third_party/WebKit',
'$root_gen_dir/third_party/blink')]),
('third_party/WebKit/public/blink_resources.grd',
[('../Source/', '../renderer/')]),
('third_party/blink/tools/compile_devtools_frontend.py',
[('\'WebKit\', \'Source\'', '\'blink\', \'renderer\'')]),
('tools/android/eclipse/.classpath',
[('third_party/WebKit/public', 'third_party/blink/public')]),
('tools/android/loading/cloud/backend/deploy.sh',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('tools/android/loading/emulation_unittest.py',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('tools/android/loading/options.py',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('tools/android/loading/request_track.py',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('tools/cfi/blacklist.txt',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('tools/gritsettings/resource_ids',
[('third_party/WebKit/public', 'third_party/blink/public'),
('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('tools/include_tracer.py',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('tools/metrics/actions/extract_actions.py',
[('third_party/WebKit/Source', 'third_party/blink/renderer')]),
('tools/metrics/histograms/update_editor_commands.py',
[('third_party/WebKit/Source/core/editing/EditorCommand.cpp',
'third_party/blink/renderer/core/editing/editor_command.cc')]),
('tools/metrics/histograms/update_use_counter_css.py',
[('third_party/WebKit/Source/core/frame/UseCounter.cpp',
'third_party/blink/renderer/core/frame/use_counter.cc')]),
('tools/metrics/histograms/update_use_counter_feature_enum.py',
[('third_party/WebKit/public', 'third_party/blink/public')]),
]
for file_path, replacement_list in file_replacement_list:
if not apply_only or file_path in apply_only:
self._update_single_file_content(file_path, replacement_list, should_write=self._options.run)
if self._options.run:
_log.info('Formatting updated %d files ...', len(self._updated_files))
git = self._create_git()
# |git cl format| can't handle too many files at once.
while len(self._updated_files) > 0:
end_index = 100
if end_index > len(self._updated_files):
end_index = len(self._updated_files)
git.run(['cl', 'format'] + self._updated_files[:end_index])
self._updated_files = self._updated_files[end_index:]
if not apply_only:
_log.info('Make a local commit ...')
git.commit_locally_with_message("""The Great Blink mv for source files, part 1.
Update file contents without moving files.
NOAUTOREVERT=true
NOPRESUBMIT=true
NOTREECHECKS=true
Bug: 768828
""")
def move(self, apply_only=None):
"""Move Blink source files.
Args:
apply_only: If it's None, move all affected files. Otherwise,
it should be a set of file paths and this function moves
only the files in |apply_only|.
"""
_log.info('Planning renaming ...')
file_pairs = plan_blink_move(self._fs, [])
if apply_only:
file_pairs = [(src, dest) for (src, dest) in file_pairs
if 'third_party/WebKit/' + src.replace('\\', '/') in apply_only]
_log.info('Will move %d files', len(file_pairs))
git = self._create_git()
files_set = self._get_checked_in_files(git)
for i, (src, dest) in enumerate(file_pairs):
src_from_repo = self._fs.join('third_party', 'WebKit', src)
if src_from_repo.replace('\\', '/') not in files_set:
_log.info('%s is not in the repository', src)
continue
dest_from_repo = self._fs.join('third_party', 'blink', dest)
self._fs.maybe_make_directory(self._repo_root, 'third_party', 'blink', self._fs.dirname(dest))
if self._options.run_git:
git.move(src_from_repo, dest_from_repo)
_log.info('[%d/%d] Git moved %s', i + 1, len(file_pairs), src)
else:
self._fs.move(self._fs.join(self._repo_root, src_from_repo),
self._fs.join(self._repo_root, dest_from_repo))
_log.info('[%d/%d] Moved %s', i + 1, len(file_pairs), src)
if apply_only:
return
self._update_single_file_content(
'build/get_landmines.py',
[('\ndef main', ' print \'The Great Blink mv for source files (crbug.com/768828)\'\n\ndef main')])
_log.info('Run run_bindings_tests.py ...')
Executive().run_command(['python',
self._fs.join(get_blink_tools_dir(), 'run_bindings_tests.py'),
'--reset-results'],
cwd=self._repo_root)
if self._options.run_git:
_log.info('Make a local commit ...')
git.commit_locally_with_message("""The Great Blink mv for source files, part 2.
Move and rename files.
NOAUTOREVERT=true
NOPRESUBMIT=true
NOTREECHECKS=true
Bug: 768828
""")
def fix_branch(self):
git = self._create_git()
status = self._get_local_change_status(git)
if len(status) == 0:
_log.info('No local changes.')
return
modified_files = {f for (s, f) in status if s != 'D'}
deleted_files = {f for (s, f) in status if s == 'D'}
self.update(apply_only=modified_files)
self.move(apply_only=modified_files)
try:
git.commit_locally_with_message('This commit should be squashed.')
except ScriptError:
_log.info('move_blink_source.py modified nothing.')
# TODO(tkent): Show a message about deleted_files.
def _get_local_change_status(self, git):
"""Returns a list of tuples representing local change summary.
Each tuple contains two strings. The first one is file change status
such as "M", "D". See --diff-filter section of git-diff manual page.
The second one is file name relative to the repository top.
"""
base_commit = git.run(['show-branch', '--merge-base', 'master', 'HEAD']).strip()
# Note that file names in the following command result are always
# slash-separated, even on Windows.
status_lines = git.run(['diff', '--name-status', '--no-renames', base_commit]).split('\n')
status_tuple_list = []
for l in status_lines:
items = l.split('\t')
if len(items) == 2:
status_tuple_list.append(tuple(items))
elif len(l) > 0:
_log.warning('Unrecognized diff output: "%s"', l)
return status_tuple_list
def _get_checked_in_files(self, git):
files_text = git.run(['ls-files',
'third_party/WebKit/Source',
'third_party/WebKit/common',
'third_party/WebKit/public'])
return set(files_text.split('\n'))
def _create_basename_maps(self, file_pairs):
basename_map = {}
basenames = []
idl_headers = set()
headers = []
for source, dest in file_pairs:
_, source_base = self._fs.split(source)
_, dest_base = self._fs.split(dest)
# OriginTrialFeaturesForCore.h in bindings/tests/results/modules/
# confuses generated/checked-in detection in _replace_include_path().
if 'bindings/tests' in source.replace('\\', '/'):
continue
if source_base.endswith('.h'):
headers.append(re.escape(source_base))
if source_base == dest_base:
continue
basename_map[source_base] = dest_base
basenames.append(re.escape(source_base))
# IDL sometimes generates implementation files as well as
# binding files. We'd like to update #includes for such files.
if source_base.endswith('.idl'):
source_header = source_base.replace('.idl', '.h')
basename_map[source_header] = dest_base.replace('.idl', '.h')
basenames.append(re.escape(source_header))
idl_headers.add(source_header)
elif source_base.endswith('.proto'):
source_header = source_base.replace('.proto', '.pb.h')
basename_map[source_header] = dest_base.replace('.proto', '.pb.h')
basenames.append(re.escape(source_header))
_log.debug('Rename %d files for snake_case', len(basename_map))
self._basename_map = basename_map
self._idl_generated_impl_headers = idl_headers
self._basename_re_list = []
self._checked_in_header_re_list = []
# Split file names into some chunks to avoid "Regular expression
# code size limit exceeded" on Windows
CHUNK_SIZE = 700
# Generated inspector/protocol/* contains a lot of names duplicated with
# checked-in core files. We don't want to rename them, and don't want to
# replace them in BUILD.gn and #include accidentally.
RE_PREFIX = r'(?<!inspector/protocol/)'
while len(basenames) > 0:
end_index = min(CHUNK_SIZE, len(basenames))
self._basename_re_list.append(re.compile(RE_PREFIX + r'\b(' + '|'.join(basenames[0:end_index]) + ')(?=["\']|$)'))
basenames = basenames[end_index:]
while len(headers) > 0:
end_index = min(CHUNK_SIZE, len(headers))
self._checked_in_header_re_list.append(re.compile(RE_PREFIX + r'\b(' + '|'.join(headers[0:end_index]) + ')$'))
headers = headers[end_index:]
def _shorten_path(self, path):
if path.startswith(self._repo_root):
return path[len(self._repo_root) + 1:]
return path
@staticmethod
def _filter_file(fs, dirname, basename):
return FileType.detect(fs.join(dirname, basename)) != FileType.NONE
def _update_build(self, content):
content = content.replace('//third_party/WebKit/Source', '//third_party/blink/renderer')
content = content.replace('//third_party/WebKit/common', '//third_party/blink/common')
content = content.replace('//third_party/WebKit/public', '//third_party/blink/public')
# export_header_blink exists outside of Blink too.
content = content.replace('export_header_blink = "third_party/WebKit/public/platform/WebCommon.h"',
'export_header_blink = "third_party/blink/public/platform/web_common.h"')
content = content.replace('$root_gen_dir/blink/public', '$root_gen_dir/third_party/blink/public')
content = content.replace('$root_gen_dir/blink', '$root_gen_dir/third_party/blink/renderer')
return content
def _update_blink_build(self, content):
content = self._update_build(content)
# Update visibility=[...]
content = content.replace('//third_party/WebKit/*', '//third_party/blink/*')
content = content.replace('//third_party/WebKit/Source/*', '//third_party/blink/renderer/*')
content = content.replace('//third_party/WebKit/public/*', '//third_party/blink/public/*')
# Update mojom variables
content = content.replace('export_header = "third_party/WebKit/common',
'export_header = "third_party/blink/common')
content = content.replace('export_header_blink = "third_party/WebKit/Source',
'export_header_blink = "third_party/blink/renderer')
# Update buildflag_header() rules
content = content.replace('header_dir = "blink/',
'header_dir = "third_party/blink/renderer/')
return self._update_basename(content)
def _update_owners(self, content):
content = content.replace('//third_party/WebKit/Source', '//third_party/blink/renderer')
content = content.replace('//third_party/WebKit/common', '//third_party/blink/common')
content = content.replace('//third_party/WebKit/public', '//third_party/blink/public')
return content
def _update_deps(self, content):
original_content = content
content = content.replace('third_party/WebKit/Source', 'third_party/blink/renderer')
content = content.replace('third_party/WebKit/common', 'third_party/blink/common')
content = content.replace('third_party/WebKit/public', 'third_party/blink/public')
content = content.replace('third_party/WebKit', 'third_party/blink')
if original_content == content:
return content
return self._update_basename(content)
def _update_blink_deps(self, content):
original_content = content
content = re.sub('(?<=[-+!])public', 'third_party/blink/public', content)
content = re.sub('(?<=[-+!])(bindings|controller|core|modules|platform)',
'third_party/blink/renderer/\\1', content)
content = content.replace('third_party/WebKit', 'third_party/blink')
if original_content == content:
return content
return self._update_basename(content)
def _update_mojom(self, content):
content = content.replace('third_party/WebKit/public', 'third_party/blink/public')
content = content.replace('third_party/WebKit/common', 'third_party/blink/common')
return content
def _update_typemap(self, content):
content = content.replace('//third_party/WebKit/Source', '//third_party/blink/renderer')
content = content.replace('//third_party/WebKit/common', '//third_party/blink/common')
content = content.replace('//third_party/WebKit/public', '//third_party/blink/public')
return self._update_basename(content)
def _update_blink_build_py(self, content):
# We don't prepend 'third_party/blink/renderer/' to matched basenames
# because it won't affect build and manual update after the great mv is
# enough.
return self._update_basename(content)
def _update_layout_tests(self, content):
return content.replace('file:///gen/third_party/WebKit/public/',
'file:///gen/third_party/blink/public/')
def _update_basename(self, content):
for regex in self._basename_re_list:
content = regex.sub(lambda match: self._basename_map[match.group(1)], content)
return content
@staticmethod
def _append_unless_upper_dir_exists(dirs, new_dir):
for i in range(0, len(dirs)):
if new_dir.startswith(dirs[i]):
return
if dirs[i].startswith(new_dir):
dirs[i] = new_dir
return
dirs.append(new_dir)
def _update_file_content(self, apply_only):
_log.info('Find *.gn, *.mojom, *.py, *.typemap, DEPS, and OWNERS ...')
files = self._fs.files_under(
self._repo_root, dirs_to_skip=['.git', 'out'], file_filter=self._filter_file)
_log.info('Scan contents of %d files ...', len(files))
updated_deps_dirs = []
for file_path in files:
file_type = FileType.detect(file_path)
original_content = self._fs.read_text_file(file_path)
content = original_content
if file_type == FileType.BUILD:
content = self._update_build(content)
elif file_type == FileType.BLINK_BUILD:
content = self._update_blink_build(content)
elif file_type == FileType.OWNERS:
content = self._update_owners(content)
elif file_type == FileType.DEPS:
if self._fs.dirname(file_path) == self._repo_root:
_log.debug("Skip //DEPS")
continue
content = self._update_deps(content)
elif file_type == FileType.BLINK_DEPS:
content = self._update_blink_deps(content)
elif file_type == FileType.MOJOM:
content = self._update_mojom(content)
elif file_type == FileType.TYPEMAP:
content = self._update_typemap(content)
elif file_type == FileType.BLINK_BUILD_PY:
content = self._update_blink_build_py(content)
elif file_type == FileType.LAYOUT_TESTS_WITH_MOJOM:
content = self._update_layout_tests(content)
if original_content == content:
continue
if self._options.run and (not apply_only or file_path.replace('\\', '/') in apply_only):
self._fs.write_text_file(file_path, content)
self._updated_files.append(file_path)
_log.info('Updated %s', self._shorten_path(file_path))
if file_type == FileType.DEPS:
self._append_unless_upper_dir_exists(updated_deps_dirs, self._fs.dirname(file_path))
return updated_deps_dirs
def _update_cpp_includes_in_directories(self, dirs, apply_only):
for dirname in dirs:
_log.info('Processing #include in %s ...', self._shorten_path(dirname))
files = self._fs.files_under(
dirname, file_filter=lambda fs, _, basename: basename.endswith(
('.h', '.cc', '.cpp', '.mm', '.cc.tmpl', '.cpp.tmpl',
'.h.tmpl', 'xpath_grammar.y', '.gperf')))
for file_path in files:
posix_file_path = file_path.replace('\\', '/')
if '/third_party/WebKit/Source/bindings/tests/results/' in posix_file_path:
continue
original_content = self._fs.read_text_file(file_path)
content = self._update_cpp_includes(original_content)
if file_path.endswith('.h') and '/third_party/WebKit/public/' in posix_file_path:
content = self._update_basename_only_includes(content, file_path)
if file_path.endswith('.h') and '/third_party/WebKit/' in posix_file_path:
content = self._update_include_guard(content, file_path)
if original_content == content:
continue
if self._options.run and (not apply_only or posix_file_path in apply_only):
self._fs.write_text_file(file_path, content)
self._updated_files.append(file_path)
_log.info('Updated %s', self._shorten_path(file_path))
def _replace_include_path(self, match):
include_or_import = match.group(1)
path = match.group(2)
# If |path| starts with 'blink/public/resources', we should prepend
# 'third_party/'.
#
# If |path| starts with 'third_party/WebKit', we should adjust the
# directory name for third_party/blink, and replace its basename by
# self._basename_map.
#
# If |path| starts with a Blink-internal directory such as bindings,
# core, modules, platform, public, it refers to a checked-in file, or a
# generated file. For the former, we should add 'third_party/blink/' and
# replace the basename. For the latter, we should update the basename
# for a name mapped from an IDL renaming, and should add
# 'third_party/blink/'.
if path.startswith('blink/public/resources'):
path = path.replace('blink/public', 'third_party/blink/public')
return '#%s "%s"' % (include_or_import, path)
if path.startswith('third_party/WebKit'):
path = path.replace('third_party/WebKit/Source', 'third_party/blink/renderer')
path = path.replace('third_party/WebKit/common', 'third_party/blink/common')
path = path.replace('third_party/WebKit/public', 'third_party/blink/public')
path = self._update_basename(path)
return '#%s "%s"' % (include_or_import, path)
match = None
for regex in self._checked_in_header_re_list:
match = regex.search(path)
if match:
break
if match:
if match.group(1) in self._basename_map:
path = path[:match.start(1)] + self._basename_map[match.group(1)]
elif 'core/inspector/protocol/' not in path:
basename_start = path.rfind('/') + 1
basename = path[basename_start:]
if basename in self._idl_generated_impl_headers:
path = path[:basename_start] + self._basename_map[basename]
elif basename.startswith('V8'):
path = path[:basename_start] + NameStyleConverter(basename[:len(basename) - 2]).to_snake_case() + '.h'
if path.startswith('public'):
path = 'third_party/blink/' + path
else:
path = 'third_party/blink/renderer/' + path
return '#%s "%s"' % (include_or_import, path)
def _update_cpp_includes(self, content):
pattern = re.compile(r'#(include|import)\s+"((bindings|controller|core|modules|platform|public|' +
r'third_party/WebKit/(Source|common|public)|blink/public/resources)/[-_\w/.]+)"')
return pattern.sub(self._replace_include_path, content)
def _replace_basename_only_include(self, subdir, source_path, match):
source_basename = match.group(1)
if source_basename in self._basename_map:
return '#include "third_party/blink/public/%s/%s"' % (subdir, self._basename_map[source_basename])
_log.warning('Basename-only %s in %s', match.group(0), self._shorten_path(source_path))
return match.group(0)
def _update_basename_only_includes(self, content, source_path):
if not source_path.endswith('.h') or '/third_party/WebKit/public/' not in source_path.replace('\\', '/'):
return
# In public/ header files, we should replace |#include "WebFoo.h"|
# with |#include "third_party/blink/public/platform-or-web/web_foo.h"|
subdir = self._fs.basename(self._fs.dirname(source_path))
# subdir is 'web' or 'platform'.
return re.sub(r'#include\s+"(\w+\.h)"',
partial(self._replace_basename_only_include, subdir, source_path), content)
def _update_include_guard(self, content, source_path):
current_guard = re.sub(r'[-.]', '_', self._fs.basename(source_path))
new_path = relative_dest(self._fs, self._fs.relpath(
source_path, start=self._fs.join(self._repo_root, 'third_party', 'WebKit')))
new_guard = 'THIRD_PARTY_BLINK_' + re.sub(r'[-\\/.]', '_', new_path.upper()) + '_'
content = re.sub(r'#ifndef\s+(WTF_)?' + current_guard, '#ifndef ' + new_guard, content);
content = re.sub(r'#define\s+(WTF_)?' + current_guard, '#define ' + new_guard, content);
content = re.sub(r'#endif\s+//\s+(WTF_)?' + current_guard, '#endif // ' + new_guard, content);
return content
def _update_single_file_content(self, file_path, replace_list, should_write=True):
full_path = self._fs.join(self._repo_root, file_path)
original_content = self._fs.read_text_file(full_path)
content = original_content
for command in replace_list:
if isinstance(command, tuple):
src, dest = command
content = content.replace(src, dest)
elif callable(command):
content = command(content)
else:
raise TypeError('A tuple or a function is expected.')
if content != original_content:
if should_write:
self._fs.write_text_file(full_path, content)
self._updated_files.append(full_path)
_log.info('Updated %s', file_path)
else:
_log.warning('%s does not contain specified source strings.', file_path)
def _create_git(self):
return Git(cwd=self._repo_root, filesystem=self._fs, platform=self._platform)
def main():
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s %(levelname)s %(name)s] %(message)s',
datefmt='%H:%M:%S')
parser = argparse.ArgumentParser(description='Blink source mover')
sub_parsers = parser.add_subparsers()
update_parser = sub_parsers.add_parser('update')
update_parser.set_defaults(command='update')
update_parser.add_argument('--run', dest='run', action='store_true',
help='Update file contents')
move_parser = sub_parsers.add_parser('move')
move_parser.set_defaults(command='move')
move_parser.add_argument('--git', dest='run_git', action='store_true',
help='Run |git mv| command instead of |mv|.')
fixbranch_parser = sub_parsers.add_parser('fixbranch')
fixbranch_parser.set_defaults(command='fixbranch', run=True, run_git=True)
options = parser.parse_args()
mover = MoveBlinkSource(FileSystem(), options, get_chromium_src_dir())
if options.command == 'update':
mover.update()
elif options.command == 'move':
mover.move()
elif options.command == 'fixbranch':
mover.fix_branch()
if __name__ == '__main__':
main()
|
vimfiles/bundle/vim-python/submodules/pylama/tests/test_core.py
|
ciskoinch8/vimrc
| 463 |
146854
|
import os.path as op
from pylama.check_async import check_async
from pylama.config import parse_options
from pylama.core import filter_errors, parse_modeline, run
from pylama.errors import Error, remove_duplicates
from pylama.hook import git_hook, hg_hook
from pylama.main import shell, check_path
def test_filter_errors():
assert list(filter_errors([Error(text='E1')], select=['E'], ignore=['E101']))
assert not list(filter_errors([Error(text='W1')], select=['W100'], ignore=['W']))
def test_remove_duplicates():
errors = [Error(linter='pycodestyle', text='E701'), Error(linter='pylint', text='C0321')]
errors = list(remove_duplicates(errors))
assert len(errors) == 1
def test_parser_modeline():
code = """
bla bla bla
# pylama: ignore=W12,E14:select=R:skip=0
"""
params = parse_modeline(code)
assert params == dict(ignore='W12,E14', select='R', skip='0')
def test_checkpath():
path = op.abspath('dummy.py')
options = parse_options([path])
result = check_path(options)
assert result
assert result[0].filename == 'dummy.py'
def test_linters_params():
options = parse_options(linters='mccabe', config=False)
options.linters_params['mccabe'] = dict(complexity=1)
errors = run('dummy.py', options=options)
assert len(errors) == 1
options.linters_params['mccabe'] = dict(complexity=20)
errors = run('dummy.py', options=options)
assert not errors
def test_sort():
options = parse_options()
options.sort = ['C', 'D']
errors = run('dummy.py', options=options)
assert errors[0].type == 'C'
def test_shell():
errors = shell('-o dummy dummy.py'.split(), error=False)
assert errors
errors = shell(['unknown.py'], error=False)
assert not errors
def test_git_hook():
assert not git_hook(False)
def test_hg_hook():
assert not hg_hook(None, dict())
def test_async():
options = parse_options(config=False)
errors = check_async(['dummy.py'], options=options, rootdir='.')
assert errors
|
wal_e/worker/gs/__init__.py
|
paalkr/wal-e
| 2,739 |
146868
|
<filename>wal_e/worker/gs/__init__.py
from wal_e.worker.gs.gs_deleter import Deleter
from wal_e.worker.gs.gs_worker import BackupFetcher
from wal_e.worker.gs.gs_worker import BackupList
from wal_e.worker.gs.gs_worker import DeleteFromContext
from wal_e.worker.gs.gs_worker import TarPartitionLister
__all__ = [
'Deleter',
'TarPartitionLister',
'BackupFetcher',
'BackupList',
'DeleteFromContext',
]
|
tencentcloud/tbp/v20190627/models.py
|
PlasticMem/tencentcloud-sdk-python
| 465 |
146869
|
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
from tencentcloud.common.abstract_model import AbstractModel
class Group(AbstractModel):
"""Group是消息组的具体定义,当前包含ContentType、Url、Content三个字段。其中,具体的ContentType字段定义,参考互联网MIME类型标准。
"""
def __init__(self):
r"""
:param ContentType: 消息类型参考互联网MIME类型标准,当前仅支持"text/plain"。
:type ContentType: str
:param Url: 返回内容以链接形式提供。
注意:此字段可能返回 null,表示取不到有效值。
:type Url: str
:param Content: 普通文本。
注意:此字段可能返回 null,表示取不到有效值。
:type Content: str
"""
self.ContentType = None
self.Url = None
self.Content = None
def _deserialize(self, params):
self.ContentType = params.get("ContentType")
self.Url = params.get("Url")
self.Content = params.get("Content")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ResponseMessage(AbstractModel):
"""从TBP-RTS服务v1.3版本起,机器人以消息组列表的形式响应,消息组列表GroupList包含多组消息,用户根据需要对部分或全部消息组进行组合使用。
"""
def __init__(self):
r"""
:param GroupList: 消息组列表。
注意:此字段可能返回 null,表示取不到有效值。
:type GroupList: list of Group
"""
self.GroupList = None
def _deserialize(self, params):
if params.get("GroupList") is not None:
self.GroupList = []
for item in params.get("GroupList"):
obj = Group()
obj._deserialize(item)
self.GroupList.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class SlotInfo(AbstractModel):
"""槽位信息
"""
def __init__(self):
r"""
:param SlotName: 槽位名称
注意:此字段可能返回 null,表示取不到有效值。
:type SlotName: str
:param SlotValue: 槽位值
注意:此字段可能返回 null,表示取不到有效值。
:type SlotValue: str
"""
self.SlotName = None
self.SlotValue = None
def _deserialize(self, params):
self.SlotName = params.get("SlotName")
self.SlotValue = params.get("SlotValue")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class TextProcessRequest(AbstractModel):
"""TextProcess请求参数结构体
"""
def __init__(self):
r"""
:param BotId: 机器人标识,用于定义抽象机器人。
:type BotId: str
:param BotEnv: 机器人版本,取值"dev"或"release",{调试版本:dev;线上版本:release}。
:type BotEnv: str
:param TerminalId: 终端标识,每个终端(或线程)对应一个,区分并发多用户。
:type TerminalId: str
:param InputText: 请求的文本。
:type InputText: str
:param SessionAttributes: 透传字段,透传给用户自定义的WebService服务。
:type SessionAttributes: str
:param PlatformType: 平台类型,{小程序:MiniProgram;小微:XiaoWei;公众号:OfficialAccount;企业微信: WXWork}。
:type PlatformType: str
:param PlatformId: 当PlatformType为微信公众号或企业微信时,传递对应微信公众号或企业微信的唯一标识
:type PlatformId: str
"""
self.BotId = None
self.BotEnv = None
self.TerminalId = None
self.InputText = None
self.SessionAttributes = None
self.PlatformType = None
self.PlatformId = None
def _deserialize(self, params):
self.BotId = params.get("BotId")
self.BotEnv = params.get("BotEnv")
self.TerminalId = params.get("TerminalId")
self.InputText = params.get("InputText")
self.SessionAttributes = params.get("SessionAttributes")
self.PlatformType = params.get("PlatformType")
self.PlatformId = params.get("PlatformId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class TextProcessResponse(AbstractModel):
"""TextProcess返回参数结构体
"""
def __init__(self):
r"""
:param DialogStatus: 当前会话状态{会话开始: START; 会话中: COUTINUE; 会话结束: COMPLETE}。
注意:此字段可能返回 null,表示取不到有效值。
:type DialogStatus: str
:param BotName: 匹配到的机器人名称。
注意:此字段可能返回 null,表示取不到有效值。
:type BotName: str
:param IntentName: 匹配到的意图名称。
注意:此字段可能返回 null,表示取不到有效值。
:type IntentName: str
:param SlotInfoList: 槽位信息。
注意:此字段可能返回 null,表示取不到有效值。
:type SlotInfoList: list of SlotInfo
:param InputText: 原始的用户说法。
注意:此字段可能返回 null,表示取不到有效值。
:type InputText: str
:param ResponseMessage: 机器人应答。
注意:此字段可能返回 null,表示取不到有效值。
:type ResponseMessage: :class:`tencentcloud.tbp.v20190627.models.ResponseMessage`
:param SessionAttributes: 透传字段,由用户自定义的WebService服务返回。
注意:此字段可能返回 null,表示取不到有效值。
:type SessionAttributes: str
:param ResultType: 结果类型 {中间逻辑出错:0; 任务型机器人:1; 问答型机器人:2; 闲聊型机器人:3; 未匹配上,返回预设兜底话术:5; 未匹配上,返回相似问题列表:6}。
注意:此字段可能返回 null,表示取不到有效值。
:type ResultType: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DialogStatus = None
self.BotName = None
self.IntentName = None
self.SlotInfoList = None
self.InputText = None
self.ResponseMessage = None
self.SessionAttributes = None
self.ResultType = None
self.RequestId = None
def _deserialize(self, params):
self.DialogStatus = params.get("DialogStatus")
self.BotName = params.get("BotName")
self.IntentName = params.get("IntentName")
if params.get("SlotInfoList") is not None:
self.SlotInfoList = []
for item in params.get("SlotInfoList"):
obj = SlotInfo()
obj._deserialize(item)
self.SlotInfoList.append(obj)
self.InputText = params.get("InputText")
if params.get("ResponseMessage") is not None:
self.ResponseMessage = ResponseMessage()
self.ResponseMessage._deserialize(params.get("ResponseMessage"))
self.SessionAttributes = params.get("SessionAttributes")
self.ResultType = params.get("ResultType")
self.RequestId = params.get("RequestId")
class TextResetRequest(AbstractModel):
"""TextReset请求参数结构体
"""
def __init__(self):
r"""
:param BotId: 机器人标识,用于定义抽象机器人。
:type BotId: str
:param BotEnv: 机器人版本,取值"dev"或"release",{调试版本:dev;线上版本:release}。
:type BotEnv: str
:param TerminalId: 终端标识,每个终端(或线程)对应一个,区分并发多用户。
:type TerminalId: str
:param PlatformType: 平台类型,{小程序:MiniProgram;小微:XiaoWei;公众号:OfficialAccount;企业微信: WXWork}。
:type PlatformType: str
:param PlatformId: 当PlatformType为微信公众号或企业微信时,传递对应微信公众号或企业微信的唯一标识
:type PlatformId: str
"""
self.BotId = None
self.BotEnv = None
self.TerminalId = None
self.PlatformType = None
self.PlatformId = None
def _deserialize(self, params):
self.BotId = params.get("BotId")
self.BotEnv = params.get("BotEnv")
self.TerminalId = params.get("TerminalId")
self.PlatformType = params.get("PlatformType")
self.PlatformId = params.get("PlatformId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class TextResetResponse(AbstractModel):
"""TextReset返回参数结构体
"""
def __init__(self):
r"""
:param DialogStatus: 当前会话状态{会话开始: START; 会话中: COUTINUE; 会话结束: COMPLETE}。
注意:此字段可能返回 null,表示取不到有效值。
:type DialogStatus: str
:param BotName: 匹配到的机器人名称。
注意:此字段可能返回 null,表示取不到有效值。
:type BotName: str
:param IntentName: 匹配到的意图名称。
注意:此字段可能返回 null,表示取不到有效值。
:type IntentName: str
:param SlotInfoList: 槽位信息。
注意:此字段可能返回 null,表示取不到有效值。
:type SlotInfoList: list of SlotInfo
:param InputText: 原始的用户说法。
注意:此字段可能返回 null,表示取不到有效值。
:type InputText: str
:param ResponseMessage: 机器人应答。
注意:此字段可能返回 null,表示取不到有效值。
:type ResponseMessage: :class:`tencentcloud.tbp.v20190627.models.ResponseMessage`
:param SessionAttributes: 透传字段,由用户自定义的WebService服务返回。
注意:此字段可能返回 null,表示取不到有效值。
:type SessionAttributes: str
:param ResultType: 结果类型 {中间逻辑出错:0; 任务型机器人:1; 问答型机器人:2; 闲聊型机器人:3; 未匹配上,返回预设兜底话术:5; 未匹配上,返回相似问题列表:6}。
注意:此字段可能返回 null,表示取不到有效值。
:type ResultType: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DialogStatus = None
self.BotName = None
self.IntentName = None
self.SlotInfoList = None
self.InputText = None
self.ResponseMessage = None
self.SessionAttributes = None
self.ResultType = None
self.RequestId = None
def _deserialize(self, params):
self.DialogStatus = params.get("DialogStatus")
self.BotName = params.get("BotName")
self.IntentName = params.get("IntentName")
if params.get("SlotInfoList") is not None:
self.SlotInfoList = []
for item in params.get("SlotInfoList"):
obj = SlotInfo()
obj._deserialize(item)
self.SlotInfoList.append(obj)
self.InputText = params.get("InputText")
if params.get("ResponseMessage") is not None:
self.ResponseMessage = ResponseMessage()
self.ResponseMessage._deserialize(params.get("ResponseMessage"))
self.SessionAttributes = params.get("SessionAttributes")
self.ResultType = params.get("ResultType")
self.RequestId = params.get("RequestId")
|
app/build/pip/debug/common/pyquery/text.py
|
hjlogzw/CrawlOnAndroid
| 1,758 |
146879
|
import re
# https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements#Elements
INLINE_TAGS = {
'a', 'abbr', 'acronym', 'b', 'bdo', 'big', 'br', 'button', 'cite',
'code', 'dfn', 'em', 'i', 'img', 'input', 'kbd', 'label', 'map',
'object', 'q', 'samp', 'script', 'select', 'small', 'span', 'strong',
'sub', 'sup', 'textarea', 'time', 'tt', 'var'
}
SEPARATORS = {'br'}
# Definition of whitespace in HTML:
# https://www.w3.org/TR/html4/struct/text.html#h-9.1
WHITESPACE_RE = re.compile(u'[\x20\x09\x0C\u200B\x0A\x0D]+')
def squash_html_whitespace(text):
# use raw extract_text for preformatted content (like <pre> content or set
# by CSS rules)
# apply this function on top of
return WHITESPACE_RE.sub(' ', text)
def _squash_artifical_nl(parts):
output, last_nl = [], False
for x in parts:
if x is not None:
output.append(x)
last_nl = False
elif not last_nl:
output.append(None)
last_nl = True
return output
def _strip_artifical_nl(parts):
if not parts:
return parts
for start_idx, pt in enumerate(parts):
if isinstance(pt, str):
# 0, 1, 2, index of first string [start_idx:...
break
iterator = enumerate(parts[:start_idx - 1 if start_idx > 0 else None:-1])
for end_idx, pt in iterator:
if isinstance(pt, str): # 0=None, 1=-1, 2=-2, index of last string
break
return parts[start_idx:-end_idx if end_idx > 0 else None]
def _merge_original_parts(parts):
output, orp_buf = [], []
def flush():
if orp_buf:
item = squash_html_whitespace(''.join(orp_buf)).strip()
if item:
output.append(item)
orp_buf[:] = []
for x in parts:
if not isinstance(x, str):
flush()
output.append(x)
else:
orp_buf.append(x)
flush()
return output
def extract_text_array(dom, squash_artifical_nl=True, strip_artifical_nl=True):
if callable(dom.tag):
return ''
r = []
if dom.tag in SEPARATORS:
r.append(True) # equivalent of '\n' used to designate separators
elif dom.tag not in INLINE_TAGS:
# equivalent of '\n' used to designate artifically inserted newlines
r.append(None)
if dom.text is not None:
r.append(dom.text)
for child in dom.getchildren():
r.extend(extract_text_array(child, squash_artifical_nl=False,
strip_artifical_nl=False))
if child.tail is not None:
r.append(child.tail)
if dom.tag not in INLINE_TAGS and dom.tag not in SEPARATORS:
# equivalent of '\n' used to designate artifically inserted newlines
r.append(None)
if squash_artifical_nl:
r = _squash_artifical_nl(r)
if strip_artifical_nl:
r = _strip_artifical_nl(r)
return r
def extract_text(dom, block_symbol='\n', sep_symbol='\n', squash_space=True):
a = extract_text_array(dom, squash_artifical_nl=squash_space)
if squash_space:
a = _strip_artifical_nl(_squash_artifical_nl(_merge_original_parts(a)))
result = ''.join(
block_symbol if x is None else (
sep_symbol if x is True else x
)
for x in a
)
if squash_space:
result = result.strip()
return result
|
plenum/test/node_catchup_with_3pc/test_catchup_with_skipped_commits.py
|
andkononykhin/plenum
| 148 |
146886
|
<reponame>andkononykhin/plenum<filename>plenum/test/node_catchup_with_3pc/test_catchup_with_skipped_commits.py
from logging import getLogger
from typing import Iterable
import pytest
from plenum.common.constants import DOMAIN_LEDGER_ID, AUDIT_LEDGER_ID
from plenum.common.messages.node_messages import Commit
from plenum.common.util import compare_3PC_keys
from plenum.server.catchup.node_leecher_service import NodeLeecherService
from plenum.test.delayers import cr_delay, delay_3pc
from plenum.test.helper import sdk_send_random_and_check, sdk_send_random_requests, sdk_get_and_check_replies, \
max_3pc_batch_limits
from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data
from plenum.test.stasher import delay_rules, start_delaying, stop_delaying_and_process
from stp_core.loop.eventually import eventually
logger = getLogger()
@pytest.fixture(scope="module")
def tconf(tconf):
with max_3pc_batch_limits(tconf, size=1) as tconf:
yield tconf
def test_catchup_with_skipped_commits(tdir, tconf,
looper,
txnPoolNodeSet,
sdk_pool_handle,
sdk_wallet_client):
lagging_node = txnPoolNodeSet[-1]
lagging_stasher = lagging_node.nodeIbStasher
other_nodes = txnPoolNodeSet[:-1]
other_stashers = [node.nodeIbStasher for node in other_nodes]
def lagging_node_state() -> NodeLeecherService.State:
return lagging_node.ledgerManager._node_leecher._state
def check_lagging_node_is_not_syncing_audit():
assert lagging_node_state() != NodeLeecherService.State.SyncingAudit
def check_lagging_node_done_catchup():
assert lagging_node_state() == NodeLeecherService.State.Idle
def check_nodes_ordered_till(nodes: Iterable, view_no: int, pp_seq_no: int):
for node in nodes:
assert compare_3PC_keys((view_no, pp_seq_no), node.master_replica.last_ordered_3pc) >= 0
# Preload nodes with some transactions
sdk_send_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client, 1)
for node in txnPoolNodeSet:
assert node.master_replica.last_ordered_3pc == (0, 1)
# Setup delayers
lagging_mid_commits = start_delaying(lagging_stasher, delay_3pc(after=3, before=6, msgs=Commit))
others_mid_commits = start_delaying(other_stashers, delay_3pc(after=3, before=6, msgs=Commit))
start_delaying(lagging_stasher, delay_3pc(before=4, msgs=Commit))
# Send more requests
reqs = sdk_send_random_requests(looper, sdk_pool_handle, sdk_wallet_client, 6)
# Wait until pool ordered till (0, 3)
looper.run(eventually(check_nodes_ordered_till, other_nodes, 0, 3))
assert lagging_node.master_replica.last_ordered_3pc == (0, 1)
with delay_rules(lagging_stasher, delay_catchup(DOMAIN_LEDGER_ID)):
with delay_rules(lagging_stasher, delay_catchup(AUDIT_LEDGER_ID)):
# Start catchup
lagging_node.start_catchup()
looper.runFor(0.5)
assert lagging_node_state() == NodeLeecherService.State.SyncingAudit
# Process missing commits on lagging node
stop_delaying_and_process(lagging_mid_commits)
looper.runFor(0.5)
# Allow to catchup audit ledger
looper.run(eventually(check_lagging_node_is_not_syncing_audit))
stop_delaying_and_process(others_mid_commits)
# Ensure that audit ledger is caught up by lagging node
looper.run(eventually(check_lagging_node_done_catchup))
# Ensure that all requests were ordered
sdk_get_and_check_replies(looper, reqs)
# Ensure that all nodes will eventually have same data
ensure_all_nodes_have_same_data(looper, txnPoolNodeSet)
def delay_catchup(ledger_id: int):
_delayer = cr_delay(ledger_filter=ledger_id)
_delayer.__name__ = "delay_catchup({})".format(ledger_id)
return _delayer
|
algorithms/PPO/train_PPO.py
|
borgwang/reinforce_py
| 119 |
146916
|
import os
import time
import logger
import random
import tensorflow as tf
import gym
import numpy as np
from collections import deque
from config import args
from utils import set_global_seeds, sf01, explained_variance
from agent import PPO
from env_wrapper import make_env
def main():
env = make_env()
set_global_seeds(env, args.seed)
agent = PPO(env=env)
batch_steps = args.n_envs * args.batch_steps # number of steps per update
if args.save_interval and logger.get_dir():
# some saving jobs
pass
ep_info_buffer = deque(maxlen=100)
t_train_start = time.time()
n_updates = args.n_steps // batch_steps
runner = Runner(env, agent)
for update in range(1, n_updates + 1):
t_start = time.time()
frac = 1.0 - (update - 1.0) / n_updates
lr_now = args.lr # maybe dynamic change
clip_range_now = args.clip_range # maybe dynamic change
obs, returns, masks, acts, vals, neglogps, advs, rewards, ep_infos = \
runner.run(args.batch_steps, frac)
ep_info_buffer.extend(ep_infos)
loss_infos = []
idxs = np.arange(batch_steps)
for _ in range(args.n_epochs):
np.random.shuffle(idxs)
for start in range(0, batch_steps, args.minibatch):
end = start + args.minibatch
mb_idxs = idxs[start: end]
minibatch = [arr[mb_idxs] for arr in [obs, returns, masks, acts, vals, neglogps, advs]]
loss_infos.append(agent.train(lr_now, clip_range_now, *minibatch))
t_now = time.time()
time_this_batch = t_now - t_start
if update % args.log_interval == 0:
ev = float(explained_variance(vals, returns))
logger.logkv('updates', str(update) + '/' + str(n_updates))
logger.logkv('serial_steps', update * args.batch_steps)
logger.logkv('total_steps', update * batch_steps)
logger.logkv('time', time_this_batch)
logger.logkv('fps', int(batch_steps / (t_now - t_start)))
logger.logkv('total_time', t_now - t_train_start)
logger.logkv("explained_variance", ev)
logger.logkv('avg_reward', np.mean([e['r'] for e in ep_info_buffer]))
logger.logkv('avg_ep_len', np.mean([e['l'] for e in ep_info_buffer]))
logger.logkv('adv_mean', np.mean(returns - vals))
logger.logkv('adv_variance', np.std(returns - vals)**2)
loss_infos = np.mean(loss_infos, axis=0)
for loss_name, loss_info in zip(agent.loss_names, loss_infos):
logger.logkv(loss_name, loss_info)
logger.dumpkvs()
if args.save_interval and update % args.save_interval == 0 and logger.get_dir():
pass
env.close()
class Runner:
def __init__(self, env, agent):
self.env = env
self.agent = agent
self.obs = np.zeros((args.n_envs,) + env.observation_space.shape, dtype=np.float32)
self.obs[:] = env.reset()
self.dones = [False for _ in range(args.n_envs)]
def run(self, batch_steps, frac):
b_obs, b_rewards, b_actions, b_values, b_dones, b_neglogps = [], [], [], [], [], []
ep_infos = []
for s in range(batch_steps):
actions, values, neglogps = self.agent.step(self.obs, self.dones)
b_obs.append(self.obs.copy())
b_actions.append(actions)
b_values.append(values)
b_neglogps.append(neglogps)
b_dones.append(self.dones)
self.obs[:], rewards, self.dones, infos = self.env.step(actions)
for info in infos:
maybeinfo = info.get('episode')
if maybeinfo:
ep_infos.append(maybeinfo)
b_rewards.append(rewards)
# batch of steps to batch of rollouts
b_obs = np.asarray(b_obs, dtype=self.obs.dtype)
b_rewards = np.asarray(b_rewards, dtype=np.float32)
b_actions = np.asarray(b_actions)
b_values = np.asarray(b_values, dtype=np.float32)
b_neglogps = np.asarray(b_neglogps, dtype=np.float32)
b_dones = np.asarray(b_dones, dtype=np.bool)
last_values = self.agent.get_value(self.obs, self.dones)
b_returns = np.zeros_like(b_rewards)
b_advs = np.zeros_like(b_rewards)
lastgaelam = 0
for t in reversed(range(batch_steps)):
if t == batch_steps - 1:
mask = 1.0 - self.dones
nextvalues = last_values
else:
mask = 1.0 - b_dones[t + 1]
nextvalues = b_values[t + 1]
delta = b_rewards[t] + args.gamma * nextvalues * mask - b_values[t]
b_advs[t] = lastgaelam = delta + args.gamma * args.lam * mask * lastgaelam
b_returns = b_advs + b_values
return (*map(sf01, (b_obs, b_returns, b_dones, b_actions, b_values, b_neglogps, b_advs, b_rewards)), ep_infos)
if __name__ == '__main__':
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
logger.configure()
main()
|
src/picktrue/logger.py
|
winkidney/PickTrue
| 118 |
146923
|
<gh_stars>100-1000
import logging
import sys
def __get_logger(name):
__log_level = logging.INFO
if "--debug-%s" % name in sys.argv:
__log_level = logging.DEBUG
fmt = "%(levelname)s - %(asctime)-15s - %(filename)s - line %(lineno)d --> %(message)s"
date_fmt = "%a %d %b %Y %H:%M:%S"
formatter = logging.Formatter(fmt, date_fmt)
handler = logging.StreamHandler()
file_handler = logging.FileHandler(
"./picktrue.all.log",
)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.addHandler(
handler
)
logger.addHandler(
file_handler
)
logger.setLevel(level=__log_level)
return logger
pk_logger = __get_logger('picktrue')
__all__ = (
'pk_logger',
)
|
tests/integration_tests/resources/dsl/deployment_update/modify_relationship_operation/modification/custom_workflow.py
|
TS-at-WS/cloudify-manager
| 124 |
146928
|
from cloudify.workflows import ctx, parameters
ctx.logger.info(parameters.node_id)
instance = [n for n in ctx.node_instances
if n.node_id == parameters.node_id][0]
for relationship in instance.relationships:
relationship.execute_source_operation('custom_lifecycle.custom_operation')
|
qf_lib_tests/integration_tests/backtesting/test_scenarios_generator.py
|
webclinic017/qf-lib
| 198 |
146931
|
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from unittest import TestCase
from qf_lib.backtesting.fast_alpha_model_tester.scenarios_generator import ScenariosGenerator
from qf_lib.containers.series.qf_series import QFSeries
class TestScenariosGenerator(TestCase):
def setUp(self):
self.generator = ScenariosGenerator()
self.num_of_scenarios = 100000
self.scenarios_length = 7
def test_make_scenarios(self):
first_ret_value = 0.05
second_ret_value = 0.1
trade_rets = QFSeries([first_ret_value, second_ret_value])
scenarios_df = self.generator.make_scenarios(trade_rets, self.scenarios_length, self.num_of_scenarios)
expected_shape = (self.scenarios_length, self.num_of_scenarios)
actual_shape = scenarios_df.shape
self.assertAlmostEqual(expected_shape, actual_shape)
values_count = scenarios_df.iloc[0, :].value_counts(normalize=True)
first_return_freq = values_count[first_ret_value]
second_return_freq = values_count[second_ret_value]
expected_frequency = 0.5
self.assertAlmostEqual(first_return_freq, expected_frequency, delta=0.01)
self.assertAlmostEqual(second_return_freq, expected_frequency, delta=0.01)
if __name__ == '__main__':
unittest.main()
|
tools/perf/page_sets/system_health/browsing_stories.py
|
iridium-browser/iridium-browser
| 575 |
146932
|
# encoding: utf-8
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# The number of lines will be reduced after 2018 update is complete and
# the old stories are removed: https://crbug.com/878390.
# pylint: disable=too-many-lines
import re
from page_sets.system_health import platforms
from page_sets.system_health import story_tags
from page_sets.system_health import system_health_story
from page_sets.login_helpers import autocad_login
from page_sets.login_helpers import facebook_login
from page_sets.login_helpers import google_login
from page_sets.login_helpers import pinterest_login
from page_sets.login_helpers import tumblr_login
from page_sets.helpers import override_online
from py_utils import TimeoutException
from telemetry.core import exceptions
from telemetry.util import js_template
class _BrowsingStory(system_health_story.SystemHealthStory):
"""Abstract base class for browsing stories.
A browsing story visits items on the main page. Subclasses provide
CSS selector to identify the items and implement interaction using
the helper methods of this class.
"""
IS_SINGLE_PAGE_APP = False
ITEM_SELECTOR = NotImplemented
# Defaults to using the body element if not set.
CONTAINER_SELECTOR = None
ABSTRACT_STORY = True
def __init__(self, story_set, take_memory_measurement,
extra_browser_args=None):
super(_BrowsingStory, self).__init__(story_set,
take_memory_measurement, extra_browser_args)
self.script_to_evaluate_on_commit = override_online.ALWAYS_ONLINE
def _WaitForNavigation(self, action_runner):
if not self.IS_SINGLE_PAGE_APP:
action_runner.WaitForNavigate()
def _NavigateToItem(self, action_runner, index):
item_selector = js_template.Render(
'document.querySelectorAll({{ selector }})[{{ index }}]',
selector=self.ITEM_SELECTOR, index=index)
# Only scrolls if element is not currently in viewport.
action_runner.WaitForElement(element_function=item_selector)
action_runner.ScrollPageToElement(
element_function=item_selector,
container_selector=self.CONTAINER_SELECTOR)
self._ClickLink(action_runner, item_selector)
def _ClickLink(self, action_runner, element_function):
action_runner.WaitForElement(element_function=element_function)
action_runner.ClickElement(element_function=element_function)
self._WaitForNavigation(action_runner)
def _NavigateBack(self, action_runner):
action_runner.NavigateBack()
self._WaitForNavigation(action_runner)
@classmethod
def GenerateStoryDescription(cls):
return 'Load %s and navigate to some items/articles.' % cls.URL
class _ArticleBrowsingStory(_BrowsingStory):
"""Abstract base class for user stories browsing news / shopping articles.
An article browsing story imitates browsing a articles:
1. Load the main page.
2. Open and scroll the first article.
3. Go back to the main page and scroll it.
4. Open and scroll the second article.
5. Go back to the main page and scroll it.
6. etc.
"""
ITEM_READ_TIME_IN_SECONDS = 3
ITEM_SCROLL_REPEAT = 2
ITEMS_TO_VISIT = 4
MAIN_PAGE_SCROLL_REPEAT = 0
ABSTRACT_STORY = True
# Some devices take long to load news webpages crbug.com/713036. Set to None
# because we cannot access DEFAULT_WEB_CONTENTS_TIMEOUT from this file.
COMPLETE_STATE_WAIT_TIMEOUT = None
# On some pages (for ex: facebook) articles appear only after we start
# scrolling. This specifies if we need scroll main page.
SCROLL_BEFORE_BROWSE = False
# In some cases we want to measure performance while we're loading. This
# introduces a lot of variability and should be used cautiously.
SCROLL_DURING_LOADING = False
def _DidLoadDocument(self, action_runner):
self._AfterNavigate(action_runner)
# Scroll main page if needed before we start browsing articles.
if self.SCROLL_BEFORE_BROWSE:
self._ScrollMainPage(action_runner)
for i in xrange(self.ITEMS_TO_VISIT):
self._NavigateToItem(action_runner, i)
self._AfterNavigate(action_runner)
self._ReadNextArticle(action_runner)
self._NavigateBack(action_runner)
self._AfterNavigate(action_runner)
self._ScrollMainPage(action_runner)
def _AfterNavigate(self, action_runner):
pass
def _ReadNextArticle(self, action_runner):
if not self.SCROLL_DURING_LOADING:
if self.COMPLETE_STATE_WAIT_TIMEOUT is not None:
action_runner.tab.WaitForDocumentReadyStateToBeComplete(
timeout=self.COMPLETE_STATE_WAIT_TIMEOUT)
else:
action_runner.tab.WaitForDocumentReadyStateToBeComplete()
action_runner.Wait(self.ITEM_READ_TIME_IN_SECONDS / 2.0)
else:
action_runner.tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
action_runner.RepeatableBrowserDrivenScroll(
repeat_count=self.ITEM_SCROLL_REPEAT)
action_runner.Wait(self.ITEM_READ_TIME_IN_SECONDS/2.0)
def _ScrollMainPage(self, action_runner):
if not self.SCROLL_DURING_LOADING:
action_runner.tab.WaitForDocumentReadyStateToBeComplete()
else:
action_runner.tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
action_runner.RepeatableBrowserDrivenScroll(
repeat_count=self.MAIN_PAGE_SCROLL_REPEAT)
##############################################################################
# News browsing stories.
##############################################################################
class CnnStory2021(_ArticleBrowsingStory):
"""The second top website in http://www.alexa.com/topsites/category/News"""
NAME = 'browse:news:cnn:2021'
URL = 'http://edition.cnn.com/'
ITEM_SELECTOR = '.cd__content > h3 > a'
ITEMS_TO_VISIT = 2
TAGS = [
story_tags.HEALTH_CHECK, story_tags.JAVASCRIPT_HEAVY, story_tags.YEAR_2021
]
class BusinessInsiderMobile2021(_ArticleBrowsingStory):
"""A newsite where we've seen janky performance in bug reports"""
NAME = 'browse:news:businessinsider:2021'
URL = 'https://www.businessinsider.com/'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
ITEM_SELECTOR = '.three-column > .tout-title-link'
ITEMS_TO_VISIT = 3
MAIN_PAGE_SCROLL_REPEAT = 2
ITEM_SCROLL_REPEAT = 4
TAGS = [story_tags.JAVASCRIPT_HEAVY, story_tags.YEAR_2021]
SCROLL_BEFORE_BROWSE = True
SCROLL_DURING_LOADING = False
_ACCEPTED_COOKIE = {
'businessinsider': '#sp_message_iframe_364841',
'insider': '#sp_message_iframe_364844'
}
def _GetCookieContextId(self, tab):
contexts = tab.EnableAllContexts().copy()
for context in contexts:
try:
result = tab.EvaluateJavaScript(
'document.querySelector(".message-button") != null;',
context_id=context)
except exceptions.EvaluateException:
continue
if result:
return context
return None
def _AfterNavigate(self, action_runner):
if self.SCROLL_DURING_LOADING:
action_runner.tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
else:
action_runner.tab.WaitForDocumentReadyStateToBeComplete()
# We want to clear any cookie.
url = re.search(r'https://(www\.)?([^.]+\.)?([^.]+)\.com.*',
action_runner.tab.GetUrl())
if url is None:
raise RuntimeError("no matching for " + action_runner.tab.GetUrl() +
" using " + url.group(2))
iframe = self._ACCEPTED_COOKIE[url.group(3)]
if iframe != '':
try:
action_runner.WaitForElement(iframe, timeout_in_seconds=1)
except TimeoutException:
# Sometimes the cookie pop up doesn't appear.
return
cookie_context = self._GetCookieContextId(action_runner.tab)
if cookie_context is not None:
self._ACCEPTED_COOKIE[url.group(3)] = ''
action_runner.ExecuteJavaScript(
('document.querySelectorAll(".message-button")[0].dispatchEvent('
'new MouseEvent("click", {bubbles: true, cancellable: true}));'),
context_id=cookie_context,
user_gesture=True)
class BusinessInsiderScrollWhileLoadingMobile2021(BusinessInsiderMobile2021):
"""A newsite where we've seen janky performance in bug reports"""
NAME = 'browse:news:businessinsider:loading:2021'
SCROLL_DURING_LOADING = True
# This is only used in system_health.scroll_jank at the moment. So to avoid
# running it on all bots we say no platform and explicitly add it in
# janky_story_set.py.
SUPPORTED_PLATFORMS = platforms.NO_PLATFORMS
class FacebookMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:social:facebook:2019'
URL = 'https://www.facebook.com/rihanna'
ITEM_SELECTOR = '._5msj'
MAIN_PAGE_SCROLL_REPEAT = 1
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
IS_SINGLE_PAGE_APP = True
SCROLL_BEFORE_BROWSE = True
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
def _Login(self, action_runner):
facebook_login.LoginWithMobileSite(action_runner, 'facebook4')
def _ScrollMainPage(self, action_runner):
action_runner.tab.WaitForDocumentReadyStateToBeComplete()
# Facebook loads content dynamically. So keep trying to scroll till we find
# the elements. Retry 5 times waiting a bit each time.
for _ in xrange(5):
action_runner.RepeatableBrowserDrivenScroll(
repeat_count=self.MAIN_PAGE_SCROLL_REPEAT)
result = action_runner.EvaluateJavaScript(
'document.querySelectorAll("._5msj").length')
if result:
break
action_runner.Wait(1)
class FacebookDesktopStory(_ArticleBrowsingStory):
NAME = 'browse:social:facebook'
URL = 'https://www.facebook.com/rihanna'
ITEM_SELECTOR = '._4-eo'
IS_SINGLE_PAGE_APP = True
# Web-page-replay does not work for this website:
# https://github.com/chromium/web-page-replay/issues/79.
SUPPORTED_PLATFORMS = platforms.NO_PLATFORMS
TAGS = [story_tags.YEAR_2016]
class InstagramMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:social:instagram:2019'
URL = 'https://www.instagram.com/badgalriri/'
ITEM_SELECTOR = '[class="v1Nh3 kIKUG _bz0w"] a'
ITEMS_TO_VISIT = 8
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
def _WaitForNavigation(self, action_runner):
action_runner.WaitForElement(selector='[title="badgalriri"]')
def _NavigateBack(self, action_runner):
action_runner.NavigateBack()
class FlipboardDesktopStory2020(_ArticleBrowsingStory):
NAME = 'browse:news:flipboard:2020'
URL = 'https://flipboard.com/explore'
IS_SINGLE_PAGE_APP = True
ITEM_SELECTOR = '.cover-image'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
class HackerNewsDesktopStory2020(_ArticleBrowsingStory):
NAME = 'browse:news:hackernews:2020'
URL = 'https://news.ycombinator.com'
ITEM_SELECTOR = '.athing .title > a'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
class NytimesDesktopStory2020(_ArticleBrowsingStory):
"""
The third top website in http://www.alexa.com/topsites/category/News
Known Replay Errors:
- window.EventTracker is not loaded
- all network errors are related to ads
"""
NAME = 'browse:news:nytimes:2020'
URL = 'http://www.nytimes.com'
ITEM_SELECTOR = "a[href*='/2020/']"
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
class NytimesMobileStory2019(_ArticleBrowsingStory):
"""The third top website in http://www.alexa.com/topsites/category/News"""
NAME = 'browse:news:nytimes:2019'
URL = 'http://mobile.nytimes.com'
ITEM_SELECTOR = '.css-1yjtett a'
# Nytimes is very heavy so only visit 2 articles.
ITEMS_TO_VISIT = 2
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.YEAR_2019]
class QqMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:news:qq:2019'
URL = 'https://xw.qq.com/#news'
ITEM_SELECTOR = '.title'
# The page seems to get stuck after three navigations.
ITEMS_TO_VISIT = 2
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.INTERNATIONAL, story_tags.YEAR_2019]
class RedditDesktopStory2020(_ArticleBrowsingStory):
"""The top website in http://www.alexa.com/topsites/category/News"""
NAME = 'browse:news:reddit:2020'
URL = 'https://www.reddit.com/r/news/top/?sort=top&t=week'
IS_SINGLE_PAGE_APP = True
ITEM_SELECTOR = 'article'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
class RedditMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:news:reddit:2019'
URL = 'https://www.reddit.com/r/news/top/?sort=top&t=week'
IS_SINGLE_PAGE_APP = True
ITEM_SELECTOR = '.PostHeader__post-title-line'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.HEALTH_CHECK, story_tags.YEAR_2019]
def _DidLoadDocument(self, action_runner):
# We encountered ads disguised as articles on the Reddit one so far. The
# following code skips that ad.
# If we encounter it more often it will make sense to have a more generic
# approach, e.g an OFFSET to start iterating from, or an index to skip.
# Add one to the items to visit since we are going to skip the ad and we
# want to still visit the same amount of articles.
for i in xrange(self.ITEMS_TO_VISIT + 1):
# Skip the ad disguised as an article.
if i == 1:
continue
self._NavigateToItem(action_runner, i)
self._ReadNextArticle(action_runner)
self._NavigateBack(action_runner)
self._ScrollMainPage(action_runner)
class TwitterMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:social:twitter:2019'
URL = 'https://www.twitter.com/nasa'
ITEM_SELECTOR = ('[class="css-901oao r-hkyrab r-1qd0xha r-1b43r93 r-16dba41 '
'r-ad9z0x r-bcqeeo r-bnwqim r-qvutc0"]')
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.HEALTH_CHECK, story_tags.YEAR_2019]
def _WaitForNavigation(self, action_runner):
action_runner.WaitForElement(selector=('[class="css-901oao css-16my406 '
'r-1qd0xha r-ad9z0x r-bcqeeo r-qvutc0"]'))
class TwitterDesktopStory2018(_ArticleBrowsingStory):
NAME = 'browse:social:twitter:2018'
URL = 'https://www.twitter.com/nasa'
IS_SINGLE_PAGE_APP = True
ITEM_SELECTOR = '.tweet-text'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2018]
class WashingtonPostMobileStory2019(_ArticleBrowsingStory):
"""Progressive website"""
NAME = 'browse:news:washingtonpost:2019'
URL = 'https://www.washingtonpost.com/pwa'
IS_SINGLE_PAGE_APP = True
ITEM_SELECTOR = '.headline > a'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
_BROWSE_FREE_SELECTOR = '[class="continue-btn button free"]'
_I_AGREE_SELECTOR = '.agree-ckb'
_CONTINUE_SELECTOR = '[class="continue-btn button accept-consent"]'
TAGS = [story_tags.YEAR_2019]
def _DidLoadDocument(self, action_runner):
# Get past GDPR and subscription dialog.
action_runner.WaitForElement(selector=self._BROWSE_FREE_SELECTOR)
action_runner.ClickElement(selector=self._BROWSE_FREE_SELECTOR)
action_runner.WaitForElement(selector=self._I_AGREE_SELECTOR)
action_runner.ClickElement(selector=self._I_AGREE_SELECTOR)
action_runner.ClickElement(selector=self._CONTINUE_SELECTOR)
super(WashingtonPostMobileStory2019, self)._DidLoadDocument(action_runner)
##############################################################################
# Search browsing stories.
##############################################################################
class GoogleAmpStory2018(_ArticleBrowsingStory):
""" Story for Google's Accelerated Mobile Pages (AMP).
The main thing we care about measuring here is load, so just query for
news articles and then load the first amp link.
"""
NAME = 'browse:search:amp:2018'
URL = 'https://www.google.com/search?q=news&hl=en'
# Need to find the first card in the news section that has an amp
# indicator on it
ITEM_SELECTOR = '.sm62ie > a[class*="amp_r"]'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.YEAR_2018]
def _DidLoadDocument(self, action_runner):
# Click on the amp news link and then just wait for it to load.
element_function = js_template.Render(
'document.querySelectorAll({{ selector }})[{{ index }}]',
selector=self.ITEM_SELECTOR, index=0)
action_runner.WaitForElement(element_function=element_function)
action_runner.ClickElement(element_function=element_function)
action_runner.Wait(2)
class GoogleAmpSXGStory2019(_ArticleBrowsingStory):
""" Story for Google's Signed Exchange (SXG) Accelerated Mobile Pages (AMP).
"""
NAME = 'browse:search:amp:sxg:2019'
# Specific URL for site that supports SXG, travel.yahoo.co.jp
# pylint: disable=line-too-long
URL='https://www.google.com/search?q=%E5%85%AD%E6%9C%AC%E6%9C%A8%E3%80%80%E3%83%A4%E3%83%95%E3%83%BC%E3%80%80%E3%83%9B%E3%83%86%E3%83%AB&esrch=SignedExchange::Demo'
# Need to find the SXG AMPlink in the results
ITEM_SELECTOR = 'a > div > span[aria-label="AMP logo"]'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.YEAR_2019]
def _DidLoadDocument(self, action_runner):
# Waiting manually for the search results to load here and below.
# Telemetry's action_runner.WaitForNavigate has some difficulty with amp
# pages as it waits for a frameId without a parent id.
action_runner.Wait(2)
# Click on the yahoo amp link and then just wait for it to load.
element_function = js_template.Render(
'document.querySelectorAll({{ selector }})[{{ index }}]',
selector=self.ITEM_SELECTOR, index=0)
action_runner.WaitForElement(element_function=element_function)
action_runner.ClickElement(element_function=element_function)
# Waiting for the document to fully render
action_runner.Wait(2)
class GoogleDesktopStory2018(_ArticleBrowsingStory):
"""
A typical google search story:
_ Start at https://www.google.com/search?q=flower
_ Click on the wikipedia link & navigate to
https://en.wikipedia.org/wiki/Flower
_ Scroll down the wikipedia page about flower.
_ Back to the search main page.
_ Refine the search query to 'delivery flower'.
_ Scroll down the page.
_ Click the next page result of 'delivery flower'.
_ Scroll the search page.
"""
NAME = 'browse:search:google:2020'
URL = 'https://www.google.com/search?q=flower&hl=en'
_SEARCH_BOX_SELECTOR = 'input[aria-label="Search"]'
_SEARCH_PAGE_2_SELECTOR = 'a[aria-label="Page 2"]'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
def _DidLoadDocument(self, action_runner):
# Click on flower Wikipedia link.
action_runner.Wait(2)
action_runner.ClickElement(text='Flower - Wikipedia')
action_runner.WaitForNavigate()
# Scroll the flower Wikipedia page, then navigate back.
action_runner.Wait(2)
action_runner.ScrollPage()
action_runner.Wait(2)
action_runner.NavigateBack()
# Click on the search box.
action_runner.WaitForElement(selector=self._SEARCH_BOX_SELECTOR)
action_runner.ExecuteJavaScript(
'document.querySelector({{ selector }}).focus()',
selector=self._SEARCH_BOX_SELECTOR)
action_runner.Wait(2)
# Submit search query.
action_runner.EnterText('delivery ')
action_runner.Wait(0.5)
action_runner.PressKey('Return')
# Scroll down & click next search result page.
action_runner.Wait(2)
action_runner.ScrollPageToElement(selector=self._SEARCH_PAGE_2_SELECTOR)
action_runner.Wait(2)
action_runner.ClickElement(selector=self._SEARCH_PAGE_2_SELECTOR)
action_runner.Wait(2)
action_runner.ScrollPage()
class GoogleIndiaDesktopStory2021(_ArticleBrowsingStory):
"""
A typical google search story in India:
1. Start at self.URL
2. Scroll down the page.
3. Refine the query & click search box
4. Scroll down the page.
5. Click the next page result
6. Scroll the search result page.
"""
NAME = 'browse:search:google_india:2021'
URL = 'https://www.google.co.in/search?q=%E0%A4%AB%E0%A5%82%E0%A4%B2&hl=hi'
_SEARCH_BOX_SELECTOR = 'input[name="q"]'
_SEARCH_BUTTON_SELECTOR = 'button[aria-label="Google Search"]'
_SEARCH_PAGE_2_SELECTOR = 'a[aria-label="Page 2"]'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.INTERNATIONAL, story_tags.YEAR_2021]
def _DidLoadDocument(self, action_runner):
# Refine search query in the search box.
action_runner.WaitForElement(self._SEARCH_BOX_SELECTOR)
action_runner.ExecuteJavaScript(
'document.querySelector({{ selector }}).select()',
selector=self._SEARCH_BOX_SELECTOR)
action_runner.Wait(1)
action_runner.EnterText(u'वितरण', character_delay_ms=250)
action_runner.Wait(2)
action_runner.ClickElement(selector=self._SEARCH_BUTTON_SELECTOR)
# Scroll down & click next search result page.
action_runner.Wait(2)
action_runner.ScrollPageToElement(selector=self._SEARCH_PAGE_2_SELECTOR)
action_runner.Wait(2)
action_runner.ClickElement(selector=self._SEARCH_PAGE_2_SELECTOR)
action_runner.Wait(2)
action_runner.ScrollPage()
##############################################################################
# Media browsing stories.
##############################################################################
class _MediaBrowsingStory(_BrowsingStory):
"""Abstract base class for media user stories
A media story imitates browsing a website with photo or video content:
1. Load a page showing a media item
2. Click on the next link to go to the next media item
3. etc.
"""
ABSTRACT_STORY = True
ITEM_VIEW_TIME_IN_SECONDS = 3
ITEMS_TO_VISIT = 15
ITEM_SELECTOR_INDEX = 0
INCREMENT_INDEX_AFTER_EACH_ITEM = False
def _DidLoadDocument(self, action_runner):
index = self.ITEM_SELECTOR_INDEX
for _ in xrange(self.ITEMS_TO_VISIT):
self._NavigateToItem(action_runner, index)
self._ViewMediaItem(action_runner, index)
if self.INCREMENT_INDEX_AFTER_EACH_ITEM:
index += 1
def _ViewMediaItem(self, action_runner, index):
del index # Unused.
action_runner.tab.WaitForDocumentReadyStateToBeComplete()
action_runner.Wait(self.ITEM_VIEW_TIME_IN_SECONDS)
class ImgurMobileStory2019(_MediaBrowsingStory):
NAME = 'browse:media:imgur:2019'
URL = 'http://imgur.com/gallery/46DfUFT'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
IS_SINGLE_PAGE_APP = True
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
USER_READ_TIME = 1
def _DidLoadDocument(self, action_runner):
# Accept the cookies
accept_button = ".qc-cmp-button"
item_selector = js_template.Render(
'document.querySelectorAll({{ selector }})[{{ index }}]',
selector=accept_button, index=1)
action_runner.WaitForElement(element_function=item_selector)
action_runner.ClickElement(element_function=item_selector)
# To simulate user looking at image
action_runner.Wait(self.USER_READ_TIME)
# Keep scrolling for the specified amount. If we see "continue browse"
# button click it to enable further scroll. This button would only be added
# after we scrolled a bit. So can't wait for this button at the start.
accepted_continue = False
for _ in xrange(15):
result = action_runner.EvaluateJavaScript(
'document.querySelectorAll(".Button-tertiary").length')
if result and not accepted_continue:
accept_button = ".Button-tertiary"
item_selector = js_template.Render(
'document.querySelectorAll({{ selector }})[{{ index }}]',
selector=accept_button, index=0)
action_runner.ScrollPageToElement(element_function=item_selector,
speed_in_pixels_per_second=400,
container_selector=None)
action_runner.ClickElement(element_function=item_selector)
accepted_continue = True
action_runner.ScrollPage(distance=800)
# To simulate user looking at image
action_runner.Wait(self.USER_READ_TIME)
class ImgurDesktopStory(_MediaBrowsingStory):
NAME = 'browse:media:imgur'
URL = 'http://imgur.com/gallery/5UlBN'
ITEM_SELECTOR = '.navNext'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
IS_SINGLE_PAGE_APP = True
TAGS = [story_tags.YEAR_2016]
class TikTokMobileStory2021(_BrowsingStory):
NAME = 'browse:media:tiktok_infinite_scroll:2021'
URL = 'https://tiktok.com/'
TAGS = [story_tags.INFINITE_SCROLL, story_tags.YEAR_2021]
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
_TIME_TO_WAIT_BEFORE_STARTING_IN_SECONDS = 2
_TIME_TO_WAIT_BETWEEN_VIDEOS = 1
_ACCEPT_ALL_SELECTOR = 'div[class$=" cookie-banner"]>div[class$=" button-wrapper"]>button'
def _DidLoadDocument(self, action_runner):
# Accept all cookies
action_runner.WaitForElement(selector=self._ACCEPT_ALL_SELECTOR)
action_runner.ClickElement(selector=self._ACCEPT_ALL_SELECTOR)
action_runner.Wait(self._TIME_TO_WAIT_BEFORE_STARTING_IN_SECONDS)
# TikTok doesn't scroll like a traditional page but responds to vertical
# swipe gestures.
for direction in ['down', 'up', 'down']:
for _ in range(0, 3):
scroll_dist = action_runner.EvaluateJavaScript(
'window.innerHeight') * 0.8
action_runner.ScrollPage(distance=scroll_dist, direction=direction)
action_runner.Wait(self._TIME_TO_WAIT_BETWEEN_VIDEOS)
class YouTubeMobileStory2019(_MediaBrowsingStory):
"""Load a typical YouTube video then navigate to a next few videos. Stop and
watch each video for few seconds.
"""
NAME = 'browse:media:youtube:2019'
URL = 'https://m.youtube.com/watch?v=TcMBFSGVi1c&autoplay=false'
ITEM_SELECTOR = '.compact-media-item > a'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
IS_SINGLE_PAGE_APP = True
ITEM_SELECTOR_INDEX = 3
ITEMS_TO_VISIT = 8
TAGS = [
story_tags.JAVASCRIPT_HEAVY, story_tags.EMERGING_MARKET,
story_tags.YEAR_2019
]
class YouTubeDesktopStory2019(_MediaBrowsingStory):
"""Load a typical YouTube video then navigate to a next few videos. Stop and
watch each video for a few seconds.
"""
NAME = 'browse:media:youtube:2019'
URL = 'https://www.youtube.com/watch?v=QGfhS1hfTWw&autoplay=0'
ITEM_SELECTOR = 'ytd-compact-video-renderer.ytd-watch-next-secondary-results-renderer a'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
IS_SINGLE_PAGE_APP = True
# A longer view time allows videos to load and play.
ITEM_VIEW_TIME_IN_SECONDS = 5
ITEMS_TO_VISIT = 8
ITEM_SELECTOR_INDEX = 3
PLATFORM_SPECIFIC = True
TAGS = [story_tags.JAVASCRIPT_HEAVY, story_tags.YEAR_2019]
class AutoCADDesktopStory2021(_MediaBrowsingStory):
"""AutoCAD desktop story,
TODO: add a description here.
"""
NAME = 'browse:tools:autocad:2021'
URL = 'https://web.autocad.com/?user=wasm-benchmark'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [
story_tags.YEAR_2021, story_tags.WEBASSEMBLY, story_tags.WEBGL,
story_tags.KEYBOARD_INPUT
]
def __init__(self, story_set, take_memory_measurement):
super(AutoCADDesktopStory2021, self).__init__(story_set,
take_memory_measurement)
def _Login(self, action_runner):
autocad_login.LoginWithDesktopSite(action_runner, 'autocad')
def _DidLoadDocument(self, action_runner):
action_runner.WaitForElement(text="Sign in")
action_runner.ClickElement(text="Sign in")
# Now we are done with the login.
action_runner.WaitForElement(text="Samples")
action_runner.ClickElement(text="Samples")
action_runner.WaitForElement(text="Dog House Plan Sample.dwg")
action_runner.ClickElement(text="Dog House Plan Sample.dwg")
# We cannot wait for an element, because the result of the loading
# action is just a drawing on the canvas.
action_runner.Wait(10)
action_runner.EnterText('MEASURE')
action_runner.PressKey('Return')
action_runner.Wait(1)
action_runner.EnterText('-3,1')
action_runner.PressKey('Return')
action_runner.Wait(5)
class EarthDesktopStory2020(_MediaBrowsingStory):
"""Load Google Earth and search for the Empire State Building. Watch the
Empire State Building for a few seconds.
"""
NAME = 'browse:tools:earth:2020'
URL = 'https://earth.google.com/web/'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [
story_tags.YEAR_2020, story_tags.WEBASSEMBLY, story_tags.WEBGL,
story_tags.KEYBOARD_INPUT
]
def __init__(self, story_set, take_memory_measurement):
super(EarthDesktopStory2020, self).__init__(story_set,
take_memory_measurement)
# This script sets values in localStorage that suggest that Google Earth has
# already been visited before. Thereby we can avoid the tutorial at startup.
self.script_to_evaluate_on_commit = '''
localStorage.setItem('earth.out_of_box.url:',
'https://www.google.com/earth/clientassets/oobe/rev0/oobe_r0__$[hl].kml');
localStorage.setItem('earth.out_of_box.major_revision:', '0');
localStorage.setItem('earth.out_of_box.client_version:', '192.168.127.12');
'''
def _DidLoadDocument(self, action_runner):
CHECK_LOADED = (
'document.querySelector("body > earth-app").shadowRoot'
'.querySelector("#earthRelativeElements > earth-view-status")'
'.shadowRoot.querySelector("#percentageText").textContent === {{target}}'
)
action_runner.WaitForJavaScriptCondition(CHECK_LOADED, target="100%")
search_selector = ('(() => document.querySelector("body > earth-app")'
'.shadowRoot.querySelector("#toolbar").shadowRoot'
'.querySelector("#search"))()')
action_runner.ClickElement(element_function=search_selector)
search_text_selector = (
'(() => document.querySelector("body > earth-app")'
'.shadowRoot.querySelector("#drawerContainer").shadowRoot'
'.querySelector("#search").shadowRoot.querySelector("#omnibox")'
'.shadowRoot.querySelector("#queryInput"))()')
action_runner.WaitForElement(element_function=search_text_selector)
action_runner.ClickElement(element_function=search_text_selector)
action_runner.EnterText('Empire State Building')
action_runner.PressKey('Return')
# Wait for 20 seconds so that the Empire State Building is reached and fully
# loaded.
action_runner.Wait(20)
compass_selector = (
'(() => document.querySelector("body > earth-app").shadowRoot'
'.querySelector("#compass").shadowRoot'
'.querySelector("#compassIcon"))()')
action_runner.ClickElement(element_function=compass_selector)
action_runner.Wait(5)
zoom_2d_selector = (
'(() => document.querySelector("body > earth-app").shadowRoot'
'.querySelector("#hoverButton").shadowRoot'
'.querySelector("#hoverButton"))()')
action_runner.ClickElement(element_function=zoom_2d_selector)
# Wait for 5 seconds to load everything. We cannot wait for 100% because of
# the non-deterministic nature of the benchmark.
action_runner.Wait(5)
class YouTubeTVDesktopStory2019(_MediaBrowsingStory):
"""Load a typical YouTube TV video then navigate to a next few videos. Stop
and watch each video for a few seconds.
"""
NAME = 'browse:media:youtubetv:2019'
URL = 'https://www.youtube.com/tv#/watch/ads/control?v=PxrnoGyBw4E&resume'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2019]
def WaitIfRecording(self, action_runner):
# Uncomment the below if recording to try and reduce network errors.
# action_runner.Wait(2)
pass
def WatchThenSkipAd(self, action_runner):
skip_button_selector = '.skip-ad-button'
action_runner.WaitForElement(selector=skip_button_selector)
action_runner.Wait(8) # Wait until the ad is skippable.
action_runner.MouseClick(selector=skip_button_selector)
self.WaitIfRecording(action_runner)
def ShortAttentionSpan(self, action_runner):
action_runner.Wait(2)
def GotoNextVideo(self, action_runner):
forward_button_selector = '.skip-forward-button'
action_runner.PressKey('ArrowDown') # Open the menu.
action_runner.WaitForElement(selector=forward_button_selector)
action_runner.MouseClick(selector=forward_button_selector)
self.WaitIfRecording(action_runner)
def NavigateInMenu(self, action_runner):
short_delay_in_ms = 300
delay_in_ms = 1000
long_delay_in_ms = 3000
# Escape to menu, skip the sign-in process.
action_runner.PressKey('Backspace', 1, long_delay_in_ms)
action_runner.PressKey('ArrowDown', 1, delay_in_ms)
action_runner.PressKey('Return', 1, long_delay_in_ms)
self.WaitIfRecording(action_runner)
# Scroll through categories and back.
action_runner.WaitForElement(selector='#guide-logo')
action_runner.PressKey('ArrowUp', 1, delay_in_ms)
action_runner.PressKey('ArrowRight', 3, delay_in_ms)
action_runner.PressKey('ArrowLeft', 3, delay_in_ms)
action_runner.PressKey('ArrowDown', 1, delay_in_ms)
self.WaitIfRecording(action_runner)
# Scroll through a few videos then open the sidebar menu.
action_runner.PressKey('ArrowRight', 3, short_delay_in_ms)
action_runner.PressKey('ArrowDown', 3, short_delay_in_ms)
action_runner.PressKey('Backspace', 2, delay_in_ms)
self.WaitIfRecording(action_runner)
# Scroll through options and then go to search.
action_runner.PressKey('ArrowDown', 3, delay_in_ms)
action_runner.PressKey('s', 1, delay_in_ms)
self.WaitIfRecording(action_runner)
# Search for 'dub stories' and start playing.
action_runner.EnterText('dub stories', short_delay_in_ms)
action_runner.PressKey('ArrowDown', 1, delay_in_ms)
action_runner.PressKey('Return', 2, delay_in_ms)
self.WaitIfRecording(action_runner)
def _DidLoadDocument(self, action_runner):
self.WatchThenSkipAd(action_runner)
self.ShortAttentionSpan(action_runner)
self.GotoNextVideo(action_runner)
self.ShortAttentionSpan(action_runner)
self.GotoNextVideo(action_runner)
self.ShortAttentionSpan(action_runner)
self.NavigateInMenu(action_runner)
# This story is mainly relevant for V8 in jitless mode, but there is no
# benchmark that enables this flag. We take the pragmatic solution and set
# this flag explicitly for this story.
def __init__(self, story_set, take_memory_measurement):
super(YouTubeTVDesktopStory2019, self).__init__(
story_set, take_memory_measurement,
extra_browser_args=['--js-flags="--jitless"'])
class YouTubeTVDesktopWatchStory2020(_MediaBrowsingStory):
"""Load a typical YouTube TV video then navigate to a next few videos. Stop
and watch each video for a few seconds.
"""
NAME = 'browse:media:youtubetv_watch:2020'
URL = ('https://www.youtube.com/tv?'
'env_adsUrl=http%3A%2F%2Fvastsynthesizer.appspot.com'
'%2Fyshi_trv_instream_10s#/watch?v=Ylo257Av-qQ')
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
def WaitIfRecording(self, action_runner):
# Uncomment the below if recording to try and reduce network errors.
# action_runner.Wait(2)
pass
def WatchThenSkipAd(self, action_runner):
skip_button_selector = '.skip-ad-button'
action_runner.WaitForElement(selector=skip_button_selector)
action_runner.Wait(8) # Wait until the ad is skippable.
action_runner.MouseClick(selector=skip_button_selector)
self.WaitIfRecording(action_runner)
def ShortAttentionSpan(self, action_runner):
action_runner.Wait(2)
def GotoNextVideo(self, action_runner):
delay_in_ms = 1000
action_runner.PressKey('ArrowDown', 1, delay_in_ms)
action_runner.PressKey('ArrowRight', 1, delay_in_ms)
action_runner.PressKey('Return', 2, delay_in_ms)
self.WaitIfRecording(action_runner)
def _DidLoadDocument(self, action_runner):
self.WatchThenSkipAd(action_runner)
self.ShortAttentionSpan(action_runner)
self.GotoNextVideo(action_runner)
self.WatchThenSkipAd(action_runner)
self.ShortAttentionSpan(action_runner)
self.GotoNextVideo(action_runner)
self.WatchThenSkipAd(action_runner)
self.ShortAttentionSpan(action_runner)
self.GotoNextVideo(action_runner)
self.WatchThenSkipAd(action_runner)
self.ShortAttentionSpan(action_runner)
# This story is mainly relevant for V8 in jitless mode, but there is no
# benchmark that enables this flag. We take the pragmatic solution and set
# this flag explicitly for this story.
def __init__(self, story_set, take_memory_measurement):
super(YouTubeTVDesktopWatchStory2020,
self).__init__(story_set,
take_memory_measurement,
extra_browser_args=['--js-flags="--jitless"'])
class FacebookPhotosMobileStory2019(_MediaBrowsingStory):
"""Load a photo page from Rihanna's facebook page then navigate a few next
photos.
"""
NAME = 'browse:media:facebook_photos:2019'
URL = (
'https://m.facebook.com/rihanna/photos/a.10152251658271676/10156761246686676/?type=3&source=54')
ITEM_SELECTOR = '._57-r.touchable'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
IS_SINGLE_PAGE_APP = True
ITEM_SELECTOR_INDEX = 0
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
class TumblrDesktopStory2018(_MediaBrowsingStory):
NAME = 'browse:media:tumblr:2018'
URL = 'https://tumblr.com/search/gifs'
ITEM_SELECTOR = '.post_media'
IS_SINGLE_PAGE_APP = True
ITEMS_TO_VISIT = 8
INCREMENT_INDEX_AFTER_EACH_ITEM = True
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2018]
def _Login(self, action_runner):
tumblr_login.LoginDesktopAccount(action_runner, 'tumblr')
action_runner.Wait(3)
def _ViewMediaItem(self, action_runner, index):
super(TumblrDesktopStory2018, self)._ViewMediaItem(action_runner, index)
action_runner.WaitForElement(selector='#tumblr_lightbox')
action_runner.MouseClick(selector='#tumblr_lightbox')
action_runner.Wait(1) # To make browsing more realistic.
class PinterestDesktopStory2018(_MediaBrowsingStory):
NAME = 'browse:media:pinterest:2018'
URL = 'https://pinterest.com'
ITEM_SELECTOR = '.pinWrapper a[data-force-refresh="1"]'
ITEM_VIEW_TIME = 5
IS_SINGLE_PAGE_APP = True
ITEMS_TO_VISIT = 8
INCREMENT_INDEX_AFTER_EACH_ITEM = True
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2018]
# SKIP_LOGIN = False
def _Login(self, action_runner):
pinterest_login.LoginDesktopAccount(action_runner, 'googletest')
def _ViewMediaItem(self, action_runner, index):
super(PinterestDesktopStory2018, self)._ViewMediaItem(action_runner, index)
# 1. click on item
# 2. pin every other item
# 3. go back to the main page
action_runner.Wait(1) # Wait to make navigation realistic.
if index % 2 == 0:
if not self.SKIP_LOGIN:
action_runner.Wait(2)
action_runner.WaitForElement(selector='.SaveButton')
action_runner.ClickElement(selector='.SaveButton')
if not self.SKIP_LOGIN:
action_runner.Wait(2)
action_runner.Wait(2.5)
action_runner.WaitForElement(
selector='div[data-test-id=BoardPickerSaveButton]')
action_runner.ClickElement(
selector='div[data-test-id=BoardPickerSaveButton]')
action_runner.Wait(1.5)
action_runner.Wait(1)
if not self.SKIP_LOGIN:
action_runner.Wait(2)
action_runner.NavigateBack()
action_runner.WaitForElement(selector='input[name=searchBoxInput]')
action_runner.Wait(1)
if not self.SKIP_LOGIN:
action_runner.Wait(2)
class GooglePlayStoreMobileStory(_MediaBrowsingStory):
""" Navigate to the movies page of Google Play Store, scroll to the bottom,
and click "see more" of a middle category (last before second scroll).
"""
NAME = 'browse:media:googleplaystore:2019'
URL = 'https://play.google.com/store/movies'
ITEM_SELECTOR = ''
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
IS_SINGLE_PAGE_APP = True
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019, story_tags.IMAGES]
# intends to select the last category of movies and its "see more" button
_SEE_MORE_SELECTOR = ('div[class*="cluster-container"]:last-of-type '
'a[class*="see-more"]')
def _DidLoadDocument(self, action_runner):
action_runner.ScrollPage()
action_runner.Wait(2)
action_runner.ScrollPage()
action_runner.Wait(2)
action_runner.MouseClick(self._SEE_MORE_SELECTOR)
action_runner.Wait(2)
action_runner.ScrollPage()
class GooglePlayStoreDesktopStory(_MediaBrowsingStory):
""" Navigate to the movies page of Google Play Store, scroll to the bottom,
and click "see more" of a middle category (last before second scroll).
"""
NAME = 'browse:media:googleplaystore:2021'
URL = 'https://play.google.com/store/movies'
ITEM_SELECTOR = ''
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
IS_SINGLE_PAGE_APP = True
TAGS = [story_tags.YEAR_2018, story_tags.IMAGES]
def _DidLoadDocument(self, action_runner):
action_runner.ScrollPage()
action_runner.Wait(2)
action_runner.ScrollPage()
action_runner.Wait(2)
action_runner.ScrollPage()
def __init__(self, story_set, take_memory_measurement,
extra_browser_args=None, name_suffix=''):
self.NAME = self.NAME + name_suffix
super(GooglePlayStoreDesktopStory, self).__init__(story_set,
take_memory_measurement,
extra_browser_args=extra_browser_args)
##############################################################################
# Emerging market browsing stories.
##############################################################################
class BrowseFlipKartMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:shopping:flipkart:2019'
URL = 'https://flipkart.com/search?q=Sunglasses'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
ITEM_SELECTOR = '.r-1hvjb8t'
BACK_SELECTOR = '._3NH1qf'
ITEMS_TO_VISIT = 4
def _WaitForNavigation(self, action_runner):
action_runner.WaitForElement(text='View Details')
def _NavigateBack(self, action_runner):
action_runner.ClickElement(selector=self.BACK_SELECTOR)
action_runner.WaitForElement(text="sunglasses")
class BrowseAmazonMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:shopping:amazon:2019'
URL = 'https://www.amazon.com.br/s/?k=telefone+celular'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
ITEM_SELECTOR = '[class="a-size-base a-color-base a-text-normal"]'
ITEMS_TO_VISIT = 4
class BrowseLazadaMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:shopping:lazada:2019'
URL = 'https://www.lazada.co.id/catalog/?q=Wrist+watch'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
ITEM_SELECTOR = '.c12p0m'
ITEMS_TO_VISIT = 4
class BrowseAvitoMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:shopping:avito:2019'
URL = 'https://www.avito.ru/rossiya'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
ITEM_SELECTOR = '._3eXe2'
ITEMS_TO_VISIT = 4
def _WaitForNavigation(self, action_runner):
action_runner.WaitForElement(selector='[class="_3uGvV YVMFh"]')
class BrowseTOIMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:news:toi:2019'
URL = 'http://m.timesofindia.com'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
ITEMS_TO_VISIT = 2
ITEM_SELECTOR = '.dummy-img'
class BrowseGloboMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:news:globo:2019'
URL = 'http://www.globo.com'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
ITEMS_TO_VISIT = 2 # 4 links causes renderer OOM crbug.com/714650.
ITEM_SELECTOR = '.hui-premium__link'
COMPLETE_STATE_WAIT_TIMEOUT = 150
class BrowseCricBuzzMobileStory2019(_ArticleBrowsingStory):
NAME = 'browse:news:cricbuzz:2019'
URL = 'http://m.cricbuzz.<EMAIL>'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.EMERGING_MARKET, story_tags.YEAR_2019]
ITEMS_TO_VISIT = 3
ITEM_SELECTOR = '.list-content'
##############################################################################
# Maps browsing stories.
##############################################################################
class GoogleMapsMobileStory2019(system_health_story.SystemHealthStory):
"""Story that browses google maps mobile page
This story searches for nearby restaurants on google maps website and finds
directions to a chosen restaurant from search results.
"""
NAME = 'browse:tools:maps:2019'
URL = 'https://maps.google.com/maps?force=pwa&source=mlpwa'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [
story_tags.HEALTH_CHECK, story_tags.EMERGING_MARKET, story_tags.YEAR_2019
]
_MAPS_SEARCH_BOX_SELECTOR = '.ml-searchbox-pwa-textarea'
_MAPS_SEARCH_BOX_FORM = '[id="ml-searchboxform"]'
_RESTAURANTS_LOADED = '.ml-panes-categorical-bottom-bar button'
_RESTAURANTS_LINK = '.ml-entity-list-item-info'
_DIRECTIONS_LINK = ('.ml-panes-entity-bottom-bar.'
'ml-panes-entity-bottom-bar-expanded '
'button[class$="last"]')
_DIRECTIONS_LOADED = ('.ml-panes-directions-bottom-bar.'
'ml-panes-directions-bottom-bar-collapsed '
'button[class$="last"]')
_MAP_LAYER = '.ml-map'
def _DidLoadDocument(self, action_runner):
# Submit search query.
self._ClickLink(self._MAPS_SEARCH_BOX_SELECTOR, action_runner)
action_runner.WaitForElement(selector=self._MAPS_SEARCH_BOX_FORM)
action_runner.Wait(1) # Waiting to type
action_runner.EnterText('restaurants near me')
action_runner.PressKey('Return')
action_runner.WaitForElement(selector=self._RESTAURANTS_LOADED)
action_runner.WaitForNetworkQuiescence()
action_runner.Wait(4) # User looking at restaurants
# Open the restaurant list and select the first.
self._ClickLink(self._RESTAURANTS_LOADED, action_runner)
action_runner.WaitForElement(selector=self._RESTAURANTS_LINK)
action_runner.Wait(3) # User reads about restaurant
self._ClickLink(self._RESTAURANTS_LINK, action_runner)
action_runner.Wait(1) # Reading description
# Open directions to the restaurant from Google.
self._ClickLink(self._DIRECTIONS_LINK, action_runner)
action_runner.Wait(0.5)
action_runner.EnterText('Google UK')
action_runner.PressKey('Return')
action_runner.WaitForElement(selector=self._DIRECTIONS_LOADED)
action_runner.WaitForNetworkQuiescence()
action_runner.Wait(2) # Seeing direction
def _ClickLink(self, selector, action_runner):
action_runner.WaitForElement(selector=selector)
action_runner.ClickElement(selector=selector)
class GoogleMapsStory2019(_BrowsingStory):
"""
Google maps story:
_ Start at https://www.maps.google.com/maps
_ Search for "restaurents near me" and wait for 4 sec.
_ Click ZoomIn two times, waiting for 3 sec in between.
_ Scroll the map horizontally and vertically.
_ Pick a restaurant and ask for directions.
"""
# When recording this story:
# Force tactile using this: http://google.com/maps?force=tt
# Force webgl using this: http://google.com/maps?force=webgl
# Reduce the speed as mentioned in the comment below for
# RepeatableBrowserDrivenScroll
NAME = 'browse:tools:maps:2019'
URL = 'https://www.google.com/maps'
_MAPS_SEARCH_BOX_SELECTOR = '#searchboxinput'
_MAPS_UPDATE_RESULTS_SELECTOR = '#section-query-on-pan-checkbox-id'
_MAPS_ZOOM_IN_SELECTOR = '#widget-zoom-in'
_MAPS_ZOOM_OUT_SELECTOR = '#widget-zoom-out'
_RESTAURANTS_LOADED = ('[class="searchbox searchbox-shadow noprint '
'clear-button-shown"]')
_RESTAURANT_LINK = '[data-result-index="1"]'
_DIRECTIONS_LINK = '.section-action-chip-button[data-value=Directions]'
_DIRECTIONS_FROM_BOX = '[class="tactile-searchbox-input"]'
_DIRECTIONS_LOADED = '[class="section-directions-trip clearfix selected"]'
# Get the current server response hash and store it for use
# in _CHECK_RESTAURANTS_UPDATED.
_GET_RESTAURANT_RESPONSE_HASH = '''
document.querySelector({{restaurant_link}}).textContent
'''
# Check if the current restaurant server response hash is different from
# the old one to checks that restaurants started to update. Also wait for
# the completion of the loading by waiting for the button to change to loaded.
# The response hash gets updated when we scroll or zoom since server provides
# a new response for the updated locations with a new hash value.
_CHECK_RESTAURANTS_UPDATED = '''
(document.querySelector({{restaurant_link}}).textContent
!= {{ old_restaurant }})
&& (document.querySelector(
'[class="searchbox searchbox-shadow noprint clear-button-shown"]')
!= null)
'''
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.JAVASCRIPT_HEAVY, story_tags.WEBGL,
story_tags.YEAR_2019]
def _DidLoadDocument(self, action_runner):
# Click on the search box.
action_runner.WaitForElement(selector=self._MAPS_SEARCH_BOX_SELECTOR)
action_runner.WaitForElement(selector=self._MAPS_ZOOM_IN_SELECTOR)
# Submit search query.
action_runner.ClickElement(selector=self._MAPS_SEARCH_BOX_SELECTOR)
action_runner.EnterText('restaurants near me')
action_runner.PressKey('Return')
action_runner.WaitForElement(selector=self._RESTAURANTS_LOADED)
action_runner.Wait(1)
# Enable updating the results on map move/zoom.
action_runner.WaitForElement(selector=self._MAPS_UPDATE_RESULTS_SELECTOR)
action_runner.ClickElement(selector=self._MAPS_UPDATE_RESULTS_SELECTOR)
# ZoomIn two times.
prev_restaurant_hash = action_runner.EvaluateJavaScript(
self._GET_RESTAURANT_RESPONSE_HASH,
restaurant_link=self._RESTAURANT_LINK)
action_runner.ClickElement(selector=self._MAPS_ZOOM_IN_SELECTOR)
action_runner.Wait(0.5)
action_runner.ClickElement(selector=self._MAPS_ZOOM_IN_SELECTOR)
action_runner.Wait(0.5)
action_runner.ClickElement(selector=self._MAPS_ZOOM_IN_SELECTOR)
action_runner.WaitForJavaScriptCondition(
self._CHECK_RESTAURANTS_UPDATED, restaurant_link=self._RESTAURANT_LINK,
old_restaurant=prev_restaurant_hash, timeout=90)
# This wait is required to fetch the data for all the tiles in the map.
action_runner.Wait(1)
prev_restaurant_hash = action_runner.EvaluateJavaScript(
self._GET_RESTAURANT_RESPONSE_HASH,
restaurant_link=self._RESTAURANT_LINK)
action_runner.ClickElement(selector=self._MAPS_ZOOM_OUT_SELECTOR)
action_runner.Wait(0.5)
action_runner.ClickElement(selector=self._MAPS_ZOOM_OUT_SELECTOR)
action_runner.WaitForJavaScriptCondition(
self._CHECK_RESTAURANTS_UPDATED, restaurant_link=self._RESTAURANT_LINK,
old_restaurant=prev_restaurant_hash, timeout=90)
# This wait is required to fetch the data for all the tiles in the map.
action_runner.Wait(1)
# Reduce the speed (the current wpr is recorded with speed set to 50) when
# recording the wpr. If we scroll too fast, the data will not be recorded
# well. After recording reset it back to the original value to have a more
# realistic scroll.
prev_restaurant_hash = action_runner.EvaluateJavaScript(
self._GET_RESTAURANT_RESPONSE_HASH,
restaurant_link=self._RESTAURANT_LINK)
action_runner.RepeatableBrowserDrivenScroll(
x_scroll_distance_ratio=0.0, y_scroll_distance_ratio=0.5,
repeat_count=2, speed=500, timeout=120, repeat_delay_ms=2000)
action_runner.WaitForJavaScriptCondition(
self._CHECK_RESTAURANTS_UPDATED, restaurant_link=self._RESTAURANT_LINK,
old_restaurant=prev_restaurant_hash, timeout=90)
prev_restaurant_hash = action_runner.EvaluateJavaScript(
self._GET_RESTAURANT_RESPONSE_HASH,
restaurant_link=self._RESTAURANT_LINK)
action_runner.RepeatableBrowserDrivenScroll(
x_scroll_distance_ratio=0.5, y_scroll_distance_ratio=0,
repeat_count=2, speed=500, timeout=120, repeat_delay_ms=2000)
action_runner.WaitForJavaScriptCondition(
self._CHECK_RESTAURANTS_UPDATED, restaurant_link=self._RESTAURANT_LINK,
old_restaurant=prev_restaurant_hash, timeout=90)
# To make the recording more realistic.
action_runner.Wait(1)
action_runner.ClickElement(selector=self._RESTAURANT_LINK)
# To make the recording more realistic.
action_runner.Wait(1)
action_runner.WaitForElement(selector=self._DIRECTIONS_LINK)
action_runner.ClickElement(selector=self._DIRECTIONS_LINK)
action_runner.ClickElement(selector=self._DIRECTIONS_FROM_BOX)
action_runner.EnterText('6 Pancras Road London')
action_runner.PressKey('Return')
action_runner.WaitForElement(selector=self._DIRECTIONS_LOADED)
action_runner.Wait(1)
# Cycle trough the travel modes.
for travel_mode in [0,1,2,3,4,6]:
selector = 'div[data-travel_mode="%s"]' % travel_mode
action_runner.WaitForElement(selector=selector)
action_runner.ClickElement(selector=selector)
action_runner.Wait(3)
##############################################################################
# Gmail browsing stories.
##############################################################################
class _GmailBrowsingStory(system_health_story.SystemHealthStory):
"""Abstract base class for Gmail browsing stories.
Adds common functionality for re-mapping + waiting on performance
mark + measure data.
"""
SKIP_LOGIN = False
# Patch performance.mark and measure to get notified about page events.
PERFOMANCE_MARK_AND_MEASURE = '''
window.__telemetry_observed_page_events = new Set();
(function () {
let reported_events = window.__telemetry_reported_page_events;
let reported_measures = window.__telemetry_reported_page_measures;
let observed = window.__telemetry_observed_page_events;
let performance_mark = window.performance.mark;
let performance_measure = window.performance.measure;
window.performance.measure = function(label, mark) {
performance_measure.call(window.performance, label, mark);
if(reported_measures.hasOwnProperty(label)) {
performance_mark.call(window.performance, reported_measures[label]);
observed.add(reported_measures[label]);
}
}
window.performance.mark = function (label) {
performance_mark.call(window.performance, label);
if (reported_events.hasOwnProperty(label)) {
performance_mark.call(
window.performance, reported_events[label]);
observed.add(reported_events[label]);
}
}
})();
'''
def __init__(self, story_set, take_memory_measurement,
events_and_measures_reported):
super(_GmailBrowsingStory, self).__init__(story_set,
take_memory_measurement)
self.script_to_evaluate_on_commit = js_template.Render(
'''{{@events_and_measures_reported_by_page}}
{{@performance_mark_and_measure}}''',
events_and_measures_reported_by_page=events_and_measures_reported,
performance_mark_and_measure=self.PERFOMANCE_MARK_AND_MEASURE)
def _Login(self, action_runner):
google_login.NewLoginGoogleAccount(action_runner, 'googletest')
# Navigating to http://mail.google.com immediately leads to an infinite
# redirection loop due to a bug in WPR (see
# https://bugs.chromium.org/p/chromium/issues/detail?id=1036791). We
# therefore first navigate to a dummy sub-URL to set up the session and
# hit the resulting redirection loop. Afterwards, we can safely navigate
# to http://mail.google.com.
action_runner.tab.WaitForDocumentReadyStateToBeComplete()
action_runner.Navigate(
'https://mail.google.com/mail/mu/mp/872/trigger_redirection_loop')
action_runner.tab.WaitForDocumentReadyStateToBeComplete()
class GmailLabelClickStory2020(_GmailBrowsingStory):
NAME = 'browse:tools:gmail-labelclick:2020'
# Needs to be http and not https.
URL = 'http://mail.google.com/'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
_IMPORTANT_SELECTOR = 'div[data-tooltip="Important"]'
# Page event queries.
LABEL_CLICK_BEGIN_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_begin"))
'''
LABEL_CLICK_END_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_end"))
'''
# These maps translates page-specific event names to event names needed for
# the reported_by_page:* metric.
EVENTS_AND_MEASURES_REPORTED_BY_PAGE = '''
window.__telemetry_reported_page_events = {
'mail:lc-1':
'telemetry:reported_by_page:benchmark_begin',
};
window.__telemetry_reported_page_measures = {
'mail:lc':
'telemetry:reported_by_page:benchmark_end'
};
'''
def __init__(self, story_set, take_memory_measurement):
super(GmailLabelClickStory2020,
self).__init__(story_set, take_memory_measurement,
self.EVENTS_AND_MEASURES_REPORTED_BY_PAGE)
def _DidLoadDocument(self, action_runner):
action_runner.Wait(1)
action_runner.EvaluateJavaScript(
"document.evaluate(\"//span[text()='More']\", "
"document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)"
".singleNodeValue.click();"
)
action_runner.WaitForElement(selector=self._IMPORTANT_SELECTOR)
action_runner.ClickElement(selector=self._IMPORTANT_SELECTOR)
action_runner.WaitForJavaScriptCondition(self.LABEL_CLICK_BEGIN_EVENT)
action_runner.WaitForJavaScriptCondition(self.LABEL_CLICK_END_EVENT)
class GmailOpenConversationStory2020(_GmailBrowsingStory):
NAME = 'browse:tools:gmail-openconversation:2020'
# Needs to be http and not https.
URL = 'http://mail.google.com/'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
_CONV_SELECTOR = 'span[data-thread-id]'
# Page event queries.
OPEN_CONVERSATION_BEGIN_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_begin"))
'''
OPEN_CONVERSATION_END_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_end"))
'''
# These maps translates page-specific event names to event names needed for
# the reported_by_page:* metric.
EVENTS_AND_MEASURES_REPORTED_BY_PAGE = '''
window.__telemetry_reported_page_events = {
'mail:o-1':
'telemetry:reported_by_page:benchmark_begin',
};
window.__telemetry_reported_page_measures = {
'mail:o':
'telemetry:reported_by_page:benchmark_end'
};
'''
def __init__(self, story_set, take_memory_measurement):
super(GmailOpenConversationStory2020,
self).__init__(story_set, take_memory_measurement,
self.EVENTS_AND_MEASURES_REPORTED_BY_PAGE)
def _DidLoadDocument(self, action_runner):
action_runner.Wait(1)
action_runner.ClickElement(selector=self._CONV_SELECTOR)
action_runner.WaitForJavaScriptCondition(self.OPEN_CONVERSATION_BEGIN_EVENT)
action_runner.WaitForJavaScriptCondition(self.OPEN_CONVERSATION_END_EVENT)
class GmailSearchStory2020(_GmailBrowsingStory):
NAME = 'browse:tools:gmail-search:2020'
# Needs to be http and not https.
URL = 'http://mail.google.com/'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
_SEARCH_SELECTOR = 'input[aria-label="Search mail and chat"]'
# Page event queries.
SEARCH_BEGIN_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_begin"))
'''
SEARCH_END_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_end"))
'''
# These maps translates page-specific event names to event names needed for
# the reported_by_page:* metric.
EVENTS_AND_MEASURES_REPORTED_BY_PAGE = '''
window.__telemetry_reported_page_events = {
'mail:se-1':
'telemetry:reported_by_page:benchmark_begin',
};
window.__telemetry_reported_page_measures = {
'mail:se':
'telemetry:reported_by_page:benchmark_end'
};
'''
def __init__(self, story_set, take_memory_measurement):
super(GmailSearchStory2020,
self).__init__(story_set, take_memory_measurement,
self.EVENTS_AND_MEASURES_REPORTED_BY_PAGE)
def _DidLoadDocument(self, action_runner):
action_runner.Wait(1)
action_runner.ExecuteJavaScript(
'document.querySelector({{ selector }}).focus()',
selector=self._SEARCH_SELECTOR)
action_runner.EnterText('deals')
action_runner.PressKey('Return')
action_runner.WaitForJavaScriptCondition(self.SEARCH_BEGIN_EVENT)
action_runner.WaitForJavaScriptCondition(self.SEARCH_END_EVENT)
class GmailComposeStory2020(_GmailBrowsingStory):
NAME = 'browse:tools:gmail-compose:2020'
# Needs to be http and not https.
URL = 'http://mail.google.com/'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.YEAR_2020]
# Page event queries.
COMPOSE_BEGIN_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_begin"))
'''
COMPOSE_END_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_end"))
'''
# These maps translates page-specific event names to event names needed for
# the reported_by_page:* metric.
EVENTS_AND_MEASURES_REPORTED_BY_PAGE = '''
window.__telemetry_reported_page_events = {
'mail:ob-1':
'telemetry:reported_by_page:benchmark_begin',
};
window.__telemetry_reported_page_measures = {
'mail:ob':
'telemetry:reported_by_page:benchmark_end'
};
'''
def __init__(self, story_set, take_memory_measurement):
super(GmailComposeStory2020,
self).__init__(story_set, take_memory_measurement,
self.EVENTS_AND_MEASURES_REPORTED_BY_PAGE)
def _DidLoadDocument(self, action_runner):
action_runner.Wait(1)
action_runner.EvaluateJavaScript(
"document.evaluate(\"//div[text()='Compose']\", document, "
"null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)"
".singleNodeValue.focus();")
action_runner.PressKey('Return')
action_runner.WaitForJavaScriptCondition(self.COMPOSE_BEGIN_EVENT)
action_runner.WaitForJavaScriptCondition(self.COMPOSE_END_EVENT)
##############################################################################
# Google sheets browsing story.
##############################################################################
class GoogleSheetsDesktopStory(system_health_story.SystemHealthStory):
NAME = 'browse:tools:sheets:2019'
URL = ('https://docs.google.com/spreadsheets/d/' +
'16jfsJs14QrWKhsbxpdJXgoYumxNpnDt08DTK82Puc2A/' +
'edit#gid=896027318&range=C:C')
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [
story_tags.HEALTH_CHECK, story_tags.JAVASCRIPT_HEAVY, story_tags.YEAR_2019
]
# This map translates page-specific event names to event names needed for
# the reported_by_page:* metric.
EVENTS_REPORTED_BY_PAGE = '''
window.__telemetry_reported_page_events = {
'ccv':
'telemetry:reported_by_page:viewable',
'fcoe':
'telemetry:reported_by_page:interactive',
'first_meaningful_calc_begin':
'telemetry:reported_by_page:benchmark_begin',
'first_meaningful_calc_end':
'telemetry:reported_by_page:benchmark_end'
};
'''
# Patch performance.mark to get notified about page events.
PERFOMANCE_MARK = '''
window.__telemetry_observed_page_events = new Set();
(function () {
let reported = window.__telemetry_reported_page_events;
let observed = window.__telemetry_observed_page_events;
let performance_mark = window.performance.mark;
window.performance.mark = function (label) {
performance_mark.call(window.performance, label);
if (reported.hasOwnProperty(label)) {
performance_mark.call(
window.performance, reported[label]);
observed.add(reported[label]);
}
}
})();
'''
# Page event queries.
INTERACTIVE_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:interactive"))
'''
CALC_BEGIN_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_begin"))
'''
CALC_END_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:benchmark_end"))
'''
CLEAR_EVENTS = 'window.__telemetry_observed_page_events.clear()'
# Start recalculation of the current column by invoking
# trixApp.module$contents$waffle$DesktopRitzApp_DesktopRitzApp$actionRegistry_
# .f_actions__com_google_apps_docs_xplat_controller_ActionRegistryImpl_
# ['trix-fill-right'].fireAction()
RECALCULATE_COLUMN = "trixApp.Cb.D['trix-fill-right'].Eb();"
# Patch the goog$Uri.prototype.setParameterValue to fix the
# session parameters that depend on Math.random and Date.now.
DETERMINISITIC_SESSION = '''
if (window.xk) {
window.xk.prototype.wc = function (a, b) {
if (a === "rand") { b = "1566829321650"; }
if (a === "zx") { b = "9azccr4i1bz5"; }
if (a === "ssfi") { b = "0"; }
this.C.set(a, b);
return this;
}
}
'''
def __init__(self, story_set, take_memory_measurement):
super(GoogleSheetsDesktopStory, self).__init__(story_set,
take_memory_measurement)
self.script_to_evaluate_on_commit = js_template.Render(
'''{{@events_reported_by_page}}
{{@performance_mark}}
document.addEventListener('readystatechange', event => {
if (event.target.readyState === 'interactive') {
{{@deterministic_session}}
}
});''',
events_reported_by_page=self.EVENTS_REPORTED_BY_PAGE,
performance_mark=self.PERFOMANCE_MARK,
deterministic_session=self.DETERMINISITIC_SESSION)
def _DidLoadDocument(self, action_runner):
# 1. Wait until the spreadsheet loads.
action_runner.WaitForJavaScriptCondition(self.INTERACTIVE_EVENT)
# 2. Idle for 5 seconds for Chrome's timeToInteractive metric.
action_runner.Wait(5)
# 3. Prepare for observing calcuation events.
action_runner.EvaluateJavaScript(self.CLEAR_EVENTS)
# 4. Recalculate the column.
action_runner.EvaluateJavaScript(self.RECALCULATE_COLUMN)
# 5. Wait for calculation completion.
action_runner.WaitForJavaScriptCondition(self.CALC_BEGIN_EVENT)
action_runner.WaitForJavaScriptCondition(self.CALC_END_EVENT)
##############################################################################
# Google docs browsing stories.
##############################################################################
class GoogleDocsDesktopScrollingStory(system_health_story.SystemHealthStory):
"""
Google Docs scrolling story:
_ Open a document
_ Wait for UI to become available
_ Scroll through the document
"""
NAME = 'browse:tools:docs_scrolling'
# Test document. safe=true forces synchronous layout which helps determinism
# pylint: disable=line-too-long
URL = 'https://docs.google.com/document/d/14sZMXhI1NljEDSFfxhgA4FNI2_rSImxx3tZ4YsNRUdU/preview?safe=true&Debug=true'
# pylint: enable=line-too-long
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.JAVASCRIPT_HEAVY, story_tags.YEAR_2020]
# This map translates page-specific event names to event names needed for
# the reported_by_page:* metric.
EVENTS_REPORTED_BY_PAGE = '''
window.__telemetry_reported_page_events = {
'ccv':
'telemetry:reported_by_page:viewable',
'fcoe':
'telemetry:reported_by_page:interactive',
};
'''
# Patch performance.mark to get notified about page events.
PERFORMANCE_MARK_PATCH = '''
window.__telemetry_observed_page_events = new Set();
(function () {
let reported = window.__telemetry_reported_page_events;
let observed = window.__telemetry_observed_page_events;
let performance_mark = window.performance.mark;
window.performance.mark = function (label) {
performance_mark.call(window.performance, label);
if (reported.hasOwnProperty(label)) {
performance_mark.call(
window.performance, reported[label]);
observed.add(reported[label]);
}
}
})();
'''
# Page event queries.
INTERACTIVE_EVENT = '''
(window.__telemetry_observed_page_events.has(
"telemetry:reported_by_page:interactive"))
'''
CLEAR_EVENTS = 'window.__telemetry_observed_page_events.clear()'
def __init__(self, story_set, take_memory_measurement):
super(GoogleDocsDesktopScrollingStory, self).__init__(
story_set, take_memory_measurement)
self.script_to_evaluate_on_commit = js_template.Render(
'''{{@events_reported_by_page}}
{{@performance_mark}}''',
events_reported_by_page=self.EVENTS_REPORTED_BY_PAGE,
performance_mark=self.PERFORMANCE_MARK_PATCH)
def _DidLoadDocument(self, action_runner):
# Wait for load.
action_runner.WaitForJavaScriptCondition(self.INTERACTIVE_EVENT)
action_runner.Wait(5)
action_runner.EvaluateJavaScript(self.CLEAR_EVENTS)
# Scroll through the document.
action_runner.RepeatableBrowserDrivenScroll(
x_scroll_distance_ratio=0.0,
y_scroll_distance_ratio=1,
repeat_count=6,
speed=800,
timeout=120)
##############################################################################
# Browsing stories with infinite scrolling
##############################################################################
class _InfiniteScrollStory(system_health_story.SystemHealthStory):
SUPPORTED_PLATFORMS = platforms.ALL_PLATFORMS
SCROLL_DISTANCE = 25000
SCROLL_STEP = 1000
MAX_SCROLL_RETRIES = 3
TIME_TO_WAIT_BEFORE_STARTING_IN_SECONDS = 5
def __init__(self, story_set, take_memory_measurement):
super(_InfiniteScrollStory, self).__init__(story_set,
take_memory_measurement)
self.script_to_evaluate_on_commit = '''
window.WebSocket = undefined;
window.Worker = undefined;
window.performance = undefined;''' + override_online.ALWAYS_ONLINE
def _DidLoadDocument(self, action_runner):
action_runner.WaitForJavaScriptCondition(
'document.body != null && '
'document.body.scrollHeight > window.innerHeight && '
'!document.body.addEventListener("touchstart", function() {})')
action_runner.Wait(self.TIME_TO_WAIT_BEFORE_STARTING_IN_SECONDS)
self._Scroll(action_runner, self.SCROLL_DISTANCE, self.SCROLL_STEP)
def _Scroll(self, action_runner, distance, step_size):
""" This function scrolls the webpage by the given scroll distance in
multiple steps, where each step (except the last one) has the given size.
If scrolling gets stuck, the function waits for the page's scroll height to
expand then retries scrolling.
"""
remaining = distance - action_runner.EvaluateJavaScript('window.scrollY')
# Scroll until the window.scrollY is within 1 pixel of the target distance.
while remaining > 1:
last_scroll_height = action_runner.EvaluateJavaScript(
'document.body.scrollHeight')
action_runner.ScrollPage(distance=min(remaining, step_size) + 1)
new_remaining = (distance -
action_runner.EvaluateJavaScript('window.scrollY'))
if remaining <= new_remaining:
# If the page contains an element with a scrollbar, then the synthetic
# gesture generated by action_runner.ScrollPage might have scrolled that
# element instead of the page. Retry scrolling at different place.
# See https://crbug.com/884183.
action_runner.ScrollPage(distance=min(remaining, step_size) + 1,
left_start_ratio=0.01,
top_start_ratio=0.01)
new_remaining = (distance -
action_runner.EvaluateJavaScript('window.scrollY'))
if remaining <= new_remaining:
# Scrolling is stuck. This can happen if the page is loading
# resources. Wait for the page's scrollheight to expand and retry
# scrolling.
action_runner.WaitForJavaScriptCondition(
'document.body.scrollHeight > {{ last_scroll_height }} ',
last_scroll_height=last_scroll_height)
else:
remaining = new_remaining
@classmethod
def GenerateStoryDescription(cls):
return 'Load %s then make a very long scroll.' % cls.URL
class DiscourseDesktopStory2018(_InfiniteScrollStory):
NAME = 'browse:tech:discourse_infinite_scroll:2018'
URL = 'https://meta.discourse.org/t/topic-list-previews/41630/28'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.INFINITE_SCROLL, story_tags.YEAR_2018]
class DiscourseMobileStory2018(_InfiniteScrollStory):
NAME = 'browse:tech:discourse_infinite_scroll:2018'
URL = 'https://meta.discourse.org/t/topic-list-previews/41630/28'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.INFINITE_SCROLL, story_tags.YEAR_2018]
class FacebookScrollDesktopStory2018(_InfiniteScrollStory):
NAME = 'browse:social:facebook_infinite_scroll:2018'
URL = 'https://www.facebook.com/shakira'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.INFINITE_SCROLL, story_tags.YEAR_2018]
def _Login(self, action_runner):
facebook_login.LoginWithDesktopSite(action_runner, 'facebook3')
class FacebookScrollMobileStory2018(_InfiniteScrollStory):
NAME = 'browse:social:facebook_infinite_scroll:2018'
URL = 'https://m.facebook.com/shakira'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [story_tags.YEAR_2018]
def _Login(self, action_runner):
facebook_login.LoginWithMobileSite(action_runner, 'facebook3')
class FlickrMobileStory2019(_InfiniteScrollStory):
NAME = 'browse:media:flickr_infinite_scroll:2019'
URL = 'https://www.flickr.com/explore'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
SCROLL_DISTANCE = 10000
TAGS = [story_tags.INFINITE_SCROLL, story_tags.YEAR_2019]
class PinterestMobileStory2021(_InfiniteScrollStory):
NAME = 'browse:social:pinterest_infinite_scroll:2021'
URL = 'https://www.pinterest.co.uk'
SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY
TAGS = [
story_tags.HEALTH_CHECK, story_tags.INFINITE_SCROLL, story_tags.YEAR_2021
]
# TODO(crbug.com/862077): Story breaks if login is skipped during replay.
SKIP_LOGIN = False
def _Login(self, action_runner):
pinterest_login.LoginMobileAccount(action_runner, 'googletest')
class TumblrStory2018(_InfiniteScrollStory):
NAME = 'browse:social:tumblr_infinite_scroll:2018'
URL = 'https://techcrunch.tumblr.com/'
SCROLL_DISTANCE = 20000
TAGS = [
story_tags.HEALTH_CHECK, story_tags.INFINITE_SCROLL,
story_tags.JAVASCRIPT_HEAVY, story_tags.YEAR_2018
]
def _Login(self, action_runner):
tumblr_login.LoginDesktopAccount(action_runner, 'tumblr')
action_runner.Wait(5)
# Without this page reload the mobile version does not correctly
# go to the https://techcrunch.tumblr.com
action_runner.ReloadPage()
class TwitterScrollDesktopStory2018(_InfiniteScrollStory):
NAME = 'browse:social:twitter_infinite_scroll:2018'
URL = 'https://twitter.com/NASA'
SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY
TAGS = [story_tags.INFINITE_SCROLL, story_tags.YEAR_2018]
|
src/genie/libs/parser/iosxr/tests/AdminShowDiagChassis/cli/equal/golden_output_1_expected.py
|
balmasea/genieparser
| 204 |
146934
|
<gh_stars>100-1000
expected_output = {
'chassis_feature': 'V2 AC PEM',
'clei': 'IPMUP00BRB',
'desc': 'ASR 9006 4 Line Card Slot Chassis with V2 AC PEM',
'device_family': 'ASR',
'device_series': '9006',
'num_line_cards': 4,
'pid': 'ASR-9006-AC-V2',
'rack_num': 0,
'sn': 'FOX1810G8LR',
'top_assy_num': '68-4235-02',
'vid': 'V02'}
|
h2o-bindings/bin/custom/R/gen_aggregator.py
|
kernelrich/h2o-3
| 6,098 |
147009
|
rest_api_version = 99
extensions = dict(
required_params=['training_frame', 'x'],
validate_required_params="",
set_required_params="""
parms$training_frame <- training_frame
if(!missing(x))
parms$ignored_columns <- .verify_datacols(training_frame, x)$cols_ignore
""",
with_model="""
model@model$aggregated_frame_id <- model@model$output_frame$name
""",
module="""
#' Retrieve an aggregated frame from an Aggregator model
#'
#' Retrieve an aggregated frame from the Aggregator model and use it to create a new frame.
#'
#' @param model an \linkS4class{H2OClusteringModel} corresponding from a \code{h2o.aggregator} call.
#' @examples
#' \dontrun{
#' library(h2o)
#' h2o.init()
#' df <- h2o.createFrame(rows = 100,
#' cols = 5,
#' categorical_fraction = 0.6,
#' integer_fraction = 0,
#' binary_fraction = 0,
#' real_range = 100,
#' integer_range = 100,
#' missing_fraction = 0)
#' target_num_exemplars = 1000
#' rel_tol_num_exemplars = 0.5
#' encoding = "Eigen"
#' agg <- h2o.aggregator(training_frame = df,
#' target_num_exemplars = target_num_exemplars,
#' rel_tol_num_exemplars = rel_tol_num_exemplars,
#' categorical_encoding = encoding)
#' # Use the aggregated frame to create a new dataframe
#' new_df <- h2o.aggregated_frame(agg)
#' }
#' @export
h2o.aggregated_frame <- function(model) {
key <- model@model$aggregated_frame_id
h2o.getFrame(key)
}
""",
)
doc = dict(
preamble="""
Build an Aggregated Frame
Builds an Aggregated Frame of an H2OFrame.
""",
params=dict(
x="""A vector containing the \code{character} names of the predictors in the model."""
),
examples="""
library(h2o)
h2o.init()
df <- h2o.createFrame(rows = 100,
cols = 5,
categorical_fraction = 0.6,
integer_fraction = 0,
binary_fraction = 0,
real_range = 100,
integer_range = 100,
missing_fraction = 0)
target_num_exemplars = 1000
rel_tol_num_exemplars = 0.5
encoding = "Eigen"
agg <- h2o.aggregator(training_frame = df,
target_num_exemplars = target_num_exemplars,
rel_tol_num_exemplars = rel_tol_num_exemplars,
categorical_encoding = encoding)
"""
)
|
tests/bulk_importer/test_bulk_importer.py
|
alessiamarcolini/hangar-py
| 202 |
147029
|
import pytest
import numpy as np
def assert_equal(arr, arr2):
assert np.array_equal(arr, arr2)
assert arr.dtype == arr2.dtype
def test_bulk_importer_ndarray(repo):
from hangar.bulk_importer import run_bulk_import
from hangar.bulk_importer import UDF_Return
def make_ndarray(column, key, shape, dtype, multiplier):
size = np.prod(shape)
arr = np.arange(size, dtype=dtype).reshape(shape) * multiplier
yield UDF_Return(column=column, key=key, data=arr)
co = repo.checkout(write=True)
co.add_ndarray_column('arr', shape=(5, 5), dtype=np.uint32)
co.commit('first')
co.close()
kwargs = []
expected_kv = []
for idx in range(200):
_kw_dict = {
'column': 'arr',
'key': idx,
'shape': (5, 5),
'dtype': np.uint32,
'multiplier': idx
}
kwargs.append(_kw_dict)
for _udf_val in make_ndarray(**_kw_dict):
expected_kv.append(_udf_val)
assert len(expected_kv) == 200
run_bulk_import(
repo,
branch_name='master',
column_names=['arr'],
udf=make_ndarray,
udf_kwargs=kwargs,
ncpus=2)
co = repo.checkout()
try:
arr_col = co['arr']
assert len(arr_col) == 200
for _expected_udf_val in expected_kv:
assert _expected_udf_val.key in arr_col
assert_equal(arr_col[_expected_udf_val.key], _expected_udf_val.data)
finally:
co.close()
def test_bulk_importer_pystr(repo):
from hangar.bulk_importer import run_bulk_import
from hangar.bulk_importer import UDF_Return
def make_pystr(column, key, str_val):
yield UDF_Return(column=column, key=key, data=str_val)
co = repo.checkout(write=True)
co.add_str_column('str')
co.commit('first')
co.close()
kwargs = []
expected_kv = []
for idx in range(200):
_kw_dict = {
'column': 'str',
'key': idx,
'str_val': f'{str(idx) * 2}',
}
kwargs.append(_kw_dict)
for _udf_val in make_pystr(**_kw_dict):
expected_kv.append(_udf_val)
assert len(expected_kv) == 200
run_bulk_import(
repo,
branch_name='master',
column_names=['str'],
udf=make_pystr,
udf_kwargs=kwargs,
ncpus=2)
co = repo.checkout()
try:
str_col = co['str']
assert len(str_col) == 200
for _expected_udf_val in expected_kv:
assert _expected_udf_val.key in str_col
assert str_col[_expected_udf_val.key] == _expected_udf_val.data
finally:
co.close()
def test_bulk_importer_pybytes(repo):
from hangar.bulk_importer import run_bulk_import
from hangar.bulk_importer import UDF_Return
def make_pybytes(column, key, str_val):
raw = str_val.encode()
yield UDF_Return(column=column, key=key, data=raw)
co = repo.checkout(write=True)
co.add_bytes_column('bytes')
co.commit('first')
co.close()
kwargs = []
expected_kv = []
for idx in range(200):
_kw_dict = {
'column': 'bytes',
'key': idx,
'str_val': f'{str(idx) * 2}',
}
kwargs.append(_kw_dict)
for _udf_val in make_pybytes(**_kw_dict):
expected_kv.append(_udf_val)
assert len(expected_kv) == 200
run_bulk_import(
repo,
branch_name='master',
column_names=['bytes'],
udf=make_pybytes,
udf_kwargs=kwargs,
ncpus=2)
co = repo.checkout()
try:
bytes_col = co['bytes']
assert len(bytes_col) == 200
for _expected_udf_val in expected_kv:
assert _expected_udf_val.key in bytes_col
assert bytes_col[_expected_udf_val.key] == _expected_udf_val.data
finally:
co.close()
def test_bulk_importer_two_col_pybytes_pystr(repo):
from hangar.bulk_importer import run_bulk_import
from hangar.bulk_importer import UDF_Return
def _make_pystr(column, key, str_val):
yield UDF_Return(column=column, key=key, data=str_val)
def _make_pybytes(column, key, str_val):
raw = str_val.encode()
yield UDF_Return(column=column, key=key, data=raw)
def make_pystr_pybytes(str_col, bytes_col, key, str_val):
yield from _make_pystr(column=str_col, key=key, str_val=str_val)
yield from _make_pybytes(column=bytes_col, key=key, str_val=str_val)
co = repo.checkout(write=True)
co.add_bytes_column('bytes')
co.add_str_column('str')
co.commit('first')
co.close()
kwargs = []
expected_kv = []
for idx in range(200):
_kw_dict = {
'str_col': 'str',
'bytes_col': 'bytes',
'key': idx,
'str_val': f'{str(idx) * 2}',
}
kwargs.append(_kw_dict)
for _udf_val in make_pystr_pybytes(**_kw_dict):
expected_kv.append(_udf_val)
assert len(expected_kv) == 400
run_bulk_import(
repo,
branch_name='master',
column_names=['bytes', 'str'],
udf=make_pystr_pybytes,
udf_kwargs=kwargs,
ncpus=2)
co = repo.checkout()
try:
pybytes_col = co['bytes']
pystr_col = co['str']
assert len(pybytes_col) == 200
assert len(pystr_col) == 200
for _expected_udf_val in expected_kv:
assert _expected_udf_val.column in ['str', 'bytes']
if _expected_udf_val.column == 'str':
assert _expected_udf_val.key in pystr_col
assert pystr_col[_expected_udf_val.key] == _expected_udf_val.data
elif _expected_udf_val.column == 'bytes':
assert _expected_udf_val.key in pystr_col
assert pybytes_col[_expected_udf_val.key] == _expected_udf_val.data
else:
raise ValueError(_expected_udf_val.column)
finally:
co.close()
def test_signature_wrong(repo):
from hangar.bulk_importer import run_bulk_import
from hangar.bulk_importer import UDF_Return
def wrong_sig_udf(a, b, c=None):
yield UDF_Return(column='str', key=a, data=f'{a} {b} {c}')
co = repo.checkout(write=True)
co.add_str_column('str')
co.commit('first')
co.close()
kwargs = []
for idx in range(200):
_kw_dict = {
'a': 'bytes',
'str_val': f'{str(idx) * 2}',
}
kwargs.append(_kw_dict)
with pytest.raises(TypeError):
run_bulk_import(
repo,
branch_name='master',
column_names=['str'],
udf=wrong_sig_udf,
udf_kwargs=kwargs,
ncpus=2)
|
code/generic/policies.py
|
ElliotMunro200/reinforcement_learning_an_introduction
| 234 |
147069
|
<filename>code/generic/policies.py<gh_stars>100-1000
#!/usr/bin/env python
"""
--------------------------------
project: code
created: 26/06/2018 17:26
---------------------------------
"""
from collections import defaultdict
import numpy as np
from generic.utils import choose_from
def greedy(state_action_values):
return max(state_action_values, key=lambda k: state_action_values[k])
# not sure if these policy classes should keep references to the action values. Maybe not...
class GreedyPolicy:
def __init__(self, action_values, cache=False):
"""
A greedy policy.
Args:
action_values (dict): Action Values
cache (bool): Whether to cache the policy decisions, useful if you only want to evaluate the policy and
you won't be updating the action values
"""
self.action_values = action_values
self._cache = cache
if cache:
self._greedy = dict()
def _cache_call(self, state):
if state not in self._greedy:
self._greedy[state] = greedy(self.action_values[state])
return self._greedy[state]
def __call__(self, state):
return self._cache_call(state) if self._cache else greedy(self.action_values[state])
class EpsilonGreedyPolicy:
def __init__(self, action_values, epsilon, random_state=None):
self.action_values = action_values
self.epsilon = epsilon
self.random_state = random_state or np.random.RandomState(seed=0)
def explore(self):
return self.random_state.binomial(n=1, p=self.epsilon) == 1
def __call__(self, state):
if self.explore():
return choose_from(list(self.action_values[state].keys()), self.random_state)
else:
return greedy(self.action_values[state])
class TimeBiasedPolicy:
def __init__(self, action_values, kappa):
self.action_values = action_values
self.kappa = kappa
self._time_last_visited_table = defaultdict(dict)
self._time_step = 0
def time_since_visited(self, state, action):
try:
t = self._time_last_visited_table[state][action]
except KeyError:
t = -1
return self._time_step - t
def __call__(self, state):
modified_av = {
a: v + self.kappa * np.sqrt(self.time_since_visited(state, a))
for a, v in self.action_values[state].items()
}
chosen_action = greedy(modified_av)
self._time_last_visited_table[state][chosen_action] = self._time_step
self._time_step += 1
return chosen_action
|
nn_pruning/tests/test_patch.py
|
ebell495/nn_pruning
| 250 |
147074
|
import unittest
from unittest import TestCase
from transformers import BertConfig, BertForQuestionAnswering
from nn_pruning.model_structure import BertStructure
from nn_pruning.modules.masked_nn import (
ChannelPruningModulePatcher,
JointPruningModulePatcher,
LinearPruningArgs,
LinearPruningModulePatcher,
LinearPruningArgs,
)
from nn_pruning.training_patcher import LinearModelPatcher, PatcherContext
class TestFun(TestCase):
MODEL_STRUCTURE = BertStructure
def test_base(self):
config = BertConfig.from_pretrained("bert-base-uncased")
model = BertForQuestionAnswering(config)
patcher = LinearModelPatcher({}, self.MODEL_STRUCTURE)
layers = patcher.get_patchable_layers(model)
# for regexp, layers in layers.items():
# print(regexp)
def test_patch_module_independent_parameters(self):
config = BertConfig.from_pretrained("bert-base-uncased")
model = BertForQuestionAnswering(config)
parameters = LinearPruningArgs(
method="topK",
submethod="default",
ampere_method="disabled",
block_rows=32,
block_cols=32,
min_elements=0.005,
)
context = PatcherContext()
p = LinearPruningModulePatcher(context, parameters, self.MODEL_STRUCTURE)
module_patchers = dict(query=p, key=p, value=p, att_dense=p, interm_dense=p, output_dense=p)
patcher = LinearModelPatcher(module_patchers, self.MODEL_STRUCTURE)
patcher.patch(model)
self.assertEqual(patcher.stats["patched"], 72)
key_sizes = {k: len(v) for k, v in context.context_modules.items()}
self.assertEqual(key_sizes, {"mask": 72})
def test_patch_module_ampere(self):
config = BertConfig.from_pretrained("bert-base-uncased")
model = BertForQuestionAnswering(config)
parameters = LinearPruningArgs(
method="topK",
submethod="default",
ampere_method="annealing",
block_rows=32,
block_cols=32,
min_elements=0.005,
)
context = PatcherContext()
p = LinearPruningModulePatcher(context, parameters, self.MODEL_STRUCTURE)
module_patchers = dict(query=p, key=p, value=p, att_dense=p, interm_dense=p, output_dense=p)
patcher = LinearModelPatcher(module_patchers, self.MODEL_STRUCTURE)
patcher.patch(model)
self.assertEqual(patcher.stats["patched"], 72)
key_sizes = {k: len(v) for k, v in context.context_modules.items()}
self.assertEqual(key_sizes, {"ampere_mask": 72, "mask": 72})
def test_patch_module_tied_attention(self):
config = BertConfig.from_pretrained("bert-base-uncased")
model = BertForQuestionAnswering(config)
parameters = LinearPruningArgs(
method="topK",
submethod="default",
ampere_method="annealing",
block_rows=32,
block_cols=32,
min_elements=0.005,
)
context = PatcherContext()
p_attention = JointPruningModulePatcher(context, parameters, self.MODEL_STRUCTURE, "attention")
p_dense = LinearPruningModulePatcher(context, parameters, self.MODEL_STRUCTURE)
module_patchers = dict(
query=p_attention,
key=p_attention,
value=p_attention,
att_dense=p_dense,
interm_dense=p_dense,
output_dense=p_dense,
)
patcher = LinearModelPatcher(module_patchers, self.MODEL_STRUCTURE)
patcher.patch(model)
self.assertEqual(patcher.stats["patched"], 72)
key_sizes = {k: len(v) for k, v in context.context_modules.items()}
self.assertEqual(key_sizes, {"ampere_mask": 72, "mask": 48})
def test_patch_tiedattention_line_pruning(self):
config = BertConfig.from_pretrained("bert-base-uncased")
model = BertForQuestionAnswering(config)
parameters_attention = LinearPruningArgs(
method="topK",
submethod="default",
ampere_method="annealing",
block_rows=32,
block_cols=32,
min_elements=0.005,
)
parameters_dense = LinearPruningArgs(
method="topK", submethod="1d", ampere_method="annealing", block_rows=32, block_cols=32, min_elements=0.005
)
context = PatcherContext()
p_attention = JointPruningModulePatcher(context, parameters_attention, self.MODEL_STRUCTURE, suffix=".attention")
p_dense = ChannelPruningModulePatcher(context, parameters_dense, self.MODEL_STRUCTURE, suffix="dense")
module_patchers = dict(
query=p_attention,
key=p_attention,
value=p_attention,
att_dense=p_dense,
interm_dense=p_dense,
output_dense=p_dense,
)
patcher = LinearModelPatcher(module_patchers, self.MODEL_STRUCTURE)
patcher.patch(model)
self.assertEqual(patcher.stats["patched"], 72)
key_sizes = {k: len(v) for k, v in context.context_modules.items()}
for k, v in key_sizes.items():
print(k, v)
for k, v in context.context_modules.items():
print(k, v)
self.assertEqual(key_sizes, {"ampere_mask": 72, "mask": 12, "mask_1d": 48})
if __name__ == "__main__":
unittest.main()
|
test/test_vectors/generators/01_radar.py
|
ZJUGuoShuai/MatX
| 280 |
147080
|
<filename>test/test_vectors/generators/01_radar.py
#!/usr/bin/env python3
import numpy as np
from scipy import signal
from scipy import io
from numpy import random
import math
import os
import matx_common
import cupy as cp
from typing import Dict, List
class simple_pipeline:
def __init__(self, dtype: str, size: List[int]):
self.size = size
self.dtype = dtype
np.random.seed(1234)
self.num_channels = 1
def set_channels(self, nc: int):
self.num_channels = nc
def run(self):
num_pulses = self.size[0]
num_uncompressed_range_bins = self.size[1]
waveform_length = self.size[2]
num_compressed_range_bins = num_uncompressed_range_bins - waveform_length + 1
NDfft = 256
#num_channels = 16
res = {}
x = matx_common.randn_ndarray(
(num_pulses, num_uncompressed_range_bins), self.dtype)
res['x_init'] = x.copy()
waveform = matx_common.randn_ndarray((waveform_length,), self.dtype)
res['waveform'] = waveform.copy()
window = signal.hamming(waveform_length)
waveform_windowed = waveform * window
res['waveform_windowed'] = waveform_windowed.copy()
waveform_windowed_norm = waveform_windowed / \
np.linalg.norm(waveform_windowed)
res['waveform_windowed_norm'] = waveform_windowed_norm.copy()
Nfft = 2**math.ceil(
math.log2(np.max([num_uncompressed_range_bins, waveform_length])))
W = np.conj(np.fft.fft(waveform_windowed_norm, Nfft))
res['W'] = W.copy()
X = np.fft.fft(x, Nfft, 1)
res['X'] = X.copy()
for pulse in range(num_pulses):
y = np.fft.ifft(np.multiply(X[pulse, :], W), Nfft, 0)
x[pulse, 0:num_compressed_range_bins] = y[0:num_compressed_range_bins]
x_compressed = x[:, 0:num_compressed_range_bins]
if self.num_channels > 1:
x_compressed_stack = np.stack([x_compressed] * self.num_channels)
res['x_compressed'] = x_compressed_stack.copy()
else:
res['x_compressed'] = x_compressed.copy()
x_conv2 = signal.convolve2d(
x_compressed, np.matrix([[1], [-2], [1]]), 'valid')
if self.num_channels > 1:
x_conv2_stack = np.stack([x_conv2] * self.num_channels)
res['x_conv2'] = x_conv2_stack.copy()
else:
res['x_conv2'] = x_conv2.copy()
num_pulses = x_conv2.shape[0]
window = np.transpose(np.repeat(np.expand_dims(
signal.hamming(num_pulses), 0), num_compressed_range_bins, axis=0))
X_window = np.fft.fft(np.multiply(x_conv2, window), NDfft, 0)
if self.num_channels > 1:
X_window_stack = np.stack([X_window] * self.num_channels).copy()
res['X_window'] = X_window_stack
else:
res['X_window'] = X_window.copy()
mask = np.transpose(np.asarray([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]]))
norm = signal.convolve2d(np.ones(X_window.shape), mask, 'same')
res['norm_conv2'] = norm.copy()
Xpow = np.abs(X_window)**2
res['Xpow'] = Xpow.copy()
background_averages = np.divide(
signal.convolve2d(Xpow, mask, 'same'), norm)
if self.num_channels > 1:
ba_stacked = np.stack([background_averages] * self.num_channels)
res['background_averages'] = ba_stacked.copy()
else:
res['background_averages'] = background_averages.copy()
Pfa = 1e-5
alpha = np.multiply(norm, np.power(Pfa, np.divide(-1.0, norm)) - 1)
dets = np.zeros(Xpow.shape)
dets[np.where(Xpow > np.multiply(alpha, background_averages))] = 1
res['alpha'] = alpha.copy()
res['dets'] = dets.copy()
if self.num_channels > 1:
dets_stacked = np.stack([dets] * self.num_channels)
res['dets'] = dets_stacked.copy()
else:
res['dets'] = dets.copy()
return res
class ambgfun:
def __init__(self, dtype: str, size: List[int]):
cp.random.seed(1234)
self.size = size
self.dtype = dtype
os.environ['CUPY_CACHE_DIR'] = "/tmp"
def run(self):
siglen = self.size[0]
x = matx_common.randn_ndarray((siglen,), self.dtype)
y = None
fs = 1e3
cutValue = 1.0
_new_ynorm_kernel = cp.ElementwiseKernel(
"int32 xlen, raw T xnorm, raw T ynorm",
"T out",
"""
int row = i / xlen;
int col = i % xlen;
int x_col = col - ( xlen - 1 ) + row;
if ( ( x_col >= 0 ) && ( x_col < xlen ) ) {
out = ynorm[col] * thrust::conj( xnorm[x_col] );
} else {
out = T(0,0);
}
""",
"_new_ynorm_kernel",
options=("-std=c++11",),
)
cut = 'delay'
if 'float64' in x.dtype.name:
x = cp.asarray(x, dtype=cp.complex128)
elif 'float32' in x.dtype.name:
x = cp.asarray(x, dtype=cp.complex64)
else:
x = cp.asarray(x)
xnorm = x / cp.linalg.norm(x)
if y is None:
y = x
ynorm = xnorm
else:
ynorm = y / cp.linalg.norm(y)
len_seq = len(xnorm) + len(ynorm)
nfreq = 2**math.ceil(math.log2(len_seq - 1))
# Consider for deletion as we add different cut values
"""
if len(xnorm) < len(ynorm):
len_diff = len(ynorm) - len(xnorm)
ynorm = cp.concatenate(ynorm, cp.zeros(len_diff))
elif len(xnorm) > len(ynorm):
len_diff = len(xnorm) - len(ynorm)
xnorm = cp.concatenate(xnorm, cp.zeros(len_diff))
"""
xlen = len(xnorm)
# if cut == '2d':
new_ynorm = cp.empty((len_seq - 1, xlen), dtype=xnorm.dtype)
_new_ynorm_kernel(xlen, xnorm, ynorm, new_ynorm)
amf_2d = nfreq * cp.abs(cp.fft.fftshift(
cp.fft.ifft(new_ynorm, nfreq, axis=1), axes=1))
# elif cut == 'delay':
Fd = cp.arange(-fs / 2, fs / 2, fs / nfreq)
fftx = cp.fft.fft(xnorm, nfreq) * \
cp.exp(1j * 2 * cp.pi * Fd * cutValue)
xshift = cp.fft.ifft(fftx)
ynorm_pad = cp.zeros(nfreq) + cp.zeros(nfreq)*1j
ynorm_pad[:ynorm.shape[0]] = ynorm
amf_delay = nfreq * cp.abs(cp.fft.ifftshift(
cp.fft.ifft(ynorm_pad * cp.conj(xshift), nfreq)))
# elif cut == 'doppler':
t = cp.arange(0, xlen) / fs
ffty = cp.fft.fft(ynorm, len_seq - 1)
fftx = cp.fft.fft(xnorm * cp.exp(1j * 2 * cp.pi * cutValue * t),
len_seq - 1)
amf_doppler = cp.abs(cp.fft.fftshift(
cp.fft.ifft(ffty * cp.conj(fftx))))
return {
'amf_2d': cp.asnumpy(amf_2d),
'amf_delay': cp.asnumpy(amf_delay),
'amf_doppler': cp.asnumpy(amf_doppler),
'x': cp.asnumpy(x),
}
|
data_validation/jellyfish_distance.py
|
ajw0100/professional-services-data-validator
| 167 |
147098
|
<gh_stars>100-1000
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import jellyfish
def extract_closest_match(search_key, target_list, score_cutoff=0):
"""Return str value from target list with highest score using Jaro
for String distance.
search_key (str): A string used to search for cloest match.
target_list (list): A list of strings for comparison.
score_cutoff (float): A scorre cutoff (betwen 0 and 1) to be met.
"""
highest_score = score_cutoff
highest_value_key = None
for target_key in target_list:
score = jellyfish.jaro_similarity(search_key, target_key)
if score >= highest_score:
highest_score = score
highest_value_key = target_key
return highest_value_key
|
tests/daemon_chdir.py
|
santosh653/daemonize
| 377 |
147126
|
#!/usr/bin/env python
from sys import argv
from daemonize import Daemonize
pid = argv[1]
working_dir = argv[2]
file_name = argv[3]
def main():
with open(file_name, "w") as f:
f.write("test")
daemon = Daemonize(app="test_app", pid=pid, action=main, chdir=working_dir)
daemon.start()
|
project/tests/helpers.py
|
InStateTeam/virtual-identities
| 267 |
147128
|
<gh_stars>100-1000
# project/tests/helpers.py
|
tests/test_elements/test_ui_horizontal_scroll_bar.py
|
glipR/pygame_gui
| 339 |
147152
|
import os
import pytest
import pygame
from tests.shared_fixtures import _init_pygame, default_ui_manager
from tests.shared_fixtures import default_display_surface, _display_surface_return_none
from tests.shared_comparators import compare_surfaces
from pygame_gui.ui_manager import UIManager
from pygame_gui.elements.ui_horizontal_scroll_bar import UIHorizontalScrollBar
from pygame_gui.core.ui_container import UIContainer
from pygame_gui.core.interfaces import IUIManagerInterface
try:
pygame.MOUSEWHEEL
except AttributeError:
pygame.MOUSEWHEEL = -1
class TestUIHorizontalScrollBar:
def test_creation(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
assert scroll_bar.image is not None
def test_rebuild(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
scroll_bar.rebuild()
assert scroll_bar.image is not None
def test_check_has_moved_recently(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
# move the scroll bar a bit
scroll_bar.right_button.held = True
scroll_bar.update(0.2)
assert scroll_bar.check_has_moved_recently() is True
def test_check_update_buttons(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
# scroll down a bit then up again to exercise update
scroll_bar.right_button.held = True
scroll_bar.update(0.3)
scroll_bar.right_button.held = False
scroll_bar.left_button.held = True
scroll_bar.update(0.3)
assert scroll_bar.check_has_moved_recently() is True
def test_check_update_sliding_bar(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(0, 0, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
# scroll down a bit then up again to exercise update
default_ui_manager.mouse_position = (100, 15)
scroll_bar.sliding_button.held = True
scroll_bar.update(0.3)
assert scroll_bar.grabbed_slider is True
scroll_bar.sliding_button.held = False
scroll_bar.update(0.3)
assert scroll_bar.grabbed_slider is False
def test_redraw_scroll_bar(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
scroll_bar.redraw_scrollbar()
assert scroll_bar.sliding_button is not None
def test_reset_scroll_position(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
scroll_bar.reset_scroll_position()
assert scroll_bar.scroll_position == 0.0 and scroll_bar.start_percentage == 0.0
def test_set_visible_percentage(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
scroll_bar.start_percentage = 0.9
scroll_bar.set_visible_percentage(0.2)
assert scroll_bar.visible_percentage == 0.2
scroll_bar.set_visible_percentage(-0.2)
assert scroll_bar.visible_percentage == 0.0
scroll_bar.set_visible_percentage(1.9)
assert scroll_bar.visible_percentage == 1.0
def test_kill(self, _init_pygame, default_ui_manager: IUIManagerInterface,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
assert len(default_ui_manager.get_root_container().elements) == 2
assert len(default_ui_manager.get_sprite_group().sprites()) == 6
scroll_bar_sprites = [default_ui_manager.get_root_container(),
scroll_bar,
scroll_bar.button_container,
scroll_bar.left_button,
scroll_bar.right_button,
scroll_bar.sliding_button]
assert default_ui_manager.get_sprite_group().sprites() == scroll_bar_sprites
scroll_bar.kill()
assert len(default_ui_manager.get_root_container().elements) == 0
assert len(default_ui_manager.get_sprite_group().sprites()) == 1
empty_sprites = [default_ui_manager.get_root_container()]
assert default_ui_manager.get_sprite_group().sprites() == empty_sprites
def test_process_event(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.7,
manager=default_ui_manager)
scroll_bar.hovered = True
assert scroll_bar.process_event(pygame.event.Event(pygame.MOUSEWHEEL, {'x': 0.5})) is True
assert scroll_bar.process_event(pygame.event.Event(pygame.MOUSEWHEEL, {'x': -0.5})) is True
def test_rebuild_from_theme_data_non_default(self, _init_pygame,
_display_surface_return_none):
manager = UIManager((800, 600), os.path.join("tests", "data",
"themes",
"ui_horizontal_scroll_bar_non_default.json"))
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.1,
manager=manager)
assert scroll_bar.image is not None
def test_rebuild_from_theme_data_no_arrow_buttons(self, _init_pygame,
_display_surface_return_none):
manager = UIManager((800, 600), os.path.join("tests", "data",
"themes",
"ui_horizontal_scroll_bar_no_arrows.json"))
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=0.1,
manager=manager)
assert scroll_bar.left_button is None
assert scroll_bar.right_button is None
assert scroll_bar.image is not None
@pytest.mark.filterwarnings("ignore:Invalid value")
@pytest.mark.filterwarnings("ignore:Colour hex code")
def test_rebuild_from_theme_data_bad_values(self, _init_pygame,
_display_surface_return_none):
manager = UIManager((800, 600), os.path.join("tests", "data",
"themes",
"ui_horizontal_scroll_bar_bad_values.json"))
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 100, 150, 30),
visible_percentage=1.0,
manager=manager)
assert scroll_bar.image is not None
def test_set_position(self, _init_pygame, default_ui_manager, _display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(80, 100, 200, 30),
visible_percentage=0.25, manager=default_ui_manager)
scroll_bar.set_position((200, 200))
# try to click on the scroll bar's left button
default_ui_manager.process_events(pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': (205, 215)}))
# if we successfully clicked on the moved scroll bar then this button should be True
assert scroll_bar.left_button.held is True
default_ui_manager.process_events(pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': (395, 215)}))
# if we successfully clicked on the moved scroll bar then this button should be True
assert scroll_bar.right_button.held is True
default_ui_manager.process_events(pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': (250, 215)}))
# if we successfully clicked on the moved scroll bar then this button should be True
assert scroll_bar.sliding_button.held is True
def test_set_relative_position(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
test_container = UIContainer(relative_rect=pygame.Rect(50, 50, 300, 250),
manager=default_ui_manager)
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(80, 100, 200, 30),
visible_percentage=0.25, manager=default_ui_manager,
container=test_container)
scroll_bar.set_relative_position((50, 50))
# try to click on the scroll bar's left button
default_ui_manager.process_events(pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': (105, 115)}))
# if we successfully clicked on the moved scroll bar then this button should be True
assert scroll_bar.left_button.held is True
default_ui_manager.process_events(pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': (295, 115)}))
# if we successfully clicked on the moved scroll bar then this button should be True
assert scroll_bar.right_button.held is True
default_ui_manager.process_events(pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': (150, 115)}))
# if we successfully clicked on the moved scroll bar then this button should be True
assert scroll_bar.sliding_button.held is True
def test_set_dimensions(self, _init_pygame, default_ui_manager,
_display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 0, 200, 30),
visible_percentage=0.25, manager=default_ui_manager)
scroll_bar.set_dimensions((100, 60))
# try to click on the slider
default_ui_manager.process_events(pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': (195, 40)}))
# if we successfully clicked on the moved slider then this button should be True
assert scroll_bar.right_button.held is True
def test_disable(self, _init_pygame: None, default_ui_manager: UIManager,
_display_surface_return_none: None):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(0, 0, 200, 30),
visible_percentage=0.25, manager=default_ui_manager)
scroll_bar.disable()
# process a mouse button down event
scroll_bar.right_button.process_event(
pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': scroll_bar.right_button.rect.center}))
scroll_bar.update(0.1)
# process a mouse button up event
scroll_bar.right_button.process_event(
pygame.event.Event(pygame.MOUSEBUTTONUP,
{'button': 1, 'pos': scroll_bar.right_button.rect.center}))
assert scroll_bar.scroll_position == 0.0 and scroll_bar.is_enabled is False
def test_enable(self, _init_pygame: None, default_ui_manager: UIManager,
_display_surface_return_none: None):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(0, 0, 200, 30),
visible_percentage=0.25, manager=default_ui_manager)
scroll_bar.disable()
scroll_bar.enable()
# process a mouse button down event
scroll_bar.right_button.process_event(
pygame.event.Event(pygame.MOUSEBUTTONDOWN,
{'button': 1, 'pos': scroll_bar.right_button.rect.center}))
scroll_bar.update(0.1)
# process a mouse button up event
scroll_bar.right_button.process_event(
pygame.event.Event(pygame.MOUSEBUTTONUP,
{'button': 1, 'pos': scroll_bar.right_button.rect.center}))
assert scroll_bar.scroll_position != 0.0 and scroll_bar.is_enabled is True
def test_show(self, _init_pygame, default_ui_manager, _display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 0, 200, 30),
visible_percentage=0.25, manager=default_ui_manager,
visible=0)
assert scroll_bar.visible == 0
assert scroll_bar.button_container.visible == 0
assert scroll_bar.sliding_button.visible == 0
assert scroll_bar.left_button.visible == 0
assert scroll_bar.right_button.visible == 0
scroll_bar.show()
assert scroll_bar.visible == 1
assert scroll_bar.button_container.visible == 1
assert scroll_bar.sliding_button.visible == 1
assert scroll_bar.left_button.visible == 1
assert scroll_bar.right_button.visible == 1
def test_hide(self, _init_pygame, default_ui_manager, _display_surface_return_none):
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(100, 0, 200, 30),
visible_percentage=0.25, manager=default_ui_manager)
assert scroll_bar.visible == 1
assert scroll_bar.button_container.visible == 1
assert scroll_bar.sliding_button.visible == 1
assert scroll_bar.left_button.visible == 1
assert scroll_bar.right_button.visible == 1
scroll_bar.hide()
assert scroll_bar.visible == 0
assert scroll_bar.button_container.visible == 0
assert scroll_bar.sliding_button.visible == 0
assert scroll_bar.left_button.visible == 0
assert scroll_bar.right_button.visible == 0
def test_show_hide_rendering(self, _init_pygame, default_ui_manager, _display_surface_return_none):
resolution = (400, 400)
empty_surface = pygame.Surface(resolution)
empty_surface.fill(pygame.Color(0, 0, 0))
surface = empty_surface.copy()
manager = UIManager(resolution)
scroll_bar = UIHorizontalScrollBar(relative_rect=pygame.Rect(25, 25, 375, 150),
visible_percentage=0.25,
manager=manager,
visible=0)
manager.update(0.01)
manager.draw_ui(surface)
assert compare_surfaces(empty_surface, surface)
surface.fill(pygame.Color(0, 0, 0))
scroll_bar.show()
manager.update(0.01)
manager.draw_ui(surface)
assert not compare_surfaces(empty_surface, surface)
surface.fill(pygame.Color(0, 0, 0))
scroll_bar.hide()
manager.update(0.01)
manager.draw_ui(surface)
assert compare_surfaces(empty_surface, surface)
|
osrc/asyncdl.py
|
dmessing/osrc
| 279 |
147153
|
<filename>osrc/asyncdl.py
# -*- coding: utf-8 -*-
__all__ = ["Downloader"]
from functools import partial
from tornado import ioloop
from tornado import httpclient
class Downloader(object):
def download(self, urls, **kwargs):
self.urls = urls
self.errors = []
self.results = []
http_client = httpclient.AsyncHTTPClient()
[http_client.fetch(url, partial(self.handle_request, url), **kwargs)
for url in urls]
ioloop.IOLoop.instance().start()
if len(self.errors):
for k, (code, error) in self.errors:
print(k, code, error)
raise RuntimeError("{0} errors".format(len(self.errors)))
return dict(self.results)
def handle_request(self, url, response):
if response.error:
self.errors.append((url, (response.code, response.error)))
else:
self.results.append((url, response.body))
if (len(self.results) + len(self.errors)) == len(self.urls):
ioloop.IOLoop.instance().stop()
|
tests/test_compiler_builtins.py
|
Ivanovitchk/EasyClangComplete
| 648 |
147169
|
"""Tests for CompilerBuiltIns class."""
import imp
from unittest import TestCase
from EasyClangComplete.plugin.flags_sources import compiler_builtins
imp.reload(compiler_builtins)
CompilerBuiltIns = compiler_builtins.CompilerBuiltIns
class TestFlag(TestCase):
"""Test getting built in flags from a target compiler."""
def test_empty(self):
"""Test empty."""
built_ins = CompilerBuiltIns("", None)
self.assertEqual(len(built_ins.includes), 0)
self.assertEqual(len(built_ins.defines), 0)
def test_plain(self):
"""Test retrieval of built ins when we are uncertain about the language.
In this test we check retrieval of built ins when we cannot be sure
about the target language. Input is a command line with the call to the
compiler but without a filename. In this case, we expect only the
compiler to be guessed correctly. Asking it for built ins should
yield C flags (which are a sub-set of flags for other languages).
"""
built_ins = CompilerBuiltIns("clang", None)
self.assertTrue(len(built_ins.defines) > 0)
self.assertTrue(len(built_ins.includes) > 0)
self.assertEqual(len(built_ins.flags),
len(built_ins.defines) + len(built_ins.includes))
def test_c(self):
"""Test retrieval of flags for a C compiler.
Here, in addition to the compiler we have an explicit hint to the
target language in use. Hence, the correct language (and also standard)
must be guessed correctly.
"""
built_ins = CompilerBuiltIns("clang", ["-std=c99", "-x", "c"])
self.assertTrue(len(built_ins.defines) > 0)
self.assertTrue(len(built_ins.includes) > 0)
self.assertIn("-D__clang__=1", built_ins.flags)
def test_cxx(self):
"""Test retrieval of flags for a C++ compiler.
We check if we can get flags for a C++ compiler. The language
can be derived from either the compiler name, an explicit
language given in the flags to the compiler or the filename. To make
sure, we check if C++ specific defines are in the retrieved flags.
"""
test_data = [
{
"args": [],
"filename": None,
"compiler": "clang++"
},
{
"args": ["-x", "c++"],
"filename": None,
"compiler": "clang"
}
]
for test_set in test_data:
print("Testing using test set: {}".format(test_set))
built_ins = CompilerBuiltIns(
test_set["compiler"], test_set["args"], test_set["filename"])
is_cpp = False
for define in built_ins.defines:
if define.startswith("-D__cplusplus="):
is_cpp = True
self.assertTrue(is_cpp)
def test_objc(self):
"""Test retrieval of flags for an Objective-C compiler.
We check if we can get flags for an Objective-C compiler.
For this, we make sure we recognize if a compilation is for Objective-C
by looking at explicit target languages or the filename of the input
file.
"""
test_data = [
{
"args": ["-x", "objective-c"],
"filename": None,
"compiler": "clang"
}
]
for test_set in test_data:
print("Testing using test set: {}".format(test_set))
built_ins = CompilerBuiltIns(
test_set["compiler"], test_set["args"], test_set["filename"])
self.assertIn("-D__OBJC__=1", built_ins.flags)
def test_objcpp(self):
"""Test retrieval of flags for an Objective-C++ compiler.
We check if we can get flags for an Objective-C++ compiler.
For this, we look if we can find an explicit language flag in the
compiler argument list.
"""
test_data = [
{
"args": ["-x", "objective-c++"],
"filename": None,
"compiler": "clang"
}
]
for test_set in test_data:
print("Testing using test set: {}".format(test_set))
built_ins = CompilerBuiltIns(
test_set["compiler"], test_set["args"], test_set["filename"])
self.assertIn("-D__OBJC__=1", built_ins.flags)
is_cpp = False
for define in built_ins.defines:
if define.startswith("-D__cplusplus="):
is_cpp = True
self.assertTrue(is_cpp)
|
babble/utils.py
|
rit-git/vanilla-snorkel
| 130 |
147172
|
from collections import Counter, defaultdict
import csv
import json
import os
import random
import sys
from time import time
from metal.contrib.info_extraction.mentions import RelationMention
from metal.contrib.info_extraction.utils import mark_entities
import numpy as np
import torch
from scipy.sparse import issparse
from .explanation import Explanation
class PrintTimer:
"""Prints msg at start, total time taken at end."""
def __init__(self, msg, prefix="###"):
self.msg = msg
self.prefix = prefix + " " if len(prefix) > 0 else prefix
def __enter__(self):
self.t0 = time()
print("{0}{1}".format(self.prefix, self.msg))
def __exit__(self, type, value, traceback):
print ("{0}Done in {1:.1f}s.\n".format(self.prefix, time() - self.t0))
class ProgressBar(object):
def __init__(self, N, length=40):
# Protect against division by zero (N = 0 results in full bar being printed)
self.N = max(1, N)
self.nf = float(self.N)
self.length = length
# Precalculate the i values that should trigger a write operation
self.ticks = set([round(i/100.0 * N) for i in range(101)])
self.ticks.add(N-1)
self.bar(0)
def bar(self, i):
"""Assumes i ranges through [0, N-1]"""
if i in self.ticks:
b = int(np.ceil(((i+1) / self.nf) * self.length))
sys.stdout.write(
"\r[{0}{1}] {2}%".format(
"="*b, " "*(self.length-b), int(100*((i+1) / self.nf))))
sys.stdout.flush()
def close(self):
# Move the bar to 100% before closing
self.bar(self.N-1)
sys.stdout.write("\n\n")
sys.stdout.flush()
class ExplanationIO(object):
def write(self, explanations, fpath):
explanations = explanations if isinstance(explanations, list) else [explanations]
with open(fpath, 'w') as tsvfile:
tsvwriter = csv.writer(tsvfile, delimiter='\t')
for exp in explanations:
if isinstance(exp.candidate, str):
candidate_id = exp.candidate
else:
candidate_id = exp.candidate.mention_id
tsvwriter.writerow([
exp.name,
exp.label,
candidate_id,
exp.condition,
])
fpath = fpath if len(fpath) < 50 else fpath[:20] + '...' + fpath[-30:]
print("Wrote {} explanations to {}".format(len(explanations), fpath))
def read(self, fpath):
with open(fpath, 'r') as tsvfile:
tsvreader = csv.reader(tsvfile, delimiter='\t')
num_read = 0
explanations = []
for (name, label, candidate_id, condition) in tsvreader:
explanations.append(
Explanation(
name=name,
label=int(label),
candidate=candidate_id,
condition=condition.strip(),
)
)
num_read += 1
fpath = fpath if len(fpath) < 50 else fpath[:20] + '...' + fpath[-30:]
print("Read {} explanations from {}".format(num_read, fpath))
return explanations
def link_explanation_candidates(explanations, candidates):
"""Doc string goes here."""
target_candidate_ids = set()
linked = 0
print("Building list of target candidate ids...")
for e in explanations:
if e.candidate is not None and not isinstance(e.candidate, RelationMention):
target_candidate_ids.add(e.candidate)
elif e.candidate:
linked += 1
if linked == len(explanations):
print("All {} explanations are already linked to candidates.".format(
len(explanations)))
return explanations
else:
print("Collected {} unique target candidate ids from {} explanations.".format(
len(target_candidate_ids), len(explanations)))
if not target_candidate_ids:
print("No candidate hashes were provided. Skipping linking.")
return explanations
candidate_map = {}
print("Gathering desired candidates...")
for candidate in candidates:
if candidate.mention_id in target_candidate_ids:
candidate_map[candidate.mention_id] = candidate
if len(candidate_map) < len(target_candidate_ids):
num_missing = len(target_candidate_ids) - len(candidate_map)
print("Could not find {} target candidates with the following mention_ids (first 5):".format(
num_missing))
num_reported = 0
for i, c_hash in enumerate(target_candidate_ids):
if c_hash not in candidate_map:
print(c_hash)
num_reported += 1
if num_reported >= 5:
break
print("Found {}/{} desired candidates".format(
len(candidate_map), len(target_candidate_ids)))
print("Linking explanations to candidates...")
for e in explanations:
if not isinstance(e.candidate, RelationMention):
try:
e.candidate = candidate_map[e.candidate]
linked += 1
except KeyError:
pass
print("Linked {}/{} explanations".format(linked, len(explanations)))
return explanations
def sparse_to_indices(X):
"""Converts a sparse matrix into a tensor of the nonzero indices
Args:
X: an [n, num_features] one-hot scipy.sparse matrix
Returns:
X_idx: an [n, h] tensor where X_idx[i,:] is a zero-padded 1D tesnor of
the nonzero indices of X[i,:]
"""
if not issparse(X):
raise ValueError("X must be a scipy.sparse matrix")
nonzeros = X.nonzero()
indices = defaultdict(list)
for i, v in zip(nonzeros[0], nonzeros[1]):
indices[i].append(v + 1)
max_len = max(map(lambda x: len(x), indices.values()))
X_idx = torch.zeros(X.shape[0], max_len).long()
for i, values in indices.items():
X_idx[i, :len(values)] = torch.LongTensor(values)
return X_idx
def display_candidate(candidate):
tokens = candidate.tokens
positions = list(zip(candidate.word_starts, candidate.word_ends))
markers = ['{', '}', '{', '}']
marked = mark_entities(tokens, positions, markers, style='concatenate')
print(' '.join(marked))
print()
print(marked)
class CandidateViewer(object):
def __init__(self, candidates, shuffle=False, seed=None):
if seed:
random.seed(seed)
self.candidates = candidates
self.idx = -1
self.order = list(range(len(candidates)))
# Shuffle indirectly to not mess up alignment between candidates and
# other objects in the workspace (e.g., labels).
if shuffle:
random.shuffle(self.order)
def view(self):
self.idx += 1
if self.idx > len(self.order):
print("Exhausted provided candidate set")
return
c = self.candidates[self.order[self.idx]]
display_candidate(c)
return c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.