hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 248 | max_stars_repo_name stringlengths 5 125 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 248 | max_issues_repo_name stringlengths 5 125 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 248 | max_forks_repo_name stringlengths 5 125 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 2.06M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.03M | alphanum_fraction float64 0 1 | count_classes int64 0 1.6M | score_classes float64 0 1 | count_generators int64 0 651k | score_generators float64 0 1 | count_decorators int64 0 990k | score_decorators float64 0 1 | count_async_functions int64 0 235k | score_async_functions float64 0 1 | count_documentation int64 0 1.04M | score_documentation float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dcca7131726cc736db9713ef7e9fc6e4d4c07906 | 226 | py | Python | sites/newbrandx/rankx/admin.py | jackytu/newbrandx | 19569a725bef86a77e94009353e7be5fc6f1b993 | [
"BSD-3-Clause"
] | null | null | null | sites/newbrandx/rankx/admin.py | jackytu/newbrandx | 19569a725bef86a77e94009353e7be5fc6f1b993 | [
"BSD-3-Clause"
] | null | null | null | sites/newbrandx/rankx/admin.py | jackytu/newbrandx | 19569a725bef86a77e94009353e7be5fc6f1b993 | [
"BSD-3-Clause"
] | null | null | null | from django.contrib import admin
# Register your models here.
from .models import Milk
from .models import Brand
from .models import Company
admin.site.register(Milk)
admin.site.register(Brand)
admin.site.register(Company)
| 18.833333 | 32 | 0.800885 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | 0.123894 |
dcca9238b45a4d07ef66ddc0ab5b12946af6ccf6 | 24 | py | Python | class.py | adadesions/python_class | f593cdf3887bff17de05958751e1b080a0a8162e | [
"MIT"
] | null | null | null | class.py | adadesions/python_class | f593cdf3887bff17de05958751e1b080a0a8162e | [
"MIT"
] | null | null | null | class.py | adadesions/python_class | f593cdf3887bff17de05958751e1b080a0a8162e | [
"MIT"
] | null | null | null | """
class lesson
""" | 8 | 16 | 0.458333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 24 | 1 |
dccc2de6c78a75b6d941a646536abd681d5266d8 | 9,797 | py | Python | Paddle_ChineseBert/PaddleNLP/paddlenlp/transformers/chinesebert/tokenizer.py | jiaqianjing/ChineseBERT-Paddle | c4a1a7d08eb8e4b3de1b8e0fb9cefeb7dc0451be | [
"MIT"
] | 1 | 2022-02-25T11:28:31.000Z | 2022-02-25T11:28:31.000Z | Paddle_ChineseBert/PaddleNLP/paddlenlp/transformers/chinesebert/tokenizer.py | jiaqianjing/ChineseBERT-Paddle | c4a1a7d08eb8e4b3de1b8e0fb9cefeb7dc0451be | [
"MIT"
] | null | null | null | Paddle_ChineseBert/PaddleNLP/paddlenlp/transformers/chinesebert/tokenizer.py | jiaqianjing/ChineseBERT-Paddle | c4a1a7d08eb8e4b3de1b8e0fb9cefeb7dc0451be | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : tokenzier.py
@Time : 2021/09/11 16:00:04
@Author : Jia Qianjing
@Version : 1.0
@Contact : jiaqianjing@gmail.com
@Desc : None
'''
import json
import os
from typing import List
import numpy as np
from pypinyin import Style, pinyin
from .. import BasicTokenizer, PretrainedTokenizer, WordpieceTokenizer
__all__ = ['ChineseBertTokenizer']
class ChineseBertTokenizer(PretrainedTokenizer):
resource_files_names = {"vocab_file": "vocab.txt"} # for save_pretrained
pretrained_resource_files_map = {}
pretrained_init_configuration = {}
padding_side = 'right'
def __init__(self,
bert_path,
max_seq_len=512,
do_lower_case=True,
unk_token="[UNK]",
sep_token="[SEP]",
pad_token="[PAD]",
cls_token="[CLS]",
mask_token="[MASK]"):
vocab_file = os.path.join(bert_path, 'vocab.txt')
config_path = os.path.join(bert_path, 'config')
if not os.path.isfile(vocab_file):
raise ValueError(
"Can't find a vocabulary file at path '{}'. To load the "
"vocabulary from a pretrained model please use "
"`tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
.format(vocab_file))
self.vocab = self.load_vocabulary(vocab_file, unk_token=unk_token)
self.max_seq_len = max_seq_len
# load pinyin map dict
with open(os.path.join(config_path, 'pinyin_map.json'),
encoding='utf8') as fin:
self.pinyin_dict = json.load(fin)
# load char id map tensor
with open(os.path.join(config_path, 'id2pinyin.json'),
encoding='utf8') as fin:
self.id2pinyin = json.load(fin)
# load pinyin map tensor
with open(os.path.join(config_path, 'pinyin2tensor.json'),
encoding='utf8') as fin:
self.pinyin2tensor = json.load(fin)
self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab,
unk_token=unk_token)
def tokenize_sentence(self, sentence):
# convert sentence to ids
tokenizer_output = self.encode(sentence)
input_ids = tokenizer_output['input_ids']
pinyin_ids = self.convert_sentence_to_pinyin_ids(sentence)
# assert,token nums should be same as pinyin token nums
# assert len(input_ids) <= self.max_seq_len
# assert len(input_ids) == len(pinyin_ids)
# convert list to tensor
# input_ids = paddle.to_tensor(input_ids)
# pinyin_ids = paddle.to_tensor(pinyin_ids).reshape([-1])
# convert list to np.array
input_ids = np.array(input_ids)
pinyin_ids = np.array(pinyin_ids).reshape([-1, 8])
return {"input_ids": input_ids, "pinyin_ids": pinyin_ids}
def convert_sentence_to_pinyin_ids(self, sentence: str, with_specail_token=True) -> List[List[int]]:
# get offsets
bert_tokens_offsets = self.get_offset_mapping(sentence)
if with_specail_token:
bert_tokens_offsets.insert(0, (0, 0))
bert_tokens_offsets.append((0, 0))
# get tokens
bert_tokens_tokens = self.tokenize(sentence)
if with_specail_token:
bert_tokens_tokens.insert(0, '[CLS]')
bert_tokens_tokens.append('[SEP]')
# get pinyin of a sentence
pinyin_list = pinyin(sentence,
style=Style.TONE3,
heteronym=True,
errors=lambda x: [['not chinese'] for _ in x])
pinyin_locs = {}
# get pinyin of each location
for index, item in enumerate(pinyin_list):
pinyin_string = item[0]
# not a Chinese character, pass
if pinyin_string == "not chinese":
continue
if pinyin_string in self.pinyin2tensor:
pinyin_locs[index] = self.pinyin2tensor[pinyin_string]
else:
ids = [0] * 8
for i, p in enumerate(pinyin_string):
if p not in self.pinyin_dict["char2idx"]:
ids = [0] * 8
break
ids[i] = self.pinyin_dict["char2idx"][p]
pinyin_locs[index] = ids
# find chinese character location, and generate pinyin ids
pinyin_ids = []
for idx, (token, offset) in enumerate(
zip(bert_tokens_tokens, bert_tokens_offsets)):
if offset[1] - offset[0] != 1:
# 非单个字的token,以及 [CLS] [SEP] 特殊 token
pinyin_ids.append([0] * 8)
continue
if offset[0] in pinyin_locs:
# 单个字为token且有拼音tensor
pinyin_ids.append(pinyin_locs[offset[0]])
else:
# 单个字为token但无拼音tensor
pinyin_ids.append([0] * 8)
return pinyin_ids
def convert_tokens_to_pinyin_ids(self,
tokens: List[str]) -> List[List[int]]:
"""
Example :
tokens: ['[CLS]', '你', '多', '大', '了', '?', '[SEP]', '我', '10', '岁', '了', '。', '[SEP]']
"""
pinyin_ids = []
for token in tokens:
if token == '[CLS]' or token == '[SEP]':
# [CLS]、[SEP] 的 token
pinyin_ids.append([0] * 8)
continue
offset = self.get_offset_mapping(token)[0]
if offset[1] - offset[0] != 1:
# 非单个字组成的 token
pinyin_ids.append([0] * 8)
continue
pinyin_string = pinyin(token,
style=Style.TONE3,
heteronym=True,
errors=lambda x: [['not chinese']
for _ in x])[0][0]
if pinyin_string == "not chinese":
# 不是中文
pinyin_ids.append([0] * 8)
else:
if pinyin_string in self.pinyin2tensor:
pinyin_ids.append(self.pinyin2tensor[pinyin_string])
else:
ids = [0] * 8
for i, p in enumerate(pinyin_string):
if p not in self.pinyin_dict["char2idx"]:
ids = [0] * 8
break
ids[i] = self.pinyin_dict["char2idx"][p]
pinyin_ids.append(ids)
return pinyin_ids
@property
def vocab_size(self):
"""
Return the size of vocabulary.
Returns:
int: The size of vocabulary.
"""
return len(self.vocab)
def _tokenize(self, text):
split_tokens = []
for token in self.basic_tokenizer.tokenize(text):
for sub_token in self.wordpiece_tokenizer.tokenize(token):
split_tokens.append(sub_token)
return split_tokens
def tokenize(self, text):
return self._tokenize(text)
def convert_tokens_to_string(self, tokens):
out_string = " ".join(tokens).replace(" ##", "").strip()
return out_string
def num_special_tokens_to_add(self, pair=False):
token_ids_0 = []
token_ids_1 = []
return len(
self.build_inputs_with_special_tokens(
token_ids_0, token_ids_1 if pair else None))
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
if token_ids_1 is None:
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
_cls = [self.cls_token_id]
_sep = [self.sep_token_id]
return _cls + token_ids_0 + _sep + token_ids_1 + _sep
def build_offset_mapping_with_special_tokens(self,
offset_mapping_0,
offset_mapping_1=None):
if offset_mapping_1 is None:
return [(0, 0)] + offset_mapping_0 + [(0, 0)]
return [(0, 0)] + offset_mapping_0 + [(0, 0)
] + offset_mapping_1 + [(0, 0)]
def create_token_type_ids_from_sequences(self,
token_ids_0,
token_ids_1=None):
_sep = [self.sep_token_id]
_cls = [self.cls_token_id]
if token_ids_1 is None:
return len(_cls + token_ids_0 + _sep) * [0]
return len(_cls + token_ids_0 + _sep) * [0] + len(token_ids_1 +
_sep) * [1]
def get_special_tokens_mask(self,
token_ids_0,
token_ids_1=None,
already_has_special_tokens=False):
if already_has_special_tokens:
if token_ids_1 is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model."
)
return list(
map(
lambda x: 1
if x in [self.sep_token_id, self.cls_token_id] else 0,
token_ids_0))
if token_ids_1 is not None:
return [1] + ([0] * len(token_ids_0)) + [1] + (
[0] * len(token_ids_1)) + [1]
return [1] + ([0] * len(token_ids_0)) + [1]
| 39.031873 | 104 | 0.526488 | 9,472 | 0.957251 | 0 | 0 | 189 | 0.019101 | 0 | 0 | 1,892 | 0.191208 |
dccc3770539a345be610b7f21997fe1acd9b086e | 9,949 | py | Python | train.py | w86763777/pytorch-simple-yolov3 | fb08b7c83493bdad3c0d60f8446a2018827b53a1 | [
"WTFPL"
] | null | null | null | train.py | w86763777/pytorch-simple-yolov3 | fb08b7c83493bdad3c0d60f8446a2018827b53a1 | [
"WTFPL"
] | null | null | null | train.py | w86763777/pytorch-simple-yolov3 | fb08b7c83493bdad3c0d60f8446a2018827b53a1 | [
"WTFPL"
] | null | null | null | import os
import argparse
from collections import defaultdict
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.multiprocessing import Process
from tqdm import trange
from tensorboardX import SummaryWriter
from pycocotools.coco import COCO
from yolov3.dataset import DetectionDataset, DistributedMultiScaleSampler
from yolov3.transforms import augmentation, preprocess
from yolov3.models import YOLOs
from yolov3.models.utils import parse_weights
from yolov3.utils import evaluate
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--logdir', default='./logs/yolov3',
help='log directory')
# dataset
parser.add_argument('--train_ann_file', type=str,
default='./data/coco/annotations/instances_trainvalno5k.json',
help='path to training annotation file')
parser.add_argument('--train_img_root', type=str,
default='./data/coco/all2014',
help='path to root of training images')
parser.add_argument('--val_ann_file', type=str,
default='./data/coco/annotations/instances_5k.json',
help='path to val annotation file')
parser.add_argument('--val_img_root', type=str,
default='./data/coco/all2014',
help='path to root of val images')
# learning
parser.add_argument('--lr', default=0.001, type=float,
help='learning rate')
parser.add_argument('--burn_in', default=1000, type=int,
help='warmup iters')
parser.add_argument('--steps', default=[400000, 450000], type=int, nargs='*',
help='lr decay iters')
parser.add_argument('--max_iters', default=500000, type=int,
help='number of iterations')
parser.add_argument('--momentum', default=0.9, type=float,
help='SGD momentum')
parser.add_argument('--decay', default=0.0005, type=float,
help='L2 regularization for convolution kernel')
parser.add_argument('--batch_size', default=4, type=int,
help='batch size')
parser.add_argument('--accumulation', default=16, type=int,
help='batch accumulation')
parser.add_argument('--num_workers', default=6, type=int,
help='dataloader workers')
parser.add_argument('--scale_range', default=[320, 608], type=int, nargs=2,
help='rnage of image size for multi-scale training')
parser.add_argument('--scale_interval', default=10, type=int)
parser.add_argument('--ckpt_interval', default=2000, type=int)
parser.add_argument('--eval_interval', default=4000, type=int)
# yolo
parser.add_argument('--model', default='yolov3', choices=YOLOs.keys(),
help='model name')
parser.add_argument('--weights', default=None, type=str,
help='path to pretrained weights')
parser.add_argument('--n_classes', default=80, type=int,
help='nunmber of classes')
parser.add_argument('--ignore_threshold', default=0.7, type=float,
help='ignore iou threshold')
parser.add_argument('--conf_threshold', default=0.005, type=float,
help='evaluation conf threshold')
parser.add_argument('--nms_threshold', default=0.45, type=float,
help='evaluation nms threshold')
parser.add_argument('--img_size', default=416, type=int,
help='evaluation image size')
parser.add_argument('--val_batch_size', default=32, type=int,
help='evaluation batch size')
args = parser.parse_args()
def inflooper(dataloader, sampler):
epoch = 0
while True:
# shuffle and randomly generate image sizes at the stat of each epoch
sampler.set_epoch(epoch)
for data in dataloader:
yield data
epoch += 1
def main(rank, world_size):
device = torch.device('cuda:%d' % rank)
if rank == 0:
os.makedirs(args.logdir)
# tensorboard writer
writer = SummaryWriter(args.logdir)
# train dataset
train_dataset = DetectionDataset(
COCO(args.train_ann_file),
args.train_img_root,
img_size=None, # changed by DistributedMultiScaleSampler
transforms=augmentation
)
multiscale_sampler = DistributedMultiScaleSampler(
train_dataset, args.batch_size * args.accumulation,
args.scale_interval, args.scale_range)
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=args.batch_size // world_size,
sampler=multiscale_sampler,
num_workers=args.num_workers,
collate_fn=DetectionDataset.collate)
# test dataset
test_dataset = DetectionDataset(
COCO(args.val_ann_file),
args.val_img_root,
args.img_size,
transforms=preprocess)
test_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=args.val_batch_size,
num_workers=args.num_workers,
collate_fn=DetectionDataset.collate)
# model
model = YOLOs[args.model](args.n_classes, args.ignore_threshold).to(device)
# optimizer
decay_params = []
other_params = []
for name, param in model.named_parameters():
if 'conv.weight' in name:
decay_params.append(param)
else:
other_params.append(param)
optim = torch.optim.SGD([
{"params": decay_params, "weight_decay": args.decay},
{"params": other_params, "weight_decay": 0},
], lr=args.lr, momentum=args.momentum)
def lr_factor(iter_i):
if iter_i < args.burn_in:
return pow(iter_i / args.burn_in, 4)
factor = 1.0
for step in args.steps:
if iter_i >= step:
factor *= 0.1
return factor
# learning rate scheduler
sched = torch.optim.lr_scheduler.LambdaLR(optim, lr_factor)
iter_state = 1
# load weights
if rank == 0 and args.weights:
if args.weights.endswith('.pt'):
print("loading pytorch weights:", args.weights)
ckpt = torch.load(args.weights)
model.load_state_dict(ckpt['model'])
optim.load_state_dict(ckpt['optim'])
sched.load_state_dict(ckpt['sched'])
iter_state = ckpt['iter'] + 1
else:
print("loading darknet weights:", args.weights)
parse_weights(model, args.weights)
dist.barrier() # it takes time to load weights
model = DDP(model, device_ids=[rank], output_device=rank)
# start training loop
looper = inflooper(train_loader, multiscale_sampler)
if rank == 0:
pbar = trange(iter_state, args.max_iters + 1, ncols=0)
else:
pbar = range(iter_state, args.max_iters + 1)
for iter_i in pbar:
# accumulation loop
optim.zero_grad()
loss_record = defaultdict(float)
for _ in range(args.accumulation):
imgs, targets, _, _ = next(looper)
imgs, targets = imgs.to(device), targets.to(device)
loss_dict = model(imgs, targets)
loss = 0
for name, value in loss_dict.items():
loss_record[name] += value.detach().item()
loss += value
# normalize the loss by the effective batch size
loss = loss / (imgs.shape[0] * args.accumulation)
loss.backward()
optim.step()
sched.step()
# logging
if rank == 0:
for key, value in loss_record.items():
writer.add_scalar('train/%s' % key, value, iter_i)
writer.add_scalar('train/lr', sched.get_last_lr()[0], iter_i)
# update progress bar
postfix_str = ", ".join(
'%s: %.3f' % (k, v) for k, v in loss_record.items())
pbar.set_postfix_str(postfix_str)
# evaluation
if iter_i % args.eval_interval == 0:
if rank == 0:
model.eval()
ap50_95, ap50 = evaluate(
model=model.module,
loader=test_loader,
conf_threshold=args.conf_threshold,
nms_threshold=args.nms_threshold,
device=device)
model.train()
writer.add_scalar('val/COCO_AP50', ap50, iter_i)
writer.add_scalar('val/COCO_AP50_95', ap50_95, iter_i)
dist.barrier()
# save checkpoint
if iter_i % args.ckpt_interval == 0:
if rank == 0:
ckpt = {
'iter': iter_i,
'model': model.module.state_dict(),
'optim': optim.state_dict(),
'sched': sched.state_dict(),
}
torch.save(
ckpt, os.path.join(args.logdir, "ckpt%d.pt" % iter_i))
dist.barrier()
if rank == 0:
pbar.close()
writer.close()
def initialize_process(rank, world_size):
import datetime
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "39846"
dist.init_process_group('nccl', timeout=datetime.timedelta(seconds=30),
world_size=world_size, rank=rank)
torch.cuda.set_device(rank)
torch.cuda.empty_cache()
print("Node %d is initialized" % rank)
main(rank, world_size)
def spawn_process():
if os.environ.get('CUDA_VISIBLE_DEVICES', None) is not None:
world_size = len(os.environ['CUDA_VISIBLE_DEVICES'].split(','))
else:
world_size = 1
processes = []
for rank in range(world_size):
p = Process(target=initialize_process, args=(rank, world_size))
p.start()
processes.append(p)
for p in processes:
p.join()
if __name__ == '__main__':
spawn_process()
| 37.123134 | 82 | 0.609911 | 0 | 0 | 250 | 0.025128 | 0 | 0 | 0 | 0 | 1,878 | 0.188763 |
dcccd3460841aa56fdd3f12e2c4b74b5af2f3969 | 1,708 | py | Python | progress.py | zzeleznick/config | f7d519004573968aa47fff850480618fd57dc0d1 | [
"MIT"
] | null | null | null | progress.py | zzeleznick/config | f7d519004573968aa47fff850480618fd57dc0d1 | [
"MIT"
] | null | null | null | progress.py | zzeleznick/config | f7d519004573968aa47fff850480618fd57dc0d1 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding=UTF-8
import sys
from blessings import Terminal
import time
import numpy as np
import argparse
# import subprocess;
# subprocess.call(["printf", "\033c"]);
def process_input():
out = None
args = sys.argv[1:]
if args:
out = args[0]
return out
def main():
sys.stderr.write("\x1b[2J\x1b[H")
term = Terminal()
task = process_input()
if not task: task = 'Important stuff'
print term.bold(task)
h = 1
i = 0
limit = 10**5
vals = np.random.random(limit) * 10
prompt = "Progress:"
sep = '|'
units = 'bits'
padding = ' ' * max(3, int(term.width * 0.025))
rhs = len(str(limit)) * 2 + len(sep) + len(units)
lhs = len(prompt) + 5
maxbarsize = max(0, int(term.width * .9) - rhs - lhs - len(padding))
def makeLine(idx = None):
if not idx: idx = i
n = ('%0.0f' % (float(idx)/limit * 100)).zfill(2)
pct = '(%s%s)' % (n, '%')
right = ('%d %s %d %s' % (idx, sep, limit, units)).rjust(rhs)
bar = '=' * int(float(idx) / limit * maxbarsize)
space = ' ' * (maxbarsize - len(bar))
mid = '%s[%s>%s]%s' % (' ', bar, space, padding)
return ' '.join([prompt, pct, mid, right])
print makeLine()
last = time.time()
while i < limit:
if time.time() - last > 0.3:
time.sleep(.05)
print term.move(h, 0) + makeLine()
last = time.time()
if i < len(vals):
time.sleep(vals[i]/10**5)
i += vals[i]
else:
i += np.random.randint(10)
print term.move(h, 0) + makeLine(limit)
print term.bold('Success!')
if __name__ == '__main__':
main() | 25.878788 | 72 | 0.522834 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 225 | 0.131733 |
dccdd28cc039a3a5144b0d2df2b3d0fb83817707 | 3,359 | py | Python | misc/jarvis-dsc-bot/challenge/bot.py | PWrWhiteHats/BtS-CTF-Challenges-03-2021 | 545880c414a6c55fe216d71f9eee2f54f64bb070 | [
"MIT"
] | 7 | 2021-03-14T16:34:56.000Z | 2022-01-18T16:46:25.000Z | misc/jarvis-dsc-bot/challenge/bot.py | PWrWhiteHats/BtS-CTF-Challenges-03-2021 | 545880c414a6c55fe216d71f9eee2f54f64bb070 | [
"MIT"
] | 4 | 2021-03-19T16:09:12.000Z | 2022-03-12T00:55:12.000Z | misc/jarvis-dsc-bot/challenge/bot.py | PWrWhiteHats/BtS-CTF-Challenges-03-2021 | 545880c414a6c55fe216d71f9eee2f54f64bb070 | [
"MIT"
] | null | null | null | # bot.py
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
from time import sleep
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
try:
with open('/app/flag.txt', 'r') as r:
FLAG = r.read().strip()
except FileNotFoundError:
FLAG = os.getenv('FLAG', 'bts{tmpflag}')
prefix = "!!"
accepted_role = "Mr.Stark"
bot = commands.Bot(command_prefix=prefix, case_insensitive=True)
bot.remove_command("help")
@bot.event
async def on_ready():
print('### Working as {0.user}'.format(bot))
@commands.guild_only()
@bot.command()
async def secret(ctx):
role = discord.utils.get(ctx.guild.roles, name=accepted_role)
if role in ctx.author.roles:
await ctx.send(f"Here is secret for you, sir: `{FLAG}`")
else:
await ctx.send(f":no_entry_sign: I am sorry {ctx.author.mention}, but you have no power of `{accepted_role}` here")
@commands.guild_only()
@bot.command()
async def armor(ctx):
role = discord.utils.get(ctx.guild.roles, name=accepted_role)
if role in ctx.author.roles:
await ctx.send(f"You armor will be delivered shortly, sir.")
sleep(0.5)
await ctx.send(f"Safe journey {ctx.author.mention}. :rocket:")
else:
await ctx.send(f"You armor will be delivered shortly, sir.")
await ctx.send(f":no_entry_sign: Wait {ctx.author.mention}, you are not `{accepted_role}` :no_entry_sign:")
@commands.guild_only()
@bot.command()
async def friday(ctx):
role = discord.utils.get(ctx.guild.roles, name=accepted_role)
if role in ctx.author.roles:
await ctx.send(f"Check this out: https://www.youtube.com/watch?v=cjgldht4PKw")
else:
await ctx.send(f":no_entry_sign: I am sorry {ctx.author.mention}, but you have no power of `{accepted_role}` :no_entry_sign:")
@commands.guild_only()
@bot.command()
async def ultron(ctx):
await ctx.send(f":shield: Thanks to {ctx.author.mention}, the Earth will have it's own shield :shield:")
@commands.guild_only()
@bot.command()
async def vision(ctx):
await ctx.send(f":superhero: Hi {ctx.author.mention}, you can call me Vision from now on :superhero:")
@commands.guild_only()
@bot.command()
async def grid(ctx):
await ctx.send(f":flag_no: No worries. I'll hide in the Grid, sir :flag_no:")
@commands.guild_only()
@bot.command()
async def help(ctx):
help_desc = f"Here is a little help for you, sir. Available of commands can be seen below."
e = discord.Embed(title=":question: Help :question:", description=help_desc)
avengers = f"""\
`{prefix}ultron` - protect the Earth
`{prefix}vision` - turn into Vision
`{prefix}grid` - hide in the Internet
"""
e.add_field(name="***Avengers***", value=avengers)
stark = f"""\
`{prefix}armor` - summon Mr. Stark's armor
`{prefix}friday` - call for replacement
`{prefix}secret` - reveal one of Mr. Stark's secrets
"""
e.add_field(name="***Stark***", value=stark)
await ctx.send(embed=e)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CommandNotFound):
e = discord.Embed(title=":exclamation: No such command :exclamation:", description="Try `!!help`")
await ctx.send(embed=e)
elif "403 Forbidden" in error:
return
else:
print(f"---- Unknown error: {error} ----")
return
bot.run(TOKEN) | 31.990476 | 134 | 0.677583 | 0 | 0 | 0 | 0 | 2,865 | 0.852932 | 2,577 | 0.767193 | 1,396 | 0.4156 |
dccfb668a1df9c3316a2a14e3756a083e3ab3839 | 3,734 | py | Python | google/ads/google_ads/v4/proto/services/campaign_bid_modifier_service_pb2_grpc.py | arammaliachi/google-ads-python | a4fe89567bd43eb784410523a6306b5d1dd9ee67 | [
"Apache-2.0"
] | 1 | 2021-04-09T04:28:47.000Z | 2021-04-09T04:28:47.000Z | google/ads/google_ads/v4/proto/services/campaign_bid_modifier_service_pb2_grpc.py | arammaliachi/google-ads-python | a4fe89567bd43eb784410523a6306b5d1dd9ee67 | [
"Apache-2.0"
] | null | null | null | google/ads/google_ads/v4/proto/services/campaign_bid_modifier_service_pb2_grpc.py | arammaliachi/google-ads-python | a4fe89567bd43eb784410523a6306b5d1dd9ee67 | [
"Apache-2.0"
] | null | null | null | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v4.proto.resources import campaign_bid_modifier_pb2 as google_dot_ads_dot_googleads__v4_dot_proto_dot_resources_dot_campaign__bid__modifier__pb2
from google.ads.google_ads.v4.proto.services import campaign_bid_modifier_service_pb2 as google_dot_ads_dot_googleads__v4_dot_proto_dot_services_dot_campaign__bid__modifier__service__pb2
class CampaignBidModifierServiceStub(object):
"""Proto file describing the Campaign Bid Modifier service.
Service to manage campaign bid modifiers.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetCampaignBidModifier = channel.unary_unary(
'/google.ads.googleads.v4.services.CampaignBidModifierService/GetCampaignBidModifier',
request_serializer=google_dot_ads_dot_googleads__v4_dot_proto_dot_services_dot_campaign__bid__modifier__service__pb2.GetCampaignBidModifierRequest.SerializeToString,
response_deserializer=google_dot_ads_dot_googleads__v4_dot_proto_dot_resources_dot_campaign__bid__modifier__pb2.CampaignBidModifier.FromString,
)
self.MutateCampaignBidModifiers = channel.unary_unary(
'/google.ads.googleads.v4.services.CampaignBidModifierService/MutateCampaignBidModifiers',
request_serializer=google_dot_ads_dot_googleads__v4_dot_proto_dot_services_dot_campaign__bid__modifier__service__pb2.MutateCampaignBidModifiersRequest.SerializeToString,
response_deserializer=google_dot_ads_dot_googleads__v4_dot_proto_dot_services_dot_campaign__bid__modifier__service__pb2.MutateCampaignBidModifiersResponse.FromString,
)
class CampaignBidModifierServiceServicer(object):
"""Proto file describing the Campaign Bid Modifier service.
Service to manage campaign bid modifiers.
"""
def GetCampaignBidModifier(self, request, context):
"""Returns the requested campaign bid modifier in full detail.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def MutateCampaignBidModifiers(self, request, context):
"""Creates, updates, or removes campaign bid modifiers.
Operation statuses are returned.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_CampaignBidModifierServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetCampaignBidModifier': grpc.unary_unary_rpc_method_handler(
servicer.GetCampaignBidModifier,
request_deserializer=google_dot_ads_dot_googleads__v4_dot_proto_dot_services_dot_campaign__bid__modifier__service__pb2.GetCampaignBidModifierRequest.FromString,
response_serializer=google_dot_ads_dot_googleads__v4_dot_proto_dot_resources_dot_campaign__bid__modifier__pb2.CampaignBidModifier.SerializeToString,
),
'MutateCampaignBidModifiers': grpc.unary_unary_rpc_method_handler(
servicer.MutateCampaignBidModifiers,
request_deserializer=google_dot_ads_dot_googleads__v4_dot_proto_dot_services_dot_campaign__bid__modifier__service__pb2.MutateCampaignBidModifiersRequest.FromString,
response_serializer=google_dot_ads_dot_googleads__v4_dot_proto_dot_services_dot_campaign__bid__modifier__service__pb2.MutateCampaignBidModifiersResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'google.ads.googleads.v4.services.CampaignBidModifierService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| 53.342857 | 186 | 0.831012 | 2,043 | 0.547134 | 0 | 0 | 0 | 0 | 0 | 0 | 911 | 0.243974 |
dccfcf5fe340584cacae04463285d5b6a560f3d3 | 4,369 | py | Python | readthedocs/oauth/models.py | adrianmugnoz/Documentacion-universidades | 0e088718cdfdb2c9c52118c181def8086c821b1e | [
"MIT"
] | 1 | 2019-05-07T15:08:53.000Z | 2019-05-07T15:08:53.000Z | readthedocs/oauth/models.py | mba811/readthedocs.org | b882cec8c0e7d741d3c58af2f6d0f48d1a123f8d | [
"MIT"
] | null | null | null | readthedocs/oauth/models.py | mba811/readthedocs.org | b882cec8c0e7d741d3c58af2f6d0f48d1a123f8d | [
"MIT"
] | null | null | null | from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class GithubOrganization(models.Model):
# Auto fields
pub_date = models.DateTimeField(_('Publication date'), auto_now_add=True)
modified_date = models.DateTimeField(_('Modified date'), auto_now=True)
users = models.ManyToManyField(User, verbose_name=_('Users'),
related_name='github_organizations')
login = models.CharField(_('Login'), max_length=255, unique=True)
email = models.EmailField(_('Email'), max_length=255, null=True, blank=True)
name = models.CharField(_('Name'), max_length=255, null=True, blank=True)
html_url = models.URLField(_('HTML URL'), max_length=200, null=True, blank=True)
active = models.BooleanField(_('Active'), default=False)
json = models.TextField('JSON')
def __unicode__(self):
return "GitHub Organization: %s" % (self.html_url)
class GithubProject(models.Model):
# Auto fields
pub_date = models.DateTimeField(_('Publication date'), auto_now_add=True)
modified_date = models.DateTimeField(_('Modified date'), auto_now=True)
users = models.ManyToManyField(User, verbose_name=_('Users'),
related_name='github_projects')
organization = models.ForeignKey(GithubOrganization, verbose_name=_('Organization'),
related_name='projects', null=True, blank=True)
name = models.CharField(_('Name'), max_length=255)
full_name = models.CharField(_('Full Name'), max_length=255, unique=True)
description = models.TextField(_('Description'), blank=True, null=True,
help_text=_('The reStructuredText description of the project'))
git_url = models.CharField(_('Git URL'), max_length=200, blank=True)
ssh_url = models.CharField(_('SSH URL'), max_length=200, blank=True)
html_url = models.URLField(_('HTML URL'), max_length=200, null=True, blank=True)
active = models.BooleanField(_('Active'), default=False)
json = models.TextField('JSON')
def __unicode__(self):
return "GitHub Project: %s" % (self.html_url)
class BitbucketTeam(models.Model):
# Auto fields
pub_date = models.DateTimeField(_('Publication date'), auto_now_add=True)
modified_date = models.DateTimeField(_('Modified date'), auto_now=True)
users = models.ManyToManyField(User, verbose_name=_('Users'),
related_name='bitbucket_organizations')
login = models.CharField(_('Login'), max_length=255, unique=True)
email = models.EmailField(_('Email'), max_length=255, null=True, blank=True)
name = models.CharField(_('Name'), max_length=255, null=True, blank=True)
html_url = models.URLField(_('HTML URL'), max_length=200, null=True, blank=True)
active = models.BooleanField(_('Active'), default=False)
json = models.TextField('JSON')
def __unicode__(self):
return "Bitbucket Team: %s" % (self.html_url)
class BitbucketProject(models.Model):
# Auto fields
pub_date = models.DateTimeField(_('Publication date'), auto_now_add=True)
modified_date = models.DateTimeField(_('Modified date'), auto_now=True)
users = models.ManyToManyField(User, verbose_name=_('Users'),
related_name='bitbucket_projects')
organization = models.ForeignKey(BitbucketTeam, verbose_name=_('Organization'),
related_name='projects', null=True, blank=True)
name = models.CharField(_('Name'), max_length=255)
full_name = models.CharField(_('Full Name'), max_length=255, unique=True)
description = models.TextField(_('Description'), blank=True, null=True,
help_text=_('The reStructuredText description of the project'))
vcs = models.CharField(_('vcs'), max_length=200, blank=True)
git_url = models.CharField(_('Git URL'), max_length=200, blank=True)
ssh_url = models.CharField(_('SSH URL'), max_length=200, blank=True)
html_url = models.URLField(_('HTML URL'), max_length=200, null=True, blank=True)
active = models.BooleanField(_('Active'), default=False)
json = models.TextField('JSON')
def __unicode__(self):
return "Bitbucket Project: %s" % (self.html_url)
| 46.978495 | 98 | 0.673838 | 4,228 | 0.967727 | 0 | 0 | 0 | 0 | 0 | 0 | 767 | 0.175555 |
dcd1979ad4bab59c6389ed6cdcd41efd03611f23 | 8,840 | py | Python | hg_agent_forwarder/forwarder.py | hostedgraphite/hg-agent-forwarder | b5bc9a69f1cbd49ba925dd33fa4f28617f1e33dc | [
"MIT"
] | null | null | null | hg_agent_forwarder/forwarder.py | hostedgraphite/hg-agent-forwarder | b5bc9a69f1cbd49ba925dd33fa4f28617f1e33dc | [
"MIT"
] | null | null | null | hg_agent_forwarder/forwarder.py | hostedgraphite/hg-agent-forwarder | b5bc9a69f1cbd49ba925dd33fa4f28617f1e33dc | [
"MIT"
] | 2 | 2018-07-17T15:11:38.000Z | 2018-08-19T12:16:55.000Z | import threading
import Queue
import os
import logging
import json
import time
import random
import requests
import multitail2
import errno
import tempfile
from requests.auth import HTTPBasicAuth
from utils import Datapoint
class MetricForwarder(threading.Thread):
'''
Simple metric data forwarder.
Forwards data over http, has a simple exponential
backoff in case of connectivity issues.
'''
def __init__(self, config, shutdown_e, *args, **kwargs):
super(MetricForwarder, self).__init__(*args, **kwargs)
self.config = config
self.name = "Metric Forwarder"
# Because multitail2 blocks on read, if there is no data being written
# to spool, we can end up with the spool reader blocking (and thus not
# noticing "shutdown"). However, it's fine for this thread to exit with
# the interpreter.
self.daemon = True
self.url = config.get('endpoint_url',
'https://agentapi.hostedgraphite.com/api/v1/sink')
self.api_key = self.config.get('api_key')
self.progress = self.load_progress_file()
self.shutdown_e = shutdown_e
self.spool_reader = SpoolReader('/var/opt/hg-agent/spool/*.spool.*',
progresses=self.progress,
shutdown=self.shutdown_e)
self.progress_writer = ProgressWriter(self.config,
self.spool_reader,
self.shutdown_e)
self.progress_writer.start()
self.retry_interval = random.randrange(200, 400)
self.request_session = requests.Session()
self.request_session.auth = HTTPBasicAuth(self.api_key, '')
self.request_timeout = config.get('request_timeout', 10)
self.batch = ""
self.batch_size = 0
self.batch_time = time.time()
self.batch_timeout = config.get('batch_timeout', 0.5)
self.max_batch_size = config.get('max_batch_size', 250)
def run(self):
while not self.shutdown_e.is_set():
try:
for line in self.spool_reader.read():
if self.shutdown_e.is_set():
break
datapoint = Datapoint(line, self.api_key)
if datapoint.validate():
self.extend_batch(datapoint)
else:
logging.error("Invalid line in spool.")
# invalid somehow, pass
continue
if self.should_send_batch():
self.forward()
except Exception as e:
continue
def extend_batch(self, data):
'''
Add a metric to the current metric batch.
'''
if not self.batch_time:
self.batch_time = time.time()
try:
metric = data.metric
value = data.value
ts = data.timestamp
except AttributeError:
# somehow, this dp is invalid, pass it by.
pass
else:
metric_str = "%s %s %s" % (metric, value, ts)
if self.batch_size == 0:
self.batch = metric_str
else:
self.batch = "%s\n%s" % (self.batch, metric_str)
self.batch_size += 1
def should_send_batch(self):
'''
Check to see if we should send the
current batch.
True if timeout is > 10 or batch
size is reached.
'''
now = time.time()
if (now - self.batch_time) > self.batch_timeout and self.batch_size != 0:
return True
elif self.batch_size > self.max_batch_size:
return True
return False
def forward(self):
not_processed = True
backoff = 0
while not_processed and not self.shutdown_e.is_set():
if self.send_data():
not_processed = False
else:
# Back off exponentially up to 6 times before levelling
# out. E.g. for a retry_interval of 300, that'll result
# in retries at 300, 600, 1200, 2400, 4800, 9600, 9600, ...
interval = (2**backoff) * self.retry_interval
if backoff < 5:
backoff += 1
logging.error('Metric sending failed, retry in %s ms',
interval)
time.sleep(interval / 1000.0)
def send_data(self):
try:
req = self.request_session.post(self.url,
data=self.batch,
stream=False,
timeout=self.request_timeout)
if req.status_code == 429:
logging.info("Metric forwarding limits hit \
please contact support.")
# Ensure exception info is logged for HTTP errors.
req.raise_for_status()
except Exception as e:
logging.error("Metric forwarding exception: %s", e)
return False
else:
# reset batch info now that send has succeeded.
self.batch = ""
self.batch_size = 0
self.batch_time = time.time()
return True
def shutdown(self):
'''Shut down this forwarder.
Deals with the forwarder's progress thread: we want to be certain that
the progress thread has a chance to finish what it's doing if it is
mid-write, so we wait on it. As the forwarder itself is a daemon thread
(which *may* block reading spools via multitail2), it will exit once
everything else is done anyway.
NB: called from outside the forwarder's thread of execution.
'''
while self.progress_writer.is_alive():
self.progress_writer.join(timeout=0.1)
time.sleep(0.1)
def load_progress_file(self):
progress_cfg = self.config.get('progress', {})
progress = {}
try:
progressfile = progress_cfg.get('path',
'/var/opt/hg-agent/spool/progress')
if progressfile is not None:
progress = json.load(file(progressfile))
except (ValueError, IOError, OSError) as e:
logging.error(
'Error loading progress file on startup; '
'spool files will be read from end: %s', e
)
return progress
class SpoolReader(object):
'''
Tails files matching a glob. yields lines from them.
'''
def __init__(self, spoolglob, progresses=None, shutdown=None):
self.progresses = progresses or {}
self.shutdown_e = shutdown
self.data_reader = multitail2.MultiTail(spoolglob,
skip_to_end=False,
offsets=progresses)
def read(self):
for (filename, byteoffset), line in self.data_reader:
if self.shutdown_e.is_set():
break
line_byte_len = len(bytes(line))
# + 1 for newline '\n'
self.progresses[filename] = byteoffset + line_byte_len + 1
try:
if len(line) > 1:
yield line
except ValueError:
logging.error('Could not parse line: %s', line)
continue
class ProgressWriter(threading.Thread):
'''
'''
def __init__(self, config, spool_reader, shutdown_e, *args, **kwargs):
super(ProgressWriter, self).__init__(*args, **kwargs)
self.shutdown_e = shutdown_e
self._config = config
self.interval = self._config.get('interval', 10)
self.spool_reader = spool_reader
self.final_path = '/var/opt/hg-agent/spool/'
def run(self):
while not self.shutdown_e.is_set():
try:
self.atomicwrite()
except Exception as e:
logging.error("Unhandled exception while writing progress: %s",
e)
time.sleep(self.interval)
def atomicwrite(self):
try:
content = json.dumps(self.spool_reader.progresses)
except:
content = {}
try:
os.makedirs('/var/opt/hg-agent/spool/', 0755)
except OSError as err:
if err.errno != errno.EEXIST:
raise
fd, temp_path = tempfile.mkstemp(dir='/var/opt/hg-agent/spool/')
with os.fdopen(fd, 'w') as fh:
fh.write(content)
os.chmod(temp_path, 0644)
os.rename(temp_path, "%s/%s" % (self.final_path, "progress"))
| 36.378601 | 81 | 0.541176 | 8,607 | 0.973643 | 493 | 0.055769 | 0 | 0 | 0 | 0 | 2,171 | 0.245588 |
dcd1af861d1db0434de55a20de85ed1a197219cd | 27 | py | Python | kutana/__main__.py | ekonda/kutana | 902f9d521c10c6c7ccabb1387ee3d87db5e2eba6 | [
"MIT"
] | 69 | 2018-10-05T21:42:51.000Z | 2022-03-16T17:22:21.000Z | kutana/__main__.py | ekonda/kutana | 902f9d521c10c6c7ccabb1387ee3d87db5e2eba6 | [
"MIT"
] | 41 | 2018-10-20T09:18:43.000Z | 2021-11-22T12:19:44.000Z | kutana/__main__.py | ekonda/kutana | 902f9d521c10c6c7ccabb1387ee3d87db5e2eba6 | [
"MIT"
] | 26 | 2018-10-20T09:13:42.000Z | 2021-12-24T17:01:02.000Z | from .cli import run
run()
| 9 | 20 | 0.703704 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
dcd27c7511190004659b9e60ba4a4a26b905d6d5 | 2,119 | py | Python | Chapter9_FormatDetection/pr9_3_1.py | SeventeenChen/Python_Speech_SZY | 0074ad1d519387a75d5eca42c77f4d6966eb0a0e | [
"MIT"
] | 7 | 2020-11-23T11:03:43.000Z | 2021-10-24T01:26:21.000Z | Chapter9_FormatDetection/pr9_3_1.py | SeventeenChen/Python_Speech_SZY | 0074ad1d519387a75d5eca42c77f4d6966eb0a0e | [
"MIT"
] | null | null | null | Chapter9_FormatDetection/pr9_3_1.py | SeventeenChen/Python_Speech_SZY | 0074ad1d519387a75d5eca42c77f4d6966eb0a0e | [
"MIT"
] | 2 | 2021-06-23T14:26:13.000Z | 2021-06-30T10:39:08.000Z | #
# pr9_3_1
from audiolazy import lazy_lpc
from scipy.signal import lfilter, find_peaks
from LPC import LPC
from Universal import *
if __name__ == '__main__':
filename = 'snn27.wav'
speech = Speech()
x, fs = speech.audioread(filename, None) # read one frame data
u = lfilter(b=np.array([1, -0.99]), a=1, x=x) # pre-emphasis
wlen = len(u) # frame length
p = 12 # LPC order
ar = lazy_lpc.lpc.autocor(u, p) # LPC coefficients
ar0 = ar.numerator
U = LPC().lpcar2pf(ar0, 255) # LPC coefficients --> spectrum
freq = np.arange(257) * fs / 512 # frequency scale in the frequency domain
df = fs / 512 # frequency resolution
U_log = 10 * np.log10(U)
Loc, _ = find_peaks(U.reshape(np.size(U), )) # peak location
Val = U[Loc] # peak value
LenLoc = len(Loc) # peak number
F = np.zeros(LenLoc) # format frequency
BW = np.zeros(LenLoc) # band width
for k in range(LenLoc):
m = Loc[k] # set m, m-1, m+1
m1 = m - 1
m2 = m + 1
p = Val[k] # set P(m), P(m-1), P(m+1)
p1 = U[m1]
p2 = U[m2]
aa = (p1 + p2) / 2 - p # (9-3-4)
bb = (p2 - p1) / 2
cc = p
dm = -bb / 2 / aa # (9-3-6)
pp = - bb * bb / 4 / aa + cc # (9-3-8)
m_new = m + dm
bf = -np.sqrt(bb * bb - 4 * aa * (cc - pp / 2)) / aa # (9-3-13)
F[k] = (m_new - 1) * df # (9-3-7)
BW[k] = bf * df # (9-3-14)
np.set_printoptions(precision=2)
print('Format = {}'.format(F))
print('Band Width = {}'.format(BW))
# figure
plt.figure(figsize=(16, 9))
plt.subplot(2, 1, 1)
plt.plot(u)
plt.xlabel('Sample points')
plt.ylabel('Amplitude')
plt.title('Pre-emphasis Signal Spectrum')
plt.axis([0, wlen, -0.5, 0.5])
plt.subplot(2, 1, 2)
plt.plot(freq, U)
for k in range(LenLoc):
plt.plot(freq[Loc[k]], Val[k], 'r', marker='o', markersize=8)
plt.plot(np.array([freq[Loc[k]], freq[Loc[k]]], dtype=object), np.array([0, Val[k]], dtype=object), 'r-.',
linewidth=2)
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude [dB]')
plt.title('Vocal Transfer Function Power Spectrum')
plt.axis([0, 4000, 0, max(U) + 2])
plt.savefig('images/lpc_format_detection.png', bbox_inches='tight', dpi=600)
plt.show()
| 30.710145 | 108 | 0.601699 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 589 | 0.277961 |
dcd3f42d79247d516e91a944ac5320d42c096f12 | 8,356 | py | Python | FP - Fundamentals Of Programming/bank-accounts-manager/tests.py | p0licat/university | 4c86fd2e7aafb830f7d9cb2d38f96a145b7e7f7b | [
"MIT"
] | 2 | 2018-03-05T14:07:37.000Z | 2021-01-24T22:44:24.000Z | FP - Fundamentals Of Programming/bank-accounts-manager/tests.py | p0licat/university | 4c86fd2e7aafb830f7d9cb2d38f96a145b7e7f7b | [
"MIT"
] | 1 | 2017-03-08T09:08:29.000Z | 2017-03-10T08:23:58.000Z | FP - Fundamentals Of Programming/bank-accounts-manager/tests.py | p0licat/university | 4c86fd2e7aafb830f7d9cb2d38f96a145b7e7f7b | [
"MIT"
] | 1 | 2017-03-08T12:25:11.000Z | 2017-03-08T12:25:11.000Z | from methods import *
'''
This file contains the test functions of every function defined in methods.py, which is imported.
This file is imported by the main file ( application.py )
'''
def sort_transactions_test(list_of_transactions):
list_of_transactions = [['7', '120', 'out', 'first'], ['7', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert sort_transactions('sort', (['asc', 'day']), list_of_transactions) == True
for i in range(1, len(list_of_transactions)):
assert ( int(list_of_transactions[i][0]) >= int(list_of_transactions[i-1][0]) ) == True
if int(list_of_transactions[i][0]) == int(list_of_transactions[i-1][0]):
assert ( int(list_of_transactions[i][1]) >= int(list_of_transactions[i-1][1]) ) == True
assert sort_transactions('sort', (['desc', 'day']), list_of_transactions) == True
for i in range(1, len(list_of_transactions)):
assert (int(list_of_transactions[i][0]) <= int(list_of_transactions[i-1][0])) == True
if int(list_of_transactions[i][0]) == int(list_of_transactions[i-1][0]):
assert (int(list_of_transactions[i][1]) <= int(list_of_transactions[i-1][1])) == True
assert sort_transactions('sort', (['asc', 'type']), list_of_transactions) == True
list_of_transactions = [['0', '10', 'out', 'test']]
assert sort_transactions('sort', (['asc', 'day']), list_of_transactions) == True
assert sort_transactions('sort', (['asc', 'type']), list_of_transactions) == True
list_of_transactions[:] = []
assert sort_transactions('sort', (['asc', 'day']), list_of_transactions) == None
assert sort_transactions('sort', (['asc', 'type']), list_of_transactions) == None
def get_max_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['0', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert get_max('max', (['in', 'day']), list_of_transactions) == '4'
assert get_max('max', (['out', 'day']), list_of_transactions) == '1'
list_of_transactions[:] = []
assert get_max('max', (['out', 'day']), list_of_transactions) == None
assert get_max('max', (['in', 'day']), list_of_transactions) == None
def get_sum_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['0', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert int(get_sum('sum', (['in', '']), list_of_transactions)) == 1000
assert int(get_sum('sum', (['out', '']), list_of_transactions)) == 315
assert int(get_sum('sum', (['out', '0']), list_of_transactions)) == 115
list_of_transactions[:] = []
assert int(get_sum('sum', (['in', '']), list_of_transactions)) == 0
def get_balance_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['0', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
# balance should be 685, for day 1 should be -200
assert int(get_balance('balance', (['']), list_of_transactions)) == 685
assert int(get_balance('balance', (['1']), list_of_transactions)) == -200
assert int(get_balance('balance', (['']), [])) == 0
assert int(get_balance('balance', (['']), [['0','440','out','ok']])) < 0 # negative
list_of_transactions[:] = []
def get_all_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['0', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert get_all('all', (['']), list_of_transactions) == list_of_transactions
assert get_all('all', (['in']), list_of_transactions) != False
result = get_all('all', (['in']), list_of_transactions)
for i in result:
assert i[2] == 'in'
result = get_all('all', (['out']), list_of_transactions)
for i in result:
assert i[2] == 'out'
list_of_transactions[:] = []
def less_than_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['0', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert less_than('greater than', (['100']), list_of_transactions) != False
result = less_than('greater than', (['100']), list_of_transactions)
if result != False and result != None:
for i in result:
assert int(i[1]) < 100
list_of_transactions[:] = []
def greater_than_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['0', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert greater_than('greater than', (['100']), list_of_transactions) != False
result = greater_than('greater than', (['100']), list_of_transactions)
if result != False and result != None:
for i in result:
assert int(i[1]) > 100
list_of_transactions[:] = []
def transaction_filter_test(list_of_transactions):
list_of_transactions = [['0', '100', 'in', 'first'], ['0', '100', 'out', 'second'], ['1', '100', 'in', 'third'], ['4', '100', 'in', 'fourth']]
assert transaction_filter('filter', (['in', '']), list_of_transactions) == True
for i in list_of_transactions:
assert i[2] == 'in'
list_of_transactions = [['0', '100', 'in', 'first'], ['0', '105', 'out', 'second'], ['1', '105', 'in', 'third'], ['4', '99', 'in', 'fourth']]
assert transaction_filter('filter', (['out', '']), list_of_transactions) == True
for i in list_of_transactions:
assert i[2] == 'out'
list_of_transactions = [['0', '100', 'in', 'first'], ['0', '105', 'out', 'second'], ['1', '105', 'in', 'third'], ['4', '99', 'in', 'fourth']]
assert transaction_filter('filter', (['in', '100']), list_of_transactions) == True
for i in list_of_transactions:
assert i[2] == 'in'
assert int(i[1]) > 100
list_of_transactions = []
def add_entry_test(list_of_transactions):
groups_commands = ['add', 'insert']
insert_groups_tuple = [[('10', '100', 'out', 'description'), True],
[('0', '30', 'in', 'desc'), True],
[('x', '3j', '', 'desc'), False],
[('0', '30', 'in', ''), False],
[('M_', '30', 'in', 'desc'), False],
[('-23', '32', '2222222', ''), False],
[(' 2313', '322', 'in2', 'desc'), False]]
add_groups_tuple = [[('10', 'in', 'correct'), True],
[('-1', '-1', '-1'), False],
[('', 'x', 'x'), False],
[('', ' ', ''), False],
[('', '', ' '), False],
[('', 'x@', ''), False],
[('11', '11', '11'), False]]
for i in insert_groups_tuple:
assert add_entry(groups_commands[1], i[0], list_of_transactions) == i[1]
for i in add_groups_tuple:
assert add_entry(groups_commands[0], i[0], list_of_transactions) == i[1]
list_of_transactions[:] = []
def remove_item_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['15', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert remove_item('remove', (['15']), list_of_transactions) == True
for i in list_of_transactions:
assert i[0] != 15
print (list_of_transactions)
assert remove_item('remove', (['in']), list_of_transactions) == True
print (list_of_transactions)
for i in list_of_transactions:
assert i[2] != 'in'
assert remove_item('remove', (['out']), list_of_transactions) == True
for i in list_of_transactions:
print (i)
assert i[2] != 'out'
list_of_transactions[:] = []
def remove_from_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['15', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert remove_from('remove from', (['1', '4']), list_of_transactions) == True
for i in list_of_transactions:
assert int(i[0]) < 1 or int(i[0]) > 4
assert remove_from('remove from', (['1', '0']), list_of_transactions) == True
list_of_transactions[:] = []
def replace_entry_test(list_of_transactions):
list_of_transactions = [['0', '10', 'out', 'first'], ['15', '105', 'out', 'second'], ['1', '200', 'out', 'third'], ['4', '1000', 'in', 'fourth']]
assert replace_entry('replace', (['15', 'out', 'second', '200']), list_of_transactions) == True
for i in list_of_transactions:
if i[0] == 15 and i[3] == 'second':
assert i[1] == 200
assert replace_entry('replace', (['11', 'out', 'second', '200']), list_of_transactions) == True
list_of_transactions[:] = []
# ========================================================= TEST FUNCTIONS ===============================================================================
| 43.072165 | 155 | 0.602202 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,285 | 0.273456 |
dcd42f2daa76bc524d4c8ee909709be681a4b7f0 | 679 | py | Python | darshan-util/pydarshan/darshan/error.py | gaocegege/darshan | 2d54cd8ec96d26db23e9ca421df48d2031a4c55e | [
"mpich2"
] | null | null | null | darshan-util/pydarshan/darshan/error.py | gaocegege/darshan | 2d54cd8ec96d26db23e9ca421df48d2031a4c55e | [
"mpich2"
] | null | null | null | darshan-util/pydarshan/darshan/error.py | gaocegege/darshan | 2d54cd8ec96d26db23e9ca421df48d2031a4c55e | [
"mpich2"
] | null | null | null | """ Darshan Error classes and functions. """
class DarshanBaseError(Exception):
"""
Base exception class for Darshan errors in Python.
"""
pass
class DarshanVersionError(NotImplementedError):
"""
Raised when using a feature which is not provided by libdarshanutil.
"""
min_version = None
def __init__(self, min_version, msg="Feature"):
self.msg = msg
self.min_version = min_version
self.version = "0.0.0"
def __repr__(self):
return "DarshanVersionError('%s')" % str(self)
def __str__(self):
return "%s requires libdarshanutil >= %s, have %s" % (self.msg, self.min_version, self.version)
| 24.25 | 103 | 0.645066 | 627 | 0.923417 | 0 | 0 | 0 | 0 | 0 | 0 | 280 | 0.412371 |
dcd4c65a2576a728fe423b160c1c1d7a8fc3fb51 | 6,618 | py | Python | etl_e2e/census_etl/dfxml/python/dfxml/fiwalk.py | thinkmoore/das | d9faabf3de987b890a5079b914f5aba597215b14 | [
"CC0-1.0"
] | 35 | 2019-04-16T19:37:01.000Z | 2022-02-14T20:33:41.000Z | etl_e2e/census_etl/dfxml/python/dfxml/fiwalk.py | thinkmoore/das | d9faabf3de987b890a5079b914f5aba597215b14 | [
"CC0-1.0"
] | 17 | 2021-07-02T21:19:52.000Z | 2022-01-27T22:30:19.000Z | etl_e2e/census_etl/dfxml/python/dfxml/fiwalk.py | thinkmoore/das | d9faabf3de987b890a5079b914f5aba597215b14 | [
"CC0-1.0"
] | 12 | 2019-05-02T19:38:06.000Z | 2021-09-11T22:02:03.000Z | #!/usr/bin/env python
# This software was developed in whole or in part by employees of the
# Federal Government in the course of their official duties, and with
# other Federal assistance. Pursuant to title 17 Section 105 of the
# United States Code portions of this software authored by Federal
# employees are not subject to copyright protection within the United
# States. For portions not authored by Federal employees, the Federal
# Government has been granted unlimited rights, and no claim to
# copyright is made. The Federal Government assumes no responsibility
# whatsoever for its use by other parties, and makes no guarantees,
# expressed or implied, about its quality, reliability, or any other
# characteristic.
#
# We would appreciate acknowledgement if the software is used.
__version__="0.7.0"
"""fiwalk module
This is the part of dfxml that is dependent on fiwalk.py
"""
import os
import sys
sys.path.append( os.path.join(os.path.dirname(__file__), ".."))
import dfxml
from sys import stderr
from subprocess import Popen,PIPE
ALLOC_ONLY = 1
fiwalk_cached_installed_version = None
def fiwalk_installed_version(fiwalk='fiwalk'):
"""Return the current version of fiwalk that is installed"""
global fiwalk_cached_installed_version
if fiwalk_cached_installed_version:
return fiwalk_cached_installed_version
from subprocess import Popen,PIPE
import re
for line in Popen([fiwalk,'-V'],stdout=PIPE).stdout.read().decode('utf-8').split("\n"):
g = re.search("^FIWalk Version:\s+(.*)$",line)
if g:
fiwalk_cached_installed_version = g.group(1)
return fiwalk_cached_installed_version
g = re.search("^SleuthKit Version:\s+(.*)$",line)
if g:
fiwalk_cached_installed_version = g.group(1)
return fiwalk_cached_installed_version
return None
class XMLDone(Exception):
def __init__(self,value):
self.value = value
class version:
def __init__(self):
self.cdata = ""
self.in_element = []
self.version = None
def start_element(self,name,attrs):
if(name=='volume'): # too far?
raise XMLDone(None)
self.in_element += [name]
self.cdata = ""
def end_element(self,name):
if ("fiwalk" in self.in_element) and ("creator" in self.in_element) and ("version" in self.in_element):
raise XMLDone(self.cdata)
if ("fiwalk" in self.in_element) and ("fiwalk_version" in self.in_element):
raise XMLDone(self.cdata)
if ("version" in self.in_element) and ("dfxml" in self.in_element) and ("creator" in self.in_element):
raise XMLDone(self.cdata)
self.in_element.pop()
self.cdata = ""
def char_data(self,data):
self.cdata += data
def get_version(self,fn):
import xml.parsers.expat
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = self.start_element
p.EndElementHandler = self.end_element
p.CharacterDataHandler = self.char_data
try:
p.ParseFile(open(fn,'rb'))
except XMLDone as e:
return e.value
except xml.parsers.expat.ExpatError:
return None # XML error
def fiwalk_xml_version(filename=None):
"""Returns the fiwalk version that was used to create an XML file.
Uses the "quick and dirty" approach to getting to getting out the XML version."""
p = version()
return p.get_version(filename)
################################################################
def E01_glob(fn):
import os.path
"""If the filename ends .E01, then glob it. Currently only handles E01 through EZZ"""
ret = [fn]
if fn.endswith(".E01") and os.path.exists(fn):
fmt = fn.replace(".E01",".E%02d")
for i in range(2,100):
f2 = fmt % i
if os.path.exists(f2):
ret.append(f2)
else:
return ret
# Got through E99, now do EAA through EZZ
fmt = fn.replace(".E01",".E%c%c")
for i in range(0,26):
for j in range(0,26):
f2 = fmt % (i+ord('A'),j+ord('A'))
if os.path.exists(f2):
ret.append(f2)
else:
return ret
return ret # don't do F01 through F99, etc.
return ret
def fiwalk_xml_stream(imagefile=None,flags=0,fiwalk="fiwalk",fiwalk_args=""):
""" Returns an fiwalk XML stream given a disk image by running fiwalk."""
if flags & ALLOC_ONLY: fiwalk_args += "-O"
from subprocess import call,Popen,PIPE
# Make sure we have a valid fiwalk
try:
res = Popen([fiwalk,'-V'],stdout=PIPE).communicate()[0]
except OSError:
raise RuntimeError("Cannot execute fiwalk executable: "+fiwalk)
cmd = [fiwalk,'-x']
if fiwalk_args: cmd += fiwalk_args.split()
p = Popen(cmd + E01_glob(imagefile.name),stdout=PIPE)
return p.stdout
def fiwalk_using_sax(imagefile=None,xmlfile=None,fiwalk="fiwalk",flags=0,callback=None,fiwalk_args=""):
"""Processes an image using expat, calling a callback for every file object encountered.
If xmlfile is provided, use that as the xmlfile, otherwise runs fiwalk."""
import dfxml
if xmlfile==None:
xmlfile = fiwalk_xml_stream(imagefile=imagefile,flags=flags,fiwalk=fiwalk,fiwalk_args=fiwalk_args)
r = dfxml.fileobject_reader(flags=flags)
r.imagefile = imagefile
r.process_xml_stream(xmlfile,callback)
def fileobjects_using_sax(imagefile=None,xmlfile=None,fiwalk="fiwalk",flags=0):
ret = []
fiwalk_using_sax(imagefile=imagefile,xmlfile=xmlfile,fiwalk=fiwalk,flags=flags,
callback = lambda fi:ret.append(fi))
return ret
def fileobjects_using_dom(imagefile=None,xmlfile=None,fiwalk="fiwalk",flags=0,callback=None):
"""Processes an image using expat, calling a callback for every file object encountered.
If xmlfile is provided, use that as the xmlfile, otherwise runs fiwalk."""
import dfxml
if xmlfile==None:
xmlfile = fiwalk_xml_stream(imagefile=imagefile,flags=flags,fiwalk=fiwalk)
return dfxml.fileobjects_dom(xmlfile=xmlfile,imagefile=imagefile,flags=flags)
ctr = 0
def cb_count(fn):
global ctr
ctr += 1
if __name__=="__main__":
import sys
for fn in sys.argv[1:]:
print("{} contains fiwalk version {}".format(fn,fiwalk_xml_version(fn)))
# Count the number of files
fiwalk_using_sax(xmlfile=open(fn,'rb'),callback=cb_count)
print("Files: {}".format(ctr))
| 37.389831 | 111 | 0.653974 | 1,398 | 0.211242 | 0 | 0 | 0 | 0 | 0 | 0 | 2,141 | 0.323512 |
dcd4e905ad3640b7680d21aba4cf6c5615e3a1ee | 17,684 | py | Python | backend/tests/test_response.py | PolyCortex/polydodo | 473d5a8b89e9bdb68ba9592241e45d30b86b471c | [
"MIT"
] | 13 | 2020-06-02T03:17:10.000Z | 2022-03-23T04:06:52.000Z | backend/tests/test_response.py | PolyCortex/polydodo | 473d5a8b89e9bdb68ba9592241e45d30b86b471c | [
"MIT"
] | 43 | 2020-07-15T04:21:06.000Z | 2022-03-06T00:32:19.000Z | backend/tests/test_response.py | PolyCortex/polydodo | 473d5a8b89e9bdb68ba9592241e45d30b86b471c | [
"MIT"
] | 2 | 2020-12-27T07:21:18.000Z | 2021-09-16T20:06:47.000Z | """
Not tested as they seemed obvious:
- "SleepTime": 31045, // Total amount of time sleeping including nocturnal awakenings (sleepOffset - sleepOnset)
- "WASO": 3932, // Total amount of time passed in nocturnal awakenings. It is the total time passed in non-wake stage
// from sleep Onset to sleep offset (totalSleepTime - efficientSleepTime)
"""
import numpy as np
from tests.setup import pytest_generate_tests # noqa: F401
from tests.setup import get_mock_request
from backend.response import ClassificationResponse
from classification.config.constants import EPOCH_DURATION, SleepStage
def get_report(request, sequence):
value_sequence = np.array([SleepStage[stage].value for stage in sequence])
response = ClassificationResponse(request, value_sequence, None)
return response.metrics.report
class TestReportTimePassedInStage():
"""Tests the time passed in each stage metrics in the response metrics
The evaluated metrics are:
"WTime": 3932, // [seconds] time passed in this stage between bedTime to wakeUpTime
"REMTime": 2370,
"N1Time": 3402,
"N2Time": 16032,
"N3Time": 5309
"""
params = {
"test_null_time_passed_in_stage": [
dict(
sequence=['W', 'W', 'W'],
WTime=3 * EPOCH_DURATION,
REMTime=0,
N1Time=0,
N2Time=0,
N3Time=0),
dict(
sequence=['REM', 'REM', 'REM'],
WTime=0,
REMTime=3 * EPOCH_DURATION,
N1Time=0,
N2Time=0,
N3Time=0),
dict(
sequence=['N1', 'N1', 'N1'],
WTime=0,
REMTime=0,
N1Time=3 * EPOCH_DURATION,
N2Time=0,
N3Time=0),
dict(
sequence=['N2', 'N2', 'N2'],
WTime=0,
REMTime=0,
N1Time=0,
N2Time=3 * EPOCH_DURATION,
N3Time=0),
dict(
sequence=['N3', 'N3', 'N3'],
WTime=0,
REMTime=0,
N1Time=0,
N2Time=0,
N3Time=3 * EPOCH_DURATION),
], "test_partial_time_passed_in_stage": [
dict(
sequence=['W', 'N1', 'N2', 'W'],
WTime=2 * EPOCH_DURATION,
REMTime=0,
N1Time=EPOCH_DURATION,
N2Time=EPOCH_DURATION,
N3Time=0),
dict(
sequence=['N1', 'W', 'W'],
WTime=2 * EPOCH_DURATION,
REMTime=0,
N1Time=EPOCH_DURATION,
N2Time=0,
N3Time=0),
dict(
sequence=['W', 'N1', 'N2', 'N3', 'REM', 'W'],
WTime=2 * EPOCH_DURATION,
REMTime=EPOCH_DURATION,
N1Time=EPOCH_DURATION,
N2Time=EPOCH_DURATION,
N3Time=EPOCH_DURATION),
dict(
sequence=['N1', 'N2', 'N2', 'REM'],
WTime=0,
REMTime=EPOCH_DURATION,
N1Time=EPOCH_DURATION,
N2Time=2 * EPOCH_DURATION,
N3Time=0),
]
}
@classmethod
def setup_class(cls):
cls.MOCK_REQUEST = get_mock_request()
def test_null_time_passed_in_stage(self, sequence, WTime, REMTime, N1Time, N2Time, N3Time):
report = get_report(self.MOCK_REQUEST, sequence)
assert report[sequence[0].upper() + 'Time'] == len(sequence) * EPOCH_DURATION
self.assert_times(sequence, report, WTime, REMTime, N1Time, N2Time, N3Time)
def test_partial_time_passed_in_stage(self, sequence, WTime, REMTime, N1Time, N2Time, N3Time):
report = get_report(self.MOCK_REQUEST, sequence)
self.assert_times(sequence, report, WTime, REMTime, N1Time, N2Time, N3Time)
def assert_times(self, sequence, report, WTime, REMTime, N1Time, N2Time, N3Time):
assert (
report['WTime']
+ report['REMTime']
+ report['N1Time']
+ report['N2Time']
+ report['N3Time']
) == len(sequence) * EPOCH_DURATION
assert report['WTime'] == WTime
assert report['REMTime'] == REMTime
assert report['N1Time'] == N1Time
assert report['N2Time'] == N2Time
assert report['N3Time'] == N3Time
class TestReportLatenciesOnset():
"""Tests the event-related latencies and onsets
The evaluated metrics are:
"sleepLatency": 1000, // Time to fall asleep [seconds] (sleepOnset - bedTime)
"remLatency": 3852, // [seconds] (remOnset- bedTime)
"sleepOnset": 1602211380, // Time at which the subject fell asleep (time of the first non-wake epoch)
"remOnset": 1602214232, // First REM epoch
"""
params = {
"test_sequence_starts_with_stage": [
dict(sequence=['REM', 'REM', 'W', 'W'], test_rem=True),
dict(sequence=['REM', 'W', 'N1', 'W'], test_rem=True),
dict(sequence=['REM', 'W', 'N1', 'N2', 'N3', 'REM', 'W'], test_rem=False),
dict(sequence=['N1', 'W', 'N1', 'N2', 'N3', 'REM', 'W'], test_rem=False),
dict(sequence=['N2', 'W', 'N1', 'N2', 'N3', 'REM', 'W'], test_rem=False),
dict(sequence=['N3', 'W', 'N1', 'N2', 'N3', 'REM', 'W'], test_rem=False),
], "test_sequence_has_no_stage": [
dict(sequence=['W', 'N1', 'N2', 'N3', 'W'], test_rem=True),
dict(sequence=['W', 'W', 'W', 'W', 'W'], test_rem=False),
dict(sequence=['W'], test_rem=False),
], "test_sequence_ends_with_stage": [
dict(sequence=['W', 'W', 'REM'], test_rem=True),
dict(sequence=['W', 'W', 'N1'], test_rem=False),
dict(sequence=['W', 'W', 'N2'], test_rem=False),
dict(sequence=['W', 'W', 'N3'], test_rem=False),
], "test_sequence_with_stage_at_middle": [
dict(
sequence=['W', 'N1', 'N2', 'N1', 'REM', 'W'],
test_rem=True,
latency=3 * EPOCH_DURATION,
), dict(
sequence=['W', 'W', 'N1', 'W', 'N1', 'W'],
test_rem=False,
latency=2 * EPOCH_DURATION,
), dict(
sequence=['W', 'W', 'N2', 'W', 'N2', 'W'],
test_rem=False,
latency=2 * EPOCH_DURATION,
), dict(
sequence=['W', 'W', 'N3', 'W', 'N3', 'W'],
test_rem=False,
latency=2 * EPOCH_DURATION,
),
],
}
@classmethod
def setup_class(cls):
cls.MOCK_REQUEST = get_mock_request()
def test_sequence_starts_with_stage(self, sequence, test_rem):
expected_latency = 0
expected_onset = self.MOCK_REQUEST.bedtime
self.assert_latency_equals_expected(expected_latency, expected_onset, sequence, test_rem)
def test_sequence_has_no_stage(self, sequence, test_rem):
expected_latency = None
expected_onset = None
self.assert_latency_equals_expected(expected_latency, expected_onset, sequence, test_rem)
def test_sequence_ends_with_stage(self, sequence, test_rem):
expected_latency = EPOCH_DURATION * (len(sequence) - 1) if not test_rem else 0
expected_onset = expected_latency + self.MOCK_REQUEST.bedtime
self.assert_latency_equals_expected(expected_latency, expected_onset, sequence, test_rem)
def test_sequence_with_stage_at_middle(self, sequence, test_rem, latency):
expected_onset = latency + self.MOCK_REQUEST.bedtime
self.assert_latency_equals_expected(latency, expected_onset, sequence, test_rem)
def get_latency_report_key(self, test_rem):
return 'remLatency' if test_rem else 'sleepLatency'
def get_onset_report_key(self, test_rem):
return 'remOnset' if test_rem else 'sleepOnset'
def assert_latency_equals_expected(self, expected_latency, expected_onset, sequence, test_rem):
report = get_report(self.MOCK_REQUEST, sequence)
assert report[self.get_latency_report_key(test_rem)] == expected_latency, (
f"Latency of {'rem' if test_rem else 'sleep'} is not as expected"
)
assert report[self.get_onset_report_key(test_rem)] == expected_onset, (
f"Onset of {'rem' if test_rem else 'sleep'} is not as expected"
)
class TestReportSleepOffset():
"""Tests timestamp at which user woke up
"sleepOffset": 1602242425, // Time at which the subject woke up (time of the epoch after the last non-wake epoch)
"""
params = {
'test_wake_up_end': [dict(
sequence=['W', 'N1', 'N2', 'N3', 'REM', 'N1', 'W'],
)], 'test_wake_up_middle': [dict(
sequence=['W', 'N1', 'N2', 'W', 'W', 'W', 'W'],
awake_index=3,
expected_wake_after_sleep_offset=4 * EPOCH_DURATION,
)], 'test_awakes_and_goes_back_to_sleep_and_wakes': [dict(
sequence=['W', 'N1', 'N2', 'W', 'N1', 'N2', 'W'],
awake_index=6,
expected_wake_after_sleep_offset=EPOCH_DURATION,
)], 'test_awakes_and_goes_back_to_sleep_and_doesnt_awake': [dict(
sequence=['W', 'N1', 'N2', 'W', 'N1', 'N2', 'N2'],
)], 'test_always_awake': [
dict(sequence=['W', 'W', 'W']),
dict(sequence=['W']),
], 'test_doesnt_awaken': [
dict(sequence=['W', 'N1', 'N2']),
dict(sequence=['N1', 'N1', 'N2']),
],
}
@classmethod
def setup_class(cls):
cls.MOCK_REQUEST = get_mock_request()
def test_wake_up_end(self, sequence):
expected_sleep_offset = self.MOCK_REQUEST.bedtime + EPOCH_DURATION * (len(sequence) - 1)
expected_wake_after_sleep_offset = EPOCH_DURATION
self.assert_sleep_offset_with_wake(sequence, expected_sleep_offset, expected_wake_after_sleep_offset)
def test_wake_up_middle(self, sequence, awake_index, expected_wake_after_sleep_offset):
expected_sleep_offset = self.MOCK_REQUEST.bedtime + EPOCH_DURATION * awake_index
self.assert_sleep_offset_with_wake(sequence, expected_sleep_offset, expected_wake_after_sleep_offset)
def test_awakes_and_goes_back_to_sleep_and_wakes(self, sequence, awake_index, expected_wake_after_sleep_offset):
expected_sleep_offset = self.MOCK_REQUEST.bedtime + EPOCH_DURATION * awake_index
self.assert_sleep_offset_with_wake(sequence, expected_sleep_offset, expected_wake_after_sleep_offset)
def test_awakes_and_goes_back_to_sleep_and_doesnt_awake(self, sequence):
expected_sleep_offset = self.MOCK_REQUEST.bedtime + EPOCH_DURATION * len(sequence)
expected_wake_after_sleep_offset = 0
self.assert_sleep_offset_with_wake(sequence, expected_sleep_offset, expected_wake_after_sleep_offset)
def test_always_awake(self, sequence):
expected_sleep_offset = None
expected_wake_after_sleep_offset = 0
self.assert_sleep_offset_with_wake(sequence, expected_sleep_offset, expected_wake_after_sleep_offset)
def test_doesnt_awaken(self, sequence):
expected_sleep_offset = self.MOCK_REQUEST.bedtime + EPOCH_DURATION * len(sequence)
expected_wake_after_sleep_offset = 0
self.assert_sleep_offset_with_wake(sequence, expected_sleep_offset, expected_wake_after_sleep_offset)
def assert_sleep_offset_with_wake(self, sequence, expected_sleep_offset, expected_wake_after_sleep_offset):
report = get_report(self.MOCK_REQUEST, sequence)
assert report['sleepOffset'] == expected_sleep_offset
assert report['wakeAfterSleepOffset'] == expected_wake_after_sleep_offset
class TestReportSleepEfficiency():
"""Tests sleep efficiency related metrics
The evaluated metrics are:
"sleepEfficiency": 0.8733, // Overall sense of how well the patient slept (totalSleepTime/bedTime)
"efficientSleepTime": 27113, // Total amount of seconds passed in non-wake stages
"""
params = {
'test_sleep_time_null': [
dict(sequence=['W', 'W', 'W']),
dict(sequence=['W']),
], 'test_sleep_time_not_null': [
dict(
sequence=['W', 'W', 'N1', 'W'],
expected_efficiency=(1 / 4),
expected_efficient_sleep_time=EPOCH_DURATION
), dict(
sequence=['W', 'W', 'N2', 'W'],
expected_efficiency=(1 / 4),
expected_efficient_sleep_time=EPOCH_DURATION
), dict(
sequence=['W', 'W', 'N3', 'W'],
expected_efficiency=(1 / 4),
expected_efficient_sleep_time=EPOCH_DURATION
), dict(
sequence=['W', 'W', 'REM', 'W'],
expected_efficiency=(1 / 4),
expected_efficient_sleep_time=EPOCH_DURATION
), dict(
sequence=['W', 'W', 'N1', 'N2', 'N3', 'REM', 'N1', 'W'],
expected_efficiency=(5 / 8),
expected_efficient_sleep_time=5 * EPOCH_DURATION
),
]
}
@classmethod
def setup_class(cls):
cls.MOCK_REQUEST = get_mock_request()
def test_sleep_time_null(self, sequence):
self.assert_sleep_efficiency(sequence, expected_efficiency=0, expected_efficient_sleep_time=0)
def test_sleep_time_not_null(self, sequence, expected_efficiency, expected_efficient_sleep_time):
self.assert_sleep_efficiency(sequence, expected_efficiency, expected_efficient_sleep_time)
def assert_sleep_efficiency(self, sequence, expected_efficiency, expected_efficient_sleep_time):
report = get_report(self.MOCK_REQUEST, sequence)
assert report['sleepEfficiency'] == expected_efficiency
assert report['efficientSleepTime'] == expected_efficient_sleep_time
class TestReportAwakenings():
"""Tests number of awakenings per night
"awakenings": 7, // number of times the subject woke up between sleep onset & offset
"""
params = {
'test_sleep_time_null': [dict(sequence=['W', 'W', 'W']), dict(sequence=['W'])],
'test_one_awakening': [
dict(sequence=['W', 'N1', 'W']),
dict(sequence=['W', 'N1', 'N2', 'N3', 'W', 'W']),
], 'test_doesnt_awaken': [
dict(sequence=['W', 'N1', 'N2', 'N3', 'REM']),
dict(sequence=['W', 'N1']),
], 'test_many_awakening': [
dict(sequence=['W', 'N1', 'W', 'N1', 'W'], nb_awakenings=2),
dict(sequence=['W', 'N1', 'N2', 'W', 'N1', 'W', 'W', 'N1', 'W'], nb_awakenings=3),
],
}
@classmethod
def setup_class(cls):
cls.MOCK_REQUEST = get_mock_request()
def test_sleep_time_null(self, sequence):
self.assert_sleep_efficiency(sequence, expected_nb_awakenings=0)
def test_one_awakening(self, sequence):
self.assert_sleep_efficiency(sequence, expected_nb_awakenings=1)
def test_doesnt_awaken(self, sequence):
self.assert_sleep_efficiency(sequence, expected_nb_awakenings=1)
def test_many_awakening(self, sequence, nb_awakenings):
self.assert_sleep_efficiency(sequence, expected_nb_awakenings=nb_awakenings)
def assert_sleep_efficiency(self, sequence, expected_nb_awakenings):
report = get_report(self.MOCK_REQUEST, sequence)
assert report['awakenings'] == expected_nb_awakenings
class TestReportStageShifts():
"""Test number of stage shifts per night
"stageShifts": 89, // number of times the subject transitionned
// from one stage to another between sleep onset & offset
"""
params = {
'test_sleep_time_null': [
dict(sequence=['W', 'W', 'W']),
dict(sequence=['W']),
], 'test_one_sleep_stage': [
dict(sequence=['W', 'W', 'N1', 'N1', 'N1', 'W']),
dict(sequence=['W', 'N1', 'W']),
], 'test_sleep_with_awakenings': [
dict(sequence=['W', 'N1', 'W', 'N1', 'N1', 'W'], sleep_shifts=4),
dict(sequence=['W', 'N1', 'W', 'N2', 'W', 'N3', 'W'], sleep_shifts=6),
], 'test_does_not_awaken': [
dict(sequence=['W', 'N1', 'N1'], sleep_shifts=2),
dict(sequence=['W', 'N1', 'N2'], sleep_shifts=3),
dict(sequence=['W', 'N1', 'N3'], sleep_shifts=3),
dict(sequence=['W', 'N1', 'REM'], sleep_shifts=3),
], 'test_many_sleep_stages': [
dict(sequence=['W', 'N1', 'N2', 'N2', 'W'], sleep_shifts=3),
dict(sequence=['W', 'N1', 'N1', 'N3', 'N3', 'REM', 'REM', 'N1', 'W'], sleep_shifts=5),
],
}
@classmethod
def setup_class(cls):
cls.MOCK_REQUEST = get_mock_request()
def test_sleep_time_null(self, sequence):
self.assert_sleep_efficiency(sequence, expected_sleep_shifts=0)
def test_one_sleep_stage(self, sequence):
self.assert_sleep_efficiency(sequence, expected_sleep_shifts=2)
def test_sleep_with_awakenings(self, sequence, sleep_shifts):
self.assert_sleep_efficiency(sequence, expected_sleep_shifts=sleep_shifts)
def test_does_not_awaken(self, sequence, sleep_shifts):
self.assert_sleep_efficiency(sequence, expected_sleep_shifts=sleep_shifts)
def test_many_sleep_stages(self, sequence, sleep_shifts):
self.assert_sleep_efficiency(sequence, expected_sleep_shifts=sleep_shifts)
def assert_sleep_efficiency(self, sequence, expected_sleep_shifts):
report = get_report(self.MOCK_REQUEST, sequence)
assert report['stageShifts'] == expected_sleep_shifts
| 42.30622 | 117 | 0.604558 | 16,837 | 0.952104 | 0 | 0 | 504 | 0.0285 | 0 | 0 | 3,740 | 0.211491 |
dcd4fad7ef29868c6597c0320970ff225d173cc6 | 602 | py | Python | ver_colores.py | maltenzo/surrendeador | a3a0acbcaafa1ddec451cfaa6a75d850904a01e4 | [
"MIT"
] | null | null | null | ver_colores.py | maltenzo/surrendeador | a3a0acbcaafa1ddec451cfaa6a75d850904a01e4 | [
"MIT"
] | null | null | null | ver_colores.py | maltenzo/surrendeador | a3a0acbcaafa1ddec451cfaa6a75d850904a01e4 | [
"MIT"
] | null | null | null | import mouse
import keyboard
from PIL import Image
import pyscreenshot
from time import sleep
import os
def ver():
while True:
img = pyscreenshot.grab()
width, height = img.size
pixel_values = list(img.getdata())
print (pixel_values[width*mouse.get_position()[1]+mouse.get_position()[0]])
def dame_colores():
img = pyscreenshot.grab()
width, height = img.size
pixel_values = list(img.getdata())
return (pixel_values[width*mouse.get_position()[1]+mouse.get_position()[0]])
while True:
# print(mouse.get_position())
print( dame_colores())
| 25.083333 | 81 | 0.679402 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 31 | 0.051495 |
dcd6208add7287d2ee89286c6cb5068024c9c289 | 8,124 | py | Python | src/train.py | 2212221352/Multimodal-Transformer | 7e57e93f75119082ed923a33259f873824c7b300 | [
"MIT"
] | null | null | null | src/train.py | 2212221352/Multimodal-Transformer | 7e57e93f75119082ed923a33259f873824c7b300 | [
"MIT"
] | null | null | null | src/train.py | 2212221352/Multimodal-Transformer | 7e57e93f75119082ed923a33259f873824c7b300 | [
"MIT"
] | null | null | null | import torch
from torch import nn
import sys
from src import models
from src import ctc
from src.utils import *
import torch.optim as optim
import numpy as np
import time
from torch.optim.lr_scheduler import ReduceLROnPlateau
import os
import pickle
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import accuracy_score, f1_score
from src.eval_metrics import *
####################################################################
#
# Construct the model and the CTC module (which may not be needed)
#
####################################################################
def initiate(hyp_params, train_loader, valid_loader, test_loader):
model = getattr(models, hyp_params.model+'Model')(hyp_params)
if hyp_params.use_cuda:
model = model.cuda()
optimizer = getattr(optim, hyp_params.optim)(model.parameters(), lr=hyp_params.lr)
criterion = getattr(nn, hyp_params.criterion)()
if hyp_params.aligned or hyp_params.model=='MULT':
ctc_criterion = None
ctc_a2l_module, ctc_v2l_module = None, None
ctc_a2l_optimizer, ctc_v2l_optimizer = None, None
scheduler = ReduceLROnPlateau(optimizer, mode='min', patience=hyp_params.when, factor=0.1, verbose=True)
settings = {'model': model,
'optimizer': optimizer,
'criterion': criterion,
'ctc_a2l_module': ctc_a2l_module,
'ctc_v2l_module': ctc_v2l_module,
'ctc_a2l_optimizer': ctc_a2l_optimizer,
'ctc_v2l_optimizer': ctc_v2l_optimizer,
'ctc_criterion': ctc_criterion,
'scheduler': scheduler}
return train_model(settings, hyp_params, train_loader, valid_loader, test_loader)
####################################################################
#
# Training and evaluation scripts
#
####################################################################
def train_model(settings, hyp_params, train_loader, valid_loader, test_loader):
model = settings['model']
optimizer = settings['optimizer']
criterion = settings['criterion']
ctc_a2l_module = settings['ctc_a2l_module']
ctc_v2l_module = settings['ctc_v2l_module']
ctc_a2l_optimizer = settings['ctc_a2l_optimizer']
ctc_v2l_optimizer = settings['ctc_v2l_optimizer']
ctc_criterion = settings['ctc_criterion']
scheduler = settings['scheduler']
def train(model, optimizer, criterion, ctc_a2l_module, ctc_v2l_module, ctc_a2l_optimizer, ctc_v2l_optimizer, ctc_criterion):
epoch_loss = 0
model.train()
num_batches = hyp_params.n_train // hyp_params.batch_size
proc_loss, proc_size = 0, 0
start_time = time.time()
for i_batch, (batch_X, batch_Y, batch_META) in enumerate(train_loader):
sample_ind, text, audio, vision = batch_X
eval_attr = batch_Y.squeeze(-1) # if num of labels is 1
model.zero_grad()
if ctc_criterion is not None:
ctc_a2l_module.zero_grad()
ctc_v2l_module.zero_grad()
if hyp_params.use_cuda:
with torch.cuda.device(0):
text, audio, vision, eval_attr = text.cuda(), audio.cuda(), vision.cuda(), eval_attr.cuda()
if hyp_params.dataset == 'iemocap':
eval_attr = eval_attr.long()
batch_size = text.size(0)
batch_chunk = hyp_params.batch_chunk
combined_loss = 0
net = nn.DataParallel(model) if batch_size > 10 else model
preds, hiddens = net(text, audio, vision)
if hyp_params.dataset == 'iemocap':
preds = preds.view(-1, 2)
eval_attr = eval_attr.view(-1)
raw_loss = criterion(preds, eval_attr)
combined_loss = raw_loss
combined_loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), hyp_params.clip)
optimizer.step()
proc_loss += raw_loss.item() * batch_size
proc_size += batch_size
epoch_loss += combined_loss.item() * batch_size
if i_batch % hyp_params.log_interval == 0 and i_batch > 0:
avg_loss = proc_loss / proc_size
elapsed_time = time.time() - start_time
print('Epoch {:2d} | Batch {:3d}/{:3d} | Time/Batch(ms) {:5.2f} | Train Loss {:5.4f}'.
format(epoch, i_batch, num_batches, elapsed_time * 1000 / hyp_params.log_interval, avg_loss))
proc_loss, proc_size = 0, 0
start_time = time.time()
return epoch_loss / hyp_params.n_train
def evaluate(model, ctc_a2l_module, ctc_v2l_module, criterion, test=False):
model.eval()
loader = test_loader if test else valid_loader
total_loss = 0.0
results = []
truths = []
with torch.no_grad():
for i_batch, (batch_X, batch_Y, batch_META) in enumerate(loader):
sample_ind, text, audio, vision = batch_X
eval_attr = batch_Y.squeeze(dim=-1) # if num of labels is 1
if hyp_params.use_cuda:
with torch.cuda.device(0):
text, audio, vision, eval_attr = text.cuda(), audio.cuda(), vision.cuda(), eval_attr.cuda()
if hyp_params.dataset == 'iemocap':
eval_attr = eval_attr.long()
batch_size = text.size(0)
net = nn.DataParallel(model) if batch_size > 10 else model
preds, _ = net(text, audio, vision)
if hyp_params.dataset == 'iemocap':
preds = preds.view(-1, 2)
eval_attr = eval_attr.view(-1)
total_loss += criterion(preds, eval_attr).item() * batch_size
# Collect the results into dictionary
results.append(preds)
truths.append(eval_attr)
avg_loss = total_loss / (hyp_params.n_test if test else hyp_params.n_valid)
results = torch.cat(results)
truths = torch.cat(truths)
return avg_loss, results, truths
best_valid = 1e8
for epoch in range(1, hyp_params.num_epochs+1):
start = time.time()
train(model, optimizer, criterion, ctc_a2l_module, ctc_v2l_module, ctc_a2l_optimizer, ctc_v2l_optimizer, ctc_criterion)
val_loss, _, _ = evaluate(model, ctc_a2l_module, ctc_v2l_module, criterion, test=False)
test_loss, results, truths = evaluate(model, ctc_a2l_module, ctc_v2l_module, criterion, test=True)
end = time.time()
duration = end-start
scheduler.step(val_loss) # Decay learning rate by validation loss
print("-"*50)
print('Epoch {:2d} | Time {:5.4f} sec | Valid Loss {:5.4f} | Test Loss {:5.4f}'.format(epoch, duration, val_loss, test_loss))
print("-"*50)
if val_loss < best_valid:
print(f"Saved model at pre_trained_models/{hyp_params.name}.pt!")
save_model(hyp_params, model, name=hyp_params.name)
best_valid = val_loss
if hyp_params.dataset == "mosei":
eval_mosei_senti(results, truths, True)
elif hyp_params.dataset == 'mosi':
eval_mosi(results, truths, True)
model = load_model(hyp_params, name=hyp_params.name)
_, results, truths = evaluate(model, ctc_a2l_module, ctc_v2l_module, criterion, test=True)
if hyp_params.dataset == "mosei_senti":
eval_mosei_senti(results, truths, True)
elif hyp_params.dataset == 'mosi':
eval_mosi(results, truths, True)
elif hyp_params.dataset == 'iemocap':
eval_iemocap(results, truths)
sys.stdout.flush()
input('[Press Any Key to start another run]')
| 40.62 | 133 | 0.590103 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,097 | 0.135032 |
dcd91413a4ee5c2dc186ccc8e249ed33ec01e5cc | 4,145 | py | Python | datawin-parse.py | BlackLotus/ogme | c163d51d495e61b96d8123cbb0efe8eae0e4fb66 | [
"MIT"
] | null | null | null | datawin-parse.py | BlackLotus/ogme | c163d51d495e61b96d8123cbb0efe8eae0e4fb66 | [
"MIT"
] | null | null | null | datawin-parse.py | BlackLotus/ogme | c163d51d495e61b96d8123cbb0efe8eae0e4fb66 | [
"MIT"
] | null | null | null | #!/usr/bin/python2
# -*- coding: utf-8 -*-
import os, sys
import binascii
import struct
import StringIO
# chunk names are 4 bytes long
# not quite sure how long the header is but I guess 8 bytes for now :>
# actually it's not really a header but the first chunk
# 4 bytes for the name (FORM) and 4 bytes for the length (filesize-8)
# so this is not needed anymore
# dwheader=binascii.unhexlify("464F524DE6EF5A03")
datawin = open("data.win", "r+")
# datawin.seek(0,2)
# dwsize=datawin.tell()
# datawin.seek(0,0)
# header=datawin.read(8)
chunks = {}
# if header==dwheader:
# print "Doogie doogie Dodger"
# else:
# print "Wrong magic bytes"
# quit()
def read_chunk(data):
# data has to be a StringIO/file... not!
if type(data) != type("foo"):
print "Somehow the data is not a string"
quit()
else:
dsize = len(binascii.hexlify(data)) / 2
data = StringIO.StringIO(data)
data.seek(0, 0)
chunkname = data.read(4)
if chunkname.isupper():
print "Reading " + chunkname
else:
print "Reading " + binascii.hexlify(chunkname)
chunksize = data.read(4)
if len(chunksize) != 4:
data.seek(0, 0)
return [data.read()]
# TODO: _THIS_ is stupid! ... let's correct this with a nice struct or somethin
# later...
foo = binascii.hexlify(chunksize)
chunksize = foo[-2:] + foo[4:6] + foo[2:4] + foo[:2]
chunksize = int(chunksize, 16)
if chunksize + 8 == dsize:
chunk = data.read(chunksize)
return [chunkname, chunk]
elif chunksize + 8 > dsize:
data.seek(0, 0)
return [data.read()]
else:
chunk = data.read(chunksize)
rest = data.read()
if len(rest) == 0:
print "Something went terrible, terrible WRONG :( WTF IS HAPPENING?????"
return [chunkname, chunk]
else:
return [chunkname, chunk, rest]
def extract_chunks(data):
if type(data) == type("Foo"):
realdatasize = len(data)
data = StringIO.StringIO(data)
else:
realdatasize = len(data.read())
data.seek(0, 2)
datasize = data.tell()
if datasize != realdatasize:
print "OK WHY ISN'T THIS WORKING??"
quit()
data.seek(0, 0)
while data.tell() != datasize:
chunk = read_chunk(data.read())
if len(chunk) == 1:
return chunk[0]
elif len(chunk) == 2:
print "One big chunk you chump"
if type(chunk[1]) == type("foo"):
return {chunk[0]: extract_chunks(chunk[1])}
else:
print "OMG LIKE THAT'S TOTALLY LIKE A DICTIONARY THAT SOMEHOW GOT LIKE RETURNED! WHAT THE EFF"
return {chunk[0]: chunk[1]}
elif len(chunk) == 3:
if type(chunk[1]) == type("foo"):
newchunk = {chunk[0]: extract_chunks(chunk[1])}
else:
newchunk = {chunk[0]: chunk[1]}
if type(chunk[2]) == type("foo"):
newdict = extract_chunks(chunk[2])
if type(newdict) == type({}):
newchunk.update(newdict)
else:
print "Ok this is a defect... this shouldn't happen.I mean _never_. It means I split a chunk that wasn't a chunk.This is a fail.... correct it... somehow"
newchunk.update({"DEFECT": newdict})
else:
newchunk.update(chunk[2])
return newchunk
final_dict = extract_chunks(datawin)
# print type(final_dict)
print len(final_dict["FORM"]["STRG"])
print type(final_dict["FORM"]["STRG"])
# for foo in final_dict["FORM"]:
# print foo
# while datawin.tell()!=dsize:
# extract chunk from data
# übergib chunk to while like this
# chunk=read_chunk(datawin)
#
# chunks[chunk[0]]=StringIO.StringIO(chunk[1])
#
# chunk=read_chunk(chunks["FORM"])
#
#
# if check_chunk(StringIO.StringIO(chunk[1]))==0:
# chunk=read_chunk(StringIO.StringIO(chunk[1]))
# while dwsize!=datawin.tell():
# chunk=read_chunk()
# chunks[chunk[0]]=chunk[1]
# check if chunk
# add chunk to dictionary
# check if chunk
# add to dictionary
| 30.255474 | 174 | 0.587696 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,674 | 0.403763 |
dcd99c7731f5c8f42cf05cb204ee8f7516acc652 | 413 | py | Python | Diena_1_4_thonny/d2_u2_d11.py | edzya/Python_RTU_08_20 | d2921d998c611c18328dd523daf976a27ce858c1 | [
"MIT"
] | 8 | 2020-08-31T16:10:54.000Z | 2021-11-24T06:37:37.000Z | Diena_1_4_thonny/d2_u2_d11.py | edzya/Python_RTU_08_20 | d2921d998c611c18328dd523daf976a27ce858c1 | [
"MIT"
] | 8 | 2021-06-08T22:30:29.000Z | 2022-03-12T00:48:55.000Z | Diena_1_4_thonny/d2_u2_d11.py | edzya/Python_RTU_08_20 | d2921d998c611c18328dd523daf976a27ce858c1 | [
"MIT"
] | 12 | 2020-09-28T17:06:52.000Z | 2022-02-17T12:12:46.000Z | try:
width=float(input("Ieraksti savas istabas platumu (metros): "))
height=float(input("Ieraksti savas istabas augstumu (metros): "))
length=float(input("Ieraksti savas istabas garumu (metros): "))
capacity=round(width*height*length, 2)
print(f"Tavas istabas tilpums ir {capacity} m\u00b3.")
except ValueError:
print("Ievadiet vērtību ciparos! Komata vietā jālieto punkts.")
print("*"*30) | 45.888889 | 69 | 0.714286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 239 | 0.573141 |
dcdafaad8c8fc0f7203bbde1fef43d4a96e917bd | 1,381 | py | Python | javaStringHashCollision.py | VivekYadav7272/hash_code_collisions | 98eed61a4a4d69f1c6985ed43f01a18feb2f9605 | [
"MIT"
] | null | null | null | javaStringHashCollision.py | VivekYadav7272/hash_code_collisions | 98eed61a4a4d69f1c6985ed43f01a18feb2f9605 | [
"MIT"
] | null | null | null | javaStringHashCollision.py | VivekYadav7272/hash_code_collisions | 98eed61a4a4d69f1c6985ed43f01a18feb2f9605 | [
"MIT"
] | null | null | null | # Program to check how effective is Java's String's Hash Collision
# for generating hash codes for Indian Phone No.s
import random
from pprint import pprint
SAMPLE_SPACE = 10000
def genJavaHashCode(phone: str) -> int:
"""
s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]
where :
s[i] – is the ith character of the string
n – is the length of the string, and
^ – indicates exponentiation
"""
return sum( ord(phone[i]) * 31**(len(phone)-i-1) for i in range(len(phone)))
def genPhoneNo():
"""
Indian Phone No.s usually begin with 7, 8, or 9.
( This doesn't include the country code +91. )
Others are usually scam calls or from other countries.
They are 10 digits long.
"""
return str(random.randint(7, 9)) + ''.join(str(random.randint(0, 9)) for _ in range(9))
phone_nos = set([genPhoneNo() for _ in range(SAMPLE_SPACE)])
hash_to_phone = {}
hashCollisions = 0
def populateHashMap():
for phone in phone_nos:
hashCode = genJavaHashCode(phone)
if hashCode in hash_to_phone.keys():
hashCollisions += 1
else:
hash_to_phone[hashCode] = phone
if __name__ == '__main__':
# pprint(phone_nos)
populateHashMap()
print(f"Hash Collisions: {hashCollisions}")
print(f"hashCollisions rate = {hashCollisions / len(phone_nos)}")
| 30.688889 | 92 | 0.627806 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 655 | 0.471562 |
dcdb3ea3ab1893474827b46227655af67fd0f6e0 | 1,701 | py | Python | arrhenuis/termodyn.py | xtotdam/leipzig-report | fe4146f9201a8453683ef1221fc768f135677153 | [
"MIT"
] | null | null | null | arrhenuis/termodyn.py | xtotdam/leipzig-report | fe4146f9201a8453683ef1221fc768f135677153 | [
"MIT"
] | null | null | null | arrhenuis/termodyn.py | xtotdam/leipzig-report | fe4146f9201a8453683ef1221fc768f135677153 | [
"MIT"
] | null | null | null | from arrhenius import stringify
"""
This script generates cool table with termodynamic parameters, taken from 'termodyn-acid.data.txt' and 'termodyn-anion.data.txt'
"""
head = '''
\\begin{center}
\\begin{tabular}{ x{1cm} x{2cm} x{2cm} x{2cm} x{2cm} x{2cm} } \\hline
Acid & E$_A$ \\newline kJ/mol & A \\newline M$^{-1}$s$^{-1}$ & \
$\\Delta \\text{S} \\ddag$ \\newline J / mol ${\\cdot}$ K & $\\Delta \\text{H} \\ddag$ \\newline kJ / mol & $\\Delta \\text{G} \\ddag$ \\newline kJ / mol \\\\ \\hline
'''
feet = '''
\\hline
\\end{tabular}
\\end{center}
'''
acidstrings, anionstrings = list(), list()
data = open('termodyn-acid.data.txt').readlines()
for line in data:
acro = line.split()[0]
ea, a, s, h, g = map(float, line.split()[1:])
string = '{} & ${:.1f}$ & ${:.2e}$ & ${:.1f}$ & ${:.1f}$ & ${:.1f}$ \\\\'.format(acro, ea, a, s, h, g)
acidstrings.append(string)
data = open('termodyn-anion.data.txt').readlines()
for line in data:
acro = line.split()[0]
ea, a, s, h, g = map(float, line.split()[1:])
string = '{} & ${:.1f}$ & ${:.2e}$ & ${:.1f}$ & ${:.1f}$ & ${:.1f}$ \\\\'.format(acro, ea, a, s, h, g)
anionstrings.append(string)
latex = 'Reactions of OH radicals with halogenated acids \n\n' + \
head + ' \n '.join(acidstrings) + '\n' + feet + '\n\n' + \
'Reactions of OH radicals with haloacetate and halopropiate anions \n\n' + \
head + ' \n '.join(anionstrings) + '\n' + feet
for i in range(5, 16):
latex = latex.replace('e+{:02d}'.format(i), ' \\cdot 10^{{{0}}} '.format(i))
latex = latex.replace('$nan$', '---')
with open('termodyn.tex', 'w') as f:
f.write(latex)
| 36.191489 | 167 | 0.542034 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 910 | 0.534979 |
dcdc34ed85ff8e76e296804c80c837bca03715e7 | 9,930 | py | Python | functree/tree.py | yutayamate/functree-ng | 0eeb59c7117c4271125871929f680f660e4a413a | [
"MIT"
] | 17 | 2019-01-17T09:20:50.000Z | 2022-02-08T05:49:35.000Z | functree/tree.py | yutayamate/functree-ng | 0eeb59c7117c4271125871929f680f660e4a413a | [
"MIT"
] | 17 | 2019-03-26T10:16:10.000Z | 2022-03-11T23:38:33.000Z | functree/tree.py | yutayamate/functree-ng | 0eeb59c7117c4271125871929f680f660e4a413a | [
"MIT"
] | 7 | 2019-04-30T02:57:58.000Z | 2021-09-01T18:53:20.000Z | #!/usr/bin/env python3
import re, copy, urllib.request, urllib.parse, argparse, json
import networkx as nx
KEGG_DOWNLOAD_HTEXT_ENDPOINT = 'http://www.genome.jp/kegg-bin/download_htext?'
EXCLUDES = ['Global and overview maps', 'Drug Development', 'Chemical structure transformation maps']
class Node(dict):
def __init__(self, *args, **kwargs):
super(Node, self).__init__(*args, **kwargs)
def add_child(self, node):
if not 'children' in self:
self['children'] = list()
self['children'].append(node)
def get_nodes(self, nodes=None):
if nodes is None:
nodes = []
nodes.append(self)
if 'children' in self:
for i in self['children']:
i.get_nodes(nodes)
return nodes
def get_tree():
nodes_layer = {key: [] for key in ['brite0', 'brite1', 'brite2', 'pathway', 'module', 'ko']}
root = Node(entry='KEGG BRITE Functional Hierarchies', name='KEGG BRITE Functional Hierarchies', layer='brite0')
nodes_layer['brite0'].append(root)
with download_htext(htext='br08901.keg') as f:
for line in f.read().decode('utf-8').split('\n'):
if line.startswith('A'):
layer = 'brite1'
line = line.lstrip('A').lstrip()
entry = name = re.sub(r'<[^>]*?>', '', line)
node = Node(entry=entry, name=name, layer=layer)
nodes_layer['brite0'][-1].add_child(node)
nodes_layer[layer].append(node)
continue
if line.startswith('B'):
layer = 'brite2'
line = line.lstrip('B').lstrip()
entry = name = line
node = Node(entry=entry, name=name, layer=layer)
nodes_layer['brite1'][-1].add_child(node)
nodes_layer[layer].append(node)
continue
if line.startswith('C'):
layer = 'pathway'
line = line.lstrip('C').lstrip()
entry, name = line.split(maxsplit=1)
entry = 'map{}'.format(entry)
node = Node(entry=entry, name=name, layer=layer)
nodes_layer['brite2'][-1].add_child(node)
nodes_layer[layer].append(node)
with download_htext(htext='ko00002.keg') as f:
for line in f.read().decode('utf-8').split('\n'):
if line.startswith('D'):
layer = 'module'
line = line.lstrip('D').lstrip()
entry, name = line.split(maxsplit=1)
node = Node(entry=entry, name=name, layer=layer)
nodes_layer[layer].append(node)
continue
if line.startswith('E'):
layer = 'ko'
line = line.lstrip('E').lstrip()
entry, name = line.split(maxsplit=1)
node = Node(entry=entry, name=name, layer=layer)
nodes_layer['module'][-1].add_child(node)
# Link modules to all associated pathways
nodes = root.get_nodes()
for node in nodes_layer['module']:
parents_match = re.search(r'\[.+?\]', node['name'])
if parents_match:
parent_entries_ = parents_match.group()[1:-1].lstrip('PATH:').split()
parent_entries = filter(lambda x: re.match('map', x), parent_entries_)
for parent_entry in parent_entries:
targets = filter(lambda x: x['entry'] == parent_entry, nodes)
for target in targets:
target.add_child(copy.deepcopy(node))
# Add KOs which belong to not module but pathway
nodes = root.get_nodes()
with download_htext(htext='ko00001.keg') as f:
for line in f.read().decode('utf-8').split('\n'):
if line.startswith('C'):
line = line.lstrip('C').lstrip()
entry = line.split(maxsplit=1)[0]
entry = 'map{}'.format(entry)
targets = list(filter(lambda x: x['entry'] == entry, nodes))
continue
if line.startswith('D'):
layer = 'ko'
line = line.lstrip('D').lstrip()
entry, name = line.split(maxsplit=1)
for target in targets:
child_ko_entries = map(lambda x: x['entry'], filter(lambda x: x['layer'] == 'ko', target.get_nodes()))
if not entry in child_ko_entries:
if 'children' not in target:
node = Node(entry='*Module undefined*', name='*Module undefined*', layer='module')
target.add_child(node)
elif target['children'][-1]['entry'] != '*Module undefined*':
node = Node(entry='*Module undefined*', name='*Module undefined*', layer='module')
target.add_child(node)
node = Node(entry=entry, name=name, layer=layer)
target['children'][-1].add_child(node)
# Remove nodes which are listed on EXCLUDES
for node in filter(lambda x: x['layer'] != 'ko', root.get_nodes()):
if 'children' in node:
for child_node in node['children'][:]:
if child_node['entry'] in EXCLUDES:
node['children'].remove(child_node)
# Remove nodes which do not have children
for node in filter(lambda x: x['layer'] not in ['ko', 'module'], root.get_nodes()):
if 'children' in node:
for child_node in node['children'][:]:
if 'children' not in child_node:
node['children'].remove(child_node)
return root
def from_json(path):
root = json.load(path)
return root
def from_tsv(path, name):
'''
Turns a TSV formatted hierarchy into a JSON-like, FuncTree compatible hierarchy
'''
root = Node(entry=name, name=name, layer='root')
# process annotation if available
entry_label = {}
line = path.readline()
if line.strip().decode() == 'Annotation-start':
#populate annotation table
line = path.readline()
while line:
line = line.strip().decode()
while line != 'Annotation-end':
entry, label = line.split('\t')
entry_label[entry] = label
line = path.readline()
# set header to current line
header = line
# if file has annotation
if len(entry_label) > 0 :
# read header from next line
header = path.readline()
levels = header.strip().decode().split('\t')
levels.insert(0, 'root')
nodes_layer = {key: {} for key in levels}
nodes_layer['root'] = {'root': root}
line = path.readline()
while line:
entries = line.strip().decode().split('\t')
# prefix empty cells by parent id
for index, entry in enumerate(entries):
if entry in ["", "-"]:
unique_entry = levels[index + 1]
if index == 0:
unique_entry = "root_" + unique_entry
else:
unique_entry = entries[index - 1] + "_" + unique_entry
entries[index] = unique_entry
for index, entry in enumerate(entries):
layer = levels[index + 1]
if entry not in nodes_layer[layer]:
parent_layer = levels[index]
name_label = entry
if entry in entry_label:
name_label = entry_label[entry]
node = Node(entry=entry, name=name_label, layer=layer)
if index > 0:
nodes_layer[parent_layer][entries[index - 1]].add_child(node)
else:
nodes_layer[parent_layer]['root'].add_child(node)
nodes_layer[layer][entry] = node
line = path.readline()
#path.close()
return root
def download_htext(htext, format='htext'):
params = {
'htext': htext,
'format': format
}
url = KEGG_DOWNLOAD_HTEXT_ENDPOINT + urllib.parse.urlencode(params)
res = urllib.request.urlopen(url)
return res
def get_nodes(node, nodes=None):
if nodes is None:
nodes = []
nodes.append(node)
if 'children' in node:
for child_node in node['children']:
get_nodes(child_node, nodes)
return nodes
def delete_children(node, layer):
if node['layer'] == layer:
node.pop('children')
if 'children' in node:
for i in node['children']:
delete_children(i, layer)
def to_graph(root):
stack = [root]
G = nx.DiGraph()
while stack:
parent = stack.pop()
if 'children' in parent:
for c in parent['children']:
if c['entry'].startswith('*'):
child = parent['entry'] + c['entry']
G.add_edge(parent['entry'], child)
for leaf in c['children']:
G.add_edge(child, leaf['entry'])
else:
G.add_edge(parent['entry'], c['entry'])
stack.append(c)
return G
def parse_arguments():
parser = argparse.ArgumentParser(prog=__file__, description='Functional Tree JSON generator')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.2.0')
parser.add_argument('-o', '--output', metavar='file', type=argparse.FileType('w'), default=sys.stdout, help='write output to file')
parser.add_argument('-i', '--indent', metavar='level', type=int, default=None, help='specify indent level')
return parser.parse_args()
if __name__ == '__main__':
import sys, json, datetime
args = parse_arguments()
data = {
'tree': get_tree(),
'created_at': datetime.datetime.utcnow().isoformat()
}
args.output.write(json.dumps(data, indent=args.indent) + '\n')
| 38.941176 | 135 | 0.544411 | 493 | 0.049648 | 0 | 0 | 0 | 0 | 0 | 0 | 1,774 | 0.178651 |
dcdd023a81feca70c98120ea168d3604a0c94976 | 416 | py | Python | app/config.py | dogukangungordi/cinetify-Movie | 85946010f4471cef0fb42873d50d59493372d060 | [
"MIT"
] | null | null | null | app/config.py | dogukangungordi/cinetify-Movie | 85946010f4471cef0fb42873d50d59493372d060 | [
"MIT"
] | null | null | null | app/config.py | dogukangungordi/cinetify-Movie | 85946010f4471cef0fb42873d50d59493372d060 | [
"MIT"
] | null | null | null | import os
TWO_WEEKS = 1209600
SECRET_KEY = os.getenv('SECRET_KEY', None)
assert SECRET_KEY
TOKEN_EXPIRES = TWO_WEEKS
DATABASE_URL = os.getenv(
'DATABASE_URL',
'postgres://postgres@{0}:5432/postgres'.format(os.getenv('DB_PORT_5432_TCP_ADDR', None)))
assert DATABASE_URL
REDIS_HOST = os.getenv('REDIS_HOST', os.getenv('REDIS_PORT_6379_TCP_ADDR', None))
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', None)
| 23.111111 | 93 | 0.759615 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 142 | 0.341346 |
dcdd6e685bb422c18bab7a2d6e2b60a9ba328309 | 597 | py | Python | 2020/day02/password_philosopy.py | rycmak/advent-of-code | 2a3289516f4c1d0bc1d24a38d495a93edcb19e29 | [
"MIT"
] | 1 | 2021-03-03T01:40:09.000Z | 2021-03-03T01:40:09.000Z | 2020/day02/password_philosopy.py | rycmak/advent-of-code | 2a3289516f4c1d0bc1d24a38d495a93edcb19e29 | [
"MIT"
] | null | null | null | 2020/day02/password_philosopy.py | rycmak/advent-of-code | 2a3289516f4c1d0bc1d24a38d495a93edcb19e29 | [
"MIT"
] | null | null | null | file = open("input.txt", "r")
num_valid = 0
for line in file:
# policy = part before colon
policy = line.strip().split(":")[0]
# get min/max number allowed for given letter
min_max = policy.split(" ")[0]
letter = policy.split(" ")[1]
min = int(min_max.split("-")[0])
max = int(min_max.split("-")[1])
# password = part after colon
password = line.strip().split(":")[1]
# check if password contains between min and max of given letter
if password.count(letter) >= min and password.count(letter) <= max:
num_valid += 1
print("Number of valid passwords = ", num_valid) | 28.428571 | 69 | 0.644891 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 228 | 0.38191 |
dcddcfee3d5454fe6a00d6247e9174457baf2d21 | 4,209 | py | Python | tools/config_setting.py | JBoRu/IMN-Pytorch-implement | 2e605353a2f9aac2c151b72c40a19eb2a9eb9967 | [
"MIT"
] | 1 | 2020-05-08T02:03:20.000Z | 2020-05-08T02:03:20.000Z | tools/config_setting.py | JBoRu/IMN-Pytorch-implement | 2e605353a2f9aac2c151b72c40a19eb2a9eb9967 | [
"MIT"
] | 1 | 2021-07-21T07:33:23.000Z | 2021-07-22T02:09:55.000Z | tools/config_setting.py | JBoRu/IMN-Pytorch-implement | 2e605353a2f9aac2c151b72c40a19eb2a9eb9967 | [
"MIT"
] | null | null | null | import argparse
import logging
import numpy as np
def Parse_Arguments():
parser = argparse.ArgumentParser()
# argument related to datasets and data preprocessing
parser.add_argument("--domain", dest="domain", type=str, metavar='<str>', default='res', help="domain of the corpus {res, lt, res_15}")
parser.add_argument("-v", "--vocab-size", dest="vocab_size", type=int, metavar='<int>', default=20000, help="Vocab size. '0' means no limit (default=20000)")
# hyper-parameters related to network training
parser.add_argument("-a", "--algorithm", dest="algorithm", type=str, metavar='<str>', default='adam', help="Optimization algorithm (rmsprop|sgd|adagrad|adadelta|adam|adamax) (default=adam)")
parser.add_argument("-b", "--batch-size", dest="batch_size", type=int, metavar='<int>', default=32, help="Batch size (default=32)")
parser.add_argument("--epochs", dest="epochs", type=int, metavar='<int>', default=80, help="Number of epochs (default=80)")
parser.add_argument("--validation-ratio", dest="validation_ratio", type=float, metavar='<float>', default=0.2, help="The percentage of training data used for validation")
parser.add_argument("--pre-epochs", dest="pre_epochs", type=int, metavar='<int>', default=5, help="Number of pretrain document-level epochs (default=5)")
parser.add_argument("-mr", dest="mr", type=int, metavar='<int>', default=2, help="#aspect-level epochs : #document-level epochs = mr:1")
# hyper-parameters related to network structure
parser.add_argument("-e", "--embdim", dest="emb_dim", type=int, metavar='<int>', default=400, help="Embeddings dimension (default=dim_general_emb + dim_domain_emb = 400)")
parser.add_argument("-c", "--cnndim", dest="cnn_dim", type=int, metavar='<int>', default=300, help="CNN output dimension. '0' means no CNN layer (default=300)")
parser.add_argument("--dropout", dest="dropout_prob", type=float, metavar='<float>', default=0.5, help="The dropout probability. (default=0.5)")
parser.add_argument("--use-doc", dest="use_doc", type=int, metavar='<int>', default=1, help="whether to exploit knowledge from document-level data")
parser.add_argument("--train-op", dest="train_op", type=int, metavar='<int>', default=1, help="whether to extract opinion terms")
parser.add_argument("--use-opinion", dest="use_opinion", type=int, metavar='<int>', default=1, help="whether to perform opinion transmission")
parser.add_argument("--shared-layers", dest="shared_layers", type=int, metavar='<int>', default=2, help="The number of CNN layers in the shared network")
parser.add_argument("--doc-senti-layers", dest="doc_senti_layers", type=int, metavar='<int>', default=0, help="The number of CNN layers for extracting document-level sentiment features")
parser.add_argument("--doc-domain-layers", dest="doc_domain_layers", type=int, metavar='<int>', default=0, help="The number of CNN layers for extracting document domain features")
parser.add_argument("--senti-layers", dest="senti_layers", type=int, metavar='<int>', default=0, help="The number of CNN layers for extracting aspect-level sentiment features")
parser.add_argument("--aspect-layers", dest="aspect_layers", type=int, metavar='<int>', default=2, help="The number of CNN layers for extracting aspect features")
parser.add_argument("--interactions", dest="interactions", type=int, metavar='<int>', default=2, help="The number of interactions")
parser.add_argument("--use-domain-emb", dest="use_domain_emb", type=int, metavar='<int>', default=1, help="whether to use domain-specific embeddings")
# random seed that affects data splits and parameter intializations
parser.add_argument("--seed", dest="seed", type=int, metavar='<int>', default=123, help="Random seed (default=123)")
# test
parser.add_argument("--vocab", dest="vocab", default=((1,2,3),(1,2,3)))
parser.add_argument("--emb_file_gen", dest="emb_file_gen", type=str, default="./corpus/glove/res.txt")
parser.add_argument("--emb_file_domain", dest="emb_file_domain",type=str, default="./corpus/glove/res.txt")
args = parser.parse_args()
return args
| 89.553191 | 195 | 0.703968 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,216 | 0.526491 |
dcde4bcab3184fcfb3d10a1de327eba5c84c244b | 3,503 | py | Python | data_loader.py | franpena-kth/learning-deep-learning | 9cd287b602dee1358672c4189445721a9c24f107 | [
"MIT"
] | null | null | null | data_loader.py | franpena-kth/learning-deep-learning | 9cd287b602dee1358672c4189445721a9c24f107 | [
"MIT"
] | null | null | null | data_loader.py | franpena-kth/learning-deep-learning | 9cd287b602dee1358672c4189445721a9c24f107 | [
"MIT"
] | null | null | null | import h5py
import numpy
import sklearn
import sklearn.datasets
from matplotlib import pyplot
def load_dataset():
data_dir = '/Users/fpena/Courses/Coursera-Deep-Learning/Assignments/datasets/'
train_dataset = h5py.File(data_dir + 'train_catvnoncat.h5', "r")
train_set_x_orig = numpy.array(train_dataset["train_set_x"][:]) # your train set features
train_set_y_orig = numpy.array(train_dataset["train_set_y"][:]) # your train set labels
test_dataset = h5py.File(data_dir + 'test_catvnoncat.h5', "r")
test_set_x_orig = numpy.array(test_dataset["test_set_x"][:]) # your test set features
test_set_y_orig = numpy.array(test_dataset["test_set_y"][:]) # your test set labels
classes = numpy.array(test_dataset["list_classes"][:]) # the list of classes
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
def preprocess_dataset(train_set_x_orig, test_set_x_orig):
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
train_set_x = train_set_x_flatten / 255.
test_set_x = test_set_x_flatten / 255.
return train_set_x, test_set_x
def plot_decision_boundary(model, X, y):
# Set min and max values and give it some padding
x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
h = 0.01
# Generate a grid of points with distance h between them
xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, h), numpy.arange(y_min, y_max, h))
# Predict the function value for the whole grid
Z = model(numpy.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# Plot the contour and training examples
pyplot.contourf(xx, yy, Z, cmap=pyplot.cm.Spectral)
pyplot.ylabel('x2')
pyplot.xlabel('x1')
pyplot.scatter(X[0, :], X[1, :], c=y, cmap=pyplot.cm.Spectral)
# pyplot.show()
def load_planar_dataset():
numpy.random.seed(1)
m = 400 # number of examples
N = int(m / 2) # number of points per class
D = 2 # dimensionality
X = numpy.zeros((m, D)) # data matrix where each row is a single example
Y = numpy.zeros((m, 1), dtype='uint8') # labels vector (0 for red, 1 for blue)
a = 4 # maximum ray of the flower
for j in range(2):
ix = range(N * j, N * (j + 1))
t = numpy.linspace(j * 3.12, (j + 1) * 3.12, N) + numpy.random.randn(N) * 0.2 # theta
r = a * numpy.sin(4 * t) + numpy.random.randn(N) * 0.2 # radius
X[ix] = numpy.c_[r * numpy.sin(t), r * numpy.cos(t)]
Y[ix] = j
X = X.T
Y = Y.T
return X, Y
def load_extra_datasets():
N = 200
noisy_circles = sklearn.datasets.make_circles(n_samples=N, factor=.5, noise=.3)
noisy_moons = sklearn.datasets.make_moons(n_samples=N, noise=.2)
blobs = sklearn.datasets.make_blobs(n_samples=N, random_state=5, n_features=2, centers=6)
gaussian_quantiles = sklearn.datasets.make_gaussian_quantiles(mean=None, cov=0.5, n_samples=N, n_features=2,
n_classes=2, shuffle=True, random_state=None)
no_structure = numpy.random.rand(N, 2), numpy.random.rand(N, 2)
return noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure
| 40.264368 | 112 | 0.666572 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 708 | 0.202112 |
dce163daae46473015d3b2a1132e2c0325c306ae | 669 | py | Python | landmarkrest/field_predictor/field_models/TwoDigitYear.py | inferlink/landmark-rest | 5bda40424bd1d62c64c9f4931855b4e341742b95 | [
"BSD-4-Clause"
] | null | null | null | landmarkrest/field_predictor/field_models/TwoDigitYear.py | inferlink/landmark-rest | 5bda40424bd1d62c64c9f4931855b4e341742b95 | [
"BSD-4-Clause"
] | null | null | null | landmarkrest/field_predictor/field_models/TwoDigitYear.py | inferlink/landmark-rest | 5bda40424bd1d62c64c9f4931855b4e341742b95 | [
"BSD-4-Clause"
] | null | null | null | from BaseModel import BaseModel
class TwoDigitYear(BaseModel):
def __init__(self):
super(TwoDigitYear, self).__init__()
def generate_confidence(self, preceding_stripes, slot_values, following_stripes):
# only care about ints for this model, so strip out anything that isn't
valid_values = [z for z in slot_values if str(z).isdigit()]
# two digit number
matches = list(enumerate([(0 <= int(a) <= 99) and str(a).isdigit() and
len(str(a)) == 2 for a in valid_values]))
confidence = float(len([z for z in matches if z[1]])) / float(len(slot_values))
return confidence
| 33.45 | 87 | 0.630792 | 634 | 0.947683 | 0 | 0 | 0 | 0 | 0 | 0 | 89 | 0.133034 |
dce57c487095cb71ffd506dd3c16e7691af00444 | 5,078 | py | Python | compressor.py | kunliu7/compress_2RDM | 29ffa35ae5172d897fefb431b7894cdaf38b91ae | [
"MIT"
] | null | null | null | compressor.py | kunliu7/compress_2RDM | 29ffa35ae5172d897fefb431b7894cdaf38b91ae | [
"MIT"
] | null | null | null | compressor.py | kunliu7/compress_2RDM | 29ffa35ae5172d897fefb431b7894cdaf38b91ae | [
"MIT"
] | null | null | null | import numpy as np
class Compressor():
def __init__(self,
num_particles: int, num_spin_orbitals: int, rdm_ideal=None) -> None:
self.num_particles = num_particles
self.num_spin_orbitals = num_spin_orbitals
self.rdm_ideal = rdm_ideal
pass
def compress(self, rdm):
N = self.num_spin_orbitals ** 2 // 4
# get num of elements by square formula of triangle
S = self._get_num_elems_of_tri_mat(N)
n = self.num_spin_orbitals // 2
# mat = self._tensor2matrix(rdm)
utri_arr = np.zeros((3*S,))
utri_arr[: S] = \
self._compress_matrix_to_upper_triangle_array(self._tensor2matrix(rdm[:n, :n, :n, :n]))
utri_arr[S: 2*S] = \
self._compress_matrix_to_upper_triangle_array(self._tensor2matrix(rdm[:n, n:, :n, n:]))
utri_arr[2*S: ] = \
self._compress_matrix_to_upper_triangle_array(self._tensor2matrix(rdm[n:, n:, n:, n:]))
return utri_arr
def decompress(self, utri_arr):
# rdm = np.zeros((self.num_spin_orbitals ** 2,) * 2) # matrix
rdm = np.zeros((self.num_spin_orbitals,) * 4) # tensor
N = self.num_spin_orbitals ** 2 // 4
n = self.num_spin_orbitals // 2
# get num of elements by square formula of triangle
S = self._get_num_elems_of_tri_mat(N)
# restore from the second triangle
A = self._restore_matrix_by_upper_triangle_array(utri_arr[S: 2*S], N)
A_tensor = self._matrix2tensor(A)
B = - A_tensor.transpose([0, 1, 3, 2])
# B = self._tensor2matrix(B)
C = A_tensor.transpose([1, 0, 3, 2])
# C = self._tensor2matrix(C)
D = - A_tensor.transpose([1, 0, 2, 3])
# restore middle 4
# rdm[N: 2*N, N: 2*N] = A
# diff = np.linalg.norm(self._tensor2matrix(self.rdm_ideal)[N: 2*N, N: 2*N] - A)
rdm[:n, n:, :n, n:] = A_tensor
# diff = np.linalg.norm(self.rdm_ideal[:n, n:, :n, n:] - A_tensor)
# print('A', diff)
# rdm[N: 2*N, 2*N: 3*N] = B
# diff = np.linalg.norm(self._tensor2matrix(self.rdm_ideal)[N: 2*N, 2*N: 3*N] - B)
rdm[:n, n:, n:, :n] = B
# diff = np.linalg.norm(self.rdm_ideal[:n, n:, n:, :n] - B)
# print('B', diff)
# rdm[2*N: 3*N, 2*N: 3*N] = C
# diff = np.linalg.norm(self._tensor2matrix(self.rdm_ideal)[2*N: 3*N, 2*N: 3*N] - C)
rdm[n:, :n, n:, :n] = C
# diff = np.linalg.norm(self.rdm_ideal[n:, :n, n:, :n] - C)
# print('C', diff)
rdm[n:, :n, :n, n:] = D
# diff = np.linalg.norm(self.rdm_ideal[n:, :n, :n, n:] - D)
# print('D', diff)
# rdm = self._tensor2matrix(rdm)
# restore upper left
rdm[:n, :n, :n, :n] = \
self._matrix2tensor(self._restore_matrix_by_upper_triangle_array(utri_arr[: S], N))
# diff = np.linalg.norm(self.rdm_ideal[:n, :n, :n, :n] - rdm[:n, :n, :n, :n])
# print('upper left', diff)
# restore button right
rdm[n:, n:, n:, n:] = \
self._matrix2tensor(self._restore_matrix_by_upper_triangle_array(utri_arr[2*S:], N))
# diff = np.linalg.norm(self.rdm_ideal[n:, n:, n:, n:] - rdm[n:, n:, n:, n:])
# print('button right', diff)
# rdm = self._tensor2matrix(rdm)
# utri = np.triu(rdm)
# diag = np.diag(np.diag(rdm))
# utri -= diag
# rdm = utri + utri.T + diag
return rdm #self._matrix2tensor(rdm)
@staticmethod
def _restore_matrix_by_upper_triangle_array(utri_arr, n):
cnt = 0
utri = np.zeros((n,) * 2) # upper triangular matrix
for i in range(n):
for j in range(i, n):
utri[i, j] = utri_arr[cnt]
cnt += 1
diag = np.diag(np.diag(utri))
mat = utri + utri.T - diag
return mat
@staticmethod
def _compress_matrix_to_upper_triangle_array(mat):
n = mat.shape[0]
num_elements = Compressor._get_num_elems_of_tri_mat(n)
utri_arr = np.zeros((num_elements))
cnt = 0
for i in range(n):
for j in range(i, n):
utri_arr[cnt] = mat[i, j]
cnt += 1
return utri_arr
@staticmethod
def _get_num_elems_of_tri_mat(n):
return (n + 1) * n // 2
@staticmethod
def _matrix2tensor(mat, transpose=False):
n = int(np.sqrt(mat.shape[0]))
if transpose:
tensor = mat.reshape((n,) * 4).transpose([0, 1, 3, 2])
else:
tensor = mat.reshape((n,) * 4)
return tensor
@staticmethod
def _tensor2matrix(tensor, transpose=False):
n = tensor.shape[0]
if transpose:
mat = tensor.transpose([0, 1, 3, 2]).reshape((n*n,) * 2)
else:
mat = tensor.reshape((n*n,) * 2)
return mat
@staticmethod
def _utri_mat2real_sym_mat(utri):
diag = np.diag(np.diag(utri))
mat = utri + utri.T - diag
return mat
| 31.153374 | 99 | 0.541355 | 5,056 | 0.995668 | 0 | 0 | 1,495 | 0.294407 | 0 | 0 | 1,412 | 0.278062 |
dce5e9ef143c58e970f4648e4aa54bd55e17fa5f | 5,285 | py | Python | Lib/site-packages/node/tests/test_lifecycle.py | Dr8Ninja/ShareSpace | 7b445783a313cbdebb1938e824e98370a42def5f | [
"MIT"
] | 11 | 2015-04-02T17:47:44.000Z | 2020-10-26T20:27:43.000Z | Lib/site-packages/node/tests/test_lifecycle.py | Dr8Ninja/ShareSpace | 7b445783a313cbdebb1938e824e98370a42def5f | [
"MIT"
] | 5 | 2017-01-18T11:05:42.000Z | 2019-03-30T06:19:21.000Z | Lib/site-packages/node/tests/test_lifecycle.py | Dr8Ninja/ShareSpace | 7b445783a313cbdebb1938e824e98370a42def5f | [
"MIT"
] | 2 | 2015-09-15T06:50:22.000Z | 2016-12-01T11:12:01.000Z | from node.behaviors import Attributes
from node.behaviors import AttributesLifecycle
from node.behaviors import DefaultInit
from node.behaviors import DictStorage
from node.behaviors import Lifecycle
from node.behaviors import NodeAttributes
from node.behaviors import Nodespaces
from node.behaviors import Nodify
from node.events import NodeAddedEvent
from node.events import NodeCreatedEvent
from node.events import NodeDetachedEvent
from node.events import NodeModifiedEvent
from node.events import NodeRemovedEvent
from node.interfaces import INode
from node.interfaces import INodeAddedEvent
from node.interfaces import INodeCreatedEvent
from node.interfaces import INodeDetachedEvent
from node.interfaces import INodeModifiedEvent
from node.interfaces import INodeRemovedEvent
from node.tests import NodeTestCase
from plumber import plumbing
import zope.component
###############################################################################
# Mock objects
###############################################################################
class Handler(object):
handled = []
def __call__(self, obj, event):
self.handled.append(event)
def clear(self):
self.handled = []
@plumbing(
DefaultInit,
Nodify,
DictStorage)
class NoLifecycleNode(object):
pass
@plumbing(AttributesLifecycle)
class LifecycleNodeAttributes(NodeAttributes):
pass
@plumbing(
Nodespaces,
Attributes,
Lifecycle,
DefaultInit,
Nodify,
DictStorage)
class LifecycleNode(object):
attributes_factory = LifecycleNodeAttributes
###############################################################################
# Tests
###############################################################################
class TestLifecycle(NodeTestCase):
def setUp(self):
super(TestLifecycle, self).setUp()
handler = self.handler = Handler()
zope.component.provideHandler(handler, [INode, INodeCreatedEvent])
zope.component.provideHandler(handler, [INode, INodeAddedEvent])
zope.component.provideHandler(handler, [INode, INodeModifiedEvent])
zope.component.provideHandler(handler, [INode, INodeRemovedEvent])
zope.component.provideHandler(handler, [INode, INodeDetachedEvent])
def test_NodeCreatedEvent(self):
# Check NodeCreation
self.handler.clear()
NoLifecycleNode(name='no_notify')
self.assertEqual(self.handler.handled, [])
LifecycleNode(name='root')
self.assertEqual(len(self.handler.handled), 1)
self.assertTrue(isinstance(self.handler.handled[0], NodeCreatedEvent))
self.handler.clear()
def test_NodeAddedEvent(self):
# Check Node adding
root = LifecycleNode(name='root')
self.handler.clear()
root['child1'] = LifecycleNode()
self.assertEqual(len(self.handler.handled), 2)
self.assertTrue(isinstance(self.handler.handled[0], NodeCreatedEvent))
self.assertTrue(isinstance(self.handler.handled[1], NodeAddedEvent))
self.handler.clear()
def test_NodeModifiedEvent(self):
# Check Node modification
root = LifecycleNode(name='root')
child = root['child'] = LifecycleNode()
self.handler.clear()
# No event, despite the node creation for the attributes nodespace
attrs = child.attrs
self.assertTrue(isinstance(attrs, LifecycleNodeAttributes))
self.assertEqual(len(self.handler.handled), 0)
self.handler.clear()
# Node modified events if the attributes nodespace is changed
child.attrs['foo'] = 1
self.assertEqual(len(self.handler.handled), 1)
self.assertTrue(isinstance(self.handler.handled[0], NodeModifiedEvent))
self.handler.clear()
del child.attrs['foo']
self.assertEqual(len(self.handler.handled), 1)
self.assertTrue(isinstance(self.handler.handled[0], NodeModifiedEvent))
self.handler.clear()
def test_NodeRemovedEvent(self):
# Check Node Deletion
root = LifecycleNode(name='root')
root['child'] = LifecycleNode()
self.handler.clear()
del root['child']
self.assertEqual(len(self.handler.handled), 1)
self.assertTrue(isinstance(self.handler.handled[0], NodeRemovedEvent))
self.handler.clear()
def test_NodeDetachedEvent(self):
# Check Node Detach
root = LifecycleNode(name='root')
root['child'] = LifecycleNode()
self.handler.clear()
root.detach('child')
self.assertEqual(len(self.handler.handled), 1)
self.assertTrue(isinstance(self.handler.handled[0], NodeDetachedEvent))
self.handler.clear()
def test__notify_suppress(self):
# Check notify suppress on ``__setitem__``
root = LifecycleNode(name='root')
self.handler.clear()
root._notify_suppress = True
root['child'] = NoLifecycleNode()
self.assertEqual(len(self.handler.handled), 0)
# Check notify suppress on attributes manipulation
attrs = root.attrs
attrs['foo'] = 'foo'
self.assertEqual(len(self.handler.handled), 0)
del attrs['foo']
self.assertEqual(len(self.handler.handled), 0)
| 30.373563 | 79 | 0.652602 | 3,863 | 0.730937 | 0 | 0 | 363 | 0.068685 | 0 | 0 | 782 | 0.147966 |
dce61460a569ea1c684c33c8c9a8695d6d330978 | 547 | py | Python | sources/t08/t08ej02.py | workready/pythonbasic | 59bd82caf99244f5e711124e1f6f4dec8de22141 | [
"MIT"
] | null | null | null | sources/t08/t08ej02.py | workready/pythonbasic | 59bd82caf99244f5e711124e1f6f4dec8de22141 | [
"MIT"
] | null | null | null | sources/t08/t08ej02.py | workready/pythonbasic | 59bd82caf99244f5e711124e1f6f4dec8de22141 | [
"MIT"
] | null | null | null | class Empleado(object):
"Clase para definir a un empleado"
def __init__(self, nombre, email):
self.nombre = nombre
self.email = email
def getNombre(self):
return self.nombre
jorge = Empleado("Jorge", "jorge@mail.com")
jorge.guapo = "Por supuesto"
# Probando hasattr, getattr, setattr
print(hasattr(jorge, 'guapo')) # True
print(getattr(jorge, 'guapo')) # Por supuesto
print(hasattr(jorge, 'listo')) # False
setattr(jorge, 'listo', 'Más que las monas')
print(getattr(jorge, 'listo')) # Mas que las monas | 27.35 | 51 | 0.670932 | 210 | 0.383212 | 0 | 0 | 0 | 0 | 0 | 0 | 208 | 0.379562 |
dce6dd052404f932eea34b3955c8909dbf822ff0 | 852 | py | Python | utils/label_smoothing.py | wdjose/keyword-transformer | ded7ee4dae3e0a164f6f2ebb46c105431aadc9d1 | [
"MIT"
] | 9 | 2021-05-15T17:57:50.000Z | 2022-03-28T14:39:43.000Z | utils/label_smoothing.py | wdjose/kws-transformer | ded7ee4dae3e0a164f6f2ebb46c105431aadc9d1 | [
"MIT"
] | null | null | null | utils/label_smoothing.py | wdjose/kws-transformer | ded7ee4dae3e0a164f6f2ebb46c105431aadc9d1 | [
"MIT"
] | 2 | 2021-05-15T18:01:36.000Z | 2021-06-02T06:22:43.000Z | import torch
from torch import nn
# LabelSmoothingLoss from: https://github.com/dreamgonfly/transformer-pytorch/blob/master/losses.py
# License: https://github.com/dreamgonfly/transformer-pytorch/blob/master/LICENSE
class LabelSmoothingLoss(nn.Module):
def __init__(self, classes, smoothing=0.0):
super(LabelSmoothingLoss, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.cls = classes
def forward(self, pred, target):
assert 0 <= self.smoothing < 1
pred = pred.log_softmax(dim=-1)
with torch.no_grad():
true_dist = torch.zeros_like(pred)
true_dist.fill_(self.smoothing / (self.cls - 1))
true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)
return torch.mean(torch.sum(-true_dist * pred, dim=-1))
| 42.6 | 99 | 0.67723 | 634 | 0.744131 | 0 | 0 | 0 | 0 | 0 | 0 | 180 | 0.211268 |
dce816b69b0582baaf4d9c46666864b3035d5fab | 931 | py | Python | lib/west_tools/westpa/reweight/__init__.py | ajoshpratt/westpa | 545a42a5ae4cfa77de0e125a38a5b1ec2b9ab218 | [
"MIT"
] | 1 | 2019-12-21T09:11:54.000Z | 2019-12-21T09:11:54.000Z | lib/west_tools/westpa/reweight/__init__.py | astatide/westpa | 545a42a5ae4cfa77de0e125a38a5b1ec2b9ab218 | [
"MIT"
] | 1 | 2020-04-14T20:49:38.000Z | 2020-04-14T20:49:38.000Z | lib/west_tools/westpa/reweight/__init__.py | ajoshpratt/westpa | 545a42a5ae4cfa77de0e125a38a5b1ec2b9ab218 | [
"MIT"
] | 1 | 2020-04-14T20:42:11.000Z | 2020-04-14T20:42:11.000Z | # Copyright (C) 2017 Matthew C. Zwier and Lillian T. Chong
#
# This file is part of WESTPA.
#
# WESTPA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WESTPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WESTPA. If not, see <http://www.gnu.org/licenses/>.
'''
Function(s) for the postanalysis toolkit
'''
import logging
log = logging.getLogger(__name__)
import _reweight
from _reweight import (stats_process, reweight_for_c) #@UnresolvedImport
from matrix import FluxMatrix
| 33.25 | 72 | 0.765843 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 760 | 0.816327 |
dce9049b9ad5800c270533fc62b259d65fd6b5da | 3,044 | py | Python | platforms/m3/programming/mbus_message.py | lab11/M-ulator | 95b49c6194678c74accca4a20af71380efbcac5f | [
"Apache-2.0",
"MIT"
] | 19 | 2015-01-26T10:47:23.000Z | 2021-08-13T11:07:54.000Z | platforms/m3/programming/mbus_message.py | lab11/M-ulator | 95b49c6194678c74accca4a20af71380efbcac5f | [
"Apache-2.0",
"MIT"
] | 14 | 2015-08-24T02:35:46.000Z | 2021-05-05T03:53:44.000Z | platforms/m3/programming/mbus_message.py | lab11/M-ulator | 95b49c6194678c74accca4a20af71380efbcac5f | [
"Apache-2.0",
"MIT"
] | 9 | 2015-05-27T23:27:35.000Z | 2020-10-05T22:02:43.000Z | #!/usr/bin/python
import sys
import logging
from m3_common import m3_common
#m3_common.configure_root_logger()
#logger = logging.getLogger(__name__)
from m3_logging import get_logger
logger = get_logger(__name__)
class mbus_message_generator(m3_common):
TITLE = "MBus Message Generator"
def add_parse_args(self):
super(mbus_message_generator, self).add_parse_args(require_binfile=False)
def install_handler(self):
self.ice.msg_handler['B++'] = self.Bpp_callback
self.ice.msg_handler['b++'] = self.Bpp_callback
def Bpp_callback(self, address, data, broadcast, success):
logger.info("")
logger.info("Received MBus message:")
logger.info(" address: " + address.encode('hex'))
logger.info(" data: " + data.encode('hex'))
logger.info("broadcast: " + str(broadcast))
logger.info(" success: " + str(success))
logger.info("")
def read_binfile(self):
pass
def set_master(self):
self.ice.mbus_set_master_onoff(True)
def set_slave(self):
self.ice.mbus_set_master_onoff(False)
m = mbus_message_generator()
#m.do_default("Run power-on sequence", m.power_on)
#m.do_default("Reset M3", m.reset_m3)
m.power_on(wait_for_rails_to_settle=False)
m.ice.mbus_set_internal_reset(True)
m.do_default("Act as MBus master", m.set_master, m.set_slave)
m.ice.mbus_set_internal_reset(False)
def build_mbus_message():
logger.info("Build your MBus message. All values hex. Leading 0x optional. Ctrl-C to Quit.")
addr = m.default_value("Address ", "0xA5").replace('0x','').decode('hex')
data = m.default_value(" Data", "0x12345678").replace('0x','').decode('hex')
return addr, data
def get_mbus_message_to_send():
logger.info("Which message would you like to send?")
logger.info("\t0) Custom")
logger.info("\t1) Enumerate (0xF0000000, 0x24000000)")
logger.info("\t2) SNS Config Bits (0x40, 0x0423dfef)")
logger.info("\t3) SNS Sample Setup (0x40, 0x030bf0f0)")
logger.info("\t4) SNS Sample Start (0x40, 0x030af0f0)")
logger.info("\t5) Test to addr 7 (0x74, 0xdeadbeef)")
selection = m.default_value("Choose a message type", "-1")
if selection == '0':
return build_mbus_message()
elif selection == '1':
return ("F0000000".decode('hex'), "24000000".decode('hex'))
elif selection == '2':
return ("40".decode('hex'), "0423dfef".decode('hex'))
elif selection == '3':
return ("40".decode('hex'), "030bf0f0".decode('hex'))
elif selection == '4':
return ('40'.decode('hex'), '030af0f0'.decode('hex'))
elif selection == '5':
return ('74'.decode('hex'), 'deadbeef'.decode('hex'))
else:
logger.info("Please choose one of the numbered options")
return get_mbus_message_to_send()
while True:
try:
addr, data = get_mbus_message_to_send()
m.ice.mbus_send(addr, data)
except KeyboardInterrupt:
break
logger.info('')
logger.info("Exiting.")
| 33.450549 | 96 | 0.654402 | 895 | 0.294021 | 0 | 0 | 0 | 0 | 0 | 0 | 966 | 0.317346 |
dce928dcf018f001f3c1247ee7dfb3079e1b064c | 1,172 | py | Python | test/test_nn/test_distribution/test_gaussian.py | brunomaga/PRML | 47d9830b39e91690cedb27003934df85cfb8c5c7 | [
"MIT"
] | 11,017 | 2017-07-03T03:06:25.000Z | 2022-03-30T18:47:20.000Z | test/test_nn/test_distribution/test_gaussian.py | brunomaga/PRML | 47d9830b39e91690cedb27003934df85cfb8c5c7 | [
"MIT"
] | 21 | 2017-08-13T01:35:41.000Z | 2022-03-21T06:25:09.000Z | test/test_nn/test_distribution/test_gaussian.py | brunomaga/PRML | 47d9830b39e91690cedb27003934df85cfb8c5c7 | [
"MIT"
] | 3,417 | 2017-07-05T12:55:52.000Z | 2022-03-30T18:47:27.000Z | import unittest
import numpy as np
import prml.nn as nn
class TestGaussian(unittest.TestCase):
def test_gaussian_draw_forward(self):
mu = nn.array(0)
sigma = nn.softplus(nn.array(-1))
gaussian = nn.Gaussian(mu, sigma)
sample = []
for _ in range(1000):
sample.append(gaussian.draw().value)
self.assertTrue(np.allclose(np.mean(sample), 0, rtol=0.1, atol=0.1), np.mean(sample))
self.assertTrue(np.allclose(np.std(sample), gaussian.std.value, 0.1, 0.1))
def test_gaussian_draw_backward(self):
mu = nn.array(0)
s = nn.array(2)
optimizer = nn.optimizer.Gradient({0: mu, 1: s}, 0.01)
prior = nn.Gaussian(1, 1)
for _ in range(1000):
mu.cleargrad()
s.cleargrad()
gaussian = nn.Gaussian(mu, nn.softplus(s))
gaussian.draw()
loss = nn.loss.kl_divergence(gaussian, prior).sum()
optimizer.minimize(loss)
self.assertTrue(np.allclose(gaussian.mean.value, 1, 0.1, 0.1))
self.assertTrue(np.allclose(gaussian.std.value, 1, 0.1, 0.1))
if __name__ == "__main__":
unittest.main()
| 32.555556 | 93 | 0.598123 | 1,064 | 0.90785 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 0.008532 |
dce9859de967085bbcf63975cb47a3c6a5bf26ec | 1,087 | py | Python | monsterapi/migrations/0023_check.py | merenor/momeback | 33195c43abd2757a361dfc5cb7e3cf56f6b57402 | [
"MIT"
] | 1 | 2018-11-05T13:08:48.000Z | 2018-11-05T13:08:48.000Z | monsterapi/migrations/0023_check.py | merenor/momeback | 33195c43abd2757a361dfc5cb7e3cf56f6b57402 | [
"MIT"
] | null | null | null | monsterapi/migrations/0023_check.py | merenor/momeback | 33195c43abd2757a361dfc5cb7e3cf56f6b57402 | [
"MIT"
] | null | null | null | # Generated by Django 2.1.3 on 2018-11-24 13:52
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('monsterapi', '0022_auto_20181123_2339'),
]
operations = [
migrations.CreateModel(
name='Check',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('result', models.BooleanField(default=None)),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('game', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='monsterapi.Game')),
('melody', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='monsterapi.Melody')),
('monster', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='monsterapi.Monster')),
],
),
]
| 40.259259 | 140 | 0.643054 | 932 | 0.857406 | 0 | 0 | 0 | 0 | 0 | 0 | 200 | 0.183993 |
dcea49ac83707e392c87416d55d53e97a16ca5a5 | 49 | py | Python | pypy/interpreter/pyparser/test/samples/snippet_generator.py | camillobruni/pygirl | ddbd442d53061d6ff4af831c1eab153bcc771b5a | [
"MIT"
] | 12 | 2016-01-06T07:10:28.000Z | 2021-05-13T23:02:02.000Z | pypy/interpreter/pyparser/test/samples/snippet_generator.py | woodrow/pyoac | b5dc59e6a38e7912db47f26fb23ffa4764a3c0e7 | [
"MIT"
] | null | null | null | pypy/interpreter/pyparser/test/samples/snippet_generator.py | woodrow/pyoac | b5dc59e6a38e7912db47f26fb23ffa4764a3c0e7 | [
"MIT"
] | 2 | 2016-07-29T07:09:50.000Z | 2016-10-16T08:50:26.000Z | def f(n):
for i in range(n):
yield n
| 12.25 | 22 | 0.469388 | 0 | 0 | 48 | 0.979592 | 0 | 0 | 0 | 0 | 0 | 0 |
dceac604206c3804e988356a36e1c21687d75def | 50 | py | Python | api_module/___init__.py | miscdec/tk-auto-study | 2c5c716ab652dfc04796c335d2fb2bc01c494ccd | [
"MIT"
] | null | null | null | api_module/___init__.py | miscdec/tk-auto-study | 2c5c716ab652dfc04796c335d2fb2bc01c494ccd | [
"MIT"
] | null | null | null | api_module/___init__.py | miscdec/tk-auto-study | 2c5c716ab652dfc04796c335d2fb2bc01c494ccd | [
"MIT"
] | null | null | null | from . import main_api
__all__=[
"main_api"
] | 10 | 22 | 0.66 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 0.2 |
dcec0a27d90cdc4a82ce90945f1522764fe59ffb | 5,852 | py | Python | result/fig1_opt/plot.py | HongdaWu1226/FedPNS | 9045da7c925bee006ae8ea5432abbc44bc84376c | [
"MIT"
] | null | null | null | result/fig1_opt/plot.py | HongdaWu1226/FedPNS | 9045da7c925bee006ae8ea5432abbc44bc84376c | [
"MIT"
] | null | null | null | result/fig1_opt/plot.py | HongdaWu1226/FedPNS | 9045da7c925bee006ae8ea5432abbc44bc84376c | [
"MIT"
] | null | null | null | import sys
import argparse
import matplotlib.pyplot as plt
import numpy as np
import pickle
def load_obj(name):
pkl_path = ""
with open(pkl_path + name + ".pkl", 'rb') as f:
return pickle.load(f)
def load_prun_obj(name):
pkl_path = ""
with open(pkl_path + name + ".pkl", 'rb') as f:
return pickle.load(f)
def result_plt(results, label):
# lists = sorted(results.items())
# x, y = zip(*lists)
plt.plot(results, label = label)
matrices = ['acc', 'loss']
# labels = ['fedavg_5iid_5niid', 'fedavg_6iid_4niid', 'fedavg_2iid_8niid', 'fedavg_8iid_2niid' ]
# labels_prun = ['fedavg_5iid_5niid_prun', 'fedavg_6iid_4niid_prun', 'fedavg_8iid_2niid_prun']
labels = ['Optimal Aggregation', 'FedAvg' ]
labels_prun = ['fedadp_5iid_5niid_0.8_prun' , 'fedadp_5iid_5niid_current_prun','fedadp_5iid_5niid']
# iid_list = [5, 6, 2, 8]
# niid_list = [10 - x for x in iid_list]
iid_list = [10]
niid_list = [10]
prob_ratio = [0.1]
model = [ 'cnn']
num_exp = 10
num_exp_3 = 3
num_round = 50
def define_and_get_arguments(args=sys.argv[1:]):
parser = argparse.ArgumentParser(
description="Run figure plot"
)
parser.add_argument("--matrice", type=str, choices=matrices, default="loss", help = "result matrices")
parser.add_argument("--iid", type=int, default=5, help="number of nodes")
parser.add_argument("--training_rounds", type=int, default = 50, help= "number of training rounds")
args = parser.parse_args(args=args)
return args
def main():
args = define_and_get_arguments()
fedavg_data = {}
fedadp_data = {}
feddel_data = {}
remove_node = {}
# for exp in range(1,num_exp+1):
# remove_node[exp] = load_obj('remove node_exp%s' %(exp))
# print(remove_node[2][0])
for exp in range(1,num_exp+1):
fedadp_data[exp] = load_obj('feddel_mnist_%s_1_exp%s' %(model[0], exp))
for exp in range(1,num_exp+1):
fedavg_data[exp] = load_obj('fedavg_mnist_%s_1_exp%s' %(model[0],exp))
if args.matrice == "acc":
overall_avg = []
for k in range(1,num_exp+1):
# print(fedadp_data[k][0])
overall_avg.extend(fedadp_data[k][0])
temp_adp = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(num_exp)])
acc_adp = np.mean(temp_adp, axis=0)
# print(acc_adp)
result_plt(acc_adp, labels[0])
overall_avg = []
for k in range(1,num_exp+1):
overall_avg.extend(fedavg_data[k][0])
temp_avg = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(num_exp)])
acc_avg = np.mean(temp_avg, axis=0)
# print(acc_avg)
result_plt(acc_avg, labels[-1])
ylabel = "Testing Accuracy"
elif args.matrice == "loss":
overall_avg = []
for k in range(1,num_exp+1):
# print(fedadp_data[k][0])
overall_avg.extend(fedadp_data[k][1])
temp_adp = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(num_exp)])
acc_adp = np.mean(temp_adp, axis=0)
# print(acc_adp)
plt.plot(list(range(num_round)), acc_adp, color='#069AF3', linewidth = '1.5', label = labels[0])
overall_avg = []
for k in range(1,num_exp+1):
overall_avg.extend(fedavg_data[k][1])
temp_avg = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(num_exp)])
acc_avg = np.mean(temp_avg, axis=0)
plt.plot(list(range(num_round)), acc_avg, '--', color='#F97306', linewidth = '1.5',label = labels[-1])
plt.xlabel("Communication Round", fontsize=13)
plt.gca().spines['right'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
plt.ylabel( "Training Loss", fontsize=13)
plt.legend(frameon=False, loc=7, prop={'size': 10})
elif args.matrice == "sts":
x = load_obj('observe node_exp10' )
# print(x[0])
overall_avg = []
for i in range(3):
temp = []
for j in range(50):
# print(x[0][j][i])
temp.append(x[0][j][i])
overall_avg.extend(temp)
data = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(3)])
# print(data[0])
# plt.figure()
# plt.subplot()
# fig, ax = plt.subplots(nrows=2, ncols=1)
label = ['Selected', 'Labeled', 'Excluded']
index = np.arange(0, 25, 1)
index_2 = np.arange(25, 50, 1)
# plt.hist()
color_index= ['lightgray','lightsteelblue','springgreen']
plt.subplot(2,1,1)
for i in range(3):
j = i+1
#index+2:是起始坐标点 #width是bar的宽度
# print(data[i])
plt.bar(index, data[i][:25],width=0.6,color=color_index[i], label= label[i])
plt.xticks(index)
plt.xticks(fontsize=7)
plt.yticks(fontsize=8)
plt.subplot(2,1,2)
for i in range(3):
j = i+1
#index+2:是起始坐标点 #width是bar的宽度
plt.bar(index_2, data[i][25:],width=0.6,color=color_index[i], label= label[i])
plt.xticks(index_2)
plt.yticks([0,15, 5, 10])
plt.legend(loc='best', prop={'size': 7})
plt.xticks(fontsize=7)
plt.yticks(fontsize=8)
# plt.gca().spines['top'].set_visible(False)
# plt.hist(data[i], index, alpha = 0.5)
# plt.hist(data[0], index, alpha = 0.5)
# plt.hist(data[1], index, alpha = 0.5)
fig_path = ""
plt.savefig(fig_path + "%s_com_%siid_%s" %(args.matrice, str(iid_list[0]), model[0]) + ".eps", format='eps', dpi=1200)
if __name__ == "__main__":
main()
| 28.827586 | 122 | 0.572454 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,523 | 0.258486 |
dcec0a932b384751e223e69c5f0bacbab7b74478 | 2,502 | py | Python | tools/solViewer.py | afkummer/gecco2020-brkga | a76438483528da54a0406925ffb8ae26a029c2eb | [
"MIT"
] | null | null | null | tools/solViewer.py | afkummer/gecco2020-brkga | a76438483528da54a0406925ffb8ae26a029c2eb | [
"MIT"
] | null | null | null | tools/solViewer.py | afkummer/gecco2020-brkga | a76438483528da54a0406925ffb8ae26a029c2eb | [
"MIT"
] | 2 | 2020-04-11T07:39:15.000Z | 2020-10-19T16:58:13.000Z | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2020
# Alberto Francisco Kummer Neto (afkneto@inf.ufrgs.br),
# Luciana Salete Buriol (buriol@inf.ufrgs.br) and
# Olinto César Bassi de Araújo (olinto@ctism.ufsm.br)
#
# 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.
#
#
# Simple script to plot a BRKGA solution as a scatter plot.
# To export a solution, use the method `Solution::writeTxt2` in
# the C++ code.
#
# @author Alberto Kummer
#
if __name__ == "__main__":
from sys import argv
if len(argv) != 2:
print("Usage: %s <1: solution path>" % argv[0])
exit(1)
fid = open(argv[1], "rt")
fid.readline()
fid.readline()
fid.readline()
fid.readline()
from matplotlib import pyplot as plt
depot_x = -1
depot_y = -1
while True:
line = fid.readline()
if len(line) == 0:
break
tks = [int(x) for x in line.split()]
vehicle = tks[0]
route_length = tks[1]
route_x = []
route_y = []
for r in range(route_length):
line = fid.readline()
tks = [int(x) for x in line.split()]
route_x.append(tks[0])
route_y.append(tks[1])
route_x.append(route_x[0])
route_y.append(route_y[0])
depot_x = route_x[0]
depot_y = route_y[0]
plt.plot(route_x, route_y, marker='*', label=("v=" + str(vehicle)))
plt.plot(depot_x, depot_y, marker='s', color='black', markersize=10)
plt.legend()
plt.show()
| 29.093023 | 82 | 0.673861 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,513 | 0.604233 |
dcec3b942ff3cfa0abdd8f17276dd930a550b6c9 | 936 | py | Python | test cases/unittest_homophone_module.py | johnbumgarner/wordhoard | c71ad970505801ffe6d5c640c63f073c434b9a47 | [
"MIT"
] | 40 | 2020-10-21T19:49:51.000Z | 2022-03-05T20:46:58.000Z | test cases/unittest_homophone_module.py | johnbumgarner/wordhoard | c71ad970505801ffe6d5c640c63f073c434b9a47 | [
"MIT"
] | 10 | 2021-08-15T13:56:03.000Z | 2022-03-03T14:15:26.000Z | test cases/unittest_homophone_module.py | johnbumgarner/wordhoard | c71ad970505801ffe6d5c640c63f073c434b9a47 | [
"MIT"
] | 4 | 2020-12-30T15:22:07.000Z | 2022-02-01T21:05:49.000Z | #!/usr/bin/env python3
"""
This Python script is designed to perform unit testing of Wordhoard's
Homophones module.
"""
__author__ = 'John Bumgarner'
__date__ = 'September 20, 2020'
__status__ = 'Quality Assurance'
__license__ = 'MIT'
__copyright__ = "Copyright (C) 2021 John Bumgarner"
import unittest
from wordhoard import Homophones
class TestHomophoneFunction(unittest.TestCase):
def test_homophone_always_pass(self):
"""
This test is designed to pass, because the word "horse" has a known Homophones
and the default output format is a list
:return:
"""
self.assertIsInstance(Homophones('horse').find_homophones(), list)
def test_homophone_always_fail(self):
"""
This test is designed to fail, because the word "pig" has no known Homophones
:return:
"""
self.assertIsNone(Homophones('horse').find_homophones())
unittest.main()
| 25.297297 | 86 | 0.690171 | 576 | 0.615385 | 0 | 0 | 0 | 0 | 0 | 0 | 512 | 0.547009 |
dcec6ff0d9def2fe9c68c69ed39626402f66ee06 | 3,492 | py | Python | resist/types/models/message.py | an-dyy/Resist | db4526e2db78bbd8d16567ae3e3880cf2c64eda1 | [
"MIT"
] | 4 | 2022-03-05T21:54:14.000Z | 2022-03-13T07:51:07.000Z | resist/types/models/message.py | an-dyy/Resist | db4526e2db78bbd8d16567ae3e3880cf2c64eda1 | [
"MIT"
] | 1 | 2022-03-09T20:15:09.000Z | 2022-03-10T10:39:25.000Z | resist/types/models/message.py | an-dyy/Resist | db4526e2db78bbd8d16567ae3e3880cf2c64eda1 | [
"MIT"
] | 1 | 2022-03-09T10:58:54.000Z | 2022-03-09T10:58:54.000Z | from __future__ import annotations
from typing import Literal, TypedDict, Union, final
from typing_extensions import NotRequired
from .asset import AssetData
class YoutubeLinkEmbedMetadata(TypedDict):
type: Literal["YouTube"]
id: str
timestamp: NotRequired[str]
class TwitchLinkEmbedMetadata(TypedDict):
type: Literal["Twitch"]
content_type: Literal["Channel", "Clip", "Video"]
id: str
class SpotifyLinkEmbedMetadata(TypedDict):
type: Literal["Spotify"]
content_type: str
id: str
SoundcloudLinkEmbedMetadata = TypedDict(
"SoundcloudLinkEmbedMetadata", {"type": Literal["Soundcloud"]}
)
class BandcampLinkEmbedMetadata(TypedDict):
type: Literal["Bandcamp"]
content_type: Literal["Album", "Track"]
id: str
class EmbedMediaData(TypedDict):
# base fields that both videos and images sent in embeds will have.
url: str
width: int
height: int
class EmbedImageData(EmbedMediaData):
# this contains the data about an image sent in an embed
# for example: a banner image in a URL's embed
size: Literal["Large", "Preview"]
class WebsiteEmbedData(TypedDict):
"""Represents the data of an embed for a URL."""
type: Literal["Website"]
url: NotRequired[str]
special: NotRequired[
YoutubeLinkEmbedMetadata
| SpotifyLinkEmbedMetadata
| TwitchLinkEmbedMetadata
| SoundcloudLinkEmbedMetadata
| BandcampLinkEmbedMetadata
]
title: NotRequired[str]
description: NotRequired[str]
image: NotRequired[EmbedImageData]
video: NotRequired[EmbedMediaData]
site_name: NotRequired[str]
icon_url: NotRequired[str]
colour: NotRequired[str]
class ImageEmbedData(EmbedImageData):
"""Represents the data of an image embed."""
type: Literal["Image"]
class TextEmbedData(TypedDict):
type: Literal["Text"]
icon_url: NotRequired[str]
url: NotRequired[str]
title: NotRequired[str]
description: NotRequired[str]
media: NotRequired[AssetData]
colour: NotRequired[str]
NoneEmbed = TypedDict("NoneEmbed", {"type": Literal["None"]})
@final
class SystemMessageContent(TypedDict):
type: Literal["text"]
content: str
@final
class UserActionSystemMessageContent(TypedDict):
type: Literal[
"user_added",
"user_remove",
"user_joined",
"user_left",
"user_kicked",
"user_banned",
]
id: str
by: NotRequired[str] # sent only with user_added and user_remove
@final
class ChannelActionSystemMessageContent(TypedDict):
type: Literal[
"channel_renamed", "channel_description_changed", "channel_icon_changed"
]
by: str
name: NotRequired[str] # sent only with channel_renamed
MessageEditedData = TypedDict("MessageEditedData", {"$date": str})
class MasqueradeData(TypedDict):
name: NotRequired[str]
avatar: NotRequired[str]
EmbedType = Union[WebsiteEmbedData, ImageEmbedData, TextEmbedData, NoneEmbed]
class MessageData(TypedDict):
_id: str
nonce: NotRequired[str]
channel: str
author: str
content: (
SystemMessageContent
| UserActionSystemMessageContent
| ChannelActionSystemMessageContent
| str
)
attachments: NotRequired[list[AssetData]]
edited: NotRequired[MessageEditedData]
embeds: NotRequired[list[EmbedType]]
mentions: NotRequired[list[str]]
replies: NotRequired[list[str]]
masquerade: NotRequired[MasqueradeData]
| 23.436242 | 80 | 0.70189 | 2,943 | 0.842784 | 0 | 0 | 622 | 0.178121 | 0 | 0 | 691 | 0.197881 |
dceca6923a77f2914c413d91ca752154c85edfb7 | 2,933 | py | Python | baseline/DRL/rpm.py | sugam45/CS771_project | 0361fd71fa65981614bc14bff8dceb763cb7c152 | [
"MIT"
] | null | null | null | baseline/DRL/rpm.py | sugam45/CS771_project | 0361fd71fa65981614bc14bff8dceb763cb7c152 | [
"MIT"
] | null | null | null | baseline/DRL/rpm.py | sugam45/CS771_project | 0361fd71fa65981614bc14bff8dceb763cb7c152 | [
"MIT"
] | 2 | 2020-12-09T05:00:24.000Z | 2021-12-05T12:00:12.000Z | # from collections import deque
import numpy as np
import random
import torch
import pickle as pickle
from torch.autograd import Variable
class rpm(object):
# replay memory
def __init__(self, buffer_size):
self.buffer_size = buffer_size
self.buffer = []
self.priorities = []
self.index = 0
def append(self, obj):
if self.size() > self.buffer_size:
print('buffer size larger than set value, trimming...')
self.buffer = self.buffer[(self.size() - self.buffer_size):]
self.priorities = self.priorities[(self.size() - self.buffer_size):]
elif self.size() == self.buffer_size:
self.buffer[self.index] = obj
self.priorities[self.index] = max(self.priorities, default=1)
self.index += 1
self.index %= self.buffer_size
else:
self.buffer.append(obj)
self.priorities.append(max(self.priorities, default=1))
def size(self):
return len(self.buffer)
def get_probabilities(self, priority_scale):
# scaled_priorities = np.array(self.priorities)
# with torch.no_grad():
scaled_priorities_torch = Variable(torch.Tensor(self.priorities))**priority_scale
denom = torch.sum(scaled_priorities_torch)
sampled_probabilities = scaled_priorities_torch/denom
return sampled_probabilities
def get_importance(self, probabilities):
importance = 1/len(self.buffer) * 1/probabilities
importance_normalized = importance/max(importance)
return importance_normalized
def sample_batch(self, batch_size, device, only_state=False, priority_scale = 0.7):
if self.size() < batch_size:
MINIBATCH_SIZE = self.size()
# batch = random.sample(self.buffer, self.size())
else:
MINIBATCH_SIZE = batch_size
# batch = random.sample(self.buffer, batch_size)
sample_probs = self.get_probabilities(priority_scale)
# print(sample_probs)
sample_indices = random.choices(range(len(self.buffer)), k = MINIBATCH_SIZE, weights= sample_probs.tolist())
batch = [self.buffer[i] for i in sample_indices]
importance = self.get_importance(sample_probs[sample_indices])
if only_state:
res = torch.stack(tuple(item[3] for item in batch), dim=0)
return res.to(device)
else:
item_count = 5
res = []
for i in range(5):
k = torch.stack(tuple(item[i] for item in batch), dim=0)
res.append(k.to(device))
return res[0], res[1], res[2], res[3], res[4], importance, sample_indices
def set_priorities(self, indices, errors, offset=0.1):
errors = errors.tolist()
for i,e in zip(indices, errors):
self.priorities[i] = abs(e[0]) + offset
| 38.592105 | 116 | 0.617797 | 2,794 | 0.952608 | 0 | 0 | 0 | 0 | 0 | 0 | 282 | 0.096147 |
dcedf5797dbbe753e782f1e510c2e2eadacb0ae4 | 1,519 | py | Python | Line bot/app/models_for_line.py | FatTtyLoser/LINE-Bot | 32c5ffaabbf9c84b161ae720333b1405887be10a | [
"MIT"
] | null | null | null | Line bot/app/models_for_line.py | FatTtyLoser/LINE-Bot | 32c5ffaabbf9c84b161ae720333b1405887be10a | [
"MIT"
] | null | null | null | Line bot/app/models_for_line.py | FatTtyLoser/LINE-Bot | 32c5ffaabbf9c84b161ae720333b1405887be10a | [
"MIT"
] | null | null | null | from app import handler
from app import line_bot_api, handler
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage, ImageSendMessage
)
import random
import re
import urllib
def google_isch(q_string):
q_string= {'tbm': 'isch' , 'q' : q_string}
url = f"http://www.google.com/search?{urllib.parse.urlencode(q_string)}/"
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'
}
req = urllib.request.Request(url,headers=headers)
conn = urllib.request.urlopen(req)
data = conn.read()
pattern = '"(https://encrypted-tbn0.gstatic.com[\S]*)"'
image_list = []
for match in re.finditer(pattern, str(data, 'utf-8')):
image_list.append(match.group(1))
return image_list[2]
@handler.add(MessageEvent, message=TextMessage)
def reply_text(event):
if event.source.user_id != "FatTtyLoserfatfatFatTtyLoserfatty":
try:
image_url = google_isch(event.message.text)
message_text = image_url
line_bot_api.reply_message(
event.reply_token,
ImageSendMessage(
original_content_url = image_url,
preview_image_url = image_url
)
)
except:
message_text = '小丑,淘汰!'
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=message_text)
)
| 29.784314 | 135 | 0.622778 | 0 | 0 | 0 | 0 | 695 | 0.453952 | 0 | 0 | 316 | 0.206401 |
dcee0aabb64225f7e08fe67c3434070100bac04e | 5,885 | py | Python | misc/m2g_script.py | PSSF23/neurodata.io | 81ae10cc5082136db2d654026737a0a64f65cd88 | [
"Apache-2.0"
] | 9 | 2018-11-23T15:21:23.000Z | 2022-03-27T22:41:29.000Z | misc/m2g_script.py | PSSF23/neurodata.io | 81ae10cc5082136db2d654026737a0a64f65cd88 | [
"Apache-2.0"
] | 515 | 2016-02-17T19:58:15.000Z | 2022-03-31T20:57:48.000Z | misc/m2g_script.py | PSSF23/neurodata.io | 81ae10cc5082136db2d654026737a0a64f65cd88 | [
"Apache-2.0"
] | 19 | 2016-03-25T19:52:57.000Z | 2022-01-11T01:17:19.000Z | import boto3
import botocore
from ruamel.yaml import YAML
yaml = YAML()
CLIENT = boto3.client('s3', # region_name='us-east-1',
config=botocore.client.Config(signature_version=botocore.UNSIGNED))
RESOURCE = boto3.resource('s3')
REF_DIFF = {'SWU4': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/swu_4.html',
'HNU1': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/hnu_1.html',
'BNU3': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/bnu_3.html',
'BNU1': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/bnu_1.html',
'KKI2009': 'http://mri.kennedykrieger.org/databases.html#Kirby21',
'NKIENH': 'http://fcon_1000.projects.nitrc.org/indi/enhanced/',
'NKI1': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/nki_1.html',
'Templeton255': '#',
'Templeton114': '#',
'MRN1313': '#'}
REF_FUNC = {
'BNU1': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/bnu_1.html',
'BNU2': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/bnu_2.html',
'BNU3': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/bnu_3.html',
'HNU1': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/hnu_1.html',
'IBATRT': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/ibatrt.html',
'IPCAS1': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/ipcas_1.html',
'IPCAS2': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/ipcas_2.html',
'IPCAS5': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/ipcas_5.html',
'IPCAS6': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/ipcas_6.html',
'IPCAS8': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/ipcas_6.html',
'NYU1': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/nyu_1.html',
'SWU1': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/swu_1.html',
'SWU2': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/swu_2.html',
'SWU3': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/swu_3.html',
'SWU4': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/swu_4.html',
'UWM': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/uwm.html',
'XHCUMS': 'http://fcon_1000.projects.nitrc.org/indi/CoRR/html/xhcums.html'
}
def scan_bucket(bucket, path):
# path needs trailing '/': "data/"
if path[-1] != '/':
path += '/'
result = CLIENT.list_objects(Bucket=bucket,
Prefix=path,
Delimiter='/'
)
listing = []
if 'CommonPrefixes' in result:
for d in result.get('CommonPrefixes'):
o = d['Prefix'].rsplit(path)[1]
o = o.strip('/')
listing.append(o)
# getting any objects in the path
my_bucket = RESOURCE.Bucket(bucket)
objs = list(my_bucket.objects.filter(Prefix=path, Delimiter='/'))
for obj in objs:
key_name = obj.key.rsplit(path)[1]
if key_name != '': # sometimes the root path returns an object
listing.append(key_name)
return listing
def to_url(bucket, things):
base = 'http://{}.s3-website-us-east-1.amazonaws.com/{}'
if things[-1] == '':
end_slash='/'
else:
end_slash=''
things = [th for th in things if th != '']
return base.format(bucket, '/'.join(things) + end_slash)
def create_yaml_data(bucket_name, bpath, seqs, refs, pathtype, url_base, output_path):
dsets = scan_bucket(bucket_name, bpath)
csvs = scan_bucket(bucket_name, 'data/fmri/covariates/')
# remove some stuff that isn't real:
for seq in seqs:
dsets.remove(seq) if seq in dsets else dsets
for dset in dsets:
data_dict = {}
data_dict['name'] = dset
path = bpath + dset
dirt = scan_bucket(bucket_name, path)
if url_base == 'fmri':
csv = [csv for csv in csvs if csv.strip(
'_phenotypic_data.csv') == dset]
if csv:
csv_path = 'covariates'
data_dict['csv'] = to_url(
bucket_name, (bpath.strip('/'), csv_path, csv[0]))
else:
csv = [d for d in dirt if '.csv' in d]
if csv:
data_dict['csv'] = to_url(
bucket_name, (url_base, path, csv[0]))
vers = [d for d in dirt if 'ndmg' in d]
if vers:
ver = sorted(vers, reverse=True)[0]
derpath = path + '/' + ver + pathtype
derivs = scan_bucket(bucket_name, derpath)
for d in derivs:
data_dict[d.replace('-', '_')] = to_url(
bucket_name, (url_base, dset,
ver, pathtype.lstrip('/'), d, '')
)
qapath = path + '/' + ver
qaderivs = scan_bucket(bucket_name, qapath)
for d in qaderivs:
data_dict[d] = to_url(
bucket_name, (url_base, dset, ver, d, ''))
data_dict['ver'] = ver.replace('-', '.', 2).strip('ndmg_')
data_dict['link'] = refs[dset]
# save the dict as yaml file to /content/diffusion
fname = 'content/{}/{}.yaml'.format(output_path, dset)
with open(fname, 'w') as f:
yaml.dump(data_dict, f)
def main():
bucket_name = 'mrneurodata'
# functional
bpath = 'data/fmri/'
pathtype = '/func'
url_base = 'fmri'
seqs = ['covariates']
create_yaml_data(bucket_name, bpath, seqs, REF_FUNC,
pathtype, url_base, 'mri_functional')
# scan /data for directories of diffusion data
bpath = 'data/'
seqs = ['NKI24', 'resources', 'MRN114', 'Jung2015', 'dwi', 'fmri']
create_yaml_data(bucket_name, bpath, seqs,
REF_DIFF, '', '', 'mri_diffusion')
if __name__ == "__main__":
main()
| 38.214286 | 89 | 0.581648 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,425 | 0.412065 |
dcf22457d7a59600a3e671d892fcbc97a92f684c | 207 | py | Python | pip_services3_prometheus/count/__init__.py | pip-services-python/pip-services-prometheus-python | 062be3bad4548c4733f0ed398d7b6069018eaffa | [
"MIT"
] | null | null | null | pip_services3_prometheus/count/__init__.py | pip-services-python/pip-services-prometheus-python | 062be3bad4548c4733f0ed398d7b6069018eaffa | [
"MIT"
] | null | null | null | pip_services3_prometheus/count/__init__.py | pip-services-python/pip-services-prometheus-python | 062be3bad4548c4733f0ed398d7b6069018eaffa | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
__all__ = ['PrometheusCounterConverter', 'PrometheusCounters']
from .PrometheusCounterConverter import PrometheusCounterConverter
from .PrometheusCounters import PrometheusCounters
| 29.571429 | 66 | 0.816425 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 71 | 0.342995 |
dcf39fbfef9164b52a639bb7ce9ec336fdfee6b7 | 635 | py | Python | datenight/urls.py | SarahJaine/date-night | fb63b68cfb115f52c5d3ec39f2e73454c5d63bb6 | [
"MIT"
] | null | null | null | datenight/urls.py | SarahJaine/date-night | fb63b68cfb115f52c5d3ec39f2e73454c5d63bb6 | [
"MIT"
] | null | null | null | datenight/urls.py | SarahJaine/date-night | fb63b68cfb115f52c5d3ec39f2e73454c5d63bb6 | [
"MIT"
] | null | null | null | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from datenight.views import HomePageView
urlpatterns = [
# Examples:
url(r'^$', HomePageView.as_view(), name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/rq/', include('django_rq.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
import debug_toolbar
from django.conf.urls.static import static
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + urlpatterns
| 27.608696 | 83 | 0.696063 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 114 | 0.179528 |
dcf431fc5aea71e31c30dbdd5ee59dfa4598f2c6 | 8,337 | py | Python | plugins/view/tightening_controller_views.py | masami10/airflow | 3df5353d7a31ec890925dc4fd7c2a82fd349a483 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 1 | 2021-03-03T07:00:02.000Z | 2021-03-03T07:00:02.000Z | plugins/view/tightening_controller_views.py | masami10/airflow | 3df5353d7a31ec890925dc4fd7c2a82fd349a483 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 36 | 2021-11-26T00:08:49.000Z | 2021-11-26T00:09:33.000Z | plugins/view/tightening_controller_views.py | masami10/airflow | 3df5353d7a31ec890925dc4fd7c2a82fd349a483 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 3 | 2020-06-30T02:38:17.000Z | 2022-01-19T06:14:08.000Z | # -*- coding: utf-8 -*-
from flask import flash, make_response, request
import json
from flask_babel import lazy_gettext, gettext
from datetime import datetime
from flask_login import current_user
from flask_appbuilder.actions import action
from flask_appbuilder import expose
from flask import redirect
from plugins.common import AirflowModelView
from airflow.plugins_manager import AirflowPlugin
from airflow.settings import TIMEZONE
from airflow.www.decorators import action_logging
from flask_wtf.csrf import CSRFProtect
import logging
import os
import pandas as pd
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from flask import current_app
from wtforms.fields import StringField
from flask_appbuilder.fieldwidgets import (
BS3TextFieldWidget, Select2Widget,
)
from flask_appbuilder.forms import DynamicForm
from airflow.security import permissions
from airflow.www.widgets import AirflowModelListWidget
from qcos_addons.access_log.log import access_log
FACTORY_CODE = os.getenv('FACTORY_CODE', 'DEFAULT_FACTORY_CODE')
_logger = logging.getLogger(__name__)
csrf = CSRFProtect()
def device_type_query():
print(current_app)
session = current_app.appbuilder.get_session()
from plugins.models.device_type import DeviceTypeModel
return session.query(DeviceTypeModel)
def _get_related_pk_func(obj):
return obj.id
class TighteningControllerForm(DynamicForm):
controller_name = StringField(
lazy_gettext('Equipment Name'),
widget=BS3TextFieldWidget())
line_code = StringField(
lazy_gettext('Line Code'),
widget=BS3TextFieldWidget())
line_name = StringField(
lazy_gettext('Line Name'),
widget=BS3TextFieldWidget())
work_center_code = StringField(
lazy_gettext('Work Center Code'),
widget=BS3TextFieldWidget())
work_center_name = StringField(
lazy_gettext('Work Center Name'),
widget=BS3TextFieldWidget())
device_type = QuerySelectField(
lazy_gettext('Device Type'),
query_factory=device_type_query,
# get_pk_func=_get_related_pk_func,
widget=Select2Widget(extra_classes="readonly")
)
class TighteningControllerListWidget(AirflowModelListWidget):
template = 'tightening_controller_list_widget.html'
class TighteningControllerView(AirflowModelView):
route_base = '/tightening_controller'
list_widget = TighteningControllerListWidget
from plugins.models.tightening_controller import TighteningController
datamodel = AirflowModelView.CustomSQLAInterface(TighteningController)
extra_fields = []
list_columns = ['controller_name', 'line_code', 'line_name', 'work_center_code', 'work_center_name', 'device_type']
add_columns = edit_columns = ['controller_name', 'line_code', 'line_name', 'work_center_code',
'work_center_name', 'device_type'] + extra_fields
add_form = edit_form = TighteningControllerForm
add_template = 'tightening_controller_create.html'
edit_template = 'tightening_controller_edit.html'
list_template = 'tightening_controller_list.html'
label_columns = {
'controller_name': lazy_gettext('Controller Name'),
'line_code': lazy_gettext('Line Code'),
'line_name': lazy_gettext('Line Name'),
'work_center_code': lazy_gettext('Work Center Code'),
'work_center_name': lazy_gettext('Work Center Name'),
'device_type_id': lazy_gettext('Device Type'),
}
method_permission_name = {
'list': 'read',
'show': 'read',
'add': 'create',
'action_muldelete': 'delete',
'controllerimport': 'create',
'action_controllerexport': 'read'
}
class_permission_name = permissions.RESOURCE_CONTROLLER
base_permissions = [
permissions.ACTION_CAN_CREATE,
permissions.ACTION_CAN_READ,
permissions.ACTION_CAN_EDIT,
permissions.ACTION_CAN_DELETE,
permissions.ACTION_CAN_ACCESS_MENU
]
base_order = ('id', 'asc')
@access_log('ADD', 'TIGHTENING_CONTROLLER', '增加控制器')
def post_add(self, item):
super(TighteningControllerView, self).post_add(item)
@access_log('UPDATE', 'TIGHTENING_CONTROLLER', '修改控制器')
def post_update(self, item):
super(TighteningControllerView, self).post_update(item)
@access_log('DELETE', 'TIGHTENING_CONTROLLER', '删除控制器')
def post_delete(self, item):
super(TighteningControllerView, self).post_delete(item)
@action('muldelete', 'Delete', 'Are you sure you want to delete selected records?',
single=False)
@access_log('DELETE', 'TIGHTENING_CONTROLLER', '删除多个控制器')
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
@expose('/controllerimport', methods=["POST"])
@action_logging
def controllerimport(self):
try:
d = pd.read_csv(request.files['file'])
if d.empty:
raise Exception('设备清单为空')
data = d.to_json(orient='records')
d = json.loads(data)
except Exception as e:
self.update_redirect()
flash(repr(e), 'error')
return redirect(self.get_redirect())
suc_count = fail_count = 0
controller: dict
for controller in d:
try:
from plugins.models.tightening_controller import TighteningController
TighteningController.add_controller(**controller)
except Exception as e:
logging.info('Controller import failed: {}'.format(repr(e)))
fail_count += 1
else:
suc_count += 1
flash("{} controller(s) successfully updated.".format(suc_count))
if fail_count:
flash("{} controller(s) failed to be updated.".format(fail_count), 'error')
self.update_redirect()
return redirect(self.get_redirect())
@action('controllerexport', 'Export', '', single=False)
def action_controllerexport(self, items):
ret = []
for controller in items:
try:
val = controller.as_dict()
except Exception as e:
val = str(controller)
ret.append(val)
d = pd.DataFrame.from_records(ret, index=[i for i in range(len(ret))])
response = make_response(d.to_csv(index=False))
response.headers["Content-Disposition"] = "attachment; filename=controllers.csv"
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response
@expose("/list/")
@access_log('VIEW', 'TIGHTENING_CONTROLLER', '查看控制器列表')
def list(self):
_has_access = self.appbuilder.sm.has_access
can_import = _has_access(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_CONTROLLER)
widgets = self._list()
return self.render_template(
self.list_template, title=self.list_title, widgets=widgets, can_import=can_import
)
class DeviceTypeView(AirflowModelView):
from plugins.models.device_type import DeviceTypeModel
datamodel = AirflowModelView.CustomSQLAInterface(DeviceTypeModel)
method_permission_name = {
'list': 'read',
'show': 'read',
'add': 'create',
}
class_permission_name = permissions.RESOURCE_DEVICE_TYPE
base_permissions = [
permissions.ACTION_CAN_CREATE,
permissions.ACTION_CAN_READ,
permissions.ACTION_CAN_EDIT,
permissions.ACTION_CAN_DELETE,
permissions.ACTION_CAN_ACCESS_MENU
]
tightening_controller_view = TighteningControllerView()
tightening_controller_package = {"name": permissions.RESOURCE_CONTROLLER,
"category": permissions.RESOURCE_MASTER_DATA_MANAGEMENT,
"view": tightening_controller_view}
device_type_view = DeviceTypeView()
device_type_package = {"name": permissions.RESOURCE_DEVICE_TYPE,
"category": permissions.RESOURCE_MASTER_DATA_MANAGEMENT,
"view": device_type_view}
class TighteningControllerViewPlugin(AirflowPlugin):
name = "tightening_controller_view"
appbuilder_views = [tightening_controller_package, device_type_package]
| 36.247826 | 119 | 0.689816 | 6,516 | 0.775068 | 0 | 0 | 3,070 | 0.365172 | 0 | 0 | 1,592 | 0.189366 |
dcf4b8560b916ceca9700c2e7bf16bb6a53c4588 | 3,601 | py | Python | src/python/nimbusml/internal/entrypoints/models_ovamodelcombiner.py | GalOshri/NimbusML | a2ba6f51b7c8cdd3c3316d5ecf4605621be3bd8d | [
"MIT"
] | 2 | 2019-03-01T01:22:54.000Z | 2019-07-10T19:57:38.000Z | src/python/nimbusml/internal/entrypoints/models_ovamodelcombiner.py | GalOshri/NimbusML | a2ba6f51b7c8cdd3c3316d5ecf4605621be3bd8d | [
"MIT"
] | null | null | null | src/python/nimbusml/internal/entrypoints/models_ovamodelcombiner.py | GalOshri/NimbusML | a2ba6f51b7c8cdd3c3316d5ecf4605621be3bd8d | [
"MIT"
] | null | null | null | # - Generated by tools/entrypoint_compiler.py: do not edit by hand
"""
Models.OvaModelCombiner
"""
from ..utils.entrypoints import EntryPoint
from ..utils.utils import try_set, unlist
def models_ovamodelcombiner(
training_data,
predictor_model=None,
model_array=None,
use_probabilities=True,
feature_column='Features',
label_column='Label',
weight_column=None,
normalize_features='Auto',
caching='Auto',
**params):
"""
**Description**
Combines a sequence of PredictorModels into a single model
:param model_array: Input models (inputs).
:param training_data: The data to be used for training (inputs).
:param use_probabilities: Use probabilities from learners instead
of raw values. (inputs).
:param feature_column: Column to use for features (inputs).
:param label_column: Column to use for labels (inputs).
:param weight_column: Column to use for example weight (inputs).
:param normalize_features: Normalize option for the feature
column (inputs).
:param caching: Whether learner should cache input training data
(inputs).
:param predictor_model: Predictor model (outputs).
"""
entrypoint_name = 'Models.OvaModelCombiner'
inputs = {}
outputs = {}
if model_array is not None:
inputs['ModelArray'] = try_set(
obj=model_array,
none_acceptable=True,
is_of_type=list)
if training_data is not None:
inputs['TrainingData'] = try_set(
obj=training_data,
none_acceptable=False,
is_of_type=str)
if use_probabilities is not None:
inputs['UseProbabilities'] = try_set(
obj=use_probabilities,
none_acceptable=True,
is_of_type=bool)
if feature_column is not None:
inputs['FeatureColumn'] = try_set(
obj=feature_column,
none_acceptable=True,
is_of_type=str,
is_column=True)
if label_column is not None:
inputs['LabelColumn'] = try_set(
obj=label_column,
none_acceptable=True,
is_of_type=str,
is_column=True)
if weight_column is not None:
inputs['WeightColumn'] = try_set(
obj=weight_column,
none_acceptable=True,
is_of_type=str,
is_column=True)
if normalize_features is not None:
inputs['NormalizeFeatures'] = try_set(
obj=normalize_features,
none_acceptable=True,
is_of_type=str,
values=[
'No',
'Warn',
'Auto',
'Yes'])
if caching is not None:
inputs['Caching'] = try_set(
obj=caching,
none_acceptable=True,
is_of_type=str,
values=[
'Auto',
'Memory',
'Disk',
'None'])
if predictor_model is not None:
outputs['PredictorModel'] = try_set(
obj=predictor_model, none_acceptable=False, is_of_type=str)
input_variables = {
x for x in unlist(inputs.values())
if isinstance(x, str) and x.startswith("$")}
output_variables = {
x for x in unlist(outputs.values())
if isinstance(x, str) and x.startswith("$")}
entrypoint = EntryPoint(
name=entrypoint_name, inputs=inputs, outputs=outputs,
input_variables=input_variables,
output_variables=output_variables)
return entrypoint
| 31.867257 | 71 | 0.599833 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,076 | 0.298806 |
dcf50395b719a7f5d100f42a4c173a03d2453dfa | 2,496 | py | Python | kraken/public/views.py | peterdemartini/KrakenMaster | 2b3ed18f6dcc720e66e1ac397a3b5ee902914e58 | [
"BSD-3-Clause"
] | 1 | 2016-12-22T22:25:05.000Z | 2016-12-22T22:25:05.000Z | kraken/public/views.py | peterdemartini/KrakenMaster | 2b3ed18f6dcc720e66e1ac397a3b5ee902914e58 | [
"BSD-3-Clause"
] | null | null | null | kraken/public/views.py | peterdemartini/KrakenMaster | 2b3ed18f6dcc720e66e1ac397a3b5ee902914e58 | [
"BSD-3-Clause"
] | 1 | 2022-03-28T00:28:07.000Z | 2022-03-28T00:28:07.000Z | # -*- coding: utf-8 -*-
'''Public section, including homepage and signup.'''
from flask import (Blueprint, request, render_template, flash, url_for,
redirect, session)
from flask.ext.login import login_user, login_required, logout_user
from kraken.extensions import login_manager
from kraken.user.models import User
from kraken.public.forms import LoginForm
from kraken.user.forms import RegisterForm
from kraken.grade.models import Grade
from kraken.utils import flash_errors
from kraken.database import db
from kraken.helpers.Skynet import Skynet
blueprint = Blueprint('public', __name__, static_folder="../static")
@login_manager.user_loader
def load_user(id):
return User.get_by_id(int(id))
@blueprint.route("/", methods=["GET", "POST"])
def home():
skynet = Skynet()
messages = []
data = skynet.get_my_events()
if data and 'events' in data:
for event in data['events']:
if event and 'message' in event:
print("MESSAGE :: %s " % event['message'])
messages.append(event['message'])
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
login_user(form.user)
flash("You are logged in.", 'success')
redirect_url = request.args.get("next") or url_for("user.members")
return redirect(redirect_url)
else:
flash_errors(form)
grades = Grade.get_recent(100, "created_at DESC");
return render_template("public/home.html", form=form, grades = grades, messages=messages)
@blueprint.route('/logout/')
@login_required
def logout():
logout_user()
flash('You are logged out.', 'info')
return redirect(url_for('public.home'))
@blueprint.route("/register/", methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form, csrf_enabled=False)
if form.validate_on_submit():
new_user = User.create(username=form.username.data,
email=form.email.data,
password=form.password.data,
active=True)
flash("Thank you for registering. You can now log in.", 'success')
return redirect(url_for('public.home'))
else:
flash_errors(form)
return render_template('public/register.html', form=form)
@blueprint.route("/about/")
def about():
form = LoginForm(request.form)
return render_template("public/about.html", form=form)
| 34.666667 | 93 | 0.659054 | 0 | 0 | 0 | 0 | 1,844 | 0.738782 | 0 | 0 | 469 | 0.187901 |
dcf7760ee0ea08cc59fe587411f1de19eb0c37fe | 374 | py | Python | web/game/migrations/0002_message_visible.py | ihsgnef/kuiperbowl | a0c3e346bc05ed149fdb34f12b872c983a40613e | [
"MIT"
] | null | null | null | web/game/migrations/0002_message_visible.py | ihsgnef/kuiperbowl | a0c3e346bc05ed149fdb34f12b872c983a40613e | [
"MIT"
] | 5 | 2019-10-01T03:34:43.000Z | 2020-05-26T14:28:40.000Z | web/game/migrations/0002_message_visible.py | jasmaa/quizbowl | 282fe17217891266da96bcf1a9da4af5eff80fcc | [
"MIT"
] | 1 | 2021-05-10T01:46:45.000Z | 2021-05-10T01:46:45.000Z | # Generated by Django 2.2.7 on 2020-05-29 19:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('game', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='message',
name='visible',
field=models.BooleanField(default=True),
),
]
| 19.684211 | 52 | 0.585561 | 281 | 0.751337 | 0 | 0 | 0 | 0 | 0 | 0 | 85 | 0.227273 |
dcf7946f10ce6e7e4b323d54039dd26ab7fa02da | 271 | py | Python | problem_49/test_prime_permutations.py | plilja/project-euler | 646d1989cf15e903ef7e3c6e487284847d522ec9 | [
"Apache-2.0"
] | null | null | null | problem_49/test_prime_permutations.py | plilja/project-euler | 646d1989cf15e903ef7e3c6e487284847d522ec9 | [
"Apache-2.0"
] | null | null | null | problem_49/test_prime_permutations.py | plilja/project-euler | 646d1989cf15e903ef7e3c6e487284847d522ec9 | [
"Apache-2.0"
] | null | null | null | import unittest
from prime_permutations import *
class PrimePermutationsTest(unittest.TestCase):
def test_prime_permutations(self):
self.assertEqual(sorted(prime_permutations()), sorted([2969, 6299, 9629]))
if __name__ == '__main__':
unittest.main()
| 20.846154 | 82 | 0.741697 | 169 | 0.623616 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 0.0369 |
dcf7baef1e6706bbb04fa4359be5af5f09500ebe | 1,495 | py | Python | lecture10/inventory_hitting_time.py | BenGravell/optimal-control-course | ae8ab619b5c138f79d466d9c6dfc7af46b2a23b6 | [
"MIT"
] | null | null | null | lecture10/inventory_hitting_time.py | BenGravell/optimal-control-course | ae8ab619b5c138f79d466d9c6dfc7af46b2a23b6 | [
"MIT"
] | null | null | null | lecture10/inventory_hitting_time.py | BenGravell/optimal-control-course | ae8ab619b5c138f79d466d9c6dfc7af46b2a23b6 | [
"MIT"
] | null | null | null | import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as plt
capacity = 6
prob_demand_mass = np.array([0.7, 0.2, 0.1])
prob_demand_supp = np.array([0, 1, 2])
T = 50
P = np.array([[0, 0, 0, 0, prob_demand_mass[0], prob_demand_mass[1], prob_demand_mass[2]],
[0, 0, 0, 0, prob_demand_mass[0], prob_demand_mass[1], prob_demand_mass[2]],
[prob_demand_mass[0], prob_demand_mass[1], prob_demand_mass[2], 0, 0, 0, 0],
[0, prob_demand_mass[0], prob_demand_mass[1], prob_demand_mass[2], 0, 0, 0],
[0, 0, prob_demand_mass[0], prob_demand_mass[1], prob_demand_mass[2], 0, 0],
[0, 0, 0, prob_demand_mass[0], prob_demand_mass[1], prob_demand_mass[2], 0],
[0, 0, 0, 0, prob_demand_mass[0], prob_demand_mass[1], prob_demand_mass[2]]])
init_state = 6 # This should not be an element of the target_states
target_states = [0, 1]
Q = np.copy(P)
for target_state in target_states:
Q[target_state] = np.zeros(capacity+1)
Q[target_state, target_state] = 1
t_hist = np.arange(T)
hit_prob_hist = np.zeros(T)
for t in t_hist:
if t > 0:
Q1 = la.matrix_power(Q, t)
Q2 = la.matrix_power(Q, t-1)
Qdiff = Q1 - Q2
hit_prob_hist[t] = np.sum([Qdiff[init_state, target_state] for target_state in target_states])
plt.close('all')
plt.style.use('../conlab.mplstyle')
plt.step(t_hist, hit_prob_hist)
plt.xlabel('Time')
plt.ylabel('Hitting probability')
plt.tight_layout()
plt.show()
| 36.463415 | 102 | 0.656856 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 104 | 0.069565 |
dcfa4eb39a27cde22f1cd1ef58378d755009e643 | 1,177 | py | Python | mongoproj/First_Q_City/Paris.py | OuassimAKEBLI/MongoDB | d224a8d7e2a2bd8451b2b46e39602e085994c6b8 | [
"Apache-2.0"
] | null | null | null | mongoproj/First_Q_City/Paris.py | OuassimAKEBLI/MongoDB | d224a8d7e2a2bd8451b2b46e39602e085994c6b8 | [
"Apache-2.0"
] | null | null | null | mongoproj/First_Q_City/Paris.py | OuassimAKEBLI/MongoDB | d224a8d7e2a2bd8451b2b46e39602e085994c6b8 | [
"Apache-2.0"
] | null | null | null | import requests
import json
from pprint import pprint
from pymongo import MongoClient
def get_vparis():
url = "https://opendata.paris.fr/api/records/1.0/search/?dataset=velib-disponibilite-en-temps-reel&q=&rows" \
"=251&facet=name&facet=is_installed&facet=is_renting&facet=is_returning&facet=nom_arrondissement_communes"
response = requests.request("GET", url)
response_json = json.loads(response.text.encode('utf8'))
return response_json.get("records", [])
v_paris = get_vparis()
v_paris_to_insert = [
{
'name': elem.get('fields', {}).get('name', '').title(),
'geometry': elem.get('geometry'),
'size': elem.get('fields', {}).get('capacity'),
'source': {
'dataset': 'Paris',
'id_ext': elem.get('fields', {}).get('stationcode')
},
'tpe': elem.get('fields', {}).get('is_renting', '') == 'OUI'
}
for elem in v_paris
]
atlas = MongoClient('mongodb+srv://main:19631963@gettingstarted.nhut8.gcp.mongodb.net/vlille?retryWrites=true&w=majori'
'ty')
db = atlas.paris_bicycle
for ve_paris in v_paris_to_insert:
db.stations.insert_one(ve_paris) | 30.179487 | 119 | 0.641461 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 481 | 0.408666 |
dcfc51bcf5d6a13b28a3e162e544af447ae8e347 | 681 | py | Python | Youcheng/twitter_REST.py | xiaoli-chen/Godel | 181b347aa88220b0e3e9ae628089f5acd1e6f170 | [
"Apache-2.0"
] | null | null | null | Youcheng/twitter_REST.py | xiaoli-chen/Godel | 181b347aa88220b0e3e9ae628089f5acd1e6f170 | [
"Apache-2.0"
] | null | null | null | Youcheng/twitter_REST.py | xiaoli-chen/Godel | 181b347aa88220b0e3e9ae628089f5acd1e6f170 | [
"Apache-2.0"
] | null | null | null | #from twython import Twython
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
import json
CONSUMER_KEY = 'pxeqo0ylpUayIIl5Nlc2kBmkb'
CONSUMER_SECRET = 'JUAAG5ilMS9TxZN1Y0ZKwPhsamtE3gFoIYTnKfwWTGqGmF6zXL'
ACCESS_TOKEN = '395150986-GiB9RbBtrjjiEetZ977wtQwYGVWCuhiPMir0962F'
ACCESS_SECRET = 'DUk5aVVGGy55PySqjVNMWV4MTghtvdfwXbDJROUEnrH9Y'
oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
# Initiate the connection to Twitter REST API
twitter = Twitter(auth=oauth)
# Search for latest tweets about "#nlproc"
twitter.search.tweets(q='#nlproc')
#twitter.search.tweets(q='#nlproc', result_type='recent', lang='en', count=10)
| 32.428571 | 78 | 0.806167 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 380 | 0.558003 |
dcfe313a4570b1136b9927ba85fb05f98e2c3f09 | 2,903 | py | Python | app/risk/RiskEngine.py | OuissalTAIM/jenkins | 7ea5bcdeb6c0bb3cc14c2826a68e4f521de163c1 | [
"BSD-1-Clause"
] | null | null | null | app/risk/RiskEngine.py | OuissalTAIM/jenkins | 7ea5bcdeb6c0bb3cc14c2826a68e4f521de163c1 | [
"BSD-1-Clause"
] | 6 | 2021-02-02T22:52:41.000Z | 2022-03-12T00:37:30.000Z | app/risk/RiskEngine.py | OuissalTAIM/jenkins | 7ea5bcdeb6c0bb3cc14c2826a68e4f521de163c1 | [
"BSD-1-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from app.data.DataManager import DataManager
from app.model.Simulator import Simulator
from app.data.Client import Driver
from app.tools.Logger import logger_sensitivity as logger
from app.model.ScenarioGenerator import ScenarioGeneratorFactory as SGF
from app.config.env import ScenarioGeneratorType, PipelineLayer
class RiskEngine:
"""
Risk sensitivity class
"""
def __init__(self):
"""
ctor
"""
self.dm = DataManager()
self.dm.load_data()
def compute_delta(self, scenario, shocks, with_logistics=False):
# base scenario
simulator = Simulator(dm=self.dm, monikers_filter=sum(scenario, []))
scenarios = [
simulator.nodes[layer] for layer in [
PipelineLayer.PAP, PipelineLayer.SAP,
PipelineLayer.BENEFICIATION, PipelineLayer.MINE, PipelineLayer.MINE_BENEFICIATION
] if layer in simulator.nodes
]
scenario_generator = SGF.create_scenario_generator(ScenarioGeneratorType.SPECIFIC_SCENARIOS, simulator,
[scenarios])
result_no_bump, _ = simulator.simulate(scenario_generator=scenario_generator, logistics_lp=with_logistics)
logger.info("Base: %f" % result_no_bump[1]["Cost PV"])
# bump data
result_with_bump = {}
raw_materials_df = Driver().get_data("raw_materials")
for raw_material in raw_materials_df:
item = raw_material["Item"]
if item not in shocks:
continue
unit = raw_material["Unit"]
currency = unit.split("/")[0]
# bump
self.dm.bump_raw_materials({item: shocks[item]})
bumped_simulator = Simulator(dm=self.dm, monikers_filter=sum(scenario, []))
bumped_scenarios = [
bumped_simulator.nodes[layer] for layer in [
PipelineLayer.PAP, PipelineLayer.SAP,
PipelineLayer.BENEFICIATION, PipelineLayer.MINE, PipelineLayer.MINE_BENEFICIATION
] if layer in bumped_simulator.nodes
]
scenario_generator = SGF.create_scenario_generator(ScenarioGeneratorType.SPECIFIC_SCENARIOS, bumped_simulator,
[bumped_scenarios])
result_with_bump[item], _ = bumped_simulator.simulate(scenario_generator=scenario_generator)
logger.info("Shock %s by %s%f: %f" % (item, currency, shocks[item], result_with_bump[item][1]["Cost PV"]))
# reset
self.dm.bump_raw_materials({item: -shocks[item]})
# deltas
base_price = result_no_bump[1]["Cost PV"]
deltas = {}
for item in result_with_bump:
deltas[item] = result_with_bump[item][1]["Cost PV"] - base_price
return deltas
| 42.072464 | 122 | 0.619015 | 2,558 | 0.881157 | 0 | 0 | 0 | 0 | 0 | 0 | 234 | 0.080606 |
0d00ee6cb81689f5aa3f9ed7df94760a8859265c | 2,129 | py | Python | upf/python/upf.py | aiplan4eu/upf-poc | 616c4044a4d0f26dc00aa3d371f61329b173bf8f | [
"Apache-2.0"
] | null | null | null | upf/python/upf.py | aiplan4eu/upf-poc | 616c4044a4d0f26dc00aa3d371f61329b173bf8f | [
"Apache-2.0"
] | null | null | null | upf/python/upf.py | aiplan4eu/upf-poc | 616c4044a4d0f26dc00aa3d371f61329b173bf8f | [
"Apache-2.0"
] | null | null | null | import importlib
from dataclasses import dataclass
from typing import FrozenSet, Callable, List
@dataclass
class Action:
name: str
precondition: FrozenSet[str]
positive_effect: FrozenSet[str]
negative_effect: FrozenSet[str]
@dataclass
class Problem:
actions: List[Action]
init: FrozenSet[str]
goal: FrozenSet[str]
class Solver():
def solve(problem: Problem, heuristic: Callable[[FrozenSet[str]], float] = None) -> List[str]:
raise NotImplementedError
def destroy():
raise NotImplementedError
class LinkedSolver(Solver):
def __init__(self, module_name):
self.module = importlib.import_module(module_name)
#print('Creating planner %s' % module_name)
def solve(self, problem: Problem, heuristic: Callable[[FrozenSet[str]], float] = None) -> List[str]:
if heuristic is None:
plan = self.module.solve(problem)
else:
plan = self.module.solve_with_heuristic(problem, heuristic)
return plan
def destroy(self):
pass
from contextlib import contextmanager
@contextmanager
def Planner(module_name):
a = LinkedSolver(module_name)
try:
yield a
finally:
a.destroy()
if __name__ == '__main__':
def generate_problem(size: int) -> Problem:
actions = [Action('mk_y', set(['x']), set(['y']), set(['x'])),
Action('reset_x', set([]), set(['x']), set([]))]
goal = []
for i in range(size):
name = f"v{i}"
goal.append(name)
actions.append(Action(f'mk_{name}', set(['y']), set([name]), set(['y'])),)
init = set(['x'])
return Problem(actions, init, set(goal))
size = 10
def goal_counter(state: FrozenSet[str]) -> float:
return size - len(state & problem.goal)
problem = generate_problem(size)
planners = ['cppplanner_upf', 'pyplanner_upf', 'jplanner_upf']
for name in planners:
with Planner(name) as p:
plan = p.solve(problem)
print(plan)
plan = p.solve(problem, goal_counter)
print(plan)
| 25.963415 | 104 | 0.610146 | 924 | 0.434007 | 117 | 0.054955 | 377 | 0.177078 | 0 | 0 | 153 | 0.071865 |
0d034550164c2e8133c022210ebe779bc78107db | 1,547 | py | Python | rnnparser/RecursiveNN/tests/test_code_gen.py | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | rnnparser/RecursiveNN/tests/test_code_gen.py | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | rnnparser/RecursiveNN/tests/test_code_gen.py | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from recursiveNN.nodes import Val,Var,VSF, Add,Mul,Dot,CTimes,Transpose, Node
def test_variables_of_expressions():
ran=lambda x : np.random.random(x)-0.5
x=Var('x',ran((1,4)))
y=Var('y',ran((1,4)))
z=Var('z',ran((1,4)))
expr=Add(Add(Add(x,y),x),z)
for var in ['x','y','z'] :
assert var in expr.variables
assert list(expr.variables).count(var)==1
def test_expressions_code_generation():
ran=lambda x : np.random.random(x)-0.5
x=Var('x',ran((1,4)))
y=Var('y',ran((4,1)))
a=Var('a',ran((5,1)))
b=Var('b',ran((6,1)))
D,C,B,A = Var('D', ran((4,4))), Var('C', ran((4,6))), Var('B', ran((6,5))), Var('A', ran((5,4)))
ns={}
f = Dot(Dot(x,C),Dot(B,VSF('sin',Add(Dot(A,y),a))))
assert f.code()=='np.dot(np.dot(x,C),np.dot(B,np.sin(np.add(np.dot(A,y),a))))'
ns=Node.Compile('f',f, ns)
assert ns['f'](A=A.val,B=B.val,C=C.val, a=a.val,x=x.val,y=y.val)==f.val
g = Dot(Dot(x,C),VSF('sin',Add(Dot(B,VSF('sin',Add(Dot(A,y),a))),b)))
assert g.code()=='np.dot(np.dot(x,C),np.sin(np.add(np.dot(B,np.sin(np.add(np.dot(A,y),a))),b)))'
ns=Node.Compile('g',g, ns)
assert ns['g'](A=A.val,B=B.val,C=C.val, a=a.val,b=b.val,x=x.val,y=y.val)==g.val
h,w,b,u,w12 =Var('h'),Var('W'),Var('b'),Var('u'), Var('word12')
phrase=VSF('tanh', Add(Dot(w, h), b))
score=Dot(u,phrase)
assert phrase.code()=='np.tanh(np.add(np.dot(W,h),b))'
assert score.code()=='np.dot(u,np.tanh(np.add(np.dot(W,h),b)))'
| 38.675 | 100 | 0.553975 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 332 | 0.214609 |
0d05520e82655910896021870c67e33da2f6dc74 | 569 | py | Python | tests/api/schemas/test_product_schema.py | igor822/product-categorization | e9c64834bf60cd9d51ab9b696b1b3ea49e702c9d | [
"MIT"
] | 19 | 2018-11-13T15:12:12.000Z | 2022-01-31T20:43:26.000Z | tests/api/schemas/test_product_schema.py | igor822/product-categorization | e9c64834bf60cd9d51ab9b696b1b3ea49e702c9d | [
"MIT"
] | null | null | null | tests/api/schemas/test_product_schema.py | igor822/product-categorization | e9c64834bf60cd9d51ab9b696b1b3ea49e702c9d | [
"MIT"
] | 8 | 2019-03-07T03:32:43.000Z | 2020-11-13T01:51:03.000Z | import unittest
import pytest
from src.api.schemas.product_schema import ProductSchema
class ProductSchemaTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_validate_valid_product(self):
product = {"name": "Produt name", "description": "Some description"}
assert ProductSchema().load(product)
def test_validate_invalid_product(self):
product = {"name": "Produt name"}
validation = ProductSchema().load(product)
assert len(validation.errors['description']) == 1
| 27.095238 | 76 | 0.683656 | 479 | 0.841828 | 0 | 0 | 0 | 0 | 0 | 0 | 82 | 0.144112 |
0d058e1ee4a48662be58d98c65151d8e58a92c4b | 430 | py | Python | InterAutoTest_W/testcase/t_pytest/pytest_class.py | xuguoyan/pytest_api3 | c83d8b1fbd2b061db9d6dee40068ac84ae81c708 | [
"MIT"
] | 7 | 2019-11-28T07:17:37.000Z | 2020-10-28T08:24:09.000Z | InterAutoTest_W/testcase/t_pytest/pytest_class.py | xuguoyan/pytest_api3 | c83d8b1fbd2b061db9d6dee40068ac84ae81c708 | [
"MIT"
] | null | null | null | InterAutoTest_W/testcase/t_pytest/pytest_class.py | xuguoyan/pytest_api3 | c83d8b1fbd2b061db9d6dee40068ac84ae81c708 | [
"MIT"
] | 7 | 2021-01-10T14:11:10.000Z | 2022-02-28T12:41:04.000Z | #coding=utf-8
"""
1.定义类;
2.创建测试方法test开头
3.创建setup_class, teardown_class
4.运行查看结果
"""
import pytest
class TestClass():
def test_a(self):
print('test_a')
def test_b(self):
print('test_b')
def setup_class(self):
print('------setup_class------')
def teardown_class(self):
print('------teardown_class------')
if __name__ == "__main__":
pytest.main(['-s', 'pytest_class.py']) | 17.2 | 43 | 0.588372 | 255 | 0.544872 | 0 | 0 | 0 | 0 | 0 | 0 | 221 | 0.472222 |
0d094d21102a554dd26ab1f57fd940c5c211f30e | 1,469 | py | Python | tests/test_cmd.py | mick88/poeditor-sync | 2326b0ff6c0537b3d4ff729fd45b079e0789d2c7 | [
"MIT"
] | 6 | 2021-07-16T14:19:44.000Z | 2022-03-10T10:27:39.000Z | tests/test_cmd.py | mick88/poeditor-sync | 2326b0ff6c0537b3d4ff729fd45b079e0789d2c7 | [
"MIT"
] | 9 | 2021-07-10T15:57:52.000Z | 2021-10-17T11:44:24.000Z | tests/test_cmd.py | mick88/poeditor-sync | 2326b0ff6c0537b3d4ff729fd45b079e0789d2c7 | [
"MIT"
] | null | null | null | from unittest import TestCase
from click.testing import CliRunner, Result
from poeditor_sync.cmd import poeditor
class CmdReadOnlyTokenTest(TestCase):
def setUp(self) -> None:
super().setUp()
self.runner = CliRunner(env={
'POEDITOR_CONFIG_FILE': 'tests/test.yml',
'POEDITOR_TOKEN': 'e1fc095d70eba2395fec56c6ad9e61c3',
})
def test_poeditor(self):
result: Result = self.runner.invoke(poeditor)
self.assertEqual(result.exit_code, 0)
self.assertTrue(result.stdout.startswith('Usage: poeditor'))
def test_poeditor_pull(self):
result: Result = self.runner.invoke(poeditor, ['pull'])
self.assertEqual(result.exit_code, 0, result.stdout)
def test_poeditor_push(self):
result: Result = self.runner.invoke(poeditor, 'push')
self.assertEqual(result.exit_code, 1)
def test_poeditor_push_terms(self):
result: Result = self.runner.invoke(poeditor, 'push')
self.assertEqual(result.exit_code, 1)
def test_poeditor_init_blank(self):
result: Result = self.runner.invoke(poeditor, args=['--config-file', 'test_blank_init.yml', 'init'])
self.assertEqual(result.exit_code, 0, result.stdout)
def test_poeditor_init_project_id(self):
result: Result = self.runner.invoke(poeditor, args=['--config-file', 'test_init_projectid.yml', 'init', '458528'])
self.assertEqual(result.exit_code, 0, result.stdout)
| 36.725 | 122 | 0.684139 | 1,351 | 0.919673 | 0 | 0 | 0 | 0 | 0 | 0 | 219 | 0.149081 |
0d09b1f3b7cd0f00460955d0c6f059dbe658e86b | 3,472 | py | Python | cats/cats_simus/vortex.py | brunellacarlomagno/CATS | 2fb85366dbca81736d75a982156674523632414f | [
"MIT"
] | null | null | null | cats/cats_simus/vortex.py | brunellacarlomagno/CATS | 2fb85366dbca81736d75a982156674523632414f | [
"MIT"
] | null | null | null | cats/cats_simus/vortex.py | brunellacarlomagno/CATS | 2fb85366dbca81736d75a982156674523632414f | [
"MIT"
] | null | null | null | import numpy as np
import cv2
import proper
from cats.cats_simus import *
def vortex(wfo, CAL, charge, f_lens, path, Debug_print):
n = int(proper.prop_get_gridsize(wfo))
ofst = 0 # no offset
ramp_sign = 1 #sign of charge is positive
#sampling = n
ramp_oversamp = 11. # vortex is oversampled for a better discretization
if charge!=0:
if CAL==1: # create the vortex for a perfectly circular pupil
if (Debug_print == True):
print ("CAL:1, charge ", charge)
writefield(path,'zz_psf', wfo.wfarr) # write the pre-vortex field
nramp = int(n*ramp_oversamp) #oversamp
# create the vortex by creating a matrix (theta) representing the ramp (created by atan 2 gradually varying matrix, x and y)
y1 = np.ones((nramp,), dtype=np.int)
y2 = np.arange(0, nramp, 1.) - (nramp/2) - int(ramp_oversamp)/2
y = np.outer(y2, y1)
x = np.transpose(y)
theta = np.arctan2(y,x)
x = 0
y = 0
#vvc_tmp_complex = np.array(np.zeros((nramp,nramp)), dtype=complex)
#vvc_tmp_complex.imag = ofst + ramp_sign*charge*theta
#vvc_tmp = np.exp(vvc_tmp_complex)
vvc_tmp = np.exp(1j*(ofst + ramp_sign*charge*theta))
theta = 0
vvc_real_resampled = cv2.resize(vvc_tmp.real, (0,0), fx=1/ramp_oversamp, fy=1/ramp_oversamp, interpolation=cv2.INTER_LINEAR) # scale the pupil to the pupil size of the simualtions
vvc_imag_resampled = cv2.resize(vvc_tmp.imag, (0,0), fx=1/ramp_oversamp, fy=1/ramp_oversamp, interpolation=cv2.INTER_LINEAR) # scale the pupil to the pupil size of the simualtions
vvc = np.array(vvc_real_resampled, dtype=complex)
vvc.imag = vvc_imag_resampled
vvcphase = np.arctan2(vvc.imag, vvc.real) # create the vortex phase
vvc_complex = np.array(np.zeros((n,n)), dtype=complex)
vvc_complex.imag = vvcphase
vvc = np.exp(vvc_complex)
vvc_tmp = 0.
writefield(path,'zz_vvc', vvc) # write the theoretical vortex field
wfo0 = wfo
proper.prop_multiply(wfo, vvc)
proper.prop_propagate(wfo, f_lens, 'OAP2')
proper.prop_lens(wfo, f_lens)
proper.prop_propagate(wfo, f_lens, 'forward to Lyot Stop')
proper.prop_circular_obscuration(wfo, 1., NORM=True) # null the amplitude iside the Lyot Stop
proper.prop_propagate(wfo, -f_lens) # back-propagation
proper.prop_lens(wfo, -f_lens)
proper.prop_propagate(wfo, -f_lens)
writefield(path,'zz_perf', wfo.wfarr) # write the perfect-result vortex field
wfo = wfo0
else:
if (Debug_print == True):
print ("CAL:0, charge ", charge)
vvc = readfield(path,'zz_vvc') # read the theoretical vortex field
vvc = proper.prop_shift_center(vvc)
scale_psf = wfo._wfarr[0,0]
psf_num = readfield(path,'zz_psf') # read the pre-vortex field
psf0 = psf_num[0,0]
psf_num = psf_num/psf0*scale_psf
perf_num = readfield(path,'zz_perf') # read the perfect-result vortex field
perf_num = perf_num/psf0*scale_psf
wfo._wfarr = (wfo._wfarr - psf_num)*vvc + perf_num # the wavefront takes into account the real pupil with the perfect-result vortex field
return
| 51.058824 | 191 | 0.615495 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,029 | 0.296371 |
0d0a48c167ff778fcf72beb6012207a10ec69a12 | 1,119 | py | Python | Search/rotated/Solution.py | Voley/AlgorithmicProblemsV2 | 0c70e4fe61b66ae3f648ee6dada4dd75a4234edd | [
"MIT"
] | null | null | null | Search/rotated/Solution.py | Voley/AlgorithmicProblemsV2 | 0c70e4fe61b66ae3f648ee6dada4dd75a4234edd | [
"MIT"
] | null | null | null | Search/rotated/Solution.py | Voley/AlgorithmicProblemsV2 | 0c70e4fe61b66ae3f648ee6dada4dd75a4234edd | [
"MIT"
] | null | null | null |
# Problem code
def search(nums, target):
return search_helper(nums, target, 0, len(nums) - 1)
def search_helper(nums, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
# right part is good
if nums[mid] <= nums[right]:
# we fall for it
if target >= nums[mid] and target <= nums[right]:
return binary_search(nums, target, mid, right)
# we don't fall for it
else:
return search_helper(nums, target, left, mid - 1)
# left part is good
if nums[mid] >= nums[left]:
# we fall for it
if target >= nums[left] and target <= nums[mid]:
return binary_search(nums, target, left, mid)
#we don't fall for it
else:
return search_helper(nums, target, mid + 1, right)
return -1
def binary_search(nums, target, left, right):
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif target > nums[mid]:
left = mid + 1
else:
right = mid - 1
return -1
| 27.292683 | 62 | 0.544236 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 128 | 0.114388 |
0d0ada3c223ce67e0153b8f576b9926c738f9141 | 21,631 | py | Python | pysnmp/CISCO-EMBEDDED-EVENT-MGR-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/CISCO-EMBEDDED-EVENT-MGR-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/CISCO-EMBEDDED-EVENT-MGR-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module CISCO-EMBEDDED-EVENT-MGR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EMBEDDED-EVENT-MGR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint")
ciscoExperiment, = mibBuilder.importSymbols("CISCO-SMI", "ciscoExperiment")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
iso, Counter64, Unsigned32, Counter32, ModuleIdentity, Bits, IpAddress, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Integer32, TimeTicks, Gauge32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Counter64", "Unsigned32", "Counter32", "ModuleIdentity", "Bits", "IpAddress", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Integer32", "TimeTicks", "Gauge32", "MibIdentifier")
TruthValue, TextualConvention, DisplayString, DateAndTime = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "TextualConvention", "DisplayString", "DateAndTime")
cEventMgrMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 10, 134))
cEventMgrMIB.setRevisions(('2006-11-07 00:00', '2003-04-16 00:00',))
if mibBuilder.loadTexts: cEventMgrMIB.setLastUpdated('200611070000Z')
if mibBuilder.loadTexts: cEventMgrMIB.setOrganization('Cisco Systems, Inc.')
cEventMgrMIBNotif = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 0))
cEventMgrMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 1))
cEventMgrConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 3))
ceemEventMap = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1))
ceemHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2))
ceemRegisteredPolicy = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3))
class NotifySource(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("server", 1), ("policy", 2))
ceemEventMapTable = MibTable((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1), )
if mibBuilder.loadTexts: ceemEventMapTable.setStatus('current')
ceemEventMapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemEventIndex"))
if mibBuilder.loadTexts: ceemEventMapEntry.setStatus('current')
ceemEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceemEventIndex.setStatus('current')
ceemEventName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemEventName.setStatus('current')
ceemEventDescrText = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemEventDescrText.setStatus('current')
ceemHistoryMaxEventEntries = MibScalar((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 50)).clone(10)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ceemHistoryMaxEventEntries.setStatus('current')
ceemHistoryLastEventEntry = MibScalar((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryLastEventEntry.setStatus('current')
ceemHistoryEventTable = MibTable((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3), )
if mibBuilder.loadTexts: ceemHistoryEventTable.setStatus('current')
ceemHistoryEventEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1), ).setIndexNames((0, "CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventIndex"))
if mibBuilder.loadTexts: ceemHistoryEventEntry.setStatus('current')
ceemHistoryEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: ceemHistoryEventIndex.setStatus('current')
ceemHistoryEventType1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType1.setStatus('current')
ceemHistoryEventType2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType2.setStatus('current')
ceemHistoryEventType3 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType3.setStatus('current')
ceemHistoryEventType4 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType4.setStatus('current')
ceemHistoryPolicyPath = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyPath.setStatus('current')
ceemHistoryPolicyName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyName.setStatus('current')
ceemHistoryPolicyExitStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-2147483648, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyExitStatus.setStatus('current')
ceemHistoryPolicyIntData1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-2147483648, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyIntData1.setStatus('current')
ceemHistoryPolicyIntData2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-2147483648, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyIntData2.setStatus('current')
ceemHistoryPolicyStrData = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 11), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyStrData.setStatus('current')
ceemHistoryNotifyType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 12), NotifySource()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryNotifyType.setStatus('current')
ceemHistoryEventType5 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 13), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType5.setStatus('current')
ceemHistoryEventType6 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 14), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType6.setStatus('current')
ceemHistoryEventType7 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 15), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType7.setStatus('current')
ceemHistoryEventType8 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 16), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType8.setStatus('current')
ceemRegisteredPolicyTable = MibTable((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1), )
if mibBuilder.loadTexts: ceemRegisteredPolicyTable.setStatus('current')
ceemRegisteredPolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1), ).setIndexNames((0, "CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyIndex"))
if mibBuilder.loadTexts: ceemRegisteredPolicyEntry.setStatus('current')
ceemRegisteredPolicyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceemRegisteredPolicyIndex.setStatus('current')
ceemRegisteredPolicyName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyName.setStatus('current')
ceemRegisteredPolicyEventType1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType1.setStatus('current')
ceemRegisteredPolicyEventType2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType2.setStatus('current')
ceemRegisteredPolicyEventType3 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType3.setStatus('current')
ceemRegisteredPolicyEventType4 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType4.setStatus('current')
ceemRegisteredPolicyStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyStatus.setStatus('current')
ceemRegisteredPolicyType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("user", 1), ("system", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyType.setStatus('current')
ceemRegisteredPolicyNotifFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 9), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyNotifFlag.setStatus('current')
ceemRegisteredPolicyRegTime = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 10), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyRegTime.setStatus('current')
ceemRegisteredPolicyEnabledTime = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 11), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEnabledTime.setStatus('current')
ceemRegisteredPolicyRunTime = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 12), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyRunTime.setStatus('current')
ceemRegisteredPolicyRunCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyRunCount.setStatus('current')
ceemRegisteredPolicyEventType5 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 14), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType5.setStatus('current')
ceemRegisteredPolicyEventType6 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 15), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType6.setStatus('current')
ceemRegisteredPolicyEventType7 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 16), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType7.setStatus('current')
ceemRegisteredPolicyEventType8 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 17), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType8.setStatus('current')
cEventMgrServerEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 10, 134, 0, 1)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType3"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType4"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyPath"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyExitStatus"))
if mibBuilder.loadTexts: cEventMgrServerEvent.setStatus('current')
cEventMgrPolicyEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 10, 134, 0, 2)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType3"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType4"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyPath"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyIntData1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyIntData2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyStrData"))
if mibBuilder.loadTexts: cEventMgrPolicyEvent.setStatus('current')
cEventMgrCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 1))
cEventMgrGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2))
cEventMgrCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 1, 1)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrDescrGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrNotificationsGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrRegisteredPolicyGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrHistoryGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrCompliance = cEventMgrCompliance.setStatus('deprecated')
cEventMgrComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 1, 2)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrDescrGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrNotificationsGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrRegisteredPolicyGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrRegisteredPolicyGroupSup1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrHistoryGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrHistoryGroupSup1"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrComplianceRev1 = cEventMgrComplianceRev1.setStatus('current')
cEventMgrDescrGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 1)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemEventName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemEventDescrText"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrDescrGroup = cEventMgrDescrGroup.setStatus('current')
cEventMgrHistoryGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 2)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryMaxEventEntries"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryLastEventEntry"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType3"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType4"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyPath"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyExitStatus"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyIntData1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyIntData2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyStrData"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryNotifyType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrHistoryGroup = cEventMgrHistoryGroup.setStatus('current')
cEventMgrNotificationsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 3)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrServerEvent"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrPolicyEvent"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrNotificationsGroup = cEventMgrNotificationsGroup.setStatus('current')
cEventMgrRegisteredPolicyGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 4)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType3"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType4"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyStatus"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyType"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyNotifFlag"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyRegTime"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEnabledTime"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyRunTime"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyRunCount"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrRegisteredPolicyGroup = cEventMgrRegisteredPolicyGroup.setStatus('current')
cEventMgrHistoryGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 5)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType5"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType6"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType7"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType8"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrHistoryGroupSup1 = cEventMgrHistoryGroupSup1.setStatus('current')
cEventMgrRegisteredPolicyGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 6)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType5"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType6"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType7"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType8"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrRegisteredPolicyGroupSup1 = cEventMgrRegisteredPolicyGroupSup1.setStatus('current')
mibBuilder.exportSymbols("CISCO-EMBEDDED-EVENT-MGR-MIB", ceemEventDescrText=ceemEventDescrText, ceemHistoryEventType5=ceemHistoryEventType5, ceemRegisteredPolicyEventType4=ceemRegisteredPolicyEventType4, ceemEventName=ceemEventName, ceemHistoryPolicyIntData1=ceemHistoryPolicyIntData1, ceemRegisteredPolicyEntry=ceemRegisteredPolicyEntry, ceemHistoryPolicyExitStatus=ceemHistoryPolicyExitStatus, ceemRegisteredPolicyRunTime=ceemRegisteredPolicyRunTime, cEventMgrDescrGroup=cEventMgrDescrGroup, ceemHistory=ceemHistory, cEventMgrNotificationsGroup=cEventMgrNotificationsGroup, cEventMgrRegisteredPolicyGroup=cEventMgrRegisteredPolicyGroup, ceemRegisteredPolicyEventType3=ceemRegisteredPolicyEventType3, ceemRegisteredPolicyStatus=ceemRegisteredPolicyStatus, ceemEventIndex=ceemEventIndex, cEventMgrConformance=cEventMgrConformance, ceemRegisteredPolicyEventType6=ceemRegisteredPolicyEventType6, cEventMgrServerEvent=cEventMgrServerEvent, cEventMgrHistoryGroup=cEventMgrHistoryGroup, ceemHistoryPolicyStrData=ceemHistoryPolicyStrData, NotifySource=NotifySource, cEventMgrPolicyEvent=cEventMgrPolicyEvent, ceemRegisteredPolicyEventType8=ceemRegisteredPolicyEventType8, cEventMgrMIBNotif=cEventMgrMIBNotif, ceemHistoryEventType2=ceemHistoryEventType2, ceemEventMap=ceemEventMap, cEventMgrGroups=cEventMgrGroups, ceemHistoryEventType6=ceemHistoryEventType6, PYSNMP_MODULE_ID=cEventMgrMIB, ceemRegisteredPolicyRegTime=ceemRegisteredPolicyRegTime, cEventMgrRegisteredPolicyGroupSup1=cEventMgrRegisteredPolicyGroupSup1, cEventMgrMIB=cEventMgrMIB, ceemHistoryPolicyIntData2=ceemHistoryPolicyIntData2, ceemRegisteredPolicyEventType7=ceemRegisteredPolicyEventType7, ceemHistoryEventEntry=ceemHistoryEventEntry, ceemHistoryEventTable=ceemHistoryEventTable, cEventMgrMIBObjects=cEventMgrMIBObjects, ceemEventMapEntry=ceemEventMapEntry, ceemRegisteredPolicyName=ceemRegisteredPolicyName, ceemRegisteredPolicy=ceemRegisteredPolicy, ceemHistoryEventType3=ceemHistoryEventType3, ceemHistoryEventType8=ceemHistoryEventType8, ceemHistoryEventIndex=ceemHistoryEventIndex, cEventMgrCompliance=cEventMgrCompliance, ceemRegisteredPolicyNotifFlag=ceemRegisteredPolicyNotifFlag, ceemRegisteredPolicyRunCount=ceemRegisteredPolicyRunCount, ceemRegisteredPolicyEventType1=ceemRegisteredPolicyEventType1, ceemRegisteredPolicyIndex=ceemRegisteredPolicyIndex, ceemHistoryEventType1=ceemHistoryEventType1, ceemHistoryPolicyName=ceemHistoryPolicyName, ceemHistoryNotifyType=ceemHistoryNotifyType, ceemRegisteredPolicyEventType5=ceemRegisteredPolicyEventType5, ceemRegisteredPolicyType=ceemRegisteredPolicyType, ceemHistoryMaxEventEntries=ceemHistoryMaxEventEntries, ceemEventMapTable=ceemEventMapTable, ceemHistoryPolicyPath=ceemHistoryPolicyPath, cEventMgrHistoryGroupSup1=cEventMgrHistoryGroupSup1, ceemRegisteredPolicyEventType2=ceemRegisteredPolicyEventType2, ceemHistoryEventType4=ceemHistoryEventType4, ceemRegisteredPolicyTable=ceemRegisteredPolicyTable, ceemHistoryLastEventEntry=ceemHistoryLastEventEntry, cEventMgrCompliances=cEventMgrCompliances, ceemRegisteredPolicyEnabledTime=ceemRegisteredPolicyEnabledTime, ceemHistoryEventType7=ceemHistoryEventType7, cEventMgrComplianceRev1=cEventMgrComplianceRev1)
| 142.309211 | 3,183 | 0.773473 | 220 | 0.010171 | 0 | 0 | 0 | 0 | 0 | 0 | 5,734 | 0.265083 |
0d0b5671587550eca8af9d7486e1e9c27446306c | 277 | py | Python | src/util_walk_sftp.py | Chrisebell24/walk_sftp | 65dcb4e4231fabe8f8d9f2a6b595371c31ddc0d6 | [
"MIT"
] | null | null | null | src/util_walk_sftp.py | Chrisebell24/walk_sftp | 65dcb4e4231fabe8f8d9f2a6b595371c31ddc0d6 | [
"MIT"
] | null | null | null | src/util_walk_sftp.py | Chrisebell24/walk_sftp | 65dcb4e4231fabe8f8d9f2a6b595371c31ddc0d6 | [
"MIT"
] | null | null | null | import paramiko
class _FastTransport(paramiko.Transport):
def __init__(self, sock):
super(_FastTransport, self).__init__(sock)
self.window_size = 2147483647
self.packetizer.REKEY_BYTES = pow(2, 40)
self.packetizer.REKEY_PACKETS = pow(2, 40) | 34.625 | 50 | 0.696751 | 260 | 0.938628 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
0d0cfb3214f9d822574bd483b912ab38da359e78 | 13,211 | py | Python | Project_2/source/project_2.py | larsjbro/FYS4150 | 95ac4e09b5aad133b29c9aabb5be1302abdd8e65 | [
"BSD-2-Clause"
] | null | null | null | Project_2/source/project_2.py | larsjbro/FYS4150 | 95ac4e09b5aad133b29c9aabb5be1302abdd8e65 | [
"BSD-2-Clause"
] | null | null | null | Project_2/source/project_2.py | larsjbro/FYS4150 | 95ac4e09b5aad133b29c9aabb5be1302abdd8e65 | [
"BSD-2-Clause"
] | null | null | null | '''
Created on 14. sep. 2017 v2
@author: LJB
'''
from __future__ import division, absolute_import
from numba import jit, float64, int64, void
import numpy as np
import matplotlib.pyplot as plt
import timeit
_DPI = 250
_SIZE = 0.7
def figure_set_default_size():
F = plt.gcf()
DefaultSize = [8 * _SIZE, 6 * _SIZE]
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image" % (_DPI * DefaultSize[0],
_DPI * DefaultSize[1])
F.set_size_inches(DefaultSize)
return F
def my_savefig(filename):
F = figure_set_default_size()
F.tight_layout()
F.savefig(filename, dpi=_DPI)
def cpu_time(repetition=10, n=100):
'''
Grid n =10^6 and two repetitions gave an average of 7.62825565887 seconds.
'''
time_per_call = timeit.timeit('solve_schroedinger({},5)'.format(n),
setup='from __main__ import solve_schroedinger',
number=repetition) / repetition
return time_per_call
def cpu_time_jacobi(repetition=10, n=100):
'''
Grid n =10^6 and two repetitions gave an average of 7.512299363 seconds.
'''
time_per_call = timeit.timeit('solve_schroedinger_jacobi({},5)'.format(n),
setup='from __main__ import solve_schroedinger_jacobi',
number=repetition) / repetition
return time_per_call
def jacobi_method(A, epsilon=1.0e-8): #2b,2d
'''
Jacobi's method for finding eigen_values
eigenvectors of the symetric matrix A.
The eigen_values of A will be on the diagonal
of A, with eigenvalue i being A[i][i].
The jth component of the ith eigenvector
is stored in R[i][j].
A: input matrix (n x n)
R: empty matrix for eigenvectors (n x n)
n: dimension of matrices
7.4 Jacobi's method 219
'''
# Setting up the eigenvector matrix
A = np.array(A) # or A=np.atleast_2d(A)
n = len(A)
eigen_vectors = np.eye(n)
# for i in range(n):
# for j in range(n):
# if i == j:
# eigen_vectors[i][j] = 1.0
# else:
# eigen_vectors[i][j] = 0.0
max_number_iterations = n**3
iterations = 0
max_value, k, l = max_off_diag(A)
while max_value > epsilon and iterations < max_number_iterations:
max_value, k, l = max_off_diag(A)
rotate(A, eigen_vectors, k, l, n)
iterations += 1
# print "Number of iterations: {}".format(iterations)
eigen_values = np.diag(A) # eigen_values are the diagonal elements of A
# return eigenvectors and eigen_values
return eigen_vectors, eigen_values, iterations
# @jit(float64(float64[:, :], int32[1], int32[1]), nopython=True)
@jit(nopython=True)
def max_off_diag(A):
''' Function to find the maximum matrix element. Can you figure out a more
elegant algorithm?'''
n = len(A)
max_val_out = 0.0
for i in range(n):
for j in range(i + 1, n):
absA = abs(A[i][j])
if absA > max_val_out:
max_val_out = absA
l = i
k = j
return max_val_out, k, l
@jit(void(float64[:, :], float64[:, :], int64, int64, int64), nopython=True)
def rotate(A, R, k, l, n):
'''Function to find the values of cos and sin'''
if A[k][l] != 0.0:
tau = (A[l][l] - A[k][k]) / (2 * A[k][l])
if tau > 0:
t = -tau + np.sqrt(1.0 + tau * tau)
else:
t = -tau - np.sqrt(1.0 + tau * tau)
c = 1 / np.sqrt(1 + t * t)
s = c * t
else:
c = 1.0
s = 0.0
# p.220 7 Eigensystems
a_kk = A[k][k]
a_ll = A[l][l]
# changing the matrix elements with indices k and l
A[k][k] = c * c * a_kk - 2.0 * c * s * A[k][l] + s * s * a_ll
A[l][l] = s * s * a_kk + 2.0 * c * s * A[k][l] + c * c * a_ll
A[k][l] = 0.0 # hard-coding of the zeros
A[l][k] = 0.0
# and then we change the remaining elements
for i in range(n):
if i != k and i != l:
a_ik = A[i][k]
a_il = A[i][l]
A[i][k] = c * a_ik - s * a_il
A[k][i] = A[i][k]
A[i][l] = c * a_il + s * a_ik
A[l][i] = A[i][l]
# Finally, we compute the new eigenvectors
r_ik = R[i][k]
r_il = R[i][l]
R[i][k] = c * r_ik - s * r_il
R[i][l] = c * r_il + s * r_ik
return
class Potential(object):
def __init__(self, omega):
self.omega = omega
def __call__(self, rho):
omega = self.omega
return omega**2 * rho**2 + 1.0 / rho
def test_rho_max_jacobi_interactive_case(omega=0.01, rho_max=40, n=512): #2d
potential = Potential(omega=omega)
# now plot the results for the three lowest lying eigenstates
r, eigenvectors, eigenvalues, iterations = solve_schroedinger_jacobi(
n=n, rho_max=rho_max, potential=potential)
# errors = []
#for i, trueeigenvalue in enumerate([3, 7, 11]):
#errors.append(np.abs(eigenvalues[i] - trueeigenvalue))
# print eigenvalues[i] - trueeigenvalue, eigenvalues[i]
FirstEigvector = eigenvectors[:, 0]
SecondEigvector = eigenvectors[:, 1]
ThirdEigvector = eigenvectors[:, 2]
plt.plot(r, FirstEigvector**2, 'b-',
r, SecondEigvector ** 2, 'g-',
r, ThirdEigvector**2, 'r-')
m0 = max(FirstEigvector**2)
we = np.sqrt(3)*omega
print((we/np.pi)**(1/4)/m0)
r0 = (2*omega**2)**(-1/3)
g = lambda r: m0*np.exp(-0.5*we*(r-r0)**2)
plt.plot(r, g(r), ':')
#plt.axis([0, 4.6, 0.0, 0.025])
plt.xlabel(r'$\rho$')
plt.ylabel(r'$u(\rho)$')
max_r = np.max(r)
print omega
#omega = np.max(errors)
plt.suptitle(r'Normalized energy for the three lowest states interactive case.') #as a function of various omega_r
plt.title(r'$\rho$ = {0:2.1f}, n={1}, omega={2:2.1g}'.format(
max_r, len(r), omega))
plt.savefig('eigenvector_rho{0}n{1}omega{2}.png'.format(int(max_r * 10), len(r),int(omega*100)))
def solve_schroedinger_jacobi(n=160, rho_max=5, potential=None):
if potential is None:
potential = lambda r: r**2
#n = 128*4
#n = 160
rho_min = 0
#rho_max = 5
h = (rho_max - rho_min) / (n + 1) # step_length
rho = np.arange(1, n + 1) * h
vi = potential(rho)
rho = rho
e = -np.ones(n - 1) / h**2
d = 2 / h**2 + vi # di
A = np.diag(d) + np.diag(e, -1) + np.diag(e, +1)
# Solve Schrodingers equation:
eigenvectors, eigenvalues, iterations = jacobi_method(A)
# self.eigenvalues, self.eigenvectors = np.linalg.eig(self.A)
r = rho
permute = eigenvalues.argsort()
eigenvalues = eigenvalues[permute]
eigenvectors = eigenvectors[:, permute]
return r, eigenvectors, eigenvalues, iterations
def test_iterations():
# now plot the results for the three lowest lying eigenstates
num_iterations = []
dims = [8, 16, 32, 64, 128, 256, 320, 512]
if False:
for n in dims:
r, eigenvectors, eigenvalues, iterations = solve_schroedinger_jacobi(
n=n, rho_max=5)
num_iterations.append(iterations)
else:
num_iterations = [80, 374, 1623, 6741, 27070, 109974, 171973, 442946]
step = np.linspace(0, 1.1 * dims[-1], 100)
coeff = np.polyfit(dims, np.array(num_iterations)/np.array(dims), deg=1)
# coeff = np.round(coeff)
coeff = np.hstack((coeff, 0))
print coeff
for plot_type, plot in zip(['linear', 'logy', 'loglog'], [plt.plot, plt.semilogy, plt.loglog]):
plt.figure()
plot(dims, num_iterations, '.', label='Exact number of iterations')
plot(step, np.polyval(coeff, step), '-',
label='{:0.2f}n**2{:0.2f}n'.format(coeff[0], coeff[1]))
# plot(step, 1.7*step**2, '-', label='1.7n^2')
plot(step, 3*step**2-5*step, '-', label='3n^2-5*n')
# plot(step, 1.5*step**2-5*step+10, '-', label='1.5n^2-5*n+10')
plt.xlabel('n')
plt.ylabel('Iterations')
plt.title('Number of similarity transformations')
plt.legend(loc=2)
plt.grid(True)
plt.savefig('num_iterations{0}n{1}{2}.png'.format(dims[-1], len(dims), plot_type))
plt.show()
def test_rho_max_jacobi(): #2b
# now plot the results for the three lowest lying eigenstates
r, eigenvectors, eigenvalues, iterations = solve_schroedinger_jacobi(
n=320, rho_max=5)
errors = []
for i, trueeigenvalue in enumerate([3, 7, 11]):
errors.append(np.abs(eigenvalues[i] - trueeigenvalue))
# print eigenvalues[i] - trueeigenvalue, eigenvalues[i]
FirstEigvector = eigenvectors[:, 0]
SecondEigvector = eigenvectors[:, 1]
ThirdEigvector = eigenvectors[:, 2]
plt.plot(r, FirstEigvector**2, 'b-', r, SecondEigvector **
2, 'g-', r, ThirdEigvector**2, 'r-')
#plt.axis([0, 4.6, 0.0, 0.025])
plt.xlabel(r'$\rho$')
plt.ylabel(r'$u(\rho)$')
max_r = np.max(r)
max_errors = np.max(errors)
plt.suptitle(r'Normalized energy for the three lowest states.')
plt.title(r'$\rho$ = {0:2.1f}, n={1}, max_errors={2:2.1g}'.format(
max_r, len(r), max_errors))
plt.savefig('eigenvector_rho{0}n{1}.png'.format(int(max_r * 10), len(r)))
plt.show()
def solve_schroedinger(Dim=400, RMax=10.0, RMin=0.0, lOrbital=0):
# Get the boundary, orbital momentum and number of integration points
# Program which solves the one-particle Schrodinger equation
# for a potential specified in function
# potential(). This example is for the harmonic oscillator in 3d
# from matplotlib import pyplot as plt
# import numpy as np
# Here we set up the harmonic oscillator potential
def potential(r):
return r * r
# Initialize constants
Step = RMax / (Dim + 1)
DiagConst = 2.0 / (Step * Step)
NondiagConst = -1.0 / (Step * Step)
OrbitalFactor = lOrbital * (lOrbital + 1.0)
# Calculate array of potential values
v = np.zeros(Dim)
r = np.linspace(RMin, RMax, Dim)
for i in xrange(Dim):
r[i] = RMin + (i + 1) * Step
v[i] = potential(r[i]) + OrbitalFactor / (r[i] * r[i])
# Setting up a tridiagonal matrix and finding eigenvectors and eigenvalues
Hamiltonian = np.zeros((Dim, Dim))
Hamiltonian[0, 0] = DiagConst + v[0]
Hamiltonian[0, 1] = NondiagConst
for i in xrange(1, Dim - 1):
Hamiltonian[i, i - 1] = NondiagConst
Hamiltonian[i, i] = DiagConst + v[i]
Hamiltonian[i, i + 1] = NondiagConst
Hamiltonian[Dim - 1, Dim - 2] = NondiagConst
Hamiltonian[Dim - 1, Dim - 1] = DiagConst + v[Dim - 1]
# diagonalize and obtain eigenvalues, not necessarily sorted
EigValues, EigVectors = np.linalg.eig(Hamiltonian)
# sort eigenvectors and eigenvalues
permute = EigValues.argsort()
EigValues = EigValues[permute]
EigVectors = EigVectors[:, permute]
return r, EigVectors, EigValues
def test_rho_max(Dim=400.0, RMax=10.0):
r, EigVectors, EigValues = solve_schroedinger(Dim, RMax)
# now plot the results for the three lowest lying eigenstates
for i in xrange(3):
print EigValues[i]
FirstEigvector = EigVectors[:, 0]
SecondEigvector = EigVectors[:, 1]
ThirdEigvector = EigVectors[:, 2]
plt.plot(r, FirstEigvector**2, 'b-', r, SecondEigvector **
2, 'g-', r, ThirdEigvector**2, 'r-')
plt.axis([0, 4.6, 0.0, 0.025])
plt.xlabel(r'$r$')
plt.ylabel(r'Radial probability $r^2|R(r)|^2$')
plt.title(
r'Radial probability distributions for three lowest-lying states')
plt.savefig('eigenvector.pdf')
plt.show()
def cpu_times_vs_dimension_plot(): #2c
'''Jacobi loeser kvadratisk tid.
Det vil si tiden er bestemt av similaritetstransformasjonen for O(n**2) operasjoner.
Eig loeser egenverdiene i lineaer tid. Det vil si at tiden er bestemt av O(n)
'''
cpu_times = []
cpu_times_jacobi = []
dims = [8, 16, 32, 64, 128]
for n in dims:
cpu_times.append(cpu_time(5, n))
cpu_times_jacobi.append(cpu_time_jacobi(5, n))
plt.plot(dims, cpu_times, label='np.linalg.eig') #
plt.plot(dims, cpu_times_jacobi, label='jacobi')
plt.xlabel('dimension')
plt.ylabel('cpu time')
plt.title('CPU time vs dimension of matrix')
plt.legend(loc=2)
filename = 'cpu_time{0}n{1}.png'.format(dims[-1], len(dims))
my_savefig(filename)
plt.show()
if __name__ == '__main__':
#cpu_times_vs_dimension_plot()
# test_compare()
# solve_poisson_with_lu(10)
# error_test()
# lu_test_compare()
# for n in [10, 100, 1000, 2000]:
# cpu_time_specific(10, n)
# cpu_time(10, n)
# cpu_time_lu_solve(10, n)
#
# plt.show()
# solve_schroedinger()
# test_rho_max_jacobi()
#test_iterations()
for rho_max, omega in zip([60, 10, 6, 3], [0.01, 0.5, 1, 5]):
plt.figure()
print(omega)
test_rho_max_jacobi_interactive_case(omega, rho_max=rho_max, n=128)
#test_rho_max_jacobi_interactive_case(omega=0.01, rho_max=60, n=128)
plt.show() | 32.379902 | 119 | 0.594202 | 185 | 0.014003 | 0 | 0 | 1,677 | 0.12694 | 0 | 0 | 4,401 | 0.333131 |
0d0d282cf5109854c1ac67b2906a8fd2bb27e9ac | 266 | py | Python | L.py | tomerl20-meet/meet2018y1mini-proj | 5c66652b900c50d0b30326170c21e1b1224c649a | [
"MIT"
] | null | null | null | L.py | tomerl20-meet/meet2018y1mini-proj | 5c66652b900c50d0b30326170c21e1b1224c649a | [
"MIT"
] | null | null | null | L.py | tomerl20-meet/meet2018y1mini-proj | 5c66652b900c50d0b30326170c21e1b1224c649a | [
"MIT"
] | null | null | null | import turtle
screen = turtle.Screen()
# this assures that the size of the screen will always be 400x400 ...
screen.setup(400, 400)
# ... which is the same size as our image
# now set the background to our space image
screen.bgpic("game.over")
turtle.mainloop()
| 20.461538 | 69 | 0.729323 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 164 | 0.616541 |
0d0dad0715867923a463d0648e569bd453764be1 | 844 | py | Python | demo.py | PAV-Laboratory/cryptoblotter | f573592a3638fbc6cae24d76305de36b932949c6 | [
"MIT"
] | 1 | 2021-08-01T19:16:02.000Z | 2021-08-01T19:16:02.000Z | demo.py | PAV-Laboratory/cryptoblotter | f573592a3638fbc6cae24d76305de36b932949c6 | [
"MIT"
] | null | null | null | demo.py | PAV-Laboratory/cryptoblotter | f573592a3638fbc6cae24d76305de36b932949c6 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
from cryptofeed import FeedHandler
from cryptofeed.defines import TRADES
from cryptoblotter.exchanges import CoinbaseBlotter
from cryptoblotter.trades import SequentialIntegerTradeCallback, ThreshCallback
from cryptoblotter.trades.constants import VOLUME
async def trades(trade):
print(trade)
if __name__ == "__main__":
fh = FeedHandler()
fh.add_feed(
CoinbaseBlotter(
symbols=["BTC-USD"],
channels=[TRADES],
callbacks={
TRADES: SequentialIntegerTradeCallback(
ThreshCallback(
trades,
thresh_attr=VOLUME,
thresh_value=1000,
window_seconds=60,
)
)
},
)
)
fh.run()
| 24.823529 | 79 | 0.562796 | 0 | 0 | 0 | 0 | 0 | 0 | 41 | 0.048578 | 41 | 0.048578 |
0d0e450b602d94ac05485326e1145ffc9479645d | 29,665 | py | Python | mars/tensor/datasource/tests/test_datasource.py | HarshCasper/mars | 4c12c968414d666c7a10f497bc22de90376b1932 | [
"Apache-2.0"
] | 2 | 2019-03-29T04:11:10.000Z | 2020-07-08T10:19:54.000Z | mars/tensor/datasource/tests/test_datasource.py | HarshCasper/mars | 4c12c968414d666c7a10f497bc22de90376b1932 | [
"Apache-2.0"
] | null | null | null | mars/tensor/datasource/tests/test_datasource.py | HarshCasper/mars | 4c12c968414d666c7a10f497bc22de90376b1932 | [
"Apache-2.0"
] | null | null | null | # Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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
import shutil
import tempfile
from weakref import ReferenceType
from copy import copy
import numpy as np
import scipy.sparse as sps
try:
import tiledb
except (ImportError, OSError): # pragma: no cover
tiledb = None
from mars import dataframe as md
from mars import opcodes
from mars.graph import DAG
from mars.tensor import ones, zeros, tensor, full, arange, diag, linspace, triu, tril, ones_like, dot
from mars.tensor.datasource import array, fromtiledb, TensorTileDBDataSource, fromdense
from mars.tensor.datasource.tri import TensorTriu, TensorTril
from mars.tensor.datasource.zeros import TensorZeros
from mars.tensor.datasource.from_dense import DenseToSparse
from mars.tensor.datasource.array import CSRMatrixDataSource
from mars.tensor.datasource.ones import TensorOnes, TensorOnesLike
from mars.tensor.fuse.core import TensorFuseChunk
from mars.tensor.core import Tensor, SparseTensor, TensorChunk
from mars.tensor.datasource.from_dataframe import from_dataframe
from mars.tests.core import TestBase
from mars.tiles import get_tiled
from mars.utils import build_fuse_chunk, enter_mode
class Test(TestBase):
def testChunkSerialize(self):
t = ones((10, 3), chunk_size=(5, 2)).tiles()
# pb
chunk = t.chunks[0]
serials = self._pb_serial(chunk)
op, pb = serials[chunk.op, chunk.data]
self.assertEqual(tuple(pb.index), chunk.index)
self.assertEqual(pb.key, chunk.key)
self.assertEqual(tuple(pb.shape), chunk.shape)
self.assertEqual(int(op.type.split('.', 1)[1]), opcodes.TENSOR_ONES)
chunk2 = self._pb_deserial(serials)[chunk.data]
self.assertEqual(chunk.index, chunk2.index)
self.assertEqual(chunk.key, chunk2.key)
self.assertEqual(chunk.shape, chunk2.shape)
self.assertEqual(chunk.op.dtype, chunk2.op.dtype)
# json
chunk = t.chunks[0]
serials = self._json_serial(chunk)
chunk2 = self._json_deserial(serials)[chunk.data]
self.assertEqual(chunk.index, chunk2.index)
self.assertEqual(chunk.key, chunk2.key)
self.assertEqual(chunk.shape, chunk2.shape)
self.assertEqual(chunk.op.dtype, chunk2.op.dtype)
t = tensor(np.random.random((10, 3)), chunk_size=(5, 2)).tiles()
# pb
chunk = t.chunks[0]
serials = self._pb_serial(chunk)
op, pb = serials[chunk.op, chunk.data]
self.assertEqual(tuple(pb.index), chunk.index)
self.assertEqual(pb.key, chunk.key)
self.assertEqual(tuple(pb.shape), chunk.shape)
self.assertEqual(int(op.type.split('.', 1)[1]), opcodes.TENSOR_DATA_SOURCE)
chunk2 = self._pb_deserial(serials)[chunk.data]
self.assertEqual(chunk.index, chunk2.index)
self.assertEqual(chunk.key, chunk2.key)
self.assertEqual(chunk.shape, chunk2.shape)
self.assertTrue(np.array_equal(chunk.op.data, chunk2.op.data))
# json
chunk = t.chunks[0]
serials = self._json_serial(chunk)
chunk2 = self._json_deserial(serials)[chunk.data]
self.assertEqual(chunk.index, chunk2.index)
self.assertEqual(chunk.key, chunk2.key)
self.assertEqual(chunk.shape, chunk2.shape)
self.assertTrue(np.array_equal(chunk.op.data, chunk2.op.data))
t1 = tensor(np.random.random((10, 3)), chunk_size=(5, 2))
t2 = (t1 + 1).tiles()
# pb
chunk1 = get_tiled(t1).chunks[0]
chunk2 = t2.chunks[0]
composed_chunk = build_fuse_chunk([chunk1.data, chunk2.data], TensorFuseChunk)
serials = self._pb_serial(composed_chunk)
op, pb = serials[composed_chunk.op, composed_chunk.data]
self.assertEqual(pb.key, composed_chunk.key)
self.assertEqual(int(op.type.split('.', 1)[1]), opcodes.FUSE)
composed_chunk2 = self._pb_deserial(serials)[composed_chunk.data]
self.assertEqual(composed_chunk.key, composed_chunk2.key)
self.assertEqual(type(composed_chunk.op), type(composed_chunk2.op))
self.assertEqual(composed_chunk.composed[0].key,
composed_chunk2.composed[0].key)
self.assertEqual(composed_chunk.composed[-1].key,
composed_chunk2.composed[-1].key)
# json
chunk1 = get_tiled(t1).chunks[0]
chunk2 = t2.chunks[0]
composed_chunk = build_fuse_chunk([chunk1.data, chunk2.data], TensorFuseChunk)
serials = self._json_serial(composed_chunk)
composed_chunk2 = self._json_deserial(serials)[composed_chunk.data]
self.assertEqual(composed_chunk.key, composed_chunk2.key)
self.assertEqual(type(composed_chunk.op), type(composed_chunk2.op))
self.assertEqual(composed_chunk.composed[0].key,
composed_chunk2.composed[0].key)
self.assertEqual(composed_chunk.composed[-1].key,
composed_chunk2.composed[-1].key)
t1 = ones((10, 3), chunk_size=2)
t2 = ones((3, 5), chunk_size=2)
c = dot(t1, t2).tiles().chunks[0].inputs[0]
# pb
serials = self._pb_serial(c)
c2 = self._pb_deserial(serials)[c]
self.assertEqual(c.key, c2.key)
# json
serials = self._json_serial(c)
c2 = self._json_deserial(serials)[c]
self.assertEqual(c.key, c2.key)
def testTensorSerialize(self):
from mars.tensor import split
t = ones((10, 10, 8), chunk_size=(3, 3, 5))
serials = self._pb_serial(t)
dt = self._pb_deserial(serials)[t.data]
self.assertEqual(dt.extra_params.raw_chunk_size, (3, 3, 5))
serials = self._json_serial(t)
dt = self._json_deserial(serials)[t.data]
self.assertEqual(dt.extra_params.raw_chunk_size, (3, 3, 5))
t2, _ = split(t, 2)
serials = self._pb_serial(t2)
dt = self._pb_deserial(serials)[t2.data]
self.assertEqual(dt.op.indices_or_sections, 2)
t2, _, _ = split(t, ones(2, chunk_size=2))
serials = self._pb_serial(t2)
dt = self._pb_deserial(serials)[t2.data]
with enter_mode(build=True):
self.assertIn(dt.op.indices_or_sections, dt.inputs)
def testOnes(self):
tensor = ones((10, 10, 8), chunk_size=(3, 3, 5))
tensor = tensor.tiles()
self.assertEqual(tensor.shape, (10, 10, 8))
self.assertEqual(len(tensor.chunks), 32)
tensor = ones((10, 3), chunk_size=(4, 2))
tensor = tensor.tiles()
self.assertEqual(tensor.shape, (10, 3))
chunk = tensor.cix[1, 1]
self.assertEqual(tensor.get_chunk_slices(chunk.index), (slice(4, 8), slice(2, 3)))
tensor = ones((10, 5), chunk_size=(2, 3), gpu=True)
tensor = tensor.tiles()
self.assertTrue(tensor.op.gpu)
self.assertTrue(tensor.chunks[0].op.gpu)
tensor1 = ones((10, 10, 8), chunk_size=(3, 3, 5))
tensor1 = tensor1.tiles()
tensor2 = ones((10, 10, 8), chunk_size=(3, 3, 5))
tensor2 = tensor2.tiles()
self.assertEqual(tensor1.chunks[0].op.key, tensor2.chunks[0].op.key)
self.assertEqual(tensor1.chunks[0].key, tensor2.chunks[0].key)
self.assertNotEqual(tensor1.chunks[0].op.key, tensor1.chunks[1].op.key)
self.assertNotEqual(tensor1.chunks[0].key, tensor1.chunks[1].key)
tensor = ones((2, 3, 4))
self.assertEqual(len(list(tensor)), 2)
tensor2 = ones((2, 3, 4), chunk_size=1)
# tensor's op key must be equal to tensor2
self.assertEqual(tensor.op.key, tensor2.op.key)
self.assertNotEqual(tensor.key, tensor2.key)
tensor3 = ones((2, 3, 3))
self.assertNotEqual(tensor.op.key, tensor3.op.key)
self.assertNotEqual(tensor.key, tensor3.key)
# test create chunk op of ones manually
chunk_op1 = TensorOnes(dtype=tensor.dtype)
chunk1 = chunk_op1.new_chunk(None, shape=(3, 3), index=(0, 0))
chunk_op2 = TensorOnes(dtype=tensor.dtype)
chunk2 = chunk_op2.new_chunk(None, shape=(3, 4), index=(0, 1))
self.assertNotEqual(chunk1.op.key, chunk2.op.key)
self.assertNotEqual(chunk1.key, chunk2.key)
tensor = ones((100, 100), chunk_size=50)
tensor = tensor.tiles()
self.assertEqual(len({c.op.key for c in tensor.chunks}), 1)
self.assertEqual(len({c.key for c in tensor.chunks}), 1)
def testZeros(self):
tensor = zeros((2, 3, 4))
self.assertEqual(len(list(tensor)), 2)
self.assertFalse(tensor.op.gpu)
tensor2 = zeros((2, 3, 4), chunk_size=1)
# tensor's op key must be equal to tensor2
self.assertEqual(tensor.op.key, tensor2.op.key)
self.assertNotEqual(tensor.key, tensor2.key)
tensor3 = zeros((2, 3, 3))
self.assertNotEqual(tensor.op.key, tensor3.op.key)
self.assertNotEqual(tensor.key, tensor3.key)
# test create chunk op of zeros manually
chunk_op1 = TensorZeros(dtype=tensor.dtype)
chunk1 = chunk_op1.new_chunk(None, shape=(3, 3), index=(0, 0))
chunk_op2 = TensorZeros(dtype=tensor.dtype)
chunk2 = chunk_op2.new_chunk(None, shape=(3, 4), index=(0, 1))
self.assertNotEqual(chunk1.op.key, chunk2.op.key)
self.assertNotEqual(chunk1.key, chunk2.key)
tensor = zeros((100, 100), chunk_size=50)
tensor = tensor.tiles()
self.assertEqual(len({c.op.key for c in tensor.chunks}), 1)
self.assertEqual(len({c.key for c in tensor.chunks}), 1)
def testDataSource(self):
from mars.tensor.base.broadcast_to import TensorBroadcastTo
data = np.random.random((10, 3))
t = tensor(data, chunk_size=2)
self.assertFalse(t.op.gpu)
t = t.tiles()
self.assertTrue((t.chunks[0].op.data == data[:2, :2]).all())
self.assertTrue((t.chunks[1].op.data == data[:2, 2:3]).all())
self.assertTrue((t.chunks[2].op.data == data[2:4, :2]).all())
self.assertTrue((t.chunks[3].op.data == data[2:4, 2:3]).all())
self.assertEqual(t.key, tensor(data, chunk_size=2).tiles().key)
self.assertNotEqual(t.key, tensor(data, chunk_size=3).tiles().key)
self.assertNotEqual(t.key, tensor(np.random.random((10, 3)), chunk_size=2).tiles().key)
t = tensor(data, chunk_size=2, gpu=True)
t = t.tiles()
self.assertTrue(t.op.gpu)
self.assertTrue(t.chunks[0].op.gpu)
t = full((2, 2), 2, dtype='f4')
self.assertFalse(t.op.gpu)
self.assertEqual(t.shape, (2, 2))
self.assertEqual(t.dtype, np.float32)
t = full((2, 2), [1.0, 2.0], dtype='f4')
self.assertEqual(t.shape, (2, 2))
self.assertEqual(t.dtype, np.float32)
self.assertIsInstance(t.op, TensorBroadcastTo)
with self.assertRaises(ValueError):
full((2, 2), [1.0, 2.0, 3.0], dtype='f4')
def testTensorGraphSerialize(self):
t = ones((10, 3), chunk_size=(5, 2)) + tensor(np.random.random((10, 3)), chunk_size=(5, 2))
graph = t.build_graph(tiled=False)
pb = graph.to_pb()
graph2 = DAG.from_pb(pb)
self.assertEqual(len(graph), len(graph2))
t = next(c for c in graph if c.inputs)
t2 = next(c for c in graph2 if c.key == t.key)
self.assertTrue(t2.op.outputs[0], ReferenceType) # make sure outputs are all weak reference
self.assertBaseEqual(t.op, t2.op)
self.assertEqual(t.shape, t2.shape)
self.assertEqual(sorted(i.key for i in t.inputs), sorted(i.key for i in t2.inputs))
jsn = graph.to_json()
graph2 = DAG.from_json(jsn)
self.assertEqual(len(graph), len(graph2))
t = next(c for c in graph if c.inputs)
t2 = next(c for c in graph2 if c.key == t.key)
self.assertTrue(t2.op.outputs[0], ReferenceType) # make sure outputs are all weak reference
self.assertBaseEqual(t.op, t2.op)
self.assertEqual(t.shape, t2.shape)
self.assertEqual(sorted(i.key for i in t.inputs), sorted(i.key for i in t2.inputs))
# test graph with tiled tensor
t2 = ones((10, 10), chunk_size=(5, 4)).tiles()
graph = DAG()
graph.add_node(t2)
pb = graph.to_pb()
graph2 = DAG.from_pb(pb)
self.assertEqual(len(graph), len(graph2))
chunks = next(iter(graph2)).chunks
self.assertEqual(len(chunks), 6)
self.assertIsInstance(chunks[0], TensorChunk)
self.assertEqual(chunks[0].index, t2.chunks[0].index)
self.assertBaseEqual(chunks[0].op, t2.chunks[0].op)
jsn = graph.to_json()
graph2 = DAG.from_json(jsn)
self.assertEqual(len(graph), len(graph2))
chunks = next(iter(graph2)).chunks
self.assertEqual(len(chunks), 6)
self.assertIsInstance(chunks[0], TensorChunk)
self.assertEqual(chunks[0].index, t2.chunks[0].index)
self.assertBaseEqual(chunks[0].op, t2.chunks[0].op)
def testTensorGraphTiledSerialize(self):
t = ones((10, 3), chunk_size=(5, 2)) + tensor(np.random.random((10, 3)), chunk_size=(5, 2))
graph = t.build_graph(tiled=True)
pb = graph.to_pb()
graph2 = DAG.from_pb(pb)
self.assertEqual(len(graph), len(graph2))
chunk = next(c for c in graph if c.inputs)
chunk2 = next(c for c in graph2 if c.key == chunk.key)
self.assertBaseEqual(chunk.op, chunk2.op)
self.assertEqual(chunk.index, chunk2.index)
self.assertEqual(chunk.shape, chunk2.shape)
self.assertEqual(sorted(i.key for i in chunk.inputs), sorted(i.key for i in chunk2.inputs))
jsn = graph.to_json()
graph2 = DAG.from_json(jsn)
self.assertEqual(len(graph), len(graph2))
chunk = next(c for c in graph if c.inputs)
chunk2 = next(c for c in graph2 if c.key == chunk.key)
self.assertBaseEqual(chunk.op, chunk2.op)
self.assertEqual(chunk.index, chunk2.index)
self.assertEqual(chunk.shape, chunk2.shape)
self.assertEqual(sorted(i.key for i in chunk.inputs), sorted(i.key for i in chunk2.inputs))
t = ones((10, 3), chunk_size=((3, 5, 2), 2)) + 2
graph = t.build_graph(tiled=True)
pb = graph.to_pb()
graph2 = DAG.from_pb(pb)
chunk = next(c for c in graph)
chunk2 = next(c for c in graph2 if c.key == chunk.key)
self.assertBaseEqual(chunk.op, chunk2.op)
self.assertEqual(sorted(i.key for i in chunk.composed), sorted(i.key for i in chunk2.composed))
jsn = graph.to_json()
graph2 = DAG.from_json(jsn)
chunk = next(c for c in graph)
chunk2 = next(c for c in graph2 if c.key == chunk.key)
self.assertBaseEqual(chunk.op, chunk2.op)
self.assertEqual(sorted(i.key for i in chunk.composed), sorted(i.key for i in chunk2.composed))
def testUfunc(self):
t = ones((3, 10), chunk_size=2)
x = np.add(t, [[1], [2], [3]])
self.assertIsInstance(x, Tensor)
y = np.sum(t, axis=1)
self.assertIsInstance(y, Tensor)
def testArange(self):
t = arange(10, chunk_size=3)
self.assertFalse(t.op.gpu)
t = t.tiles()
self.assertEqual(t.shape, (10,))
self.assertEqual(t.nsplits, ((3, 3, 3, 1),))
self.assertEqual(t.chunks[1].op.start, 3)
self.assertEqual(t.chunks[1].op.stop, 6)
t = arange(0, 10, 3, chunk_size=2)
t = t.tiles()
self.assertEqual(t.shape, (4,))
self.assertEqual(t.nsplits, ((2, 2),))
self.assertEqual(t.chunks[0].op.start, 0)
self.assertEqual(t.chunks[0].op.stop, 6)
self.assertEqual(t.chunks[0].op.step, 3)
self.assertEqual(t.chunks[1].op.start, 6)
self.assertEqual(t.chunks[1].op.stop, 12)
self.assertEqual(t.chunks[1].op.step, 3)
self.assertRaises(TypeError, lambda: arange(10, start=0))
self.assertRaises(TypeError, lambda: arange(0, 10, stop=0))
self.assertRaises(TypeError, lambda: arange())
self.assertRaises(ValueError, lambda: arange('1066-10-13', dtype=np.datetime64, chunks=3))
def testDiag(self):
# test 2-d, shape[0] == shape[1], k == 0
v = tensor(np.arange(16).reshape(4, 4), chunk_size=2)
t = diag(v)
self.assertEqual(t.shape, (4,))
self.assertFalse(t.op.gpu)
t = t.tiles()
self.assertEqual(t.nsplits, ((2, 2),))
v = tensor(np.arange(16).reshape(4, 4), chunk_size=(2, 3))
t = diag(v)
self.assertEqual(t.shape, (4,))
t = t.tiles()
self.assertEqual(t.nsplits, ((2, 1, 1),))
# test 1-d, k == 0
v = tensor(np.arange(3), chunk_size=2)
t = diag(v, sparse=True)
self.assertEqual(t.shape, (3, 3))
t = t.tiles()
self.assertEqual(t.nsplits, ((2, 1), (2, 1)))
self.assertEqual(len([c for c in t.chunks
if c.op.__class__.__name__ == 'TensorDiag']), 2)
self.assertTrue(t.chunks[0].op.sparse)
# test 2-d, shape[0] != shape[1]
v = tensor(np.arange(24).reshape(4, 6), chunk_size=2)
t = diag(v)
self.assertEqual(t.shape, np.diag(np.arange(24).reshape(4, 6)).shape)
t = t.tiles()
self.assertEqual(tuple(sum(s) for s in t.nsplits), t.shape)
v = tensor(np.arange(24).reshape(4, 6), chunk_size=2)
t = diag(v, k=1)
self.assertEqual(t.shape, np.diag(np.arange(24).reshape(4, 6), k=1).shape)
t = t.tiles()
self.assertEqual(tuple(sum(s) for s in t.nsplits), t.shape)
t = diag(v, k=2)
self.assertEqual(t.shape, np.diag(np.arange(24).reshape(4, 6), k=2).shape)
t = t.tiles()
self.assertEqual(tuple(sum(s) for s in t.nsplits), t.shape)
t = diag(v, k=-1)
self.assertEqual(t.shape, np.diag(np.arange(24).reshape(4, 6), k=-1).shape)
t = t.tiles()
self.assertEqual(tuple(sum(s) for s in t.nsplits), t.shape)
t = diag(v, k=-2)
self.assertEqual(t.shape, np.diag(np.arange(24).reshape(4, 6), k=-2).shape)
t = t.tiles()
self.assertEqual(tuple(sum(s) for s in t.nsplits), t.shape)
# test tiled zeros' keys
a = arange(5, chunk_size=2)
t = diag(a)
t = t.tiles()
# 1 and 2 of t.chunks is ones, they have different shapes
self.assertNotEqual(t.chunks[1].op.key, t.chunks[2].op.key)
def testLinspace(self):
a = linspace(2.0, 3.0, num=5, chunk_size=2)
self.assertEqual(a.shape, (5,))
a = a.tiles()
self.assertEqual(a.nsplits, ((2, 2, 1),))
self.assertEqual(a.chunks[0].op.start, 2.)
self.assertEqual(a.chunks[0].op.stop, 2.25)
self.assertEqual(a.chunks[1].op.start, 2.5)
self.assertEqual(a.chunks[1].op.stop, 2.75)
self.assertEqual(a.chunks[2].op.start, 3.)
self.assertEqual(a.chunks[2].op.stop, 3.)
a = linspace(2.0, 3.0, num=5, endpoint=False, chunk_size=2)
self.assertEqual(a.shape, (5,))
a = a.tiles()
self.assertEqual(a.nsplits, ((2, 2, 1),))
self.assertEqual(a.chunks[0].op.start, 2.)
self.assertEqual(a.chunks[0].op.stop, 2.2)
self.assertEqual(a.chunks[1].op.start, 2.4)
self.assertEqual(a.chunks[1].op.stop, 2.6)
self.assertEqual(a.chunks[2].op.start, 2.8)
self.assertEqual(a.chunks[2].op.stop, 2.8)
_, step = linspace(2.0, 3.0, num=5, chunk_size=2, retstep=True)
self.assertEqual(step, .25)
def testTriuTril(self):
a_data = np.arange(12).reshape(4, 3)
a = tensor(a_data, chunk_size=2)
t = triu(a)
self.assertFalse(t.op.gpu)
t = t.tiles()
self.assertEqual(len(t.chunks), 4)
self.assertIsInstance(t.chunks[0].op, TensorTriu)
self.assertIsInstance(t.chunks[1].op, TensorTriu)
self.assertIsInstance(t.chunks[2].op, TensorZeros)
self.assertIsInstance(t.chunks[3].op, TensorTriu)
t = triu(a, k=1)
t = t.tiles()
self.assertEqual(len(t.chunks), 4)
self.assertIsInstance(t.chunks[0].op, TensorTriu)
self.assertIsInstance(t.chunks[1].op, TensorTriu)
self.assertIsInstance(t.chunks[2].op, TensorZeros)
self.assertIsInstance(t.chunks[3].op, TensorZeros)
t = triu(a, k=2)
t = t.tiles()
self.assertEqual(len(t.chunks), 4)
self.assertIsInstance(t.chunks[0].op, TensorZeros)
self.assertIsInstance(t.chunks[1].op, TensorTriu)
self.assertIsInstance(t.chunks[2].op, TensorZeros)
self.assertIsInstance(t.chunks[3].op, TensorZeros)
t = triu(a, k=-1)
t = t.tiles()
self.assertEqual(len(t.chunks), 4)
self.assertIsInstance(t.chunks[0].op, TensorTriu)
self.assertIsInstance(t.chunks[1].op, TensorTriu)
self.assertIsInstance(t.chunks[2].op, TensorTriu)
self.assertIsInstance(t.chunks[3].op, TensorTriu)
t = tril(a)
self.assertFalse(t.op.gpu)
t = t.tiles()
self.assertEqual(len(t.chunks), 4)
self.assertIsInstance(t.chunks[0].op, TensorTril)
self.assertIsInstance(t.chunks[1].op, TensorZeros)
self.assertIsInstance(t.chunks[2].op, TensorTril)
self.assertIsInstance(t.chunks[3].op, TensorTril)
t = tril(a, k=1)
t = t.tiles()
self.assertEqual(len(t.chunks), 4)
self.assertIsInstance(t.chunks[0].op, TensorTril)
self.assertIsInstance(t.chunks[1].op, TensorTril)
self.assertIsInstance(t.chunks[2].op, TensorTril)
self.assertIsInstance(t.chunks[3].op, TensorTril)
t = tril(a, k=-1)
t = t.tiles()
self.assertEqual(len(t.chunks), 4)
self.assertIsInstance(t.chunks[0].op, TensorTril)
self.assertIsInstance(t.chunks[1].op, TensorZeros)
self.assertIsInstance(t.chunks[2].op, TensorTril)
self.assertIsInstance(t.chunks[3].op, TensorTril)
t = tril(a, k=-2)
t = t.tiles()
self.assertEqual(len(t.chunks), 4)
self.assertIsInstance(t.chunks[0].op, TensorZeros)
self.assertIsInstance(t.chunks[1].op, TensorZeros)
self.assertIsInstance(t.chunks[2].op, TensorTril)
self.assertIsInstance(t.chunks[3].op, TensorZeros)
def testSetTensorInputs(self):
t1 = tensor([1, 2], chunk_size=2)
t2 = tensor([2, 3], chunk_size=2)
t3 = t1 + t2
t1c = copy(t1)
t2c = copy(t2)
self.assertIsNot(t1c, t1)
self.assertIsNot(t2c, t2)
self.assertIs(t3.op.lhs, t1.data)
self.assertIs(t3.op.rhs, t2.data)
self.assertEqual(t3.op.inputs, [t1.data, t2.data])
self.assertEqual(t3.inputs, [t1.data, t2.data])
with self.assertRaises(StopIteration):
t3.inputs = []
t1 = tensor([1, 2], chunk_size=2)
t2 = tensor([True, False], chunk_size=2)
t3 = t1[t2]
t1c = copy(t1)
t2c = copy(t2)
t3c = copy(t3)
t3c.inputs = [t1c, t2c]
with enter_mode(build=True):
self.assertIs(t3c.op.input, t1c.data)
self.assertIs(t3c.op.indexes[0], t2c.data)
def testFromSpmatrix(self):
t = tensor(sps.csr_matrix([[0, 0, 1], [1, 0, 0]], dtype='f8'), chunk_size=2)
self.assertIsInstance(t, SparseTensor)
self.assertIsInstance(t.op, CSRMatrixDataSource)
self.assertTrue(t.issparse())
self.assertFalse(t.op.gpu)
t = t.tiles()
self.assertEqual(t.chunks[0].index, (0, 0))
self.assertIsInstance(t.op, CSRMatrixDataSource)
self.assertFalse(t.op.gpu)
m = sps.csr_matrix([[0, 0], [1, 0]])
self.assertTrue(np.array_equal(t.chunks[0].op.indices, m.indices))
self.assertTrue(np.array_equal(t.chunks[0].op.indptr, m.indptr))
self.assertTrue(np.array_equal(t.chunks[0].op.data, m.data))
self.assertTrue(np.array_equal(t.chunks[0].op.shape, m.shape))
def testFromDense(self):
t = fromdense(tensor([[0, 0, 1], [1, 0, 0]], chunk_size=2))
self.assertIsInstance(t, SparseTensor)
self.assertIsInstance(t.op, DenseToSparse)
self.assertTrue(t.issparse())
t = t.tiles()
self.assertEqual(t.chunks[0].index, (0, 0))
self.assertIsInstance(t.op, DenseToSparse)
def testOnesLike(self):
t1 = tensor([[0, 0, 1], [1, 0, 0]], chunk_size=2).tosparse()
t = ones_like(t1, dtype='f8')
self.assertIsInstance(t, SparseTensor)
self.assertIsInstance(t.op, TensorOnesLike)
self.assertTrue(t.issparse())
self.assertFalse(t.op.gpu)
t = t.tiles()
self.assertEqual(t.chunks[0].index, (0, 0))
self.assertIsInstance(t.op, TensorOnesLike)
self.assertTrue(t.chunks[0].issparse())
def testFromArray(self):
x = array([1, 2, 3])
self.assertEqual(x.shape, (3,))
y = array([x, x])
self.assertEqual(y.shape, (2, 3))
z = array((x, x, x))
self.assertEqual(z.shape, (3, 3))
@unittest.skipIf(tiledb is None, 'TileDB not installed')
def testFromTileDB(self):
ctx = tiledb.Ctx()
for sparse in (True, False):
dom = tiledb.Domain(
tiledb.Dim(ctx=ctx, name="i", domain=(1, 30), tile=7, dtype=np.int32),
tiledb.Dim(ctx=ctx, name="j", domain=(1, 20), tile=3, dtype=np.int32),
tiledb.Dim(ctx=ctx, name="k", domain=(1, 10), tile=4, dtype=np.int32),
ctx=ctx,
)
schema = tiledb.ArraySchema(ctx=ctx, domain=dom, sparse=sparse,
attrs=[tiledb.Attr(ctx=ctx, name='a', dtype=np.float32)])
tempdir = tempfile.mkdtemp()
try:
# create tiledb array
array_type = tiledb.DenseArray if not sparse else tiledb.SparseArray
array_type.create(tempdir, schema)
tensor = fromtiledb(tempdir)
self.assertIsInstance(tensor.op, TensorTileDBDataSource)
self.assertEqual(tensor.op.issparse(), sparse)
self.assertEqual(tensor.shape, (30, 20, 10))
self.assertEqual(tensor.extra_params.raw_chunk_size, (7, 3, 4))
self.assertIsNone(tensor.op.tiledb_config)
self.assertEqual(tensor.op.tiledb_uri, tempdir)
self.assertIsNone(tensor.op.tiledb_key)
self.assertIsNone(tensor.op.tiledb_timestamp)
tensor = tensor.tiles()
self.assertEqual(len(tensor.chunks), 105)
self.assertIsInstance(tensor.chunks[0].op, TensorTileDBDataSource)
self.assertEqual(tensor.chunks[0].op.issparse(), sparse)
self.assertEqual(tensor.chunks[0].shape, (7, 3, 4))
self.assertIsNone(tensor.chunks[0].op.tiledb_config)
self.assertEqual(tensor.chunks[0].op.tiledb_uri, tempdir)
self.assertIsNone(tensor.chunks[0].op.tiledb_key)
self.assertIsNone(tensor.chunks[0].op.tiledb_timestamp)
self.assertEqual(tensor.chunks[0].op.tiledb_dim_starts, (1, 1, 1))
# test axis_offsets of chunk op
self.assertEqual(tensor.chunks[0].op.axis_offsets, (0, 0, 0))
self.assertEqual(tensor.chunks[1].op.axis_offsets, (0, 0, 4))
self.assertEqual(tensor.cix[0, 2, 2].op.axis_offsets, (0, 6, 8))
self.assertEqual(tensor.cix[0, 6, 2].op.axis_offsets, (0, 18, 8))
self.assertEqual(tensor.cix[4, 6, 2].op.axis_offsets, (28, 18, 8))
tensor2 = fromtiledb(tempdir, ctx=ctx)
self.assertEqual(tensor2.op.tiledb_config, ctx.config().dict())
tensor2 = tensor2.tiles()
self.assertEqual(tensor2.chunks[0].op.tiledb_config, ctx.config().dict())
finally:
shutil.rmtree(tempdir)
@unittest.skipIf(tiledb is None, 'TileDB not installed')
def testDimStartFloat(self):
ctx = tiledb.Ctx()
dom = tiledb.Domain(
tiledb.Dim(ctx=ctx, name="i", domain=(0.0, 6.0), tile=6, dtype=np.float64),
ctx=ctx,
)
schema = tiledb.ArraySchema(ctx=ctx, domain=dom, sparse=True,
attrs=[tiledb.Attr(ctx=ctx, name='a', dtype=np.float32)])
tempdir = tempfile.mkdtemp()
try:
# create tiledb array
tiledb.SparseArray.create(tempdir, schema)
with self.assertRaises(ValueError):
fromtiledb(tempdir, ctx=ctx)
finally:
shutil.rmtree(tempdir)
def testFromDataFrame(self):
mdf = md.DataFrame({'a': [0, 1, 2], 'b': [3, 4, 5],
'c': [0.1, 0.2, 0.3]}, index=['c', 'd', 'e'], chunk_size=2)
tensor = from_dataframe(mdf)
self.assertEqual(tensor.shape, (3, 3))
self.assertEqual(np.float64, tensor.dtype)
| 38.228093 | 103 | 0.607821 | 27,945 | 0.942019 | 0 | 0 | 3,639 | 0.12267 | 0 | 0 | 1,295 | 0.043654 |
0d0f8d40c6da19e8a82a8164266b4e9bf0bbd18d | 1,259 | py | Python | setup.py | n1k0r/tplink-wr-api | 7f4e29b4b08cf6564b06d9bc3381ab5682afd83f | [
"MIT"
] | 5 | 2021-11-02T13:13:10.000Z | 2021-12-14T14:13:28.000Z | setup.py | n1k0r/tplink-wr-api | 7f4e29b4b08cf6564b06d9bc3381ab5682afd83f | [
"MIT"
] | null | null | null | setup.py | n1k0r/tplink-wr-api | 7f4e29b4b08cf6564b06d9bc3381ab5682afd83f | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from setuptools import find_packages, setup
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setup(
name="tplink-wr-api",
version="0.2.1",
url="https://github.com/n1k0r/tplink-wr-api",
author="n1k0r",
author_email="me@n1k0r.me",
description="API to some budget TP-Link routers",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Intended Audience :: Telecommunications Industry",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Communications",
"Topic :: Software Development :: Libraries",
"Topic :: System :: Networking",
],
packages=find_packages(exclude=["tests", "tests.*"]),
python_requires=">=3.8",
install_requires=[
"requests~=2.26",
],
)
| 32.282051 | 59 | 0.619539 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 706 | 0.560763 |
0d10a5908b7fb6316071dd7f27f26e87d1e2419d | 5,835 | py | Python | examples/qp2q/preprocessing/session_data_processing.py | xeisberg/pecos | c9cf209676205dd000479861667351e724f0ba1c | [
"Apache-2.0"
] | 288 | 2021-04-26T21:34:12.000Z | 2022-03-29T19:50:06.000Z | examples/qp2q/preprocessing/session_data_processing.py | xeisberg/pecos | c9cf209676205dd000479861667351e724f0ba1c | [
"Apache-2.0"
] | 32 | 2021-04-29T23:58:23.000Z | 2022-03-28T17:23:04.000Z | examples/qp2q/preprocessing/session_data_processing.py | xeisberg/pecos | c9cf209676205dd000479861667351e724f0ba1c | [
"Apache-2.0"
] | 63 | 2021-04-28T20:12:59.000Z | 2022-03-29T14:10:36.000Z | """The module contains functions to preprocess input
datasets into usable format."""
import gc
import gzip
import json
import logging
import multiprocessing as mp
import pathlib
import sys
from itertools import repeat
import numpy as np
import scipy.sparse as smat
logging.basicConfig(
stream=sys.stdout,
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
_FUNC = None # place holder to Pool functions.
def _worker_init(func):
"init method to invoke Pool."
global _FUNC
_FUNC = func
def _worker(x):
"init function to invoke pool"
return _FUNC(x)
def open_file_helper(filename, compressed, mode="rt"):
"""
Supports reading of gzip compressed or uncompressed file.
Parameters:
----------
filename : str
Name of the file to open.
compressed : bool
If true, treat filename as gzip compressed.
mode : str
Reading mode.
Returns:
--------
file handle to the opened file.
"""
return gzip.open(filename, mode=mode) if compressed else open(filename, mode)
def _get_unique_rows_cols(filename, compressed, delim="<@@>"):
"""Function to load a json file in the format of processed session-data
for qp2q. Then it returns dictionary of query<delim>prefix as r2i and next_query
as c2i.
"""
r2i = {}
c2i = {}
logger.info("Processing file for rows and columns: {}".format(filename))
with open_file_helper(filename, compressed) as fp:
for line in fp:
try:
pline = json.loads(line)
except json.decoder.JSONDecodeError:
logger.warn(f"Failed to parse: {line}")
continue
query_prefix = delim.join([pline["prev_query"], pline["prefix"]])
kw = pline["next_query"]
if query_prefix not in r2i:
r2i[query_prefix] = 1
if kw not in c2i:
c2i[kw] = 1
return r2i, c2i
def _transform_file_to_matrix_qp2q(filename, compressed, delim, g_r2i, g_c2i):
"""
Helper Function to extract qp2q matrix from input_file which was generated
as a output of the function parallel_process_session_data_qp2p.
Parameters:
----------
input_file: filename
full filepath of input dataframe
compressed: bool
compressed or not
delim: str
delim separating query and prefix
g_r2i: dictionary
mapping for input items
g_c2i: dictionary
mapping of output item
Returns:
-------
qp2q count matrix
"""
rows = []
cols = []
data = []
logger.info("Processing file for matrix: {}".format(filename))
with open_file_helper(filename, compressed) as fp:
for line in fp:
try:
pline = json.loads(line)
except json.decoder.JSONDecodeError:
logger.warn(f"Failed to parse: {line}")
continue
query_prefix = delim.join([pline["prev_query"], pline["prefix"]])
kw = pline["next_query"]
freq = 1
data.append(freq)
rows.append(g_r2i[query_prefix])
cols.append(g_c2i[kw])
matrix = smat.coo_matrix((data, (rows, cols)), shape=(len(g_r2i), len(g_c2i)), dtype=np.float32)
return matrix
def parallel_get_qp2q_sparse_data(fdir, compressed, delim="<@@>", n_jobs=4):
"""Process session data to sparse matrix and dictionaries mapping rows and columns.
Parameters:
----------
fdir: str
path to directory having all the files in json format
compressed: bool
files being compressed or not
delim: str
delimiter between query and prefix
n_jobs: int
number of threads to be used
Returns:
-------
dictionary mapping row index to row names
dictionary mapping col index to col names
qp2q sparse csr matrix containing freq. of occurences.
"""
if compressed:
extension = "*.gz"
else:
extension = "*.json"
if pathlib.Path(fdir).is_dir():
files = pathlib.Path(fdir).glob(extension)
else:
raise ValueError(f"{fdir} is not a valid directory")
files = [str(f) for f in files]
logger.info("Getting qp2q unique rows and columns from files in {}".format(fdir))
if n_jobs > 1:
with mp.Pool(processes=n_jobs) as pool:
dicts = pool.starmap(
_get_unique_rows_cols,
zip(files, repeat(compressed), repeat(delim)),
)
else:
dicts = [_get_unique_rows_cols(file, compressed, delim) for file in files]
g_r2i = {}
g_c2i = {}
for dic in dicts:
g_r2i.update(dic[0])
g_c2i.update(dic[1])
g_i2r = {}
g_i2c = {}
for i, k in enumerate(g_r2i.keys()):
g_r2i[k] = i
g_i2r[i] = k
for i, k in enumerate(g_c2i.keys()):
g_c2i[k] = i
g_i2c[i] = k
del dicts
gc.collect()
logger.info("Number of unique rows: {}".format(len(g_r2i)))
logger.info("Number of unique cols: {}".format(len(g_c2i)))
if n_jobs > 1:
with mp.Pool(
processes=n_jobs,
initializer=_worker_init,
initargs=(
lambda x: _transform_file_to_matrix_qp2q(x, compressed, delim, g_r2i, g_c2i),
),
) as pool:
matrices = pool.map(_worker, files)
else:
matrices = [
_transform_file_to_matrix_qp2q(x, compressed, delim, g_r2i, g_c2i) for x in files
]
matrices = [m.tocsr() for m in matrices]
qp2q_matrix = matrices[0]
for i in range(1, len(matrices)):
qp2q_matrix += matrices[i]
del matrices
gc.collect()
return g_i2r, g_i2c, qp2q_matrix
| 28.188406 | 100 | 0.605484 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,181 | 0.373779 |
0d10c86dafeed929c1872fcc51e0ca638cea38e6 | 1,585 | py | Python | tests/test_policyengine_deviceManager.py | Brewgarten/c4-policy-engine | 4f39f21448952a994d0cbb24f2d02e622fbaa320 | [
"MIT"
] | null | null | null | tests/test_policyengine_deviceManager.py | Brewgarten/c4-policy-engine | 4f39f21448952a994d0cbb24f2d02e622fbaa320 | [
"MIT"
] | 1 | 2017-10-16T16:04:07.000Z | 2017-10-16T16:04:07.000Z | tests/test_policyengine_deviceManager.py | Brewgarten/c4-policy-engine | 4f39f21448952a994d0cbb24f2d02e622fbaa320 | [
"MIT"
] | null | null | null | import logging
import pytest
from c4.devices.policyengine import PolicyEngineManager
from c4.messaging import Router, RouterClient
from c4.system.configuration import States, Roles
from c4.system.deviceManager import DeviceManager
from c4.system.messages import (LocalStartDeviceManager, LocalStopDeviceManager,
Status)
log = logging.getLogger(__name__)
pytestmark = pytest.mark.usefixtures("temporaryIPCPath")
@pytest.fixture
def systemManagerClusterInfo(backend):
return backend.ClusterInfo("test", "ipc://test.ipc", "ipc://test.ipc", Roles.ACTIVE, States.RUNNING)
class TestPolicyEngineManager(object):
def test_getOperations(self):
operations = PolicyEngineManager.getOperations()
assert {"setPolicies", "start", "stop"} == set(operations.keys())
def test_status(self, systemManagerClusterInfo):
router = Router("test") # @UnusedVariable
deviceManager = DeviceManager(systemManagerClusterInfo, "policyengine", PolicyEngineManager)
assert deviceManager.start()
client = RouterClient("test/policyengine")
startResponse = client.sendRequest(LocalStartDeviceManager("test", "test/policyengine"))
statuses = []
for _ in range(3):
statuses.append(client.sendRequest(Status("test/policyengine")))
stopResponse = client.sendRequest(LocalStopDeviceManager("test", "test/policyengine"))
assert deviceManager.stop()
assert startResponse["state"] == States.RUNNING
assert stopResponse["state"] == States.REGISTERED
| 33.020833 | 104 | 0.719874 | 974 | 0.614511 | 0 | 0 | 159 | 0.100315 | 0 | 0 | 221 | 0.139432 |
0d13f252a44ac30eabb61fd5ab7b47904eed9525 | 3,113 | py | Python | astropy/wcs/tests/test_tabprm.py | MatiasRepetto/astropy | 689f9d3b063145150149e592a879ee40af1fac06 | [
"BSD-3-Clause"
] | 4 | 2021-03-25T15:49:56.000Z | 2021-12-15T09:10:04.000Z | astropy/wcs/tests/test_tabprm.py | MatiasRepetto/astropy | 689f9d3b063145150149e592a879ee40af1fac06 | [
"BSD-3-Clause"
] | 20 | 2021-05-03T18:02:23.000Z | 2022-03-12T12:01:04.000Z | astropy/wcs/tests/test_tabprm.py | MatiasRepetto/astropy | 689f9d3b063145150149e592a879ee40af1fac06 | [
"BSD-3-Clause"
] | 3 | 2021-03-28T16:13:00.000Z | 2021-07-16T10:27:25.000Z | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from copy import deepcopy
import pytest
import numpy as np
from astropy import wcs
from . helper import SimModelTAB
def test_wcsprm_tab_basic(tab_wcs_2di):
assert len(tab_wcs_2di.wcs.tab) == 1
t = tab_wcs_2di.wcs.tab[0]
assert tab_wcs_2di.wcs.tab[0] is not t
def test_tabprm_coord(tab_wcs_2di_f):
t = tab_wcs_2di_f.wcs.tab[0]
c0 = t.coord
c1 = np.ones_like(c0)
t.coord = c1
assert np.allclose(tab_wcs_2di_f.wcs.tab[0].coord, c1)
def test_tabprm_crval_and_deepcopy(tab_wcs_2di_f):
w = deepcopy(tab_wcs_2di_f)
t = tab_wcs_2di_f.wcs.tab[0]
pix = np.array([[2, 3]], dtype=np.float32)
rd1 = tab_wcs_2di_f.wcs_pix2world(pix, 1)
c = t.crval.copy()
d = 0.5 * np.ones_like(c)
t.crval += d
assert np.allclose(tab_wcs_2di_f.wcs.tab[0].crval, c + d)
rd2 = tab_wcs_2di_f.wcs_pix2world(pix - d, 1)
assert np.allclose(rd1, rd2)
rd3 = w.wcs_pix2world(pix, 1)
assert np.allclose(rd1, rd3)
def test_tabprm_delta(tab_wcs_2di):
t = tab_wcs_2di.wcs.tab[0]
assert np.allclose([0.0, 0.0], t.delta)
def test_tabprm_K(tab_wcs_2di):
t = tab_wcs_2di.wcs.tab[0]
assert np.all(t.K == [4, 2])
def test_tabprm_M(tab_wcs_2di):
t = tab_wcs_2di.wcs.tab[0]
assert t.M == 2
def test_tabprm_nc(tab_wcs_2di):
t = tab_wcs_2di.wcs.tab[0]
assert t.nc == 8
def test_tabprm_extrema(tab_wcs_2di):
t = tab_wcs_2di.wcs.tab[0]
extrema = np.array(
[[[-0.0026, -0.5], [1.001, -0.5]],
[[-0.0026, 0.5], [1.001, 0.5]]]
)
assert np.allclose(t.extrema, extrema)
def test_tabprm_map(tab_wcs_2di_f):
t = tab_wcs_2di_f.wcs.tab[0]
assert np.allclose(t.map, [0, 1])
t.map[1] = 5
assert np.all(tab_wcs_2di_f.wcs.tab[0].map == [0, 5])
t.map = [1, 4]
assert np.all(tab_wcs_2di_f.wcs.tab[0].map == [1, 4])
def test_tabprm_sense(tab_wcs_2di):
t = tab_wcs_2di.wcs.tab[0]
assert np.all(t.sense == [1, 1])
def test_tabprm_p0(tab_wcs_2di):
t = tab_wcs_2di.wcs.tab[0]
assert np.all(t.p0 == [0, 0])
def test_tabprm_print(tab_wcs_2di_f, capfd):
tab_wcs_2di_f.wcs.tab[0].print_contents()
captured = capfd.readouterr()
s = str(tab_wcs_2di_f.wcs.tab[0])
out = str(captured.out)
lout= out.split('\n')
assert out == s
assert lout[0] == ' flag: 137'
assert lout[1] == ' M: 2'
def test_wcstab_copy(tab_wcs_2di_f):
t = tab_wcs_2di_f.wcs.tab[0]
c0 = t.coord
c1 = np.ones_like(c0)
t.coord = c1
assert np.allclose(tab_wcs_2di_f.wcs.tab[0].coord, c1)
def test_tabprm_crval(tab_wcs_2di_f):
w = deepcopy(tab_wcs_2di_f)
t = tab_wcs_2di_f.wcs.tab[0]
pix = np.array([[2, 3]], dtype=np.float32)
rd1 = tab_wcs_2di_f.wcs_pix2world(pix, 1)
c = t.crval.copy()
d = 0.5 * np.ones_like(c)
t.crval += d
assert np.allclose(tab_wcs_2di_f.wcs.tab[0].crval, c + d)
rd2 = tab_wcs_2di_f.wcs_pix2world(pix - d, 1)
assert np.allclose(rd1, rd2)
rd3 = w.wcs_pix2world(pix, 1)
assert np.allclose(rd1, rd3)
| 22.395683 | 63 | 0.641182 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 101 | 0.032445 |
0d150ae27d6a08f38d400e708a1891dd25859e78 | 11,560 | py | Python | services/dts/tests/unit/test_physical_appliance.py | honzajavorek/oci-cli | 6ea058afba323c6b3b70e98212ffaebb0d31985e | [
"Apache-2.0"
] | null | null | null | services/dts/tests/unit/test_physical_appliance.py | honzajavorek/oci-cli | 6ea058afba323c6b3b70e98212ffaebb0d31985e | [
"Apache-2.0"
] | null | null | null | services/dts/tests/unit/test_physical_appliance.py | honzajavorek/oci-cli | 6ea058afba323c6b3b70e98212ffaebb0d31985e | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
import os
import random
import shutil
import string
import tempfile
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from OpenSSL import crypto
from services.dts.src.oci_cli_dts.appliance_auth_manager import ApplianceAuthManager
from services.dts.src.oci_cli_dts.appliance_cert_manager import ApplianceCertManager
from services.dts.src.oci_cli_dts.appliance_config_manager import ApplianceConfigManager
from services.dts.src.oci_cli_dts.appliance_config_spec import ApplianceConfigSpec
from services.dts.src.oci_cli_dts.appliance_constants import APPLIANCE_CERT_FILE_NAME
from oci import exceptions
APPLIANCE_CONFIG_FOLDER = "appliance_config_test"
CERT_FINGERPRINT = "AB:CD:EF:GH"
class AuthSpec:
def __init__(self, config_spec, config_manager):
self.appliance_config_spec = config_spec
self.appliance_config_manager = config_manager
class PhysicalApplianceTest(unittest.TestCase):
def setUp(self):
"""
Create a temporary folder and use this folder as the path to create all the configs
:return:
"""
self.test_dir = tempfile.mkdtemp()
self.cert_manager = mock.Mock()
def tearDown(self):
"""
Deletes the temporary folder where all the configs have been created
:return:
"""
shutil.rmtree(self.test_dir)
def _get_auth_manager(self, auth_spec, cert_fingerprint=CERT_FINGERPRINT):
return ApplianceAuthManager(auth_spec.appliance_config_spec, cert_fingerprint,
auth_spec.appliance_config_manager, self.cert_manager)
@staticmethod
def _validate_init_auth(auth_spec):
config_spec = auth_spec.appliance_config_spec
assert os.path.exists(auth_spec.appliance_config_manager.get_base_dir())
assert os.path.exists(auth_spec.appliance_config_manager.get_config_dir(config_spec.get_profile()))
appliance_config = auth_spec.appliance_config_manager.get_config(config_spec.get_profile())
if config_spec.get_endpoint()[1] == 443:
appliance_url = "https://{}".format(config_spec.get_endpoint()[0])
else:
appliance_url = "https://{}:{}".format(config_spec.get_endpoint()[0], config_spec.get_endpoint()[1])
assert appliance_config.get_appliance_url() == appliance_url
assert appliance_config.get_access_token() == config_spec.get_access_token()
assert appliance_config.get_appliance_serial_id() == config_spec.get_serial_id()
def _generate_cert_file(self, auth_spec):
config_manager = self._get_config_manager()
config_manager.create_config_dir(auth_spec.appliance_config_spec.get_profile())
# return self.test_dir + "/{}/{}".format(auth_spec.appliance_config_spec.get_profile(), APPLIANCE_CERT_FILE_NAME)
return "{}/{}".format(
config_manager.get_config_dir(auth_spec.appliance_config_spec.get_profile()), APPLIANCE_CERT_FILE_NAME)
def _test_init_auth(self, auth_spec, validate_cert_manager_calls=True, cert_fingerprint=CERT_FINGERPRINT):
auth_manager = self._get_auth_manager(auth_spec, cert_fingerprint)
auth_manager.initialize_auth()
self._validate_init_auth(auth_spec)
if validate_cert_manager_calls:
self.cert_manager.fetch_cert.assert_called_once_with(self._generate_cert_file(auth_spec))
self.cert_manager.validate_cert.assert_called_once_with(self._generate_cert_file(auth_spec),
cert_fingerprint)
@staticmethod
def _generate_random_string(string_len):
return ''.join(random.choice(string.ascii_lowercase) for _ in range(string_len))
def _get_test_auth_spec(self, config_manager, appliance_ip, port):
config_spec = ApplianceConfigSpec(profile=self._generate_random_string(7),
endpoint=(appliance_ip, port),
access_token=self._generate_random_string(10),
serial_id=self._generate_random_string(8))
return AuthSpec(config_spec, config_manager)
def _get_config_manager(self):
return ApplianceConfigManager(self.test_dir)
def test_init_auth_with_single_profile(self):
auth_spec = self._get_test_auth_spec(self._get_config_manager(), "1.2.3.4", 443)
self._test_init_auth(auth_spec)
def test_init_auth_with_non_default_https_port(self):
auth_spec = self._get_test_auth_spec(self._get_config_manager(), "1.2.3.4", 8443)
self._test_init_auth(auth_spec)
def _init_multiple_appliances(self, config_manager, num_appliances):
specs = []
for i in range(num_appliances):
appliance_ip = "10.0.1.{}".format(i)
auth_spec = self._get_test_auth_spec(config_manager, appliance_ip, 443 + i)
self._get_auth_manager(auth_spec).initialize_auth()
specs.append(auth_spec)
return specs
def test_init_auth_with_multiple_profiles(self):
config_manager = self._get_config_manager()
specs = self._init_multiple_appliances(config_manager, 10)
assert len(os.listdir(config_manager.get_base_dir())) == 10
for spec in specs:
self._validate_init_auth(spec)
def test_init_auth_overwrite_different_access_token(self):
auth_spec = self._get_test_auth_spec(self._get_config_manager(), "1.2.3.4", 443)
self._test_init_auth(auth_spec)
modified_access_token = self._generate_random_string(10)
auth_spec_with_different_access_token = AuthSpec(ApplianceConfigSpec(
profile=auth_spec.appliance_config_spec.get_profile(),
endpoint=auth_spec.appliance_config_spec.get_endpoint(),
access_token=modified_access_token,
serial_id=auth_spec.appliance_config_spec.get_serial_id()), auth_spec.appliance_config_manager)
self._test_init_auth(auth_spec_with_different_access_token, False)
modified_endpoint = ("5.6.7.8", 8443)
auth_spec_with_different_endpoint = AuthSpec(ApplianceConfigSpec(
profile=auth_spec.appliance_config_spec.get_profile(),
endpoint=modified_endpoint,
access_token=auth_spec.appliance_config_spec.get_access_token(),
serial_id=auth_spec.appliance_config_spec.get_serial_id()), auth_spec.appliance_config_manager)
self._test_init_auth(auth_spec_with_different_endpoint, False)
modified_serial_id = self._generate_random_string(8)
auth_spec_with_different_serial_id = AuthSpec(ApplianceConfigSpec(
profile=auth_spec.appliance_config_spec.get_profile(),
endpoint=auth_spec.appliance_config_spec.get_endpoint(),
access_token=auth_spec.appliance_config_spec.get_access_token(),
serial_id=modified_serial_id), auth_spec.appliance_config_manager)
self._test_init_auth(auth_spec_with_different_serial_id, False)
@staticmethod
def _create_and_write_cert(cert_file):
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 1024)
cert = crypto.X509()
cert.get_subject().C = "US"
cert.get_subject().ST = "CA"
cert.get_subject().L = "Dummy"
cert.get_subject().OU = "Dummy"
cert.get_subject().CN = "Dummy"
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'md5')
ssl_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
with open(cert_file, 'wb') as f:
f.write(ssl_cert)
return cert.digest("md5")
def test_init_auth_valid_cert_fingerprint(self):
# Mock only the fetch_cert() method of the cert_manager
auth_spec = self._get_test_auth_spec(self._get_config_manager(), "1.2.3.4", 443)
endpoint = auth_spec.appliance_config_spec.get_endpoint()
# Override the mock cert manager
self.cert_manager = ApplianceCertManager(endpoint)
self.cert_manager.fetch_cert = mock.MagicMock()
# Create a certificate and write to the cert file
cert_fingerprint = self._create_and_write_cert(self._generate_cert_file(auth_spec))
self._test_init_auth(auth_spec, validate_cert_manager_calls=False, cert_fingerprint=cert_fingerprint)
self._validate_init_auth(auth_spec)
def test_init_auth_invalid_cert_fingerprint(self):
with self.assertRaises(exceptions.RequestException):
# Mock only the fetch_cert() method of the cert_manager
auth_spec = self._get_test_auth_spec(self._get_config_manager(), "1.2.3.4", 443)
endpoint = auth_spec.appliance_config_spec.get_endpoint()
# Override the mock cert manager
self.cert_manager = ApplianceCertManager(endpoint)
self.cert_manager.fetch_cert = mock.MagicMock()
# Create a certificate and write to the cert file
self._create_and_write_cert(self._generate_cert_file(auth_spec))
self._test_init_auth(auth_spec, validate_cert_manager_calls=False, cert_fingerprint="AB:CD:EF:GH")
def test_get_config_without_init_auth(self):
with self.assertRaises(exceptions.InvalidConfig):
self._get_config_manager().get_config("fake-appliance")
def test_list_configs(self):
config_manager = self._get_config_manager()
assert len(config_manager.list_configs()) == 0
specs = self._init_multiple_appliances(config_manager, 10)
config_dict = config_manager.list_configs()
assert len(config_dict) == len(specs)
for spec in specs:
assert spec.appliance_config_spec.get_profile() in config_dict
config = config_manager.get_config(spec.appliance_config_spec.get_profile())
assert config_dict[spec.appliance_config_spec.get_profile()] == config
def test_delete_config(self):
config_manager = self._get_config_manager()
auth_spec = self._get_test_auth_spec(config_manager, "1.2.3.4", 443)
self._test_init_auth(auth_spec)
config_manager.delete_config(auth_spec.appliance_config_spec.get_profile())
assert len(config_manager.list_configs()) == 0
assert not config_manager.is_config_present(auth_spec.appliance_config_spec.get_profile())
assert not os.path.exists(config_manager.get_config_dir(auth_spec.appliance_config_spec.get_profile()))
def test_delete_without_init_auth(self):
with self.assertRaises(exceptions.InvalidConfig):
self._get_config_manager().delete_config("fake-appliance")
def test_delete_one_of_many_configs(self):
config_manager = self._get_config_manager()
specs = self._init_multiple_appliances(config_manager, 10)
appliance_profile_to_del = specs[0].appliance_config_spec.get_profile()
config_manager.delete_config(appliance_profile_to_del)
assert len(config_manager.list_configs()) == 9
assert not config_manager.is_config_present(appliance_profile_to_del)
assert not os.path.exists(config_manager.get_config_dir(appliance_profile_to_del))
for i in range(1, len(specs)):
assert config_manager.is_config_present(specs[i].appliance_config_spec.get_profile())
| 48.368201 | 121 | 0.716696 | 10,729 | 0.928114 | 0 | 0 | 1,799 | 0.155623 | 0 | 0 | 945 | 0.081747 |
0d168a4c61af1ef7a21e7295eab4769153682c76 | 7,544 | py | Python | collect.py | peitur/colag | 7ffefaa1a622a12718e94439f77b6e47db7c4452 | [
"MIT"
] | 1 | 2019-09-02T18:28:07.000Z | 2019-09-02T18:28:07.000Z | collect.py | peitur/colag | 7ffefaa1a622a12718e94439f77b6e47db7c4452 | [
"MIT"
] | 5 | 2019-01-05T12:51:37.000Z | 2021-11-12T10:53:13.000Z | collect.py | peitur/colag | 7ffefaa1a622a12718e94439f77b6e47db7c4452 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import sys,re,os,re, datetime
import requests
import json
import hashlib
import getopt
from pprint import pprint
from pathlib import Path
################################################################################
## Hashing large files
################################################################################
def file_hash( filename, chksum="sha256" ):
BLOCKSIZE = 65536
if chksum == "sha1":
hasher = hashlib.sha1()
elif chksum == "sha224":
hasher = hashlib.sha224()
elif chksum == "sha256":
hasher = hashlib.sha256()
elif chksum == "sha384":
hasher = hashlib.sha384()
elif chksum == "sha512":
hasher = hashlib.sha512()
else:
hasher = hashlib.sha256()
with open( filename, 'rb') as f:
buf = f.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(BLOCKSIZE)
return hasher.hexdigest()
################################################################################
## HTTP operations, download large files
################################################################################
def download_file( proj, url_filename, local_filename, **opt ):
x_size = 0
l_size = 0
r_size = 0
bsize=1024
overwrite = False
timeout = 10
debug = False
if 'debug' in opt: debug = opt['debug']
if 'bsize' in opt: bsize = opt['bsize']
if 'timeout' in opt: timeout = opt['timeout']
if 'overwrite' in opt and opt['overwrite'] in (True,False):
overwrite = opt['overwrite']
if Path( local_filename ).exists():
l_size = Path( local_filename ).stat().st_size
r = requests.get( url_filename, timeout=timeout, stream=True)
if 'content-length' in r.headers:
r_size = r.headers['content-length']
if debug:
pprint( r.headers )
if r.status_code != 200:
print("# ERROR: Could not find %s, %s : " % ( url_filename, r.status_code ) )
return None
if not Path( local_filename ).exists() or overwrite:
with open( local_filename, 'wb') as f:
for chunk in r.iter_content( chunk_size=bsize ):
if chunk: # filter out keep-alive new chunks
x_size += len( chunk )
f.write(chunk)
print("# [ %s ] [ %s / %s ] --> %s" % ( proj, x_size, r_size, local_filename ), end="\r" )
print("")
else:
print("# [ %s ] [ skip ] --> %s " % ( proj, local_filename ) )
r.close()
return local_filename
################################################################################
## Local file operaitons
################################################################################
def _read_text( filename ):
result = list()
try:
fd = open( filename, "r" )
for line in fd.readlines():
result.append( line.lstrip().rstrip() )
return result
except Exception as e:
print("ERROR Reading %s: %s" % ( filename, e ))
return result
def _read_json( filename ):
return json.loads( "\n".join( _read_text( filename ) ) )
def load_file( filename ):
filesplit = re.split( r"\.", filename )
if filesplit[-1] in ( "json" ):
return _read_json( filename )
else:
return _read_text( filename )
def _write_json( filename, data ):
return _write_text( filename, json.dumps( data, indent=2, sort_keys=True ) )
def _write_text( filename, data ):
fd = open( filename, "w" )
fd.write( str( data ) )
fd.close()
def write_file( filename, data ):
filesplit = re.split( "\.", filename )
if filesplit[-1] in ( "json" ):
return _write_json( filename, data )
else:
return _write_text( filename, data )
################################################################################
def read_env( key ):
if key not in os.environ:
return None
return os.environ.get( key )
################################################################################
def _apply_version( string, version ):
return re.sub( r"<%\s*version\s*%>", version, string )
def _apply_project( string, version ):
return re.sub( r"<%\s*project\s*%>", version, string )
################################################################################
if __name__ == "__main__":
opt = dict()
opt['config'] = "collect.json"
opt['config_d'] = "collect.d"
opt['load'] = None
opt['script'] = sys.argv.pop(0)
if len( sys.argv ):
opt['load'] = sys.argv.pop(0)
config = load_file( "collect.json" )[0]
conf_dir = Path( opt['config_d'] )
for conf_file in conf_dir.iterdir():
for xo in load_file( str( conf_file ) ):
hdata = dict()
x_dir = re.split("\.", str( conf_file.name ) )[0]
if opt['load'] and opt['load'] != x_dir:
continue
if 'skip' in xo and xo['skip']:
continue
if not Path( "%s/%s" % ( config['target'], x_dir )).exists():
Path( "%s/%s" % ( config['target'], x_dir )).mkdir()
bsize = 8192
chksum = "sha256"
if 'checksum' in config: chksum = config['checksum']
if 'checksum' in xo: chksum = xo['checksum']
if 'bsize' in config: bsize = int( config['bsize'] )
if 'bsize' in xo: bsize = int( xo['bsize'] )
if 'version' not in xo: xo['version'] = ""
x_url = _apply_version( xo['url'], xo['version'] )
x_path = "%s/%s/%s" % ( config['target'], x_dir, re.split( r"\/", x_url )[-1] )
if 'filename' in xo:
x_path = "%s/%s/%s" % ( config['target'], x_dir, _apply_version( xo['filename'], xo['version'] ) )
try:
download_file( x_dir, x_url, x_path, bsize=bsize )
except Exception as e:
print( "# EXCEPTION: Failed to download %s to %s: %s" % ( x_url, x_path, e ) )
pprint( e )
if not Path( x_path ).exists():
print( "# ERROR: Failed to download %s to %s, already exists" % ( x_url, x_path ) )
continue
chkfile = "%s.%s.json" % (x_path, chksum)
fst = os.stat( x_path )
hdata['01.filename'] = x_path
hdata['02.source'] = x_url
hdata['03.atime'] = datetime.datetime.fromtimestamp( fst.st_atime ).isoformat()
hdata['04.ctime'] = datetime.datetime.fromtimestamp( fst.st_ctime ).isoformat()
hdata['05.mtime'] = datetime.datetime.fromtimestamp( fst.st_mtime ).isoformat()
hdata['06.size'] = fst.st_size
hdata['07.checksum'] = "%s:%s" % ( chksum, file_hash( x_path, chksum ) )
if 'signature' in xo:
x_sign = _apply_version( xo['signature'], xo['version'] )
x_lsign = _apply_version( "%s/%s/%s" % ( config['target'], x_dir, re.split( r"\/", xo['signature'] )[-1] ), xo['version'] )
try:
download_file( x_dir, x_sign, x_lsign, bsize=1024 )
except Exception as e:
print( "# EXCEPTION: Failed to download %s to %s" % ( x_sign, x_lsign ) )
pprint( e )
hdata['10.signature'] = x_lsign
hdata['11.signature_checksum'] = "%s:%s" % ( chksum, file_hash( x_lsign, chksum ) )
if not Path( chkfile ).exists():
write_file( chkfile, [ hdata ] )
| 32.943231 | 139 | 0.4943 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,908 | 0.252916 |
0d19256930f4495b8add0763a8be0add5773382d | 151 | py | Python | common.py | camillescott/explotiv | 649285c73cdbb85cd55285e4c3920051efd7f89d | [
"BSD-3-Clause"
] | 1 | 2016-08-25T02:46:25.000Z | 2016-08-25T02:46:25.000Z | common.py | camillescott/explotiv | 649285c73cdbb85cd55285e4c3920051efd7f89d | [
"BSD-3-Clause"
] | null | null | null | common.py | camillescott/explotiv | 649285c73cdbb85cd55285e4c3920051efd7f89d | [
"BSD-3-Clause"
] | null | null | null | import os
pkg_path = os.path.dirname(__file__)
static_folder = os.path.join(pkg_path, 'static')
template_folder = os.path.join(pkg_path, 'templates')
| 25.166667 | 53 | 0.768212 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 19 | 0.125828 |
0d1974a13ecd52da41d57fd5cb8316c87eb40657 | 2,421 | py | Python | ALDS/ALDS1_12_C.py | yu8ikmnbgt6y/MyAOJ | 474b21a2a0c25e1c1f3d6d66d2a2ea52aecaa39b | [
"Unlicense"
] | 1 | 2020-01-08T16:33:46.000Z | 2020-01-08T16:33:46.000Z | ALDS/ALDS1_12_C.py | yu8ikmnbgt6y/MyAOJ | 474b21a2a0c25e1c1f3d6d66d2a2ea52aecaa39b | [
"Unlicense"
] | null | null | null | ALDS/ALDS1_12_C.py | yu8ikmnbgt6y/MyAOJ | 474b21a2a0c25e1c1f3d6d66d2a2ea52aecaa39b | [
"Unlicense"
] | null | null | null | import sys
import io
import time
import pprint
input_txt = """
10
0 2 1 1 2 3
1 2 3 3 2 1
2 2 3 1 6 10
3 1 4 1
4 1 7 1
5 2 3 1 6 1
6 2 3 1 8 1
7 2 5 1 8 4
8 1 9 100000
9 0
"""
#sys.stdin = open("ALDS1_11_D_in11.txt","r")#io.StringIO(input_txt)
#sys.stdin = io.StringIO(input_txt)
sys.stdin = open("ALDS1_12_C_in8.txt", 'r')
#tmp = input()
start = time.time()
# copy the below part and paste to the submission form.
# ---------function------------
import sys
from collections import defaultdict
from typing import Dict
def find_shortest_distance(start_vertex: int, n: int, relations: Dict[int, Dict]) -> Dict[int, int]:
unreached_vertices = [x for x in range(1, n)]
distance = {x: sys.maxsize for x in range(n)}
distance[start_vertex] = 0
vtx = None
tmp_distance = [sys.maxsize for x in range(n)]
for k, v in relations[start_vertex].items():
tmp_distance[k] = v
while True:
min_dist = sys.maxsize
for i in unreached_vertices:
dist = tmp_distance[i]
if dist < min_dist:
min_dist = dist
vtx = i
if min_dist == sys.maxsize:
break
unreached_vertices.remove(vtx)
distance[vtx] = min_dist
neighbor_vertices = relations[vtx]
for n_vtx, n_dist in neighbor_vertices.items():
n_dist_from_start = distance[vtx] + n_dist
tmp_dist = tmp_distance[n_vtx]
if tmp_dist == sys.maxsize:
tmp_distance[n_vtx] = n_dist_from_start
else:
if n_dist_from_start < tmp_dist:
tmp_distance[n_vtx] = n_dist_from_start
return distance
def main():
n = int(input())
relations = defaultdict(dict)
lines = sys.stdin.readlines()
for i in range(n):
u, k, *vtx_wght = map(int, lines[i].split())
for v_i in range(k):
relations[u][vtx_wght[2*v_i]] = vtx_wght[2*v_i+1]
dist_from_0 = find_shortest_distance(0, n, relations)
answers = [None] * n
sorted_dist = sorted(dist_from_0.items(), key=lambda x: x[0])
for i in range(n):
answers[i] = f"{sorted_dist[i][0]} {sorted_dist[i][1]}"
[print(ans) for ans in answers]
return
main()
# -----------------------------
print("elapsed:", time.time()-start)
sys.stdin = sys.__stdin__
| 27.202247 | 102 | 0.576621 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 442 | 0.182569 |
0d19939c79927199a00a6644497c9b26cbcdaa17 | 1,103 | py | Python | ejercicios/mayores_de_edad.py | carlosviveros/Soluciones | 115f4fa929c7854ca497e4c994352adc64565456 | [
"MIT"
] | 4 | 2021-12-14T23:51:25.000Z | 2022-03-24T11:14:00.000Z | ejercicios/mayores_de_edad.py | leugimkm/Soluciones | d71601c8d9b5e86e926f48d9e49462af8a956b6d | [
"MIT"
] | null | null | null | ejercicios/mayores_de_edad.py | leugimkm/Soluciones | d71601c8d9b5e86e926f48d9e49462af8a956b6d | [
"MIT"
] | 5 | 2021-11-10T06:49:50.000Z | 2022-03-24T01:42:28.000Z | """AyudaEnPython: https://www.facebook.com/groups/ayudapython
# ------------------------ REDACCION ORIGINAL ------------------------
1. Crear un programa que pida un número entero e imprimirlo, si no se
ingresa deberá preguntar otra vez por el número entero hasta que
ingrese un número positivo.
2. Crear una lista que almacene edades.
3. Con la lista anterior, contar cuantos son mayores de edad.
# --------------------------------------------------------------------
NOTA: Los ejercicios estan mal redactados, el instructor deberia tener
mas claridad e integrar lo enseñado con ejercicios bien diseñados.
"""
def ingresar_numero():
while True:
n = input("Ingrese un número entero: ")
try:
n = int(n)
if n >= 0:
return n
else:
print("El número debe ser positivo.")
except ValueError:
print("No es un número entero.")
print(ingresar_numero()) # 1
edades = [18, 13, 11, 19, 17, 15, 16, 14, 12, 10, 20] # 2
print(f"Mayores de edad: {len([e for e in edades if e >= 18])} personas") # 3 | 33.424242 | 77 | 0.574796 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 786 | 0.706835 |
0d1a17352a3f05296cc6555c34672a19c51dc19a | 2,523 | py | Python | SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py | Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | [
"Apache-2.0"
] | 427 | 2018-05-29T14:21:02.000Z | 2022-03-16T03:17:54.000Z | SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py | PolideaPlayground/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | [
"Apache-2.0"
] | 25 | 2018-07-23T08:34:15.000Z | 2021-11-05T07:13:36.000Z | SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py | PolideaPlayground/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | [
"Apache-2.0"
] | 52 | 2018-07-19T19:57:32.000Z | 2022-03-11T16:05:38.000Z | """
Test expression command options.
Test cases:
o test_expr_options:
Test expression command options.
"""
from __future__ import print_function
import os
import time
import lldb
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test.lldbtest import *
class ExprOptionsTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
self.main_source = "main.cpp"
self.main_source_spec = lldb.SBFileSpec(self.main_source)
self.line = line_number('main.cpp', '// breakpoint_in_main')
self.exe = os.path.join(os.getcwd(), "a.out")
def test_expr_options(self):
"""These expression command options should work as expected."""
self.build()
# Set debugger into synchronous mode
self.dbg.SetAsync(False)
# Create a target by the debugger.
target = self.dbg.CreateTarget(self.exe)
self.assertTrue(target, VALID_TARGET)
# Set breakpoints inside main.
breakpoint = target.BreakpointCreateBySourceRegex(
'// breakpoint_in_main', self.main_source_spec)
self.assertTrue(breakpoint)
# Now launch the process, and do not stop at entry point.
process = target.LaunchSimple(
None, None, self.get_process_working_directory())
self.assertTrue(process, PROCESS_IS_VALID)
threads = lldbutil.get_threads_stopped_at_breakpoint(
process, breakpoint)
self.assertEqual(len(threads), 1)
frame = threads[0].GetFrameAtIndex(0)
options = lldb.SBExpressionOptions()
# test --language on C++ expression using the SB API's
# Make sure we can evaluate a C++11 expression.
val = frame.EvaluateExpression('foo != nullptr')
self.assertTrue(val.IsValid())
self.assertTrue(val.GetError().Success())
self.DebugSBValue(val)
# Make sure it still works if language is set to C++11:
options.SetLanguage(lldb.eLanguageTypeC_plus_plus_11)
val = frame.EvaluateExpression('foo != nullptr', options)
self.assertTrue(val.IsValid())
self.assertTrue(val.GetError().Success())
self.DebugSBValue(val)
# Make sure it fails if language is set to C:
options.SetLanguage(lldb.eLanguageTypeC)
val = frame.EvaluateExpression('foo != nullptr', options)
self.assertTrue(val.IsValid())
self.assertFalse(val.GetError().Success())
| 31.148148 | 71 | 0.664685 | 2,253 | 0.892985 | 0 | 0 | 0 | 0 | 0 | 0 | 675 | 0.267539 |
0d1a377e75b203d7f18a99dc9d5d200921019cc3 | 1,724 | py | Python | lib_bgp_data/collectors/mrt/mrt_base/tables.py | jfuruness/lib_bgp_data | 25f7d57b9e2101c7aefb325e8d728bd91f47d557 | [
"BSD-3-Clause"
] | 16 | 2018-09-24T05:10:03.000Z | 2021-11-29T19:18:59.000Z | lib_bgp_data/collectors/mrt/mrt_base/tables.py | jfuruness/lib_bgp_data | 25f7d57b9e2101c7aefb325e8d728bd91f47d557 | [
"BSD-3-Clause"
] | 4 | 2019-10-09T18:54:17.000Z | 2021-03-05T14:02:50.000Z | lib_bgp_data/collectors/mrt/mrt_base/tables.py | jfuruness/lib_bgp_data | 25f7d57b9e2101c7aefb325e8d728bd91f47d557 | [
"BSD-3-Clause"
] | 3 | 2018-09-17T17:35:18.000Z | 2020-03-24T16:03:31.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module contains class MRT_Announcements_Table
Announcements_Table inherits from the Generic_Table class. The Generic_Table
class allows for the conection to a database upon initialization. Also
upon initialization the _create_tables function is called to initialize
any tables if they do not yet exist. Beyond that the class can clear the
table, create an index, and has the name and columns properties that are
used in utils function to insert CSVs into the database. This class does
not contain an index creation function, because it would only ever be
used when combining with the roas table, which does a parallel seq_scan,
thus any indexes are not used since they are not efficient. Each table
follows the table name followed by a _Table since it inherits from the
database class.
"""
__author__ = "Justin Furuness"
__credits__ = ["Justin Furuness"]
__Lisence__ = "BSD"
__maintainer__ = "Justin Furuness"
__email__ = "jfuruness@gmail.com"
__status__ = "Production"
from ....utils.database import Generic_Table
class MRT_Announcements_Table(Generic_Table):
"""Class with database functionality.
In depth explanation at the top of the file."""
__slots__ = []
name = "mrt_announcements"
columns = ["prefix", "as_path", "origin", "time"]
def _create_tables(self):
"""Creates tables if they do not exist.
Called during initialization of the database class.
"""
sql = f"""CREATE UNLOGGED TABLE IF NOT EXISTS {self.name} (
prefix INET,
as_path bigint ARRAY,
origin BIGINT,
time BIGINT
);"""
self.execute(sql)
| 32.528302 | 76 | 0.707077 | 647 | 0.37529 | 0 | 0 | 0 | 0 | 0 | 0 | 1,390 | 0.806265 |
0d1a4439199c9ef84e882067c41f55f763548eaa | 4,138 | py | Python | src/permission/backends.py | dkopitsa/django-permission | 0319ea3bf0993ca1bd7232e4d60c4b8ec635787d | [
"MIT"
] | 234 | 2015-01-05T17:09:08.000Z | 2021-11-15T09:52:43.000Z | src/permission/backends.py | dkopitsa/django-permission | 0319ea3bf0993ca1bd7232e4d60c4b8ec635787d | [
"MIT"
] | 54 | 2015-02-13T08:06:32.000Z | 2021-05-19T14:07:03.000Z | src/permission/backends.py | dkopitsa/django-permission | 0319ea3bf0993ca1bd7232e4d60c4b8ec635787d | [
"MIT"
] | 35 | 2015-04-13T09:10:38.000Z | 2022-02-15T01:43:03.000Z | # coding=utf-8
"""
Logical permission backends module
"""
from permission.conf import settings
from permission.utils.handlers import registry
from permission.utils.permissions import perm_to_permission
__all__ = ('PermissionBackend',)
class PermissionBackend(object):
"""
A handler based permission backend
"""
supports_object_permissions = True
supports_anonymous_user = True
supports_inactive_user = True
# pylint:disable=unused-argument
def authenticate(self, username, password):
"""
Always return ``None`` to prevent authentication within this backend.
"""
return None
def has_perm(self, user_obj, perm, obj=None):
"""
Check if user have permission (of object) based on registered handlers.
It will raise ``ObjectDoesNotExist`` exception when the specified
string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object).
Raises
------
django.core.exceptions.ObjectDoesNotExist
If the specified string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
"""
if settings.PERMISSION_CHECK_PERMISSION_PRESENCE:
# get permission instance from string permission (perm)
# it raise ObjectDoesNotExists when the permission is not exists
try:
perm_to_permission(perm)
except AttributeError:
# Django 1.2 internally use wrong permission string thus ignore
pass
# get permission handlers fot this perm
cache_name = '_%s_cache' % perm
if hasattr(self, cache_name):
handlers = getattr(self, cache_name)
else:
handlers = [h for h in registry.get_handlers()
if perm in h.get_supported_permissions()]
setattr(self, cache_name, handlers)
for handler in handlers:
if handler.has_perm(user_obj, perm, obj=obj):
return True
return False
def has_module_perms(self, user_obj, app_label):
"""
Check if user have permission of specified app based on registered
handlers.
It will raise ``ObjectDoesNotExist`` exception when the specified
string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
Parameters
----------
user_obj : django user model instance
A django user model instance which is checked
app_label : string
`app_label.codename` formatted permission string
Returns
-------
boolean
Whether the specified user have specified permission.
Raises
------
django.core.exceptions.ObjectDoesNotExist
If the specified string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
"""
# get permission handlers fot this perm
cache_name = '_%s_cache' % app_label
if hasattr(self, cache_name):
handlers = getattr(self, cache_name)
else:
handlers = [h for h in registry.get_handlers()
if app_label in h.get_supported_app_labels()]
setattr(self, cache_name, handlers)
for handler in handlers:
if handler.has_module_perms(user_obj, app_label):
return True
return False
| 33.918033 | 80 | 0.61479 | 3,895 | 0.941276 | 0 | 0 | 0 | 0 | 0 | 0 | 2,486 | 0.600773 |
0d1b4daa79d88bc89d8bb4d70a65c117aac274ea | 50,782 | py | Python | watex/core/erp.py | WEgeophysics/watex | 21616ce35372a095c3dd624f82a5282b15cb2c91 | [
"MIT"
] | 3 | 2021-06-19T02:16:46.000Z | 2021-07-16T15:56:49.000Z | watex/core/erp.py | WEgeophysics/watex | 21616ce35372a095c3dd624f82a5282b15cb2c91 | [
"MIT"
] | null | null | null | watex/core/erp.py | WEgeophysics/watex | 21616ce35372a095c3dd624f82a5282b15cb2c91 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright (c) 2021 Kouadio K. Laurent, zju-ufhb
# This module is part of the WATex core package, which is released under a
# MIT- licence.
"""
===============================================================================
Copyright (c) 2021 Kouadio K. Laurent
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.
===============================================================================
.. synopsis:: 'watex.core.erp'
Module to deal with Electrical resistivity profile (ERP)
exploration tools
Created on Tue May 18 12:33:15 2021
@author: @Daniel03
"""
import os
import re
import sys
import warnings
import json
import datetime
import shutil
import numpy as np
import pandas as pd
from scipy.signal import argrelextrema
from ..utils.__init__ import savepath as savePath
from ..utils._watexlog import watexlog
import watex.utils.exceptions as Wex
import watex.utils.tricks as wfunc
import watex.utils.exmath as wMath
import watex.utils.func_utils as func
import watex.utils.gis_tools as gis
_logger =watexlog.get_watex_logger(__name__)
sys.path.insert(0, os.path.abspath('.'))
class ERP_collection:
"""
Collection objects. The class collects all `erp` survey lines.
Each `erp` is an singleton class object with their corresponding
attributes. The goal is to build a container geao-elecricals to
straigthforwardly given to :class:`~watex.core.geofeatures.Features`
class.
Arguments:
----------
*listOferpfn*: list, ndarray
list of different `erp` files.
*listOfposMinMax* : list
collection of different selected anomaly boundaries.
If not provided, the :attr:`~.core.erp.ERP.auto`
will triggered. It's recommanded to provided for all
`erp` your convenient anomaly boundaries like::
listOfposMinMax=[(90, 130), (10, 70), ...]
where ``(90,130)``is boundaries of selected anomaly on
the first `erp` line and ``(10,70)``is the boundaries
of the second `erp` survey line and so on.
*erpObjs*: list, ndarray
Collection of objects from :class:~core.erp.ERP`. If objects
are alread created. Gather them on a list and pass though the
argument `erpObjs`
Holds on others optionals infos in ``kws`` arguments:
====================== ============== ===================================
Attributes Type Description
====================== ============== ===================================
list_of_dipole_lengths list Collection of `dipoleLength`. User
can provide the distance between
sites measurements as performed on
investigations site. If given, the
automaticall `dipoleLength` compu-
tation will be turned off.
fnames array_like Array of `erp`survey lines name.
If each survey name is the location
name then will keep it.
id array_like Each `erp`obj reference numbers
erps_data nd.array Array composed of geo-electrical
parameters. ndarray(nerp, 8) where
num is the number of `erp`obj
collected.
erpdf pd.DataFrame A dataFrame of collected `erp` line
and the number of lines correspond
to the number of collected `erp`.
====================== ============== ===================================
It's posible to get from each `erp` collection the singular array of
different parameters considered as properties params::
>>> from watex.core.erp import ERP_collection as ERPC
>>> erpcol = ERPC(listOferpfn='list|path|filename')
>>> erpcol.survey_ids
>>> erpcol.selectedPoints
Call the following :class:`~.erp.ERP_collection` properties attributes:
==================== ================ ===================================
properties Type Description
==================== ================ ===================================
selectedPoints array_like Collection of Best anomaly
position points
survey_ids array_like Collection of all `erp` survey
survey ids. :Note:Each ids is fol-
lowing by the prefix **e**.
sfis array_like Collection of best anomaly standard
fracturation index value.
powers array_like Collection of best anomaly `power`
magnitudes array_like Colection of best anomaly
magnitude in *ohm.m*
shapes array_like Collection of best anomaly shape.
For more details please refer to
:doc:`~core.erp.ERP`.
types array_like Collection of best anomaly type.
Refer to :doc:`~core.erp.ERP` for
more details.
==================== ================ ===================================
:Example:
>>> from watex.core.erp import ERP_collection
>>> erpObjs =ERP_collection(listOferpfn= 'data/erp')
>>> erpObjs.erpdf
>>> erpObjs.survey_ids
... ['e2059734331848' 'e2059734099144' 'e2059734345608']
"""
erpColums =['id',
'east',
'north',
'power',
'magnitude',
'shape',
'type',
'sfi']
def __init__(self, listOferpfn=None, listOfposMinMax=None, erpObjs=None,
**kws):
self._logging =watexlog().get_watex_logger(self.__class__.__name__)
self.erpObjs = erpObjs
self.anomBoundariesObj= listOfposMinMax
self.dipoleLengthObjs= kws.pop('list_of_dipole_lengths', None)
self.export_data =kws.pop('export', False)
self.export_fex= kws.pop('extension', 'csv')
self.listOferpfn =listOferpfn
self.id =None
for key in list(kws.keys()):
setattr(self, key, kws[key])
self._readErpObjs()
def _readErpObjs(self, listOferpfn=None,listOfposMinMax=None,
erpObjs=None, **kwargs):
"""
Read or cread `erp` objects and populate attributes.
"""
self._logging.info('Collecting `erp` files and populates '
'main attributes')
dipoleLengthObjs =kwargs.pop('list_of_dipole_lengths', None)
if listOferpfn is not None :
self.listOferpfn =listOferpfn
if listOfposMinMax is not None :
self.anomBoundariesObj =listOfposMinMax
if erpObjs is not None :
self.erpObjs = erpObjs
if dipoleLengthObjs is not None :
self.dipoleLengthObjs = dipoleLengthObjs
if self.listOferpfn is None and self.erpObjs is None :
self._logging.error('No ERP file nor ERP object detected.'
'Please provide at least `ERP` file or '
' `erp` object.')
if self.listOferpfn is not None:
if isinstance(self.listOferpfn, str):
if os.path.isfile(self.listOferpfn):
self.listOferpfn=[self.listOferpfn]
elif os.path.isdir(self.listOferpfn):
self.listOferpfn=[os.path.join(self.listOferpfn,file)
for file in os.listdir (
self.listOferpfn)]
else :
raise Wex.WATexError_ERP(
'File or path provided is wrong! Please give a'
' a right path.')
if self.dipoleLengthObjs is not None :
assert len(self.listOferpfn)== len(
self.dipoleLengthObjs),'Length of dipoles lenghths is'\
' = {0}. It must be equal to number of `erp line'\
' provided (is ={1}).'.format(len(
self.dipoleLengthObjs), len(self.listOferpfn))
else :
self.dipoleLengthObjs = [
None for ii in range(len(self.listOferpfn ))]
if self.anomBoundariesObj is not None :
assert len(self.anomBoundariesObj)== len(self.listOferpfn ), \
'Length of selected anomalies boundaries (is={0}) must be '\
'equal to the length of number of `erp` line provided '\
'(is={1}).'.format(len(self.anomBoundariesObj),
len(len(self.listOferpfn )))
else :
self.anomBoundariesObj= [None for nn in range(
len(self.listOferpfn ))]
unreadfiles =[] # collected uncesse
fmterp_text = '|{0:<7}|{1:>45}|{2:>15}|'
if self.erpObjs is None:
self.erpObjs=[]
print('-'*70)
print(fmterp_text.format('Num', 'ERPlines', 'status'))
print('-'*70)
for ii, erp_filename in enumerate(self.listOferpfn) :
try :
name_file = os.path.basename(
os.path.splitext(erp_filename)[0])
except :
# for consistency takes at least the basename
# to display.
name_file = os.path.basename(erp_filename)
try :
erpObj = ERP(erp_fn= erp_filename,
dipole_length=self.dipoleLengthObjs[ii],
posMinMax=self.anomBoundariesObj[ii])
except :
unreadfiles.append(name_file)
print(fmterp_text.format(ii+1,
name_file,
'*Failed'))
else:
print(fmterp_text.format(ii+1,
name_file,
'Passed'))
self.erpObjs.append(erpObj)
print('-'*70)
if len(unreadfiles)>=1 :
self._logging.error (
f'Unable to read the files `{unreadfiles}`')
warnings.warn(f'Unable to read file `{len(unreadfiles)}`.'
' Please check your files.')
print(' --!> {0} ERP file not read. Please check your file'
f' {"s" if len(unreadfiles)>1 else ""} enumerate below:'
.format(len(unreadfiles)))
func.display_infos(infos=unreadfiles,
header=f"Unread file{'s' if len(unreadfiles)>1 else ''}")
if self.erpObjs is not None and self.listOferpfn is None :
lenOrpfn = len(self.erpObjs)
elif self.erpObjs is not None and self.listOferpfn is not None :
lenOrpfn= len(self.listOferpfn)
print('-'*70)
print(' {0}/{1} ERP files have been succesffuly read.'.format(
len(self.erpObjs),lenOrpfn ))
print('-'*70)
# collected the ERP filenames and generated the id from each object.
self.fnames = self.get_property_infos('_name')
self.id = np.array([id(obj) for obj in self.fnames])
# create a dataframe object
self._logging.info('Setting and `ERP` data array '
'and create pd.Dataframe')
self.erps_data= func.concat_array_from_list([
self.survey_ids,
self.easts,
self.norths,
self.powers,
self.magnitudes,
self.shapes,
self.types,
self.sfis], concat_axis=1)
self.erpdf =pd.DataFrame(data = self.erps_data,
columns=self.erpColums)
self.erpdf=self.erpdf.astype( {'east':np.float,
'north': np.float,
'power': np.float,
'magnitude':np.float,
'sfi':np.float})
if self.export_data is True :
self.exportErp()
def get_property_infos(self, attr_name , objslist =None):
"""
From each obj `erp` ,get the attribute infos and set
on data array
:param attr_name:
Name of attribute to get the informations of the properties
:type attra_name: str
:param objslist: list of collection objects
:type objslist; list
:Example:
>>> from watex.core.erp.ERP_collection as ERPcol
>>> erpObjs =ERPcol(listOferpfn= 'data/erp',
... export_erpFeatures=True,
... filename='ykroS')
"""
if objslist is not None :
self.erpObjs = objslist
return np.array([getattr(obj, attr_name) for obj in self.erpObjs ])
def exportErp(self, extension_file=None, savepath =None, **kwargs ):
"""
Export `erp` data after computing different geo_electrical features.
:param extension_file:
Extension type to export the files. Can be ``xlsx`` or ``csv``.
The default `extension_file` is ``csv``.
:type extension_file: str
:param savepath: Path like string to save the output file.
:type savepath: str
"""
filename = kwargs.pop('filename', None)
if filename is not None :
self.filename =filename
if extension_file is not None :
self.export_fex = extension_file
if savepath is not None :
self.savepath = savepath
if self.export_fex.find('csv') <0 and self.export_fex.find('xlsx') <0:
self.export_fex ='.csv'
self.export_fex= self.export_fex.replace('.', '')
erp_time = '{0}_{1}'.format(datetime.datetime.now().date(),
datetime.datetime.now().time())
# check whether `savepath` and `filename` attributes are set.
for addf in ['savepath', 'filename']:
if not hasattr(self, addf):
setattr(self, addf, None)
if self.filename is None :
self.filename = 'erpdf-{0}'.format(
erp_time + '.'+ self.export_fex).replace(':','-')
elif self.filename is not None :
self.filename += '.'+ self.export_fex
# add name into the workbooks
exportdf = self.erpdf.copy()
exportdf.insert(loc=1, column='name', value =self.fnames )
exportdf.reset_index(inplace =True)
exportdf.insert(loc=0, column='num', value =exportdf['index']+1 )
exportdf.drop(['id', 'index'], axis =1 , inplace=True)
if self.export_fex =='xlsx':
# with pd.ExcelWriter(self.filename ) as writer:
# exportdf.to_excel(writer, index=False, sheet_name='data')
exportdf.to_excel(self.filename , sheet_name='data',
index=False)
elif self.export_fex =='csv':
exportdf.to_csv(self.filename, header=True,
index =False)
if self.savepath is None :
self.savepath = savePath('_erpData_')
if self.savepath is not None :
if not os.path.isdir(self.savepath):
self.savepath = savePath('_erpData_')
try :
shutil.move(os.path.join(os.getcwd(),self.filename) ,
os.path.join(self.savepath , self.filename))
except :
self._logging.debug("We don't find any path to save ERP data.")
else:
print('--> ERP features file <{0}> is well exported to {1}'.
format(self.filename, self.savepath))
@property
def survey_ids (self) :
"""Get the `erp` filenames """
return np.array(['e{}'.format(idd) for idd in self.id])
@property
def selectedPoints (self):
"""Keep on array the best selected anomaly points"""
return self.get_property_infos('selected_best_point_')
@property
def powers(self):
""" Get the `power` of select anomaly from `erp`"""
return self.get_property_infos('best_power')
@property
def magnitudes(self):
""" Get the `magnitudes` of select anomaly from `erp`"""
return self.get_property_infos('best_magnitude')
@property
def shapes (self):
""" Get the `shape` of the selected anomaly. """
return self.get_property_infos('best_shape')
@property
def types(self):
""" Collect selected anomalies types from `erp`."""
return self.get_property_infos('best_type')
@property
def sfis (self):
"""Collect `sfi` for selected anomaly points """
return self.get_property_infos('best_sfi')
@property
def easts(self):
"""Collect the utm_easting value from `erp` survey line. """
return self.get_property_infos('best_east')
@property
def norths(self):
"""Collect the utm_northing value from `erp` survey line. """
return self.get_property_infos('best_north')
class ERP :
"""
Electrical resistivity profiling class . Define anomalies and compute
its features. Can select multiples anomalies on ERP and give their
features values.
Arguments:
----------
* erp_fn: str
Path to electrical resistivity profile
* dipole_length: float
Measurement electrodes. Distance between two electrodes in
meters.
* auto: bool
Trigger the automatic computation . If the `auto` is set to
``True``, dont need to provide the `posMinMax` argument
otherwise `posMinMax` must be given.
* posMinMax: tuple, list, nd.array(1,2)
Selected anomaly boundary. The boundaries matches the startpoint
as the begining of anomaly position and the endpoint as the end
of anomaly position. If provided , `auto` will be turn off at
``False`` even ``True``.
:Note: Provide the `posMinMax` is strongly recommended for accurate
geo-electrical features computation. If not given, the best anomaly
will be selected automatically and probably could not match what you
expect.
...
Hold others informations:
================= =================== ===================================
Attributes Type Description
================= =================== ===================================
lat float sation latitude
lon float station longitude
elev float station elevantion
in m or ft
east float station easting coordinate (m)
north float station northing coordinate (m)
azim float station azimuth in meter (m)
utm_zone str UTM location zone
resistivity dict resistivity value at each
station (ohm.m)
name str survey location name
turn_on bool turn on/off the displaying computa-
tion parameters.
best_point float/int position of the selected anomaly
best_rhoa float selected anomaly app.resistivity
display_autoinfos bool display the selected three best
anomaly points selected automatic-
cally.
================= =================== ===================================
- To get the geo-electrical-features, create an `erp` object by calling::
>>> from watex.core.erp import ERP
>>> anomaly_obj =ERP(erp_fn = '~/location_filename')
The call of the following `erp` properties attributes:
==================== ================ ===================================
properties Type Description
==================== ================ ===================================
select_best_point_ float Best anomaly position points
select_best_value_ float Best anomaly app.resistivity value.
best_points float Best positions points selected
automatically.
best_sfi float Best anomaly standart fracturation
index value.
best_anr float Best
best_power float Best anomaly power in *meter(m)*.
best_magnitude float Best anomlay magnitude in *ohm.m*
best_shape str Best anomaly shape. can be ``V``,
``W``,``K``, ``H``, ``C``, ``M``.
best_type str Best anomaly type. Can be :
- ``EC`` for Extensive conductive.
- ``NC`` for narrow conductive.
- ``CP`` for conductive plane.
- ``CB2P`` for contact between two
planes.
==================== ================ ===================================
:Example:
>>> from watex.core.erp import ERP
>>> anom_obj= ERP(erp_fn = 'data/l10_gbalo.xlsx', auto=False,
... posMinMax= (90, 130),turn_off=True)
>>> anom_obj.name
... l10_gbalo
>>> anom_obj.select_best_point_
...110
>>> anom_obj.select_best_value_
...132
>>> anom_obj.best_magnitude
...5
>>> nom_obj.best_power
..40
>>> anom_obj.best_sfi
...1.9394488747363936
>>> anom_obj.best_anr
...0.5076113145430543
"""
erpLabels =['pk',
'east',
'north',
'rhoa'
]
dataType ={
".csv":pd.read_csv,
".xlsx":pd.read_excel,
".json":pd.read_json,
".html":pd.read_json,
".sql" : pd.read_sql
}
def __init__(self, erp_fn =None , dipole_length =None, auto =False,
posMinMax=None, **kwargs) :
""" Read :ref:`erp` file and initilize the following
attributes attributes. Set `auto` to ``True`` to let the program
selecting the best anomaly points. """
self._logging =watexlog.get_watex_logger(self.__class__.__name__)
self.erp_fn =erp_fn
self._dipoleLength =dipole_length
self.auto =auto
self.anom_boundaries = posMinMax
self._select_best_point =kwargs.pop('best_point', None)
self.turn_on =kwargs.pop('display', 'off')
self._select_best_value =kwargs.pop('best_rhoa', None)
self._power =None
self._magnitude =None
self._lat =None
self._name = None
self._lon =None
self._east=None
self._north =None
self._sfi = None
self._type =None
self._shape= None
self.utm_zone =kwargs.pop('utm_zone', None)
self.data=None
self._fn =None
self._df =None
for key in list(kwargs.keys()):
setattr(self, key, kwargs[key])
if self.erp_fn is not None :
self._read_erp()
@property
def fn(self):
"""
``erp`` file type
"""
return self._fn
@fn.setter
def fn(self, erp_f):
""" Find the type of data and call pd.Dataframe for reading.
numpy array data can get from Dataframe
:param erp_f: path to :ref:`erp` file
:type erp_f: str
"""
if erp_f is not None : self.erp_fn = erp_f
if not os.path.isfile(self.erp_fn):
raise Wex.WATexError_file_handling(
'No right file detected ! Please provide the right path.')
name , exT=os.path.splitext(self.erp_fn)
if exT in self.dataType.keys():
self._fn =exT
else: self._fn ='?'
df_ = self.dataType[exT](self.erp_fn)
# Check into the dataframe whether the souding location and anomaly
#boundaries are given
self.auto, self._shape, self._type, self._select_best_point,\
self.anom_boundaries, self._df = \
wfunc.getdfAndFindAnomalyBoundaries(df_)
self.data =self._df.to_numpy()
self._name = os.path.basename(name)
def _read_erp(self, erp_fn=None ):
"""
Read :ref:`erp` file and populate attribute
:param erp_fn: Path to electrical resistivity profile
:type erp_fn: str
"""
if erp_fn is not None :
self.erp_fn = erp_fn
self.fn = self.erp_fn
self.sanitize_columns()
if self.coord_flag ==1 :
self._longitude= self.df['lon'].to_numpy()
self._latitude = self.df['lat'].to_numpy()
easting= np.zeros_like(self._longitude)
northing = np.zeros_like (self._latitude)
for ii in range(len(self._longitude)):
try :
self.utm_zone, utm_easting, utm_northing = gis.ll_to_utm(
reference_ellipsoid=23,
lon=self._longitude[ii],
lat = self._latitude[ii])
except :
utm_easting, utm_northing, \
self.utm_zone= gis.project_point_ll2utm(
lon=self._longitude[ii],
lat = self._latitude[ii])
easting[ii] = utm_easting
northing [ii] = utm_northing
self.df.insert(loc=1, column ='east', value = easting)
self.df.insert(loc=2, column='north', value=northing)
# get informations from anomaly
if self.coord_flag ==0 :
# compute latitude and longitude coordinates if not given
self._latitude = np.zeros_like(self.df['east'].to_numpy())
self._longitude = np.zeros_like(self._latitude)
if self.utm_zone is None :
self._logging.debug("UTM zone must be provide for accurate"
"location computation. We'll use `30N`"
"as default value")
warnings.warn("Please set the `UTM_zone` for accurating "
"`longitude` and `latitude` computing. If not"
" given, 30N `lon` and `lat` is used as"
" default value.")
self.utm_zone = '30N'
for ii, (north, east) in enumerate(zip(self.df['north'].to_numpy(),
self.df['east'].to_numpy())):
try :
self._latitude [ii],\
self._longitude [ii] = gis.utm_to_ll(23,
northing = north,
easting = east,
zone = self.utm_zone)
except:
self._latitude[ii], \
self._longitude [ii] = gis.project_point_utm2ll(
northing = north,
easting = east,
utm_zone = self.utm_zone)
if self.anom_boundaries is None or \
None in np.array(self.anom_boundaries):
# for consistency enable `automatic option`
if not self.auto :
self._logging.info ('Automatic trigger is set to ``False``.'
" For accuracy it's better to provide "
'anomaly location via its positions '
'boundaries. Can be a tuple or a list of '
'startpoint and endpoint.')
self._logging.debug('Automatic option is triggered!')
self.auto=True
if self.turn_on in ['off', False]: self.turn_on =False
elif self.turn_on in ['on', True]: self.turn_on =True
else : self.turn_on =False
if self._dipoleLength is None :
self._dipoleLength=(self.df['pk'].to_numpy().max()- \
self.df['pk'].to_numpy().min())/(len(
self.df['pk'].to_numpy())-1)
self.aBestInfos= wfunc.select_anomaly(
rhoa_array= self.df['rhoa'].to_numpy(),
pos_array= self.df['pk'].to_numpy(),
auto = self.auto,
dipole_length=self._dipoleLength ,
pos_bounds=self.anom_boundaries,
pos_anomaly = self._select_best_point,
display=self.turn_on
)
self._best_keys_points = list(self.aBestInfos.keys())
for ckey in self._best_keys_points :
if ckey.find('1_pk')>=0 :
self._best_key_point = ckey
break
def sanitize_columns(self):
"""
Get the columns of :ref:`erp` dataframe and set new names according to
:class:`~watex.core.ERP.erpLabels` .
"""
self.coord_flag=0
columns =[ c.lower().strip() for c in self._df.columns]
for ii, sscol in enumerate(columns):
try :
if re.match(r'^sta+', sscol) or re.match(r'^site+', sscol) or \
re.match(r'^pk+', sscol) :
columns[ii] = 'pk'
if re.match(r'>east+', sscol) or re.match(r'^x|X+', sscol):
columns[ii] = 'east'
if re.match(r'^north+', sscol) or re.match(r'^y|Y+', sscol):
columns[ii] = 'north'
if re.match(r'^lon+', sscol):
columns[ii] = 'lon'
self._coord_flag = 1
if re.match(r'^lat+', sscol):
columns[ii] = 'lat'
if re.match(r'^rho+', sscol) or re.match(r'^res+', sscol):
columns[ii] = 'rhoa'
except KeyError:
print(f'keys {self.erpLabels} are not found in {sscol}')
except:
self._logging.error(
f"Unrecognized header keys {sscol}. "
f"Erp keys are ={self.erpLabels}"
)
self.df =pd.DataFrame(data =self.data, columns= columns)
@property
def select_best_point_(self):
""" Select the best anomaly points."""
self._select_best_point_= self.aBestInfos[self._best_key_point][0]
mes ='The best point is found at position (pk) = {0} m. '\
'----> Station number {1}'.format(
self._select_best_point_,
int(self._select_best_point_/self.dipoleLength)+1
)
wfunc.wrap_infos(mes, on =self.turn_on)
return self._select_best_point_
@property
def dipoleLength(self):
"""Get the dipole length i.e the distance between two measurement."""
wfunc.wrap_infos(
'Distance bewteen measurement is = {0} m.'.
format(self._dipoleLength), off = self.turn_on)
return self._dipoleLength
@property
def best_points (self) :
""" Get the best points from auto computation """
if len(self._best_keys_points)>1 : verb, pl='were','s'
else: verb, pl='was',''
mess =['{0} best point{1} {2} found :\n '.
format(len(self._best_keys_points),pl,verb)]
self._best_points ={}
for ii, bp in enumerate (self._best_keys_points):
cods = float(bp.replace('{0}_pk'.format(ii+1), ''))
pmes='{0:02} : position = {1} m ----> rhoa = {2} Ω.m\n '.format(
ii+1, cods,
self.aBestInfos[bp][1])
mess.append(pmes)
self._best_points['{}'.format(cods)]=self.aBestInfos[bp][1]
mess[-1]=mess[-1].replace('\n', '')
wfunc.wrap_infos(''.join([ss for ss in mess]),
on = self.turn_on)
return self._best_points
@property
def best_power (self):
"""Get the power from the select :attr:`select_best_point_`"""
self._power =wMath.compute_power(
posMinMax=self.aBestInfos[self._best_key_point][2])
wfunc.wrap_infos(
'The power of selected best point is = {0}'.format(self._power),
on = self.turn_on)
return self._power
@property
def best_magnitude(self):
""" Get the magnitude of the select :attr:`select_best_point_"""
self._magnitude =wMath.compute_magnitude(
rhoa_max=self.rhoa_max,rhoa_min=self.select_best_value_)
wfunc.wrap_infos(
'The magnitude of selected best point is = {0}'.
format(self._magnitude),
on = self.turn_on)
return self._magnitude
@property
def best_sfi(self) :
"""Get the standard fraturation index from
:attr:`select_best_point_"""
self._sfi = wMath.compute_sfi(pk_min=self.posi_min,
pk_max=self.posi_max,
rhoa_min=self.rhoa_min,
rhoa_max=self.rhoa_max,
rhoa=self.select_best_value_,
pk=self.select_best_point_)
wfunc.wrap_infos('SFI computed at the selected best point is = {0}'.
format(self._sfi),
on =self.turn_on)
return self._sfi
@property
def posi_max (self):
"""Get the right position of :attr:`select_best_point_ boundaries
using the station locations of unarbitrary positions got from
:attr:`dipoleLength`."""
return np.array(self.aBestInfos[self._best_key_point][2]).max()
@property
def posi_min (self):
"""Get the left position of :attr:`select_best_point_ boundaries
using the station locations of unarbitrary positions got from
:attr:`dipoleLength`."""
return np.array(self.aBestInfos[self._best_key_point][2]).min()
@property
def rhoa_min (self):
"""Get the buttom position of :attr:`select_best_point_ boundaries
using the magnitude got from :attr:`abest_magnitude`."""
return np.array(self.aBestInfos[self._best_key_point][3]).min()
@property
def rhoa_max (self):
"""Get the top position of :attr:`select_best_point_ boundaries
using the magnitude got from :attr:`abest_magnitude`."""
return np.array(self.aBestInfos[self._best_key_point][3]).max()
@property
def select_best_value_(self):
""" Select the best anomaly points."""
self._select_best_value= float(
self.aBestInfos[self._best_key_point][1]
)
wfunc.wrap_infos('Best conductive value selected is = {0} Ω.m'.
format(self._select_best_value),
on =self.turn_on)
return self._select_best_value
@property
def best_anr (self ):
"""Get the select best anomaly ratio `abest_anr` along the
:class:`~watex.core.erp.ERP`"""
pos_min_index = int(np.where(self.df['pk'].to_numpy(
) ==self.posi_min)[0])
pos_max_index = int(np.where(self.df['pk'].to_numpy(
) ==self.posi_max)[0])
self._anr = wMath.compute_anr(sfi = self.best_sfi,
rhoa_array = self.df['rhoa'].to_numpy(),
pos_bound_indexes= [pos_min_index ,
pos_max_index ])
wfunc.wrap_infos('Best cover = {0} % of the whole ERP line'.
format(self._anr*100),
on =self.turn_on)
return self._anr
@property
def best_type (self):
""" Get the select best anomaly type """
if self._type is None:
self._type = get_type(erp_array= self.df['rhoa'].to_numpy() ,
posMinMax = np.array([float(self.posi_max),
float(self.posi_min)]),
pk= self.select_best_point_ ,
pos_array=self.df['pk'].to_numpy() ,
dl= self.dipoleLength)
wfunc.wrap_infos('Select anomaly type is = {}'.
format(self._type),
on =self.turn_on)
return self._type
@property
def best_shape (self) :
""" Find the selected anomaly shape"""
if self._shape is None:
self._shape = get_shape(
rhoa_range=self.aBestInfos[self._best_key_point][4])
wfunc.wrap_infos('Select anomaly shape is = {}'.
format(self._shape),
on =self.turn_on)
return self._shape
@property
def best_east(self):
""" Get the easting coordinates of selected anomaly"""
self._east = self.df['east'].to_numpy()[self.best_index]
return self._east
@property
def best_north(self):
""" Get the northing coordinates of selected anomaly"""
self._north = self.df['north'].to_numpy()[self.best_index]
return self._north
@property
def best_index(self):
""" Keeop the index of selected best anomaly """
v_= (np.where( self.df['pk'].to_numpy(
)== self.select_best_point_)[0])
if len(v_)>1:
v_=v_[0]
return int(v_)
@property
def best_lat(self):
""" Get the latitude coordinates of selected anomaly"""
self._lat = self._latitude[self.best_index]
return self._lat
@property
def best_lon(self):
""" Get the longitude coordinates of selected anomaly"""
self._lat = self._longitude[self.best_index]
return self._lon
@property
def best_rhoaRange(self):
"""
Collect the resistivity values range from selected anomaly boundaries.
"""
return self.aBestInfos[self._best_key_point][4]
def get_type (erp_array, posMinMax, pk, pos_array, dl):
"""
Find anomaly type from app. resistivity values and positions locations
:param erp_array: App.resistivty values of all `erp` lines
:type erp_array: array_like
:param posMinMax: Selected anomaly positions from startpoint and endpoint
:type posMinMax: list or tuple or nd.array(1,2)
:param pk: Position of selected anomaly in meters
:type pk: float or int
:param pos_array: Stations locations or measurements positions
:type pos_array: array_like
:param dl:
Distance between two receiver electrodes measurement. The same
as dipole length in meters.
:returns:
- ``EC`` for Extensive conductive.
- ``NC`` for narrow conductive.
- ``CP`` for conductive plane
- ``CB2P`` for contact between two planes.
:Example:
>>> from watex.core.erp import get_type
>>> x = [60, 61, 62, 63, 68, 65, 80, 90, 100, 80, 100, 80]
>>> pos= np.arange(0, len(x)*10, 10)
>>> ano_type= get_type(erp_array= np.array(x),
... posMinMax=(10,90), pk=50, pos_array=pos, dl=10)
>>> ano_type
...CB2P
"""
# Get position index
anom_type ='CP'
index_pos = int(np.where(pos_array ==pk)[0])
# if erp_array [:index_pos +1].mean() < np.median(erp_array) or\
# erp_array[index_pos:].mean() < np.median(erp_array) :
# anom_type ='CB2P'
if erp_array [:index_pos+1].mean() < np.median(erp_array) and \
erp_array[index_pos:].mean() < np.median(erp_array) :
anom_type ='CB2P'
elif erp_array [:index_pos +1].mean() >= np.median(erp_array) and \
erp_array[index_pos:].mean() >= np.median(erp_array) :
if dl <= (max(posMinMax)- min(posMinMax)) <= 5* dl:
anom_type = 'NC'
elif (max(posMinMax)- min(posMinMax))> 5 *dl:
anom_type = 'EC'
return anom_type
def get_shape(rhoa_range):
"""
Find anomaly `shape` from apparent resistivity values framed to
the best points.
:param rhoa_range: The apparent resistivity from selected anomaly bounds
:attr:`~core.erp.ERP.anom_boundaries`
:type rhoa_range: array_like or list
:returns:
- V
- W
- K
- C
- M
- U
:Example:
>>> from watex.core.erp import get_shape
>>> x = [60, 70, 65, 40, 30, 31, 34, 40, 38, 50, 61, 90]
>>> shape = get_shape (rhoa_range= np.array(x))
...U
"""
shape ='V'
try:
minlocals_ix, = argrelextrema(rhoa_range, np.less)
except :
minlocals_ix = argrelextrema(rhoa_range, np.less)
try :
maxlocals_ix, = argrelextrema(rhoa_range, np.greater)
except : maxlocals_ix = argrelextrema(rhoa_range, np.greater)
value_of_median = np.median(rhoa_range)
coef_UH = 1.2
c_=[rhoa_range[0] , rhoa_range[-1] ]
if len(minlocals_ix)==0 :
if len(maxlocals_ix)==0 and\
(max(c_) and min(c_)) > value_of_median :
return 'U'
return 'C'
if len(minlocals_ix) ==1 :
if max(c_) > np.median(rhoa_range) and min(c_) < value_of_median/2:
return 'C'
elif rhoa_range[minlocals_ix] > value_of_median or \
rhoa_range[minlocals_ix] > max(c_):
return 'M'
if len(minlocals_ix)>1 :
if (max(c_) or min(c_))> value_of_median :
shape ='W'
if max(c_) > value_of_median and\
min(c_) > value_of_median:
if rhoa_range[maxlocals_ix].mean()> value_of_median :
if coef_UH * rhoa_range[minlocals_ix].mean():
shape ='H'
coef_UH = 1.
if rhoa_range[minlocals_ix].mean() <= coef_UH * \
rhoa_range[maxlocals_ix].mean():
shape = 'U'
else : shape ='K'
elif (rhoa_range[0] and rhoa_range[-1]) < np.median(rhoa_range):
shape = 'M'
return shape
return shape
def get_type2 (erp_array, posMinMax, pk, pos_array, dl=None):
"""
Find anomaly type from app. resistivity values and positions locations
:param erp_array: App.resistivty values of all `erp` lines
:type erp_array: array_like
:param posMinMax: Selected anomaly positions from startpoint and endpoint
:type posMinMax: list or tuple or nd.array(1,2)
:param pk: Position of selected anomaly in meters
:type pk: float or int
:param pos_array: Stations locations or measurements positions
:type pos_array: array_like
:param dl:
Distance between two receiver electrodes measurement. The same
as dipole length in meters.
:returns:
- ``EC`` for Extensive conductive.
- ``NC`` for narrow conductive.
- ``CP`` for conductive plane
- ``CB2P`` for contact between two planes.
:Example:
>>> from watex.core.erp import get_type
>>> x = [60, 61, 62, 63, 68, 65, 80, 90, 100, 80, 100, 80]
>>> pos= np.arange(0, len(x)*10, 10)
>>> ano_type= get_type(erp_array= np.array(x),
... posMinMax=(10,90), pk=50, pos_array=pos, dl=10)
>>> ano_type
...CB2P
"""
if dl is None:
dl = max(pos_array) - min(pos_array) / (len(pos_array)-1)
# Get position index
pos_ix = np.array(pos_array)- min(pos_array) /dl
pos_ix.astype(np.int32) # get index
anom_type ='CP'
index_pos = int(np.where(pos_array ==pk)[0])
left_bound= erp_array [:index_pos+1].mean()
right_bound = erp_array[index_pos:].mean()
med_= np.median(erp_array)
if (left_bound < med_ and right_bound >= med_) or \
(left_bound >= med_ and right_bound < med_) :
anom_type ='CB2P'
if left_bound > med_ and right_bound > med_ :
if dl <= (max(posMinMax)- min(posMinMax)) <= 5* dl:
anom_type = 'NC'
elif (max(posMinMax)- min(posMinMax))> 5 *dl:
anom_type = 'EC'
return anom_type
if __name__=='__main__' :
erp_data='data/erp/l10_gbalo.xlsx'# 'data/l11_gbalo.csv'
erp_path ='data/erp/test_anomaly.xlsx'
pathBag = r'F:\repositories\watex\data\Bag.main&rawds\ert_copy\an_dchar'#\zhouphouetkaha_1.xlsx'
test_fn = 'l10_gbalo.xlsx'
# erpObj =ERP(erp_fn=pathBag, turn_on ='off', utm_zone ='29N')
# erpObjs =ERP_collection(listOferpfn=pathBag, export =True , extension ='.xlsx',
# filename = '_testfile', savepath = 'data/exFeatures')
| 38.413011 | 100 | 0.490666 | 41,181 | 0.810905 | 0 | 0 | 10,553 | 0.207802 | 0 | 0 | 23,199 | 0.456817 |
0d1b7c2182554a8a0f1a06812e62cc4dae4383a2 | 122 | py | Python | py_tdlib/constructors/location.py | Mr-TelegramBot/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 24 | 2018-10-05T13:04:30.000Z | 2020-05-12T08:45:34.000Z | py_tdlib/constructors/location.py | MrMahdi313/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 3 | 2019-06-26T07:20:20.000Z | 2021-05-24T13:06:56.000Z | py_tdlib/constructors/location.py | MrMahdi313/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 5 | 2018-10-05T14:29:28.000Z | 2020-08-11T15:04:10.000Z | from ..factory import Type
class location(Type):
latitude = None # type: "double"
longitude = None # type: "double"
| 17.428571 | 35 | 0.680328 | 92 | 0.754098 | 0 | 0 | 0 | 0 | 0 | 0 | 32 | 0.262295 |
0d1d498ac11ac88aa3a027d6cc2474196fa5251f | 1,816 | py | Python | Task2G.py | caizicharles/IA-Floodwarning | 2f4931d000ca98b6c304507a422aabb49b4bd231 | [
"MIT"
] | null | null | null | Task2G.py | caizicharles/IA-Floodwarning | 2f4931d000ca98b6c304507a422aabb49b4bd231 | [
"MIT"
] | null | null | null | Task2G.py | caizicharles/IA-Floodwarning | 2f4931d000ca98b6c304507a422aabb49b4bd231 | [
"MIT"
] | null | null | null | from floodsystem.flood import stations_level_over_threshold
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.analysis import polyfit
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.utils import sorted_by_key
import numpy as np
from datetime import timedelta
def warning():
stations = build_station_list()
update_water_levels(stations)
name_ratio = stations_level_over_threshold(stations, 1)
t = 10
station_name = []
station_data = set()
station_list = set()
value = []
severity = []
output = []
for i in name_ratio:
for j in stations:
if i[0] == j.name and j.latest_level != None and j.typical_range != None and j.measure_id != None:
station_data.add(j)
for x in station_data:
if x.name == "Bissoe" or x.name == "Letcombe Bassett":
continue
else:
station_list.add(x)
for k in station_list:
station_name.append(k.name)
dates, levels = fetch_measure_levels(k.measure_id , dt = timedelta(days = t))
poly, d0 = polyfit(dates, levels, 4)
derivative = np.polyder(poly)
value.append(derivative(9))
for gradient in value:
if gradient < 0.1:
severity.append("Low")
elif gradient >= 0.1 and gradient < 0.2:
severity.append("Moderate")
elif gradient >= 0.2 and gradient < 0.3:
severity.append("High")
else:
severity.append("Severe")
for z in range(0, len(severity)):
output.append((station_name[z], severity[z]))
return sorted_by_key(output, 0, reverse=False)
if __name__ == "__main__":
print("*** Task 2G: CUED Part IA Flood Warning System ***")
print(warning()) | 31.310345 | 110 | 0.639317 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 117 | 0.064427 |
0d1d8f3ba1cb047658f3bd978f75518c9dd50942 | 3,514 | py | Python | simplecoin_rpc_client/scheduler.py | uingei/simplecoin_rpc_client_20171208 | 10ebea80b70db15944c8200923b41f78480d7f68 | [
"0BSD"
] | 2 | 2015-01-02T21:34:59.000Z | 2018-10-17T15:54:47.000Z | simplecoin_rpc_client/scheduler.py | uingei/simplecoin_rpc_client_20171208 | 10ebea80b70db15944c8200923b41f78480d7f68 | [
"0BSD"
] | 2 | 2015-03-26T00:08:55.000Z | 2015-06-06T21:31:17.000Z | simplecoin_rpc_client/scheduler.py | uingei/simplecoin_rpc_client_20171208 | 10ebea80b70db15944c8200923b41f78480d7f68 | [
"0BSD"
] | 6 | 2015-01-03T08:20:17.000Z | 2019-06-23T15:55:12.000Z | import logging
import os
import sqlalchemy
import setproctitle
import argparse
import yaml
from apscheduler.scheduler import Scheduler
from cryptokit.rpc_wrapper import CoinRPC
from simplecoin_rpc_client.sc_rpc import SCRPCClient
logger = logging.getLogger('apscheduler.scheduler')
os_root = os.path.abspath(os.path.dirname(__file__) + '/../')
class PayoutManager(object):
def __init__(self, logger, sc_rpc, coin_rpc):
self.logger = logger
self.sc_rpc = sc_rpc
self.coin_rpc = coin_rpc
def pull_payouts(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.pull_payouts()
def send_payout(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
# Try to pay out known payouts
result = sc_rpc.send_payout()
if isinstance(result, bool):
continue
else:
coin_txid, tx, payouts = result
sc_rpc.associate_all()
# Push completed payouts to SC
sc_rpc.associate(coin_txid, payouts, tx.fee)
def associate_all_payouts(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.associate_all()
def confirm_payouts(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.confirm_trans()
def init_db(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.init_db()
def dump_incomplete(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.dump_incomplete()
def dump_complete(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.dump_complete()
def entry():
parser = argparse.ArgumentParser(prog='simplecoin rpc client scheduler')
parser.add_argument('-l', '--log-level',
choices=['DEBUG', 'INFO', 'WARN', 'ERROR'],
default='INFO')
parser.add_argument('-cl', '--config-location',
default='/config.yml')
args = parser.parse_args()
# Setup logging
root = logging.getLogger()
hdlr = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s [%(name)s] [%(levelname)s] %(message)s')
hdlr.setFormatter(formatter)
root.addHandler(hdlr)
root.setLevel(getattr(logging, args.log_level))
# Setup yaml configs
# =========================================================================
cfg = yaml.load(open(os_root + args.config_location))
# Setup our CoinRPCs + SCRPCClients
coin_rpc = {}
sc_rpc = {}
for curr_cfg in cfg['currencies']:
if not curr_cfg['enabled']:
continue
cc = curr_cfg['currency_code']
coin_rpc[cc] = CoinRPC(curr_cfg, logger=logger)
curr_cfg.update(cfg['sc_rpc_client'])
sc_rpc[cc] = SCRPCClient(curr_cfg, coin_rpc[cc], logger=logger)
pm = PayoutManager(logger, sc_rpc, coin_rpc)
sched = Scheduler(standalone=True)
logger.info("=" * 80)
logger.info("SimpleCoin cron scheduler starting up...")
setproctitle.setproctitle("simplecoin_scheduler")
# All these tasks actually change the database, and shouldn't
# be run by the staging server
sched.add_cron_job(pm.pull_payouts, minute='*/1')
sched.add_cron_job(pm.send_payout, hour='23')
sched.add_cron_job(pm.associate_all_payouts, hour='0')
sched.add_cron_job(pm.confirm_payouts, hour='1')
sched.start()
if __name__ == "__main__":
entry()
| 30.293103 | 87 | 0.628913 | 1,345 | 0.382755 | 0 | 0 | 0 | 0 | 0 | 0 | 639 | 0.181844 |
0d1e5454f292c59dd72eec135f4dab6607754ce9 | 716 | py | Python | SpeakyTo/interfaces/irc2.py | SpeakyTo/SCORE | 244f7e732a40a0d29e796f38823aab57d31ce786 | [
"Apache-2.0"
] | null | null | null | SpeakyTo/interfaces/irc2.py | SpeakyTo/SCORE | 244f7e732a40a0d29e796f38823aab57d31ce786 | [
"Apache-2.0"
] | null | null | null | SpeakyTo/interfaces/irc2.py | SpeakyTo/SCORE | 244f7e732a40a0d29e796f38823aab57d31ce786 | [
"Apache-2.0"
] | null | null | null |
from iconservice import *
class IRC2Interface(InterfaceScore):
""" An interface of ICON Token Standard, IRC-2"""
@interface
def name(self) -> str:
pass
@interface
def symbol(self) -> str:
pass
@interface
def decimals(self) -> int:
pass
@interface
def totalSupply(self) -> int:
pass
@interface
def balanceOf(self, _owner: Address) -> int:
pass
@interface
def transfer(self, _to: Address, _value: int, _data: bytes = None):
pass
@interface
def treasury_withdraw(self, _dest: Address, _value: int):
pass
@interface
def treasury_deposit(self, _src: Address, _value: int):
pass
| 18.358974 | 71 | 0.597765 | 685 | 0.956704 | 0 | 0 | 548 | 0.765363 | 0 | 0 | 49 | 0.068436 |
0d20b57c8cffa9b2d57ee77c2abe05ad04d2a179 | 8,686 | py | Python | io_import_planar_code.py | tsurutana/planer_code-importer-blender | 409423277adc56f7d7dda9429de4d5ae807226e4 | [
"MIT"
] | null | null | null | io_import_planar_code.py | tsurutana/planer_code-importer-blender | 409423277adc56f7d7dda9429de4d5ae807226e4 | [
"MIT"
] | null | null | null | io_import_planar_code.py | tsurutana/planer_code-importer-blender | 409423277adc56f7d7dda9429de4d5ae807226e4 | [
"MIT"
] | null | null | null | bl_info = {
"name": "Import Planar Code",
"author": "Naoya Tsuruta",
"version": (1, 0),
"blender": (2, 80, 0),
"location": "File > Import > Planar Code",
"description": "Import planar code and construct mesh by assigning vertex positions.",
"warning": "",
"support": "TESTING",
"wiki_url": "",
"tracker_url": "",
"category": "Import-Export",
}
import bpy
import bmesh
import numpy as np
import mathutils as mu
from bpy.props import StringProperty, IntProperty, BoolProperty
import struct
import collections
import os
import random
class PlanarCodeReader:
def __init__(self, filename, index, embed2d, embed3d):
self.faceCounters = []
verts_loc, faces = self.read(filename, index)
if (not verts_loc):
return
if (len(verts_loc) <= 0):
return
# create new mesh
name = os.path.basename(filename) + "_" + str(index)
mesh = bpy.data.meshes.new(name)
mesh.from_pydata(verts_loc,[],faces)
mesh.update(calc_edges=True)
# create new bmesh
bm = bmesh.new()
bm.from_mesh(mesh)
# enable lookup
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
if (embed2d):
pv = self.embed(bm)
print(pv)
if (embed3d):
self.liftup(bm, pv)
bm.to_mesh(mesh)
# create new object
obj = bpy.data.objects.new(name, mesh)
# set object location
obj.location = bpy.context.scene.cursor.location
# link the object to collection
bpy.context.scene.collection.objects.link(obj)
def read(self, filename, index):
self.f = open(filename, "rb")
verts = []
faces = []
try:
DEFAULT_HEADER = b">>planar_code<<"
header = self.f.read(len(DEFAULT_HEADER))
if (header == DEFAULT_HEADER):
print(index)
self.skip(index)
# create verts
num_vert = struct.unpack('b', self.f.read(1))
i = 0
while i < num_vert[0]:
# create vertex
verts.append((0, 0, 0))
# read adjacant vertices
adj = []
while True:
tmp = struct.unpack('b', self.f.read(1))
if (tmp[0] <= 0): # 0 means separator
break
adj.append(tmp[0])
# add face counter
lastIndex = len(adj)-1
for j in range(lastIndex):
self.addIfAbsent(collections.Counter([i, adj[j]-1, adj[j+1]-1]))
self.addIfAbsent(collections.Counter([i, adj[0]-1, adj[lastIndex]-1]))
i += 1
for counter in self.faceCounters:
faces.append(tuple(counter))
except:
print(f"Error in reading {filename}")
self.f.close()
return
self.f.close()
del self.f
return verts, faces
def skip(self, index):
# skip to target index
for i in range(index):
num_vert = struct.unpack('b', self.f.read(1))
n = num_vert[0]
while n > 0:
d = struct.unpack('b', self.f.read(1))
if (d[0] == 0):
n -= 1
def addIfAbsent(self, fc):
for counter in self.faceCounters:
if (counter == fc):
break
else:
self.faceCounters.append(fc)
def embed(self, bm):
# randomly pick up a face
outerFace = bm.faces[random.randint(0, len(bm.faces)-1)]
# embed an outer face to form a regular polygon inscribed into a circle
n = len(outerFace.verts)
inv_sqrt = 1.0 / np.sqrt(n)
angle = 360.0 / n
for i, v in enumerate(outerFace.verts):
rad = (i * angle / 180.0) * np.pi
x = inv_sqrt * np.cos(rad)
y = inv_sqrt * np.sin(rad)
v.co.x = x
v.co.y = y
rests = []
for v in bm.verts:
if (not v in outerFace.verts):
rests.append(v)
# variables for the force F_uv on a Edge(u,v)
fuv = np.zeros((len(bm.edges), 3))
# force F_v on a Vertex(v)
fv = np.zeros((len(bm.verts), 3))
# Constant value
n_pi = np.sqrt(len(bm.verts) / np.pi)
# final double A = 2.5;
avg_area = np.pi / len(bm.verts)
loop = 0
# iterations
while (loop < 500):
# Set F_v to zero
fv[:] = 0
# Calculate F_uv for Edges
for j, e in enumerate(bm.edges):
v = e.verts[0]
u = e.verts[1]
C = n_pi
x = C * np.power(v.co.x - u.co.x, 3)
y = C * np.power(v.co.y - u.co.y, 3)
if (np.isfinite(x) and np.isfinite(y)):
fuv[j] = [x, y, 0]
# Update the forces on v and u
fv[v.index] -= fuv[j]
fv[u.index] += fuv[j]
# Move Vertices
cool = np.sqrt(avg_area) / (1.0 + np.power(np.sqrt(avg_area * loop), 3))
for v in rests:
f = np.linalg.norm(fv[v.index])
size = min(f, cool)
if f != 0:
fv[v.index] /= f
fv[v.index] *= size
v.co.x += fv[v.index, 0]
v.co.y += fv[v.index, 1]
loop += 1
return self.periphericity(bm, outerFace)
def periphericity(self, bm, outer):
stack0 = []
stack1 = []
per = 0
pv = np.full(len(bm.verts), -1)
for v in outer.verts:
stack0.append(v)
while (stack0):
for v in stack0:
pv[v.index] = per
# Search adjoining verts
for vi in stack0:
links = vi.link_edges
for e in links:
vo = e.verts[1] if vi.index == e.verts[0].index else e.verts[0]
if (pv[vo.index] < 0):
if (not vo in stack1):
stack1.append(vo)
stack0.clear()
stack0.extend(stack1)
stack1.clear()
per += 1
return pv
def liftup(self, bm, pv):
H = 0.3
for v in bm.verts:
z = H * pv[v.index]
v.co.z = z
class IMPORT_OT_pcode(bpy.types.Operator):
"""Import Planar Code Operator"""
bl_idname = "import_planarcode.pcode"
bl_label = "Import planar code"
bl_description = "Embed a graph written in planar code (binary file)"
bl_options = {"REGISTER", "UNDO"}
bpy.types.Scene.ch = None
bpy.types.Scene.poly = None
filepath: StringProperty(
name="File Path",
description="Filepath used for importing the Planar code file",
maxlen=1024,
default="",
)
CODE_INDEX: IntProperty(
name="Planer code index",
description="An index follows generated order",
default=0,
min=0,
)
EMBED_2D: BoolProperty(
name="Embedding in 2D",
description="Embed a graph in the plane",
default=True,
)
EMBED_3D: BoolProperty(
name="Realizing a graph",
description="Make a polyhedron by giving the heights to the vertices",
default=True,
)
def invoke(self, context, event):
wm = context.window_manager
wm.fileselect_add(self)
return {"RUNNING_MODAL"}
def execute(self, context):
PlanarCodeReader(self.filepath, self.CODE_INDEX, self.EMBED_2D, self.EMBED_3D)
return {"FINISHED"}
def menu_func(self, context):
self.layout.operator(IMPORT_OT_pcode.bl_idname, text="Planar code (.*)")
classes = (
IMPORT_OT_pcode,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.TOPBAR_MT_file_import.append(menu_func)
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
bpy.types.TOPBAR_MT_file_import.remove(menu_func)
if __name__ == "__main__":
register()
| 31.70073 | 91 | 0.489523 | 7,587 | 0.873475 | 0 | 0 | 0 | 0 | 0 | 0 | 1,361 | 0.156689 |
0d2173d31093a043314df76aaf701045b2fe730c | 1,233 | py | Python | webtool/server/models/equipment.py | wodo/WebTool3 | 1582a03d619434d8a6139f705a1b5860e9b5b8b8 | [
"BSD-2-Clause"
] | 13 | 2018-12-16T21:01:24.000Z | 2019-07-03T06:23:41.000Z | webtool/server/models/equipment.py | dav-kempten/WebTool3 | 859f39df67cb0f853c7fe33cb5d08b999d8692fc | [
"BSD-2-Clause"
] | 26 | 2019-07-07T06:44:06.000Z | 2021-09-07T07:28:34.000Z | webtool/server/models/equipment.py | dav-kempten/WebTool3 | 859f39df67cb0f853c7fe33cb5d08b999d8692fc | [
"BSD-2-Clause"
] | 3 | 2017-06-18T06:22:52.000Z | 2019-07-03T06:21:05.000Z | # -*- coding: utf-8 -*-
from django.db import models
from .mixins import SeasonsMixin
from .time_base import TimeMixin
from . import fields
class EquipmentManager(models.Manager):
def get_by_natural_key(self, code):
return self.get(code=code)
class Equipment(SeasonsMixin, TimeMixin, models.Model):
objects = EquipmentManager()
code = models.CharField(
'Kurzzeichen',
unique=True,
max_length=10,
help_text="Kurzzeichen für die Ausrüstung",
)
name = fields.NameField(
'Bezeichnung',
help_text="Bezeichnung der Ausrüstung",
)
description = fields.DescriptionField(
'Beschreibung',
help_text="Beschreibung der Ausrüstung",
)
default = models.BooleanField(
'Die initiale Ausrüstung',
blank=True, default=False
)
def natural_key(self):
return self.code,
natural_key.dependencies = ['server.season']
def __str__(self):
return "{} ({})".format(self.name, self.code)
class Meta:
get_latest_by = "updated"
verbose_name = "Ausrüstung"
verbose_name_plural = "Ausrüstungen"
unique_together = ('code', 'name')
ordering = ('code', ) | 22.833333 | 55 | 0.634225 | 1,094 | 0.882258 | 0 | 0 | 0 | 0 | 0 | 0 | 261 | 0.210484 |
0d22a9dd7d5f467850b8900e066974665ef38818 | 2,394 | py | Python | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/NV/draw_vulkan_image.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/NV/draw_vulkan_image.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/NV/draw_vulkan_image.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | '''OpenGL extension NV.draw_vulkan_image
This module customises the behaviour of the
OpenGL.raw.GL.NV.draw_vulkan_image to provide a more
Python-friendly API
Overview (from the spec)
This extension provides a new function, DrawVkImageNV(), allowing
applications to draw a screen-aligned rectangle displaying some or all of
the contents of a two-dimensional Vulkan VkImage. Callers specify a
Vulkan VkImage handle, an optional OpenGL sampler object, window
coordinates of the rectangle to draw, and texture coordinates corresponding
to the corners of the rectangle. For each fragment produced by the
rectangle, DrawVkImageNV interpolates the texture coordinates, performs
a texture lookup, and uses the texture result as the fragment color.
No shaders are used by DrawVkImageNV; the results of the texture lookup
are used in lieu of a fragment shader output. The fragments generated are
processed by all per-fragment operations. In particular,
DrawVkImageNV() fully supports blending and multisampling.
In order to synchronize between Vulkan and OpenGL there are three other
functions provided; WaitVkSemaphoreNV(), SignalVkSemaphoreNV() and
SignalVkFenceNV(). These allow OpenGL to wait for Vulkan to complete work
and also Vulkan to wait for OpenGL to complete work. Together OpenGL
and Vulkan can synchronize on the server without application
interation.
Finally the function GetVkProcAddrNV() is provided to allow the OpenGL
context to query the Vulkan entry points directly and avoid having to
load them through the typical Vulkan loader.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/NV/draw_vulkan_image.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.GL import _types, _glgets
from OpenGL.raw.GL.NV.draw_vulkan_image import *
from OpenGL.raw.GL.NV.draw_vulkan_image import _EXTENSION_NAME
def glInitDrawVulkanImageNV():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( _EXTENSION_NAME )
# INPUT glGetVkProcAddrNV.name size not checked against 'name'
glGetVkProcAddrNV=wrapper.wrapper(glGetVkProcAddrNV).setInputArraySize(
'name', None
)
### END AUTOGENERATED SECTION | 45.169811 | 77 | 0.789474 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,910 | 0.797828 |
0d246003e8c49782d663db0652fc20c6c7b5ad5f | 426 | py | Python | orders/urls.py | techonerd/kobbyshop | e79f009f75f576fdc2e8ac037781f5817a2e255f | [
"MIT"
] | 4 | 2021-11-25T15:45:31.000Z | 2022-01-11T21:31:56.000Z | orders/urls.py | KwabenaYeboah/kobbyshop | 850a04b24fafa8aa538fdbf039a0e8fafc3ebfc2 | [
"MIT"
] | 1 | 2021-12-30T08:18:28.000Z | 2021-12-30T08:18:28.000Z | orders/urls.py | techonerd/kobbyshop | e79f009f75f576fdc2e8ac037781f5817a2e255f | [
"MIT"
] | 2 | 2021-12-26T05:11:00.000Z | 2021-12-30T08:18:13.000Z | from django.urls import path
from django.utils.translation import gettext_lazy as _
from .views import create_order_view, order_detail_view, generate_order_pdf_view
urlpatterns = [
path('admin/order/<int:order_id>/', order_detail_view, name='admin_order_detail'),
path('admin/order/<int:order_id>/pdf/', generate_order_pdf_view, name='generate_order_pdf'),
path(_(''), create_order_view, name='create_order'),
]
| 38.727273 | 96 | 0.7723 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 118 | 0.276995 |
0d264d356130367d822124ae49b5e060a6d3d6dd | 21,781 | py | Python | ncov_ism/_visualization.py | z2e2/ncov_ism | 14e3dcd7c568e21b437dfdb7d74353ed8bd93c8f | [
"BSD-3-Clause"
] | null | null | null | ncov_ism/_visualization.py | z2e2/ncov_ism | 14e3dcd7c568e21b437dfdb7d74353ed8bd93c8f | [
"BSD-3-Clause"
] | null | null | null | ncov_ism/_visualization.py | z2e2/ncov_ism | 14e3dcd7c568e21b437dfdb7d74353ed8bd93c8f | [
"BSD-3-Clause"
] | 1 | 2020-08-04T23:59:26.000Z | 2020-08-04T23:59:26.000Z | import logging
import matplotlib
import pickle
matplotlib.use('Agg')
import matplotlib.colors as mcolors
import numpy as np
import matplotlib.pyplot as plt
plt.ioff()
font = {# 'family' : 'serif', # Times (source: https://matplotlib.org/tutorials/introductory/customizing.html)
'family': 'sans-serif', # Helvetica
'size' : 12}
matplotlib.rc('font', **font)
text = {'usetex': False}
matplotlib.rc('text', **text)
monospace_font = {'fontname':'monospace'}
CSS4_COLORS = mcolors.CSS4_COLORS
logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO)
def ISM_filter(dict_freq, threshold):
"""
collapse low frequency ISMs into "OTHER" per location
Parameters
----------
dict_freq: dictionary
ISM frequency of a location of interest
threshold: float
ISMs lower than this threshold will be collapsed into "OTHER"
Returns
-------
res_dict: dictionary
filtered ISM frequency of a location of interest
"""
res_dict = {'OTHER': [0, 0]}
total = sum([int(dict_freq[ISM][1]) for ISM in dict_freq])
for ISM in dict_freq:
if int(dict_freq[ISM][1])/total < threshold:
res_dict['OTHER'] = [0, res_dict['OTHER'][1] + int(dict_freq[ISM][1])]
else:
res_dict[ISM] = [dict_freq[ISM][0], int(dict_freq[ISM][1]) + res_dict.get(ISM, [0, 0])[1]]
if res_dict['OTHER'][1] == 0:
del res_dict['OTHER']
return res_dict
def ISM_time_series_filter(dict_freq, threshold):
"""
collapse low frequency ISMs into "OTHER" per location
Parameters
----------
dict_freq: dictionary
ISM frequency of a location of interest
threshold: float
ISMs lower than this threshold will be collapsed into "OTHER"
Returns
-------
res_dict: dictionary
filtered ISM frequency of a location of interest
"""
res_dict = {'OTHER': [0, 0]}
total = sum([int(dict_freq[ISM]) for ISM in dict_freq])
for ISM in dict_freq:
if int(dict_freq[ISM])/total < threshold:
res_dict['OTHER'] = [0, res_dict['OTHER'][1] + int(dict_freq[ISM])]
else:
res_dict[ISM] = [dict_freq[ISM], int(dict_freq[ISM]) + res_dict.get(ISM, [0, 0])[1]]
if res_dict['OTHER'][1] == 0:
del res_dict['OTHER']
return res_dict
def ISM_visualization(region_raw_count, state_raw_count, count_dict, region_list, state_list, time_series_region_list,
output_folder, ISM_FILTER_THRESHOLD=0.05, ISM_TIME_SERIES_FILTER_THRESHOLD=0.025):
'''
Informative Subtype Marker analysis visualization
Parameters
----------
region_raw_count: dictionary
ISM frequency per region
state_raw_count: dictionary
ISM frequency per state
count_dict: dictionary
ISM frequency time series per region
region_list: list
regions of interest
state_list: list
states of interest
time_series_region_list: list
regions of interest for time series analysis
output_folder: str
path to the output folder
ISM_FILTER_THRESHOLD: float
ISM filter threshold
ISM_TIME_SERIES_FILTER_THRESHOLD: float
ISM filter threshold for time series
Returns
-------
Objects for downstream visualization
'''
ISM_set = set([])
region_pie_chart = {}
for idx, region in enumerate(region_list):
dict_freq_filtered = ISM_filter(region_raw_count[region], ISM_FILTER_THRESHOLD)
region_pie_chart[region] = dict_freq_filtered
ISM_set.update(dict_freq_filtered.keys())
state_pie_chart = {}
for idx, state in enumerate(state_list):
dict_freq_filtered = ISM_filter(state_raw_count[state], ISM_FILTER_THRESHOLD)
state_pie_chart[state] = dict_freq_filtered
ISM_set.update(dict_freq_filtered.keys())
count_list = []
date_list = []
sorted_date = sorted(count_dict.keys())
for date in sorted_date:
dict_freq = {}
for region in time_series_region_list:
regional_dict_freq = count_dict[date][region]
dict_freq_filtered = ISM_time_series_filter(regional_dict_freq, ISM_TIME_SERIES_FILTER_THRESHOLD )
ISM_set.update(list(dict_freq_filtered.keys()))
dict_freq[region] = dict_freq_filtered
count_list.append(dict_freq)
date_list.append(date)
return ISM_set, region_pie_chart, state_pie_chart, count_list, date_list
def customized_ISM_visualization(region_raw_count, count_dict, region_list, output_folder,
ISM_FILTER_THRESHOLD=0.05, ISM_TIME_SERIES_FILTER_THRESHOLD=0.025):
'''
Informative Subtype Marker analysis visualization
Parameters
----------
region_raw_count: dictionary
ISM frequency per region
state_raw_count: dictionary
ISM frequency per state
count_dict: dictionary
ISM frequency time series per region
region_list: list
regions of interest
state_list: list
states of interest
time_series_region_list: list
regions of interest for time series analysis
output_folder: str
path to the output folder
ISM_FILTER_THRESHOLD: float
ISM filter threshold
ISM_TIME_SERIES_FILTER_THRESHOLD: float
ISM filter threshold for time series
Returns
-------
Objects for downstream visualization
'''
ISM_set = set([])
region_pie_chart = {}
for idx, region in enumerate(region_list):
dict_freq_filtered = ISM_filter(region_raw_count[region], ISM_FILTER_THRESHOLD)
region_pie_chart[region] = dict_freq_filtered
ISM_set.update(dict_freq_filtered.keys())
count_list = []
date_list = []
sorted_date = sorted(count_dict.keys())
for date in sorted_date:
dict_freq = {}
for region in region_list:
regional_dict_freq = count_dict[date][region]
dict_freq_filtered = ISM_time_series_filter(regional_dict_freq, ISM_TIME_SERIES_FILTER_THRESHOLD )
ISM_set.update(list(dict_freq_filtered.keys()))
dict_freq[region] = dict_freq_filtered
count_list.append(dict_freq)
date_list.append(date)
return ISM_set, region_pie_chart, count_list, date_list
def get_color_names(CSS4_COLORS, num_colors):
'''
Prepare colors for each ISM.
'''
bad_colors = set(['seashell', 'linen', 'ivory', 'oldlace','floralwhite',
'lightyellow', 'lightgoldenrodyellow', 'honeydew',
'mintcream', 'azure', 'lightcyan', 'aliceblue',
'ghostwhite', 'lavenderblush'
])
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))),
name)
for name, color in CSS4_COLORS.items())
names = [name for hsv, name in by_hsv][14:]
prime_names = ['red', 'orange', 'green', 'blue', 'gold',
'lightskyblue', 'brown', 'black', 'pink',
'yellow']
OTHER = 'gray'
name_list = [name for name in names if name not in prime_names and name != OTHER and name not in bad_colors]
if num_colors > len(name_list) - 10:
logging.info('NOTE: Repetitive colors for different ISMs (inadequate distinctive colors)')
name_list = name_list + ceil(num_colors/len(name_list)) * name_list
if num_colors > len(prime_names):
ind_list = np.linspace(0, len(name_list), num_colors - 10, dtype = int, endpoint=False).tolist()
color_names = prime_names + [name_list[ind] for ind in ind_list]
else:
color_names = prime_names[:num_colors]
return color_names
def global_color_map(COLOR_DICT, ISM_list, out_dir):
'''
Plot color-ISM map for reference.
Adapted from https://matplotlib.org/3.1.0/gallery/color/named_colors.html
'''
ncols = 3
n = len(COLOR_DICT)
nrows = n // ncols + int(n % ncols > 0)
cell_width = 1300
cell_height = 100
swatch_width = 180
margin = 30
topmargin = 40
width = cell_width * 3 + 2 * margin
height = cell_height * nrows + margin + topmargin
dpi = 300
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
fig.subplots_adjust(margin/width, margin/height,
(width-margin)/width, (height-topmargin)/height)
ax.set_xlim(0, cell_width * 4)
ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
ax.yaxis.set_visible(False)
ax.xaxis.set_visible(False)
ax.set_axis_off()
# ax.set_title(title, fontsize=24, loc="left", pad=10)
ISM_list.append('OTHER')
for i, name in enumerate(ISM_list):
row = i % nrows
col = i // nrows
y = row * cell_height
swatch_start_x = cell_width * col
swatch_end_x = cell_width * col + swatch_width
text_pos_x = cell_width * col + swatch_width + 50
ax.text(text_pos_x, y, name, fontsize=14,
fontname='monospace',
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y, swatch_start_x, swatch_end_x,
color=COLOR_DICT[name], linewidth=18)
plt.savefig('{}/COLOR_MAP.png'.format(out_dir), bbox_inches='tight', dpi=dpi)
plt.close(fig)
def func(pct, allvals):
'''
covert to absolute value for pie chart plot.
'''
absolute = int(round(pct/100.*np.sum(allvals)))
return "{:d}".format(absolute)
def plot_pie_chart(sizes, labels, colors, ax):
'''
plot pie chart
Adapted from https://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/pie_and_donut_labels.html#sphx-glr-gallery-pie-and-polar-charts-pie-and-donut-labels-py
'''
wedges, texts, autotexts = ax.pie(sizes, autopct=lambda pct: func(pct, sizes), colors = colors, textprops=dict(color="w"))
time_labels = ['-' if label == 'OTHER' else label.split(' ')[1] for label in labels]
ax.legend(wedges, time_labels,
# title="Oligotypes",
loc="lower left",
bbox_to_anchor=(0.8, 0, 0.5, 1))
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
return wedges, labels
def regional_growth_plot(region, ISM_df, REFERENCE_date, count_list, date_list, COLOR_DICT, OUTPUT_FOLDER):
'''
time series plot for a region of interest
'''
xlim_len = (ISM_df[ISM_df['country/region'] == region]['date'].max().date() - REFERENCE_date).days
fig = plt.figure(figsize = (30, 15))
n = 4
ax=plt.subplot(1, 1, 1)
regional_total = []
ISM_regional_set = set([])
for i in range(len(count_list)):
regional_dict_freq = count_list[i][region]
regional_total.append(sum([regional_dict_freq[ISM][1] for ISM in regional_dict_freq]))
ISM_regional_set.update(regional_dict_freq.keys())
ISM_regional_list = []
for ISM in ISM_regional_set:
if ISM != 'OTHER':
ISM_regional_list.append(ISM)
NONOTHER = len(ISM_regional_list)
if 'OTHER' in ISM_regional_set:
ISM_regional_list.append('OTHER')
for ISM in ISM_regional_list:
ISM_regional_growth = []
for i in range(len(count_list)):
regional_dict_freq = count_list[i][region]
if ISM in regional_dict_freq and regional_dict_freq[ISM][1]!= 0:
ISM_regional_growth.append(regional_dict_freq[ISM][1]/regional_total[i])
else:
if ISM == 'OTHER':
other_count = sum([regional_dict_freq[ISM][1] for ISM in regional_dict_freq if ISM not in ISM_regional_set])
if regional_total[i] != 0:
ISM_regional_growth.append(other_count/regional_total[i])
else:
ISM_regional_growth.append(0)
else:
ISM_regional_growth.append(0)
ax.plot(ISM_regional_growth, color = COLOR_DICT[ISM], label = ISM, linewidth = 4, marker = 'o', markersize = 4)
major_ticks = np.arange(0, len(date_list), 5)
minor_ticks = np.arange(0, len(date_list))
major_label = []
for i in major_ticks.tolist():
major_label.append(str(date_list[i]))
ax.set_xticks(minor_ticks, minor=True)
ax.set_xticks(major_ticks)
ax.set_xticklabels(major_label)
plt.setp(ax.get_xticklabels(), rotation=90)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.legend(
loc="lower left",
bbox_to_anchor=(1, 0, 0.5, 1),
prop={'family': monospace_font['fontname']})
plt.xlim([-1, xlim_len])
plt.ylabel('Relative abundance')
ax.grid(which='minor', alpha=0.3, linestyle='--')
ax.grid(which='major', alpha=0.8)
plt.savefig('{}/3_ISM_growth_{}.png'.format(OUTPUT_FOLDER, region), bbox_inches='tight')
plt.close(fig)
def ISM_plot(ISM_df, ISM_set, region_list, region_pie_chart, state_list, state_pie_chart, REFERENCE_date, time_series_region_list, count_list, date_list, OUTPUT_FOLDER):
'''
Generate figures for ISM analysis.
'''
ISM_index = {}
idx = 0
for ISM, counts in ISM_df['ISM'].value_counts().items():
ISM_index[ISM] = idx
idx += 1
logging.info('{} ISMs will show up in the visualizations'.format(len(ISM_set)))
ISM_list = []
for ISM in ISM_set:
if ISM == 'OTHER':
continue
ISM_list.append((ISM, ISM_index[ISM]))
ISM_list = sorted(ISM_list, key = lambda x: x[1])
ISM_list = [item[0] for item in ISM_list]
color_map = get_color_names(CSS4_COLORS, len(ISM_list))
COLOR_DICT = {}
for idx, ISM in enumerate(ISM_list):
COLOR_DICT[ISM] = color_map[idx]
COLOR_DICT['OTHER'] = 'gray'
pickle.dump(COLOR_DICT, open('COLOR_DICT.pkl', 'wb'))
global_color_map(COLOR_DICT, ISM_list, OUTPUT_FOLDER)
DPI = 100
fig = plt.figure(figsize=(25, 15))
wedges_list = []
for idx, region in enumerate(region_list):
dict_freq = region_pie_chart[region]
total = sum([dict_freq[ISM][1] for ISM in dict_freq])
labels = []
sizes = []
colors = []
for ISM in dict_freq:
if ISM == 'OTHER':
continue
labels.append('{}: {}'.format(ISM, dict_freq[ISM][0]))
colors.append(COLOR_DICT[ISM])
sizes.append(dict_freq[ISM][1])
if 'OTHER' in dict_freq:
labels.append('OTHER')
colors.append(COLOR_DICT['OTHER'])
sizes.append(dict_freq['OTHER'][1])
ax=plt.subplot(5, 5, idx+1)
wedges, labels = plot_pie_chart(sizes, labels, colors, ax)
ax.set_title(region)
wedges_list.append((wedges, labels))
labels_handles = {}
handles_OTHER = None
for wedges, labels in wedges_list:
for idx, label in enumerate(labels):
label = label.split(':')[0]
if label == 'OTHER':
handles_OTHER = [wedges[idx], label]
continue
if label not in labels_handles:
labels_handles[label] = wedges[idx]
if handles_OTHER:
handles_list = list(labels_handles.values()) + [handles_OTHER[0]]
labels_list = list(labels_handles.keys()) + [handles_OTHER[1]]
fig.legend(
handles_list,
labels_list,
bbox_to_anchor=(0.82, 0.25),
bbox_transform=plt.gcf().transFigure,
ncol=5,
prop={'family': monospace_font['fontname']}
)
else:
fig.legend(
labels_handles.values(),
labels_handles.keys(),
bbox_to_anchor=(0.82, 0.25),
bbox_transform=plt.gcf().transFigure,
ncol=5,
prop={'family': monospace_font['fontname']}
)
plt.savefig('{}/1_regional_ISM.png'.format(OUTPUT_FOLDER), bbox_inches='tight', dpi=DPI, transparent=True)
plt.close(fig)
fig = plt.figure(figsize=(25, 20))
subplot_y = int(np.sqrt(len(state_list)))
subplot_x = int(np.sqrt(len(state_list))) + 1
if subplot_x * subplot_y < len(state_list):
subplot_y = subplot_x
wedges_list = []
for idx, state in enumerate(state_list):
dict_freq = state_pie_chart[state]
total = sum([dict_freq[ISM][1] for ISM in dict_freq])
labels = []
sizes = []
colors = []
for ISM in dict_freq:
if ISM == 'OTHER':
continue
labels.append('{}: {}'.format(ISM, dict_freq[ISM][0]))
colors.append(COLOR_DICT[ISM])
sizes.append(dict_freq[ISM][1])
if 'OTHER' in dict_freq:
labels.append('OTHER')
colors.append(COLOR_DICT['OTHER'])
sizes.append(dict_freq['OTHER'][1])
ax=plt.subplot(subplot_x, subplot_y, idx+1)
wedges, labels = plot_pie_chart(sizes, labels, colors, ax)
ax.set_title(state)
wedges_list.append((wedges, labels))
labels_handles = {}
handles_OTHER = None
for wedges, labels in wedges_list:
for idx, label in enumerate(labels):
label = label.split(':')[0]
if label == 'OTHER':
handles_OTHER = [wedges[idx], label]
continue
if label not in labels_handles:
labels_handles[label] = wedges[idx]
if handles_OTHER:
handles_list = list(labels_handles.values()) + [handles_OTHER[0]]
labels_list = list(labels_handles.keys()) + [handles_OTHER[1]]
fig.legend(
handles_list,
labels_list,
bbox_to_anchor=(0.82, 0.25),
bbox_transform=plt.gcf().transFigure,
ncol=5,
prop={'family': monospace_font['fontname']}
)
else:
fig.legend(
labels_handles.values(),
labels_handles.keys(),
bbox_to_anchor=(0.82, 0.25),
bbox_transform=plt.gcf().transFigure,
ncol=5,
prop={'family': monospace_font['fontname']}
)
plt.savefig('{}/2_intra-US_ISM.png'.format(OUTPUT_FOLDER), bbox_inches='tight', dpi=DPI, transparent=True)
plt.close(fig)
font = {'family': 'sans-serif', # Helvetica
'size' : 25}
matplotlib.rc('font', **font)
for region in time_series_region_list:
regional_growth_plot(region, ISM_df, REFERENCE_date, count_list, date_list, COLOR_DICT, OUTPUT_FOLDER)
def customized_ISM_plot(ISM_df, ISM_set, region_list, region_pie_chart, REFERENCE_date, count_list, date_list, OUTPUT_FOLDER):
'''
Generate figures for ISM analysis.
'''
ISM_index = {}
idx = 0
for ISM, counts in ISM_df['ISM'].value_counts().items():
ISM_index[ISM] = idx
idx += 1
logging.info('{} ISMs will show up in the visualizations'.format(len(ISM_set)))
ISM_list = []
for ISM in ISM_set:
if ISM == 'OTHER':
continue
ISM_list.append((ISM, ISM_index[ISM]))
ISM_list = sorted(ISM_list, key = lambda x: x[1])
ISM_list = [item[0] for item in ISM_list]
color_map = get_color_names(CSS4_COLORS, len(ISM_list))
COLOR_DICT = {}
for idx, ISM in enumerate(ISM_list):
COLOR_DICT[ISM] = color_map[idx]
COLOR_DICT['OTHER'] = 'gray'
pickle.dump(COLOR_DICT, open('COLOR_DICT.pkl', 'wb'))
global_color_map(COLOR_DICT, ISM_list, OUTPUT_FOLDER)
DPI = 100
fig = plt.figure(figsize=(25, 15))
wedges_list = []
for idx, region in enumerate(region_list):
dict_freq = region_pie_chart[region]
total = sum([dict_freq[ISM][1] for ISM in dict_freq])
labels = []
sizes = []
colors = []
for ISM in dict_freq:
if ISM == 'OTHER':
continue
labels.append('{}: {}'.format(ISM, dict_freq[ISM][0]))
colors.append(COLOR_DICT[ISM])
sizes.append(dict_freq[ISM][1])
if 'OTHER' in dict_freq:
labels.append('OTHER')
colors.append(COLOR_DICT['OTHER'])
sizes.append(dict_freq['OTHER'][1])
ax=plt.subplot(5, 5, idx+1)
wedges, labels = plot_pie_chart(sizes, labels, colors, ax)
ax.set_title(region)
wedges_list.append((wedges, labels))
labels_handles = {}
handles_OTHER = None
for wedges, labels in wedges_list:
for idx, label in enumerate(labels):
label = label.split(':')[0]
if label == 'OTHER':
handles_OTHER = [wedges[idx], label]
continue
if label not in labels_handles:
labels_handles[label] = wedges[idx]
if handles_OTHER:
handles_list = list(labels_handles.values()) + [handles_OTHER[0]]
labels_list = list(labels_handles.keys()) + [handles_OTHER[1]]
fig.legend(
handles_list,
labels_list,
bbox_to_anchor=(0.82, 0.25),
bbox_transform=plt.gcf().transFigure,
ncol=5,
prop={'family': monospace_font['fontname']}
)
else:
fig.legend(
labels_handles.values(),
labels_handles.keys(),
bbox_to_anchor=(0.82, 0.25),
bbox_transform=plt.gcf().transFigure,
ncol=5,
prop={'family': monospace_font['fontname']}
)
plt.savefig('{}/1_regional_ISM.png'.format(OUTPUT_FOLDER), bbox_inches='tight', dpi=DPI, transparent=True)
plt.close(fig)
font = {'family': 'sans-serif', # Helvetica
'size' : 25}
matplotlib.rc('font', **font)
for region in region_list:
regional_growth_plot(region, ISM_df, REFERENCE_date, count_list, date_list, COLOR_DICT, OUTPUT_FOLDER) | 36.301667 | 169 | 0.618567 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4,471 | 0.205271 |
0d26782c58b3c4b8dcb10b8b861fb7a599e50c84 | 2,272 | py | Python | gsh/plugins/executors/ssh.py | varunl/gsh | f0b4eb404afead35195d72a1abe4250c693b1e7c | [
"MIT"
] | 23 | 2015-01-30T04:16:58.000Z | 2021-07-28T22:31:01.000Z | gsh/plugins/executors/ssh.py | varunl/gsh | f0b4eb404afead35195d72a1abe4250c693b1e7c | [
"MIT"
] | 2 | 2015-04-21T06:55:44.000Z | 2016-03-29T22:29:15.000Z | gsh/plugins/executors/ssh.py | varunl/gsh | f0b4eb404afead35195d72a1abe4250c693b1e7c | [
"MIT"
] | 5 | 2015-04-21T06:43:58.000Z | 2018-11-03T10:14:35.000Z | import gevent
from gevent.queue import Queue, Empty
from gevent_subprocess import Popen, PIPE
from gsh.plugin import BaseExecutor, BaseInnerExecutor
class SshExecutor(BaseExecutor):
def __init__(self, args, kwargs):
self.ssh_opts = kwargs.get("ssh_opts", [])
super(SshExecutor, self).__init__(args, kwargs)
class Executor(BaseInnerExecutor):
def __init__(self, *args, **kwargs):
self.names = {}
self._output_queue = Queue()
super(SshExecutor.Executor, self).__init__(*args, **kwargs)
@staticmethod
def _stream_fd(fd, queue):
for line in iter(fd.readline, b""):
queue.put_nowait((fd, line))
def _consume(self, queue):
while True:
try:
output = queue.get()
except Empty:
continue
# None is explicitly sent to shutdown the consumer
if output is None:
return
fd, line = output
self.update(self.hostname, self.names[fd], line)
def run(self):
_proc = Popen(
["ssh", "-no", "PasswordAuthentication=no"] + self.parent.ssh_opts + [self.hostname] + self.command,
stdout=PIPE, stderr=PIPE
)
self.names = {
_proc.stdout: "stdout",
_proc.stderr: "stderr",
}
out_worker = gevent.spawn(self._stream_fd, _proc.stdout, self._output_queue)
err_worker = gevent.spawn(self._stream_fd, _proc.stderr, self._output_queue)
waiter = gevent.spawn(_proc.wait)
consumer = gevent.spawn(self._consume, self._output_queue)
gevent.joinall([out_worker, err_worker, waiter], timeout=self.timeout)
# If we've made it here and the process hasn't completed we've timed out.
if _proc.poll() is None:
self._output_queue.put_nowait(
(_proc.stderr, "GSH: command timed out after %s second(s).\n" % self.timeout))
_proc.kill()
rc = _proc.wait()
self._output_queue.put_nowait(None)
consumer.join()
return rc
| 33.910448 | 116 | 0.556778 | 2,120 | 0.933099 | 0 | 0 | 141 | 0.06206 | 0 | 0 | 235 | 0.103433 |
0d269caf9870407b800e22ac3a36faa1d6165a79 | 656 | py | Python | algDev/visualization/plot_indicators.py | ajmal017/ralph-usa | 41a7f910da04cfa88f603313fad2ff44c82b9dd4 | [
"Apache-2.0"
] | null | null | null | algDev/visualization/plot_indicators.py | ajmal017/ralph-usa | 41a7f910da04cfa88f603313fad2ff44c82b9dd4 | [
"Apache-2.0"
] | 7 | 2021-03-10T10:08:30.000Z | 2022-03-02T07:38:13.000Z | algDev/visualization/plot_indicators.py | ajmal017/ralph-usa | 41a7f910da04cfa88f603313fad2ff44c82b9dd4 | [
"Apache-2.0"
] | 1 | 2020-04-17T19:15:06.000Z | 2020-04-17T19:15:06.000Z | from models.indicators import Indicators
import numpy as np
import matplotlib.pyplot as plt
def plot_prices(ax, prices, line_style):
i = np.arange(len(prices))
ax.plot(ax, prices, line_style)
return ax
def plot_macd(ax, prices, slow_period, fast_period, line_style='k-'):
macd = Indicators.macd(prices, slow_period, fast_period)[slow_period - 1:]
i = np.arange(len(prices))[slow_period-1:]
ax.plot(i, macd, line_style)
return ax
def plot_ema(ax, prices, period, line_style='k-'):
ema = Indicators.ema(prices, period)[period-1:]
i = np.arange(len(prices))[period-1:]
ax.plot(i, ema, line_style)
return ax
| 26.24 | 78 | 0.692073 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 0.012195 |
0d26a577889f50bd86268acdd8f4b35667d26c74 | 4,318 | py | Python | app/db_worker.py | ryan-rushton/Basement | 69e1ee78b430a98069d1039f7e833151704fba86 | [
"Unlicense"
] | 5 | 2016-11-14T18:05:49.000Z | 2018-07-17T11:40:44.000Z | app/db_worker.py | ryan-rushton/Basement | 69e1ee78b430a98069d1039f7e833151704fba86 | [
"Unlicense"
] | null | null | null | app/db_worker.py | ryan-rushton/Basement | 69e1ee78b430a98069d1039f7e833151704fba86 | [
"Unlicense"
] | 4 | 2016-12-21T12:42:23.000Z | 2018-12-14T17:39:30.000Z | from multiprocessing import Process, Queue
from app.es_search import add_to_es, delete_all_es, reindex_es, delete_from_es
from logging import getLogger
from flask_sqlalchemy import SQLAlchemy
import sys
from app import app
from .models import Paste
logger = getLogger(__name__)
def delete_by_date_paste(date):
"""
Deletes the paste entries older than a certain date. Note that it will delete any document/index type entered into
it for elasticsearch, the paste restriction is due to postgreql
:return: True once
"""
# Create a connection to the database (seemd to want it in this case)
db = SQLAlchemy(app)
# Add the start of the day to ensure anything older gets deleted
date += " 00:00:00.000000"
# Make the query to get the pastes to be deleted
old_pastes = db.session.query(Paste).filter(Paste.datetime < date)
# Attempt to delete old pastes
for item in old_pastes:
try:
delete_from_es(item)
db.session.delete(item)
db.session.commit()
except:
logger.error("Did not delete item from one or more databases: %s", item)
return True
class DbDrone(Process):
"""
A Process subclass to handle database transactions
"""
def __init__(self, data, ready_q):
"""
A subprocess to handle single database transactions
:param data: (String, Model)
:param ready_q: Queue to tell DB worker when it can start a new process
"""
Process.__init__(self)
# Set to daemon to ensure it closes when app closes
self.daemon = True
self.ready_q = ready_q
self.data = data
def run(self):
"""
The necessary run function for a Process
:return: None
"""
db = SQLAlchemy(app)
# The data tuple is split into a keyword, action, and the datum itself
action, datum = self.data
# Delete everything in the databases
if action == 'Delete':
try:
num = db.session.query(Paste).delete()
db.session.commit()
delete_all_es()
logger.info('%s entries deleted from db', num)
except:
db.session.rollback()
logger.error("Failed to delete all entries in both databases")
# Reindex elasticsearch using entries in th postgresql database
elif action == 'Reindex ES':
reindex_es()
# Delete everything older than a given date
elif action == 'Delete Date':
delete_by_date_paste(datum)
# Add an entry to the databases
elif action == 'Add':
in_db = False
# Try to add to postgresql databse
try:
db.session.add(datum)
db.session.commit()
in_db = True
logger.info('DB got %s', datum)
except:
db.session.rollback()
logger.error('Could not be added to DB: %s , %s', datum, sys.exc_info())
# If previous add successful add to elasticsearch
if in_db:
try:
add_to_es(datum)
logger.info('ES got %s', datum)
except:
logger.error('Could not be added to ES, putting back into Queue: %s', datum)
# Add true to the queue so that the next process can be started
self.ready_q.put(True)
class DbWorker(Process):
"""
A persistent Process subclass that listens for inputs and passes them to the DbDrone to handle
"""
def __init__(self):
Process.__init__(self)
# A multiprocessing Queue to pass messages
self.q = Queue()
self.child_q = Queue()
self.next = None
self.ready = True
def run(self):
logger.info('A DbWorker has started')
while True:
if self.next is None:
self.next = self.q.get()
if self.next is not None and not self.ready:
self.ready = self.child_q.get()
if self.next is not None and self.ready:
tmp = self.next
self.next = None
self.ready = False
DbDrone(tmp, self.child_q).start()
| 32.223881 | 118 | 0.583372 | 3,151 | 0.729736 | 0 | 0 | 0 | 0 | 0 | 0 | 1,689 | 0.391153 |
0d273c1d1f4925a594d10dc698fbd7f793d46ab3 | 449 | py | Python | tests/strings/test_basic.py | jaebradley/python_problems | 24b8ecd49e3095f5c607906cb36019b9e865a20f | [
"MIT"
] | null | null | null | tests/strings/test_basic.py | jaebradley/python_problems | 24b8ecd49e3095f5c607906cb36019b9e865a20f | [
"MIT"
] | 5 | 2017-08-25T20:43:16.000Z | 2019-10-18T16:49:43.000Z | tests/strings/test_basic.py | jaebradley/python_problems | 24b8ecd49e3095f5c607906cb36019b9e865a20f | [
"MIT"
] | null | null | null | """
Unit Test for strings.basic problems
"""
from unittest import TestCase
from strings.basic import alphabetize
class TestAlphabetize(TestCase):
"""
Unit Test for alphabetize method
"""
def test_should_return_alphabet(self):
"""
Test alphabetize method using every uppercase and lowercase character
"""
self.assertEqual('aBbcDeFgHiJkLmNoPqRsTuVwXyZ', alphabetize('ZyXwVuTsRqPoNmLkJiHgFeDcBba'))
| 22.45 | 99 | 0.714922 | 331 | 0.737194 | 0 | 0 | 0 | 0 | 0 | 0 | 243 | 0.541203 |
0d281e7eb3d40eae3e191f01e52cfee3344410ff | 6,162 | py | Python | Python3/HayStack_API.py | ConsensusGroup/Haystack | c2d0b8fb7b2064b05a5d256bb949dda9a0ef569d | [
"MIT"
] | 1 | 2019-11-28T08:50:26.000Z | 2019-11-28T08:50:26.000Z | Python3/HayStack_API.py | ConsensusGroup/Haystack | c2d0b8fb7b2064b05a5d256bb949dda9a0ef569d | [
"MIT"
] | 3 | 2019-11-22T04:23:47.000Z | 2019-11-30T07:11:24.000Z | Python3/HayStack_API.py | ConsensusGroup/Haystack | c2d0b8fb7b2064b05a5d256bb949dda9a0ef569d | [
"MIT"
] | 3 | 2018-03-19T05:20:44.000Z | 2019-11-22T00:56:31.000Z | #This script is going to be used API calls but first it will serve as a testing script.
from IOTA_Module import *
from Configuration_Module import *
from Tools_Module import *
from UserProfile_Module import *
from Cryptography_Module import *
from NodeFinder_Module import *
from DynamicPublicLedger_Module import *
import config
from time import sleep
class HayStack:
def __init__(self):
pass
def Seed_Generator(self):
Output = Seed_Generator()
#Output: A 81 character seed for IOTA
return Output
def Write_File(self, File_Directory, Data, Setting = "w"):
Output = Tools().Write_File(File_Directory, Data, Setting)
#Output: True if file was written, False if failed
return None
def Delete_File(self, File_Directory):
Output = Tools().File_Manipulation(File_Directory, Setting = "d")
#Output: True if file deleted, False if failed to delete file
return Output
def Read_File(self, File_Directory):
Output = Tools().Read_File(File_Directory)
#Output: False if file not found/read, Else contents get returned
return Output
def Initialization(self):
Output = Initialization()
#Output: None
return None
def Asymmetric_KeyGen(self, Password):
Output = Key_Generation().Asymmetric_KeyGen(Password)
#Output: Private key as bytes
return Output
def Import_PrivateKey(self, PrivateKey, Password):
Output = Key_Generation().Import_PrivateKey(PrivateKey, Password)
#Output Objects: PrivateKey, PublicKey
return Output
def JSON_Manipulation(self, File_Directory, **kwargs):
Output = Tools().JSON_Manipulation(File_Directory, **kwargs)
#Optional Input: Dictionary
#Output: Write to file -> True, Error(FileNotFoundError) -> False, Read from file = Dictionary
return Output
def UserProfile_Keys(self, Password):
Output = UserProfile().Get_Keys(Password)
#Output: Output.PrivateKey (bytes), Output.PrivateSeed [Decrypted = bytes, Failed Decryption = False], Output.PublicKey
return Output
def IOTA_Generate_Address(self, Seed, Node, Index):
Output = IOTA(Seed = Seed, Node = Node).Generate_Address(Index = Index)
#Output: 81 tryte address in 'bytes'
return Output
def IOTA_Send(self, Seed, Node, PoW, Receiver_Address, Message):
Output = IOTA(Seed = Seed, Node = Node, PoW = PoW).Send(Receiver_Address = Receiver_Address, Message = Message)
#Output: TX_Hash (81 tryte Tx hash, otherwise False [Bool])
return Output
def IOTA_Receive(self, Seed, Node, Start, Stop):
Output = IOTA(Seed = Seed, Node = Node).Receive(Start = Start, Stop = Stop)
#Output: Dictionary {"BundleHash":{"ReceiverAddress", "Tokens", "Timestamp (ms)", "Index", "Message", "Message_Tag"}}, else False [Bool]
return Output
def Test_IOTA_Nodes(self):
Output = Test_Nodes()
# Output: Nothing
return None
def Fastest_Node(self):
Output = Return_Optimal_Node()
# Output: [Fastest_Sending: {"Node", "PoW"}, Fastest_Receiving: {"Node", "PoW"}]
return Output
def Tangle_Block(self, Seed, Node):
Output = IOTA(Seed = Seed, Node = Node).TangleTime()
#Output: Output.Current_Time (time in ms)[int], Output.Block_Remainder (fraction of block left)[float], Output.CurrentBlock (Current block)[int]
return self
#Code to later delete!!!!
def Start_Dynamic_Ledger(self):
#First initialize the directories
self.Initialization()
#self.Test_IOTA_Nodes()
for i in range(1000000):
Submission = DynamicPublicLedger().Check_Current_Ledger()
if Submission == True:
delay = 5
elif Submission == False:
delay = 60
else:
delay = 120
print(Submission)
sleep(5)
if __name__ == "__main__":
x = HayStack()
c = Configuration()
#Change this to test module
Function = "Start_Dynamic_Ledger"
if Function == "Start_Dynamic_Ledger":
x.Start_Dynamic_Ledger()
if Function == "Fastest_Node":
print(x.Fastest_Node())
if Function == "Tangle_Block":
Seed = c.PublicSeed
Node = c.Preloaded_Nodes[0]
x.Tangle_Block(Seed = Seed, Node = Node)
if Function == "Test_IOTA_Nodes":
x.Test_IOTA_Nodes()
if Function == "Seed_Generator":
print(x.Seed_Generator())
if Function == "Write_File":
x.Write_File(File_Directory = c.User_Folder+"/"+c.Keys_Folder+"/"+c.PrivateKey_File, Data = "Hello")
if Function == "Delete_File":
x.Delete_File(File_Directory = c.User_Folder+"/"+c.Keys_Folder+"/"+c.PrivateKey_File)
if Function == "Read_File":
print(x.Read_File(File_Directory = c.User_Folder+"/"+c.Keys_Folder+"/"+c.PrivateKey_File))
if Function == "Initialization":
x.Initialization()
if Function == "Asymmetric_KeyGen":
print(x.Asymmetric_KeyGen(Password = ""))
if Function == "JSON_Manipulation":
x.JSON_Manipulation(File_Directory = c.User_Folder+"/"+c.Keys_Folder+"/"+c.PrivateKey_File, Dictionary = {})
if Function == "UserProfile_Keys":
print(x.UserProfile_Keys(Password = config.Password).PrivateSeed)
if Function == "IOTA_Generate_Address":
Seed = c.PublicSeed
Node = c.Preloaded_Nodes[0]
print(x.IOTA_Generate_Address(Seed = Seed, Node = Node, Index = 0))
if Function == "IOTA_Send":
Seed = c.PublicSeed
Node = c.Preloaded_Nodes[2]
Test_Message = "Test12134"
Address = x.IOTA_Generate_Address(Seed = Seed, Node = Node, Index = 7)
print(x.IOTA_Send(Seed = Seed, Node = Node, PoW = True, Receiver_Address = Address, Message = Test_Message))
print(x.Tangle_Block(Seed = c.PublicSeed, Node = Node))
if Function == "IOTA_Receive":
Seed = c.PublicSeed
Node = c.Preloaded_Nodes[0]
print(x.IOTA_Receive(Seed = Seed, Node = Node, Start = 6, Stop = 7))
| 35.618497 | 152 | 0.648815 | 3,645 | 0.591529 | 0 | 0 | 0 | 0 | 0 | 0 | 1,521 | 0.246835 |
0d2a081f35a5539acf6a7c3973e88ead36b9c6c5 | 2,230 | py | Python | clickctl/cli.py | ciscochina/click-demo | ed26c34dc14a761b3eb94c0f0896bd22dd81079e | [
"Apache-2.0"
] | 7 | 2017-03-06T08:23:29.000Z | 2021-12-15T12:12:31.000Z | clickctl/cli.py | ciscochina/click-demo | ed26c34dc14a761b3eb94c0f0896bd22dd81079e | [
"Apache-2.0"
] | null | null | null | clickctl/cli.py | ciscochina/click-demo | ed26c34dc14a761b3eb94c0f0896bd22dd81079e | [
"Apache-2.0"
] | 3 | 2018-04-02T15:36:08.000Z | 2021-12-15T06:06:51.000Z | # Copyright 2017 Cisco Systems, 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 os
import sys
import click
CONTEXT_SETTINGS = dict(auto_envvar_prefix='DEMO')
class Context(object):
def __init__(self):
self.verbose = False
self.home = os.getcwd()
def log(self, msg, *args):
"""Logs a message to stderr."""
if args:
msg %= args
click.echo(msg, file=sys.stderr)
def vlog(self, msg, *args):
"""Logs a message to stderr only if verbose is enabled."""
if self.verbose:
self.log(msg, *args)
pass_context = click.make_pass_decorator(Context, ensure=True)
cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'commands'))
class SdnadmCLI(click.MultiCommand):
def list_commands(self, ctx):
rv = []
for filename in os.listdir(cmd_folder):
if filename.endswith('.py') and \
filename.startswith('cmd_'):
rv.append(filename[4:-3])
rv.sort()
return rv
def get_command(self, ctx, name):
try:
if sys.version_info[0] == 2:
name = name.encode('ascii', 'replace')
mod = __import__('clickctl.commands.cmd_' + name,
None, None, ['cli'])
except ImportError:
return
return mod.cli
@click.command(cls=SdnadmCLI, context_settings=CONTEXT_SETTINGS)
@click.option('-v', '--verbose', is_flag=True,
help='show debug message.')
@pass_context
def cli(ctx, verbose):
"""Click Demo Command Line Interface"""
ctx.verbose = verbose
if __name__ == '__main__':
cli()
| 28.227848 | 81 | 0.625561 | 1,053 | 0.472197 | 0 | 0 | 260 | 0.116592 | 0 | 0 | 866 | 0.388341 |
0d2a6256b8a5f3ec748bace05b5caa68782cdbfb | 653 | py | Python | database/Database.py | TADebastiani/SistemasEspecialistas | 09b925ca44d9d8a1145b9cb253ce8879bf8400f0 | [
"MIT"
] | null | null | null | database/Database.py | TADebastiani/SistemasEspecialistas | 09b925ca44d9d8a1145b9cb253ce8879bf8400f0 | [
"MIT"
] | null | null | null | database/Database.py | TADebastiani/SistemasEspecialistas | 09b925ca44d9d8a1145b9cb253ce8879bf8400f0 | [
"MIT"
] | null | null | null | import sqlite3
from pathlib import Path
class Database:
def _cursor(self):
root = Path(__file__).parent
self._conn = sqlite3.connect(f'{root}/knowledge.sqlite')
return self._conn.cursor()
def _commit(self):
self._conn.commit()
def _close(self):
self._conn.close()
def get(self, table):
cursor = self._cursor()
if table == 'motor':
cursor.execute(f'select status, positivo, negativo from {table}')
else:
cursor.execute(f'select sintoma, estado from {table}')
resultado = cursor.fetchall()
self._close()
return resultado
| 24.185185 | 77 | 0.600306 | 610 | 0.93415 | 0 | 0 | 0 | 0 | 0 | 0 | 120 | 0.183767 |
0d2eef0e6b41c739ce4208807368ff89025b240e | 358 | py | Python | setup.py | Mr-TelegramBot/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 24 | 2018-10-05T13:04:30.000Z | 2020-05-12T08:45:34.000Z | setup.py | MrMahdi313/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 3 | 2019-06-26T07:20:20.000Z | 2021-05-24T13:06:56.000Z | setup.py | MrMahdi313/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 5 | 2018-10-05T14:29:28.000Z | 2020-08-11T15:04:10.000Z | #!/usr/bin/env python
from distutils.core import setup
setup(
name="python-tdlib",
version="1.4.0",
author="andrew-ld",
license="MIT",
url="https://github.com/andrew-ld/python-tdlib",
packages=["py_tdlib", "py_tdlib.constructors", "py_tdlib.factory"],
install_requires=["werkzeug", "simplejson"],
python_requires=">=3.6",
)
| 23.866667 | 71 | 0.656425 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 181 | 0.505587 |
0d2f27a4418e1470048e931eb3e58013861b8b5e | 30,937 | py | Python | viz_funcs.py | cjsmith015/phytochemical-diversity-cannabis | 4f71fec4e6c662dbb6aaafad23f01cef9b9aa8b5 | [
"CC0-1.0"
] | null | null | null | viz_funcs.py | cjsmith015/phytochemical-diversity-cannabis | 4f71fec4e6c662dbb6aaafad23f01cef9b9aa8b5 | [
"CC0-1.0"
] | null | null | null | viz_funcs.py | cjsmith015/phytochemical-diversity-cannabis | 4f71fec4e6c662dbb6aaafad23f01cef9b9aa8b5 | [
"CC0-1.0"
] | null | null | null | import numpy as np
import pandas as pd
import scipy.stats as scs
import itertools
from collections import defaultdict
import textwrap
import pingouin as pg
from statsmodels.stats.multicomp import pairwise_tukeyhsd
from sklearn.neighbors import NearestNeighbors
from sklearn.decomposition import PCA
from sklearn.cluster import DBSCAN, KMeans, OPTICS
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.preprocessing import StandardScaler
from sklearn.metrics.pairwise import cosine_distances, cosine_similarity
from sklearn.preprocessing import StandardScaler, MinMaxScaler
pd.options.display.max_columns = 150
from umap import UMAP
from statannot import add_stat_annotation
import plotly
import plotly.graph_objs as go
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.colors as mcolors
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
from mpl_toolkits import mplot3d
import matplotlib.cm as cm
from adjustText import adjust_text
import matplotlib.patheffects as PathEffects
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
###
def simple_axis(ax):
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
def run_by_group(orig_df,
**kwargs):
g = orig_df.groupby(kwargs['groupby'])
base_name = kwargs['save_name']
for group, data in g:
kwargs['title'] = group
kwargs['save_name'] = base_name+'_'+group
run_graph(data, **kwargs)
return
def run_graph(df,
**kwargs):
fig, ax = plt.subplots(figsize=kwargs['figsize'])
if 'violin' in kwargs['save_name']:
ax = run_violin(df, ax, **kwargs)
elif 'scatter' in kwargs['save_name']:
if '5' in kwargs['save_name']:
ax = run_scatter_5(df, ax, **kwargs)
else:
ax = run_scatter(df, ax, **kwargs)
if 'comp_df' in kwargs:
ax = run_loadings(df, ax, **kwargs)
elif 'reg' in kwargs['save_name']:
ax = run_scatter(df, ax, **kwargs)
elif 'hist' in kwargs['save_name']:
ax = run_hist(df, ax, **kwargs)
elif 'bar' in kwargs['save_name']:
ax = run_bar(df, ax, **kwargs)
elif 'stacked' in kwargs['save_name']:
ax = run_stacked_bar(df, ax, **kwargs)
elif 'box' in kwargs['save_name']:
ax = run_box(df, ax, **kwargs)
elif 'sil' in kwargs['save_name']:
ax = run_sil(df, ax, **kwargs)
elif 'kde' in kwargs['save_name']:
ax = run_kde(df, ax, **kwargs)
elif 'line' in kwargs['save_name']:
ax = run_line(df, ax, **kwargs)
if 'log' in kwargs:
# ax.set_xscale('symlog', linthreshx=1e-1)
# ax.set_yscale('symlog', linthreshy=1e-1)
ax.set_xscale('log')
ax.set_yscale('log')
if 'xlims' in kwargs:
if len(kwargs['xlims']) == 1:
xlims = ax.get_xlim()
kwargs['xlims'] = (kwargs['xlims'][0], xlims[1])
ax.set_xlim(kwargs['xlims'])
if 'ylims' in kwargs:
if len(kwargs['ylims']) == 1:
ylims = ax.get_ylim()
kwargs['ylims'] = (kwargs['ylims'][0], ylims[1])
ax.set_ylim(kwargs['ylims'])
ax.set_xlabel(kwargs['x_label'], fontweight='bold', fontsize=11)
ax.set_ylabel(kwargs['y_label'], fontweight='bold', fontsize=11)
# if 'comp_df' in kwargs:
# ax2 = ax.twiny()
# ax2.set_xticks( ax.get_xticks() )
# ax2.set_xbound(ax.get_xbound())
# ax2.set_xticklabels([x/ax.get_xticks().max() for x in ax.get_xticks()])
# ax2.set_xlabel('Loadings on PC'+str(kwargs['x']+1), fontweight='bold', fontsize=11)
# ax3 = ax.twinx()
# ax3.set_yticks(ax.get_yticks())
# ax3.set_ybound(ax.get_ybound())
# ax3.set_yticklabels([y/ax.get_yticks().max() for y in ax.get_yticks()])
# ax3.set_ylabel('Loadings on PC'+str(kwargs['y']+1), fontweight='bold', fontsize=11)
ax.set_title(kwargs['title'], fontweight='bold', fontsize=12)
simple_axis(ax)
plt.tight_layout()
fig.savefig('viz/'+kwargs['save_name']+'.png')
return
def sample_df(df, x):
if x==1:
return df
elif x<1:
return df.sample(frac=x, random_state=56)
else:
return df.sample(n=x, random_state=56)
def run_violin(data, ax, **kwargs):
sub_df = sample_df(data, kwargs['sample_frac'])
# get ns from full dataset
if kwargs['x'] == 'region':
df = pd.melt(data.loc[:, kwargs['cols']],
id_vars='region', value_vars='tot_thc').drop(columns=['variable'])
sub_df = pd.melt(sub_data.loc[:, kwargs['cols']],
id_vars='region', value_vars='tot_thc').drop(columns=['variable'])
order, n_dict = violin_order(df, group_by='region')
else:
if 'cols' in kwargs:
df = pd.melt(data.loc[:, kwargs['cols']], var_name=kwargs['x'])
sub_df = pd.melt(sub_df.loc[:, kwargs['cols']], var_name=kwargs['x'])
order, n_dict = violin_order(df, group_by=kwargs['x'])
else:
df = data
sub_df = sub_df
order, n_dict = violin_order(df, group_by=kwargs['x'])
# if pre-set order, use that
if 'order' in kwargs:
order = kwargs['order']
# plot with sampled data
if 'palette' in kwargs:
sns.violinplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df,
scale='width', order=order,
palette=kwargs['palette'], linewidth=0, ax=ax)
else:
sns.violinplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df,
scale='width', order=order,
color='lightslategray', linewidth=0, ax=ax)
PROPS = {
'boxprops':{'facecolor':'black', 'edgecolor':'black', 'linewidth':3},
'medianprops':{'color':'white', 'linewidth':2},
'whiskerprops':{'color':'black', 'linewidth':2}
}
boxplot = sns.boxplot(x=kwargs['x'], y=kwargs['y'],
data=df, order=order,
showcaps=False, width=0.06,
fliersize=0.5, ax=ax, **PROPS)
if kwargs['avg']:
avg_avgs = df.groupby(kwargs['x'])[kwargs['y']].mean().mean()
ax.axhline(avg_avgs, color='black', linestyle='--')
if 'axhline' in kwargs:
ax.axhline(kwargs['axhline'], color='black', linestyle='--')
if 'sil-scores' in kwargs['save_name']:
ax.axhline(0, color='black', linestyle='--')
if kwargs['sig_comp']:
box_pairs = list(itertools.combinations(order,r=2))
test_results = add_stat_annotation(ax, data=df,
x=kwargs['x'], y=kwargs['y'],
order=order,
box_pairs=box_pairs,
text_annot_custom=[get_stats(df, pair, kwargs['x']) for pair in box_pairs],
perform_stat_test=False, pvalues=[0, 0, 0],
loc='outside', verbose=0)
# ttest_df = pd.DataFrame(index=order, columns=['y_val','p_val','cohens_d'])
# ttest_df[['y_val','p_val','cohens_d']] = ttest_df.apply(run_cohens, args=(df, ), axis=1, result_type='expand')
# p_val_adj = 0.05/ttest_df.shape[0]
# ttest_df['reject'] = ttest_df['p_val'] <= p_val_adj
# bins = [0, 0.2, 0.5, 0.8, np.inf]
# names = ['', '*', '**', '***']
# ttest_df['star'] = pd.cut(np.abs(ttest_df['cohens_d']), bins, labels=names)
# for i, region in enumerate(order):
# if ttest_df.loc[region, 'reject']:
# y = ttest_df.loc[region, 'y_val']
# ax.text(i, y+2, ttest_df.loc[region, 'star'], ha='center', size=20)
if 'v_xticklabels' in kwargs:
xtick_labels = ax.get_xticklabels()
labels = [textwrap.fill(x.get_text(),10) for x in xtick_labels]
_ = ax.set_xticklabels(labels, rotation=90, ha='center')
else:
xtick_labels = ax.get_xticklabels()
labels = [x.get_text()+'\nn='+str(n_dict[x.get_text()]['value']) for x in xtick_labels]
_ = ax.set_xticklabels(labels)
return ax
def violin_order(df, group_by='Cannab'):
order = df.groupby(group_by).median().sort_values(by='value', ascending=False).index
n_dict = df.groupby(group_by).count().T.to_dict(orient='dict')
return order.values, n_dict
def run_scatter(df, ax, **kwargs):
no_nan = df.dropna(subset=[kwargs['x'], kwargs['y']], how='any')
sub_df = sample_df(no_nan, kwargs['sample_frac'])
if 'size' in kwargs:
s = kwargs['size']
else:
s = mpl.rcParams['lines.markersize']**2
if 'edgecolor' in kwargs:
ec = kwargs['edgecolor']
else:
ec = 'white'
if 'hue' in kwargs:
if 'sort_list' in kwargs:
hue_order = kwargs['sort_list']
sub_df = sub_df.sort_values(kwargs['hue'], key=make_sorter(kwargs['sort_list']))
else:
hue_order = sub_df[kwargs['hue']].value_counts().index
sns.scatterplot(x=kwargs['x'], y=kwargs['y'],
hue=kwargs['hue'],
data=sub_df,
s=s,
edgecolor=ec,
alpha=0.5,
hue_order=hue_order,
palette=kwargs['palette'],
ax=ax)
# include full ns
handles, labels = ax.get_legend_handles_labels()
if 'n_display' in kwargs:
labels_n = [(cat, df.loc[df[kwargs['hue']]==cat].shape[0]) for cat in hue_order]
labels = [cat+'\nn='+str(n) for cat, n in labels_n]
ax.legend(handles=handles[:kwargs['n_display']], labels=labels[:kwargs['n_display']], title=kwargs['hue'].title(), handlelength=4)
else:
labels_n = [(cat, df.loc[df[kwargs['hue']]==cat].shape[0]) for cat in hue_order]
labels = [cat+'\nn='+str(n) for cat, n in labels_n]
ax.legend(handles=handles, labels=labels, title=kwargs['hue'].title(), handlelength=4)
else:
sns.regplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df,
scatter_kws={'alpha':0.1, 'color':'lightslategray', 'rasterized':True},
line_kws={'color':'orange'},
ax=ax)
r, p = scs.spearmanr(no_nan[kwargs['x']], no_nan[kwargs['y']])
labels = ['rho = {:.2f}'.format(r)]
if p < 1e-300:
labels.append('p < 1e-300')
else:
labels.append('p = {:.1e}'.format(p))
ax.legend(labels=['\n'.join(labels)])
if 'prod_strains' in kwargs:
s_colors = ['black', 'gray', 'white']
s_markers = ['^', 'D', 'o']
n_strains = len(kwargs['prod_strains'])
for strain, color, marker in zip(kwargs['prod_strains'], s_colors[:n_strains], s_markers[:n_strains]):
sns.scatterplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df.loc[sub_df['strain_slug']==strain],
s=s+35,
edgecolor='black',
linewidth=1.5,
color=color,
label=strain,
marker=marker,
ax=ax)
return ax
def get_log(df, cannab_1='tot_thc', cannab_2='tot_cbd'):
# get THC_CBD ratio for batches without 0 tot_thc (avoid dividing by 0)
df['ratio'] = 0
df.loc[df[cannab_2] != 0, 'ratio'] = (df.loc[df[cannab_2] != 0, cannab_1]) / (df.loc[df[cannab_2] != 0, cannab_2])
# get log_THC_CBD vals
df['log_ratio'] = 0
df.loc[df['ratio'] != 0, 'log_ratio'] = np.log10(df.loc[df['ratio'] != 0, 'ratio'])
# set the 0 tot_cbd batches to an extraneous high bin
df.loc[df[cannab_2] == 0, 'log_ratio'] = 4
df.loc[df[cannab_1] == 0, 'log_ratio'] = -2
log_ratio = df['log_ratio']
return log_ratio
def run_hist(df, ax, **kwargs):
sub_df = sample_df(df, kwargs['sample_frac'])
# some cut-offs
ct_thresh_high = 5
ct_thresh_low = 0.25
max_log = 4
min_log = -2.0
# get log data
log_cannab = get_log(sub_df, cannab_1='tot_'+kwargs['x'], cannab_2='tot_'+kwargs['y'])
# get histogram
hist, bins = np.histogram(log_cannab, bins=np.arange(min_log-0.1, max_log+0.1, 0.05))
# get colors
colors = []
for low, high in zip(bins,bins[1:]):
avg = np.mean([low, high])
if avg >= np.log10(ct_thresh_high):
colors.append('darkblue')
elif avg <= np.log10(ct_thresh_low):
colors.append('black')
else:
colors.append('steelblue')
# plot histogram, thresholds
ax.bar(bins[:-1], hist.astype(np.float32) / hist.sum(),
width=(bins[1]-bins[0]), color=colors)
ax.plot([np.log10(ct_thresh_high), np.log10(ct_thresh_high)], [0, kwargs['ylims'][1]-0.02],
linestyle='--', color='k', linewidth=1)
ax.plot([np.log10(ct_thresh_low), np.log10(ct_thresh_low)], [0, kwargs['ylims'][1]-0.02],
linestyle='--', color='k', linewidth=1)
ax.set_xticklabels(['',float("-inf"), -1, 0, 1, 2, 3, float("inf")])
# draw legend
chemotypes = ['THC-Dom', 'Bal THC/CBD', 'CBD-Dom']
ct_1 = mpatches.Patch(color='darkblue', label='THC-Dom')
ct_2 = mpatches.Patch(color='steelblue', label='Bal THC/CBD')
ct_3 = mpatches.Patch(color='black', label='CBD-Dom')
ct_handles, ct_labels = ax.get_legend_handles_labels()
ct_labels_n = [(x, df.loc[df['chemotype']==x].shape[0]) for x in chemotypes]
ct_labels = [x+'\nn='+str(n) for x, n in ct_labels_n]
ax.legend(handles=[ct_1,ct_2,ct_3], labels=ct_labels,title='Chemotype',handlelength=4)
return ax
def normalize(df, cols):
df.loc[:, cols] = (df.loc[:, cols]
.div(df.loc[:, cols].sum(axis=1), axis=0)
.multiply(100))
return df
def max_min(arr):
return arr/(arr.max()-arr.min())
def make_sorter(sort_list):
"""
Create a dict from the list to map to 0..len(l)
Returns a mapper to map a series to this custom sort order
"""
sort_order = {k:v for k,v in zip(sort_list, range(len(sort_list)))}
return lambda s: s.map(lambda x: sort_order[x])
def run_bar(df, ax, **kwargs):
if 'hue' in kwargs:
sns.barplot(x=kwargs['x'], y=kwargs['y'],
hue=kwargs['hue'],
data=df,
palette=kwargs['palette'],
order=kwargs['order'])
elif 'palette' in kwargs:
sns.barplot(x=kwargs['x'], y=kwargs['y'],
data=df,
palette=kwargs['palette'],
order=kwargs['order'])
else:
sns.barplot(x=kwargs['x'], y=kwargs['y'],
color='lightslategray')
return ax
def run_box(df, ax, **kwargs):
if 'palette' in kwargs:
sns.boxplot(x=kwargs['x'], y=kwargs['y'],
data=df,
palette=kwargs['palette'],
order=kwargs['order'])
else:
sns.boxplot(x=kwargs['x'], y=kwargs['y'],
color='lightslategray')
return ax
def run_pca(df, cols, norm=True, n_components=2, max_min_arr=False):
df[cols] = df[cols].fillna(0)
# get rid of rows that are all 0 for specified columns
zero_bool = (df[cols]==0).sum(axis=1)==len(cols)
df = df[~zero_bool].copy()
if norm:
X = normalize(df, cols).copy()
else:
X = df.copy()
model = PCA(n_components=n_components)
model.fit(X.loc[:, cols])
arr = model.fit_transform(X.loc[:, cols])
if max_min_arr:
arr = np.apply_along_axis(max_min, arr=arr, axis=0)
# add first three component scores to df
X[0] = arr[:,0]
X[1] = arr[:,1]
X[2] = arr[:,2]
return X, arr, model
def run_loadings(df, ax, **kwargs):
comp_df = kwargs['comp_df']
comp_df['combo_score'] = np.abs(comp_df[[kwargs['x'],kwargs['y']]]).sum(axis=1)
comp_df = comp_df.sort_values(by='combo_score', ascending=False).iloc[:kwargs['n_display']]
max_x = df[kwargs['x']].max()
max_y = df[kwargs['y']].max()
texts = []
for x in comp_df.iterrows():
texts.append(ax.text(x[1][kwargs['x']]*max_x,
x[1][kwargs['y']]*max_y,
x[0],
fontweight='bold',
bbox=dict(facecolor='white', edgecolor='blue', pad=2, alpha=0.75)))
ax.arrow(0, 0,
x[1][kwargs['x']]*max_x,
x[1][kwargs['y']]*max_y,
color='black', alpha=1,
lw=2, head_width=1)
adjust_text(texts)
return ax
def run_sil(df, ax, **kwargs):
sub_df = sample_df(df, kwargs['sample_frac'])
labels = df[kwargs['hue']]
sub_labels = sub_df[kwargs['hue']]
label_list = labels.value_counts().index
silhouette_avg = silhouette_score(df[kwargs['cols']], labels)
sample_sil_val = silhouette_samples(sub_df[kwargs['cols']], sub_labels)
y_lower=0
for i, label in enumerate(label_list[:kwargs['n_display']]):
ith_cluster_sil_val = sample_sil_val[sub_labels==label]
ith_cluster_sil_val.sort()
size_cluster_i = ith_cluster_sil_val.shape[0]
y_upper = y_lower+size_cluster_i
color = kwargs['palette'][label]
ax.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_sil_val,
facecolor=color, edgecolor=color, alpha=0.7)
ax.text(-0.05, y_lower+0.5*size_cluster_i, label)
y_lower = y_upper+1
ax.axvline(silhouette_avg, color='lightslategray', linestyle='--')
ax.legend(labels=['Avg Silhouette Score {:.2f}'.format(silhouette_avg)])
ax.set_ylim(0, y_upper+10)
return ax
def score2loading(x):
return x / x.max()
def loading2score(x):
return x * x.max()
def get_ct(df):
# determine THC/CBD ratio
df['chemotype_ratio'] = df['tot_thc'].div(df['tot_cbd'], fill_value=0)
df.loc[(df['tot_thc']==0)&(df['tot_cbd']!=0), 'chemotype_ratio'] = -np.inf
df.loc[(df['tot_thc']!=0)&(df['tot_cbd']==0), 'chemotype_ratio'] = np.inf
# bin chemotypes by ratio
df['chemotype'] = pd.cut(df['chemotype_ratio'],
[-np.inf, 0.2, 5, np.inf],
labels=['CBD-Dom','Bal THC/CBD', 'THC-Dom'],
include_lowest=True)
return df
def run_stacked_bar(df, ax, **kwargs):
if 'order' in kwargs:
df[kwargs['order']].plot(kind='bar', stacked=True, color=kwargs['palette'], ax=ax)
else:
df.plot(kind='bar', stacked=True, color=kwargs['palette'], ax=ax)
# .patches is everything inside of the chart
for rect in ax.patches:
# Find where everything is located
height = rect.get_height()
width = rect.get_width()
x = rect.get_x()
y = rect.get_y()
# The height of the bar is the data value and can be used as the label
label_text = f'{height:.1f}%' # f'{height:.2f}' to format decimal values
# ax.text(x, y, text)
label_x = x + width / 2
label_y = y + height / 2
# plot only when height is greater than specified value
if height > 5:
txt = ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=10, fontweight='bold', color='black')
txt.set_path_effects([PathEffects.withStroke(linewidth=4, foreground='w')])
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
return ax
# def run_polar_plot(df, ax, **kwargs):
# # print(df.loc[:,kwargs['cols']])
# mean_cols = list(df.loc[:,kwargs['cols']].mean(axis=0))
# mean_cols2 = mean_cols + mean_cols[:1]
# angles = [n / len(mean_cols) * 2 * np.pi for n in range(len(mean_cols))]
# angles = angles + angles[:1]
# # get color
# order = np.argsort(mean_cols)[::-1]
# top_val = np.array(kwargs['cols'])[order][0]
# if 'colors' in kwargs:
# colors = kwargs['colors']
# else:
# colors = kwargs['palette'][top_val]
# # # error bars
# # err_cols = list(df.loc[:,kwargs['cols']].std(axis=0))
# # err_cols2 = err_cols + err_cols[:1]
# # ax.errorbar(angles, mean_cols2, yerr=err_cols2, capsize=0, color=colors, linestyle='solid', ecolor='lightslategray')
# # plot
# if kwargs['avg']:
# ax.plot(angles, mean_cols2, color=colors, lw=1, linestyle='solid')
# ax.fill(angles, mean_cols2, colors, alpha=0.1)
# # y limits
# ax.set_ylim(0, np.max(mean_cols2))
# else:
# for row_idx, row in df[kwargs['cols']].iterrows():
# row_list = list(row)
# row_list2 = row_list + row_list[:1]
# if type(colors)==str:
# ax.plot(angles, row_list2, color=colors, lw=0.5)
# else:
# ax.plot(angles, row_list2, color=colors[row_idx], lw=0.5)
# ax.set_ylim(0, np.max(df[kwargs['cols']].max()))
# # tick labels
# tick_labs = kwargs['cols']
# ax.set_xticks(angles[:-1])
# ax.set_xticklabels(tick_labs, color='black', size=10)
# ax.set_yticks([])
# return ax
def run_polar_plot(df, ax, **kwargs):
# print(df.loc[:,kwargs['cols']])
mean_cols = list(df.loc[:,kwargs['cols']].mean(axis=0))
mean_cols2 = mean_cols + mean_cols[:1]
angles = [n / len(mean_cols) * 2 * np.pi for n in range(len(mean_cols))]
angles = angles + angles[:1]
# plot samples
if 'sub_n' in kwargs:
sub_data = df.sort_values('n_samps', ascending=False)[:kwargs['sub_n']]
else:
sub_data = df
for row_idx, row in sub_data[kwargs['cols']].iterrows():
row_list = list(row)
row_list2 = row_list + row_list[:1]
if type(kwargs['colors'])==str:
ax.plot(angles, row_list2, color=kwargs['colors'], lw=0.5, alpha=0.5)
else:
ax.plot(angles, row_list2, color=kwargs['colors'][row_idx], lw=0.5)
if kwargs['avg']:
# get for average color
order = np.argsort(mean_cols)[::-1]
top_val = np.array(kwargs['cols'])[order][0]
avg_color = kwargs['palette'][top_val]
ax.plot(angles, mean_cols2, color=avg_color, lw=1, linestyle='solid', zorder=11)
ax.fill(angles, mean_cols2, avg_color, alpha=0.5, zorder=10)
ax.set_ylim(0, np.max(mean_cols2))
else:
ax.set_ylim(0, np.max(sub_data[kwargs['cols']].max()))
# tick labels
tick_labs = kwargs['cols']
ax.set_xticks(angles[:-1])
ax.set_xticklabels(tick_labs, color='black', size=10)
ax.set_yticks([])
return ax
def run_pairwise(df,
cann_cols, terp_cols):
df_sim = pd.DataFrame(columns=['cann','terp','all'])
for idx, cols in enumerate([cann_cols, terp_cols, cann_cols+terp_cols]):
if idx==2:
df[cols] = MinMaxScaler().fit_transform(df[cols].fillna(0))
sim_scores = cosine_similarity(df[cols].fillna(0))
sim_scores[sim_scores > 0.9999999999999] = np.nan
df_sim.iloc[:, idx] = np.nanmean(sim_scores, axis=0)
return df_sim
def get_scaled_dfs(df, cann, terps):
X_cann = df[cann].fillna(0)
X_cann_standard = MinMaxScaler().fit_transform(X_cann)
X_terps = df[terps].fillna(0)
X_terps_standard = MinMaxScaler().fit_transform(X_terps)
X_all = df[cann+terps].fillna(0)
X_all_standard = MinMaxScaler().fit_transform(X_all)
return X_cann, X_cann_standard, X_terps, X_terps_standard, X_all, X_all_standard
def avg_sd(a,b):
num = np.var(a)+np.var(b)
return np.sqrt(num/2)
def get_stats(df, pair, col):
x = df.loc[df[col]==pair[0], 'value']
y = df.loc[df[col]==pair[1], 'value']
ttest = scs.ttest_ind(x, y, equal_var=False)
d_prime = (x.mean()-y.mean())/avg_sd(x,y)
labels = []
if ttest[1] < 1e-300:
labels.append('p < 1e-300')
else:
labels.append('p = {:.1e}'.format(ttest[1]))
labels.append("d'="+str(np.round(np.abs(d_prime),2)))
return ', '.join(labels)
def get_prod_df(df, n_samp_min, n_prod_min,
common_cannabs,
common_terps):
n_samp_df = df.groupby(['anon_producer','strain_slug'])['u_id'].count()
df = df.merge(n_samp_df.rename('n_samp'), left_on=['anon_producer','strain_slug'], right_index=True)
# create producer df
prod_df = df.loc[(df['n_samp']>=n_samp_min)].groupby(['anon_producer','strain_slug'])[common_cannabs+common_terps].mean()
prod_df = get_ct(prod_df)
prod_df = prod_df.reset_index(drop=False)
# get n_prod counts
n_prod_df = prod_df.groupby('strain_slug')['anon_producer'].count()
prod_df = prod_df.merge(n_prod_df.rename('n_prod'), left_on='strain_slug', right_index=True)
prod_df = prod_df.merge(n_samp_df.rename('n_samps'), left_on=['anon_producer','strain_slug'], right_index=True)
# subset to n_prod_min and thc-dom
fin_prod_df = prod_df.loc[(prod_df['n_prod']>=n_prod_min)].sort_values(['n_prod','strain_slug','anon_producer'], ascending=[False, False, True]).copy()
fin_prod_df['strain_slug'] = fin_prod_df['strain_slug'].astype(str)
return fin_prod_df
def get_pal_dict(df, common_terps, terp_dict):
pal_dict = {}
for label in set(df['kmeans_label']):
terp_order = df.loc[df['kmeans_label']==label, common_terps].mean().sort_values(ascending=False)
pal_dict[label] = terp_dict[terp_order[:1].index[0]]
return pal_dict
def get_kmeans(df, common_terps,
k=3):
df_norm, arr, model = run_pca(df, common_terps, norm=True, n_components=3)
# set up kmeans
clust = KMeans(3, random_state=56)
# get cluster labels
df_norm['kmeans_label'] = clust.fit_predict(df_norm[common_terps])
clust_dict = {x:y for x,y in zip(df_norm['kmeans_label'].value_counts().index, ['A','B','C'])}
df_norm['kmeans_label'] = df_norm['kmeans_label'].replace(clust_dict)
return df_norm
def get_umap(df, common_terps,
n_neighbors=6,
random_state=56):
umap_ = UMAP(n_components=2, n_neighbors=n_neighbors,
random_state=random_state)
X_terps_umap = umap_.fit_transform(df[common_terps])
df['umap_0'] = X_terps_umap[:,0]
df['umap_1'] = X_terps_umap[:,1]
return df
def get_round(arr, sig_fig=1):
return np.round(arr*100,sig_fig)
def get_cos_sim(df, add_nan=False):
sim_scores = cosine_similarity(df)
if add_nan:
sim_scores[sim_scores > 0.9999999999999] = np.nan
else:
sim_scores[sim_scores > 0.9999999999999] = 1
return sim_scores
def group_cos_sim(df, group_level=False):
if df.shape[0]==1:
# if only one product, do not return cos sim
return np.nan
else:
sim_scores = get_cos_sim(df, add_nan=True)
if group_level:
return np.mean(np.nanmean(sim_scores, axis=0))
else:
return list(np.nanmean(sim_scores, axis=0))
def format_df(df):
return df.explode().to_frame().rename(columns={0:'bw_prod_sim'}).reset_index(drop=False)
def weighted_avg(avgs, weights):
return np.average(avgs, weights=weights)
def run_all_cos_sims(df, cols,
groupby='strain_slug'):
groups = df.groupby(groupby)[cols]
bw_prod_df = format_df(groups.apply(lambda x: group_cos_sim(x)))
avgs = groups.apply(lambda x: group_cos_sim(x, group_level=True))
weights = groups.size()[groups.size()>1]
return bw_prod_df, avgs, weights
def run_kde(df, ax, **kwargs):
no_nan = df.dropna(subset=[kwargs['x'], kwargs['y']], how='any')
sub_df = sample_df(no_nan, kwargs['sample_frac'])
_ = sns.kdeplot(x=kwargs['x'],
y=kwargs['y'],
data=sub_df,
fill=True,
cmap='RdBu_r',
cbar=True,
vmin=0,
levels=75,
ax=ax)
return ax
def run_line(df, ax, **kwargs):
_ = ax.plot(kwargs['x'], kwargs['y'])
return ax
def run_scatter_5(df, ax, **kwargs):
no_nan = df.dropna(subset=[kwargs['x'], kwargs['y']], how='any')
sub_df = sample_df(no_nan, kwargs['sample_frac'])
if 'size' in kwargs:
s = kwargs['size']
else:
s = mpl.rcParams['lines.markersize']**2
if 'edgecolor' in kwargs:
ec = kwargs['edgecolor']
else:
ec = 'white'
hue_order = ['THC-Dom', 'Bal THC/CBD', 'CBD-Dom']
s_colors = ['darkblue', 'steelblue', 'black']
s_markers = ['D', '^', 'o']
for ct, color, marker in zip(hue_order, s_colors, s_markers):
if ct=='THC-Dom':
sns.scatterplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df.loc[df['chemotype']==ct], alpha=.5,
color=color,
marker=marker,
s=25,
edgecolor='white',
linewidth=0.5,
label=ct,
ax=ax)
else:
sns.scatterplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df.loc[df['chemotype']==ct], alpha=1,
color=color,
marker=marker,
s=25,
edgecolor='white',
linewidth=0.5,
label=ct,
ax=ax)
# include full ns
handles, labels = ax.get_legend_handles_labels()
if 'n_display' in kwargs:
labels_n = [(cat, df.loc[df[kwargs['hue']]==cat].shape[0]) for cat in hue_order]
labels = [cat+'\nn='+str(n) for cat, n in labels_n]
ax.legend(handles=handles[:kwargs['n_display']], labels=labels[:kwargs['n_display']], title=kwargs['hue'].title(), handlelength=4)
else:
labels_n = [(cat, df.loc[df[kwargs['hue']]==cat].shape[0]) for cat in hue_order]
labels = [cat+'\nn='+str(n) for cat, n in labels_n]
ax.legend(handles=handles, labels=labels, title=kwargs['hue'].title(), handlelength=4)
return ax
| 33.922149 | 155 | 0.56809 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7,300 | 0.235963 |
0d2f4d0205d878f2318704a83c9245cfde3dc957 | 39,442 | py | Python | app.py | yumei86/iRamen_linebot | 5b9f2653076faa04118f281970edf639288d79fd | [
"MIT"
] | 16 | 2020-12-29T11:23:01.000Z | 2022-01-01T01:55:42.000Z | app.py | yumei86/iRamen_linebot | 5b9f2653076faa04118f281970edf639288d79fd | [
"MIT"
] | null | null | null | app.py | yumei86/iRamen_linebot | 5b9f2653076faa04118f281970edf639288d79fd | [
"MIT"
] | 4 | 2020-12-27T14:43:35.000Z | 2021-02-26T09:35:03.000Z | from flask import Flask, request, abort
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import *
import json
import os
from linebot.exceptions import LineBotApiError
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
import random
import csv
import re
import requests
from msg_template import Gps,Weather,Flex_template,Text_template
#----------------呼叫我們的line bot(這邊直接取用heroku的環境變數)-----------------
app = Flask(__name__)
USER = os.environ.get('CHANNEL_ACCESS_TOKEN')
PASS = os.environ.get('CHANNEL_SECRET')
line_bot_api = LineBotApi(USER)
handler = WebhookHandler(PASS)
#----------------資料庫設定-----------------
ENV = 'prod'
if ENV == 'dev':
from dotenv import load_dotenv
load_dotenv()
SQLALCHEMY_DATABASE_URI_PRIVATE = os.getenv("SQLALCHEMY_DATABASE_URI_PRIVATE")
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI_PRIVATE
else:
DATABASE_URL = os.environ.get('DATABASE_URL')
app.debug = False
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# # #https://flask-sqlalchemy.palletsprojects.com/en/2.x/models/
# #---------------------------------initialize tables--------------------------
class Main_store(db.Model):
__tablename__ = 'main_store'
store_id = db.Column (db.Integer, primary_key = True)
main_store = db.Column(db.String(50), nullable=False, unique = True)
detail_store_relationship = db.relationship('Store', backref= 'main_store', lazy=True)
post_relationship = db.relationship('Post', backref= 'main_store', lazy=True)
def __init__(self, main_store):
self.main_store = main_store
class Store(db.Model):
__tablename__ = 'store'
detail_store_id = db.Column (db.String(10), primary_key = True)
store_id = db.Column (db.Integer, db.ForeignKey('main_store.store_id'), nullable=False, onupdate ='CASCADE')
store = db.Column (db.String(50), nullable=False, unique = True)
still_there = db.Column (db.Boolean, nullable=False)
address = db.Column (db.String(200))
discription = db.Column (db.String(500))
open_time = db.Column (db.String(200))
latitude = db.Column (db.Numeric(10,8))
longtitute = db.Column (db.Numeric(10,7))
map_review = db.Column (db.Text())
region = db.Column (db.String(1))
province = db.Column (db.String(3))
soup = db.Column (db.String(200))
transport = db.Column (db.String(100))
store_favorite_relationship = db.relationship('Favorite', backref= 'store', lazy=True)
def __init__(self, store_id, store, still_there, address, discription,\
open_time, latitude, longtitute, map_review, region, province, soup, transport):
self.store_id = store_id
self.store = store
self.still_there = still_there
self.address = address
self.discription = discription
self.open_time = open_time
self.latitude = latitude
self.longtitute = longtitute
self.map_review = map_review
self.region = region
self.province = province
self.soup = soup
self.transport = transport
class Post(db.Model):
__tablename__ = 'post'
post_id = db.Column (db.String(10), primary_key = True)
store_id = db.Column (db.Integer, db.ForeignKey('main_store.store_id'), nullable=False, onupdate ='CASCADE')
stores = db.Column (db.String(30))
create_on = db.Column (db.DateTime)
ramen_name = db.Column (db.String(100))
fb_review = db.Column (db.Text())
def __init__(self, store_id, stores, create_on, ramen_name, fb_review):
self.store_id = store_id
self.stores = stores
self.create_on = create_on
self.ramen_name = ramen_name
self.fb_review = fb_review
class Favorite(db.Model):
__tablename__ = 'favorite'
id = db.Column (db.Integer, primary_key = True)
line_id = db.Column (db.String(34), nullable = False)
detail_store_id = db.Column (db.String(10), db.ForeignKey('store.detail_store_id'), nullable = False, onupdate ='CASCADE')
def __init__(self, line_id, detail_store_id):
self.line_id = line_id
self.detail_store_id = detail_store_id
def get_data_str(lst):
output_before_random = ''
for r in lst:
if r[2] is None:
output_before_random += f'STORE:{r[1].store},ADDRESS:{r[1].address},DISCRIPTION:{r[1].discription},TRANSPORT:{r[1].transport},\
MAP_REVIEW:{r[1].map_review},\
LONGITUDE:{r[1].longtitute},LATITUDE:{r[1].latitude},OPEN_TIME:{r[1].open_time},\
CHECK_TAG:{r[1].soup},CHECK_CITY:{r[1].province}%'
else:
try:
output_before_random += f'STORE:{r[1].store},ADDRESS:{r[1].address},DISCRIPTION:{r[1].discription},TRANSPORT:{r[1].transport},\
FB_R_CREATE:{r[2].create_on},FB_R_RAMEN:{r[2].ramen_name},FB_R_CONTENT:{r[2].fb_review},\
LONGITUDE:{r[1].longtitute},LATITUDE:{r[1].latitude},OPEN_TIME:{r[1].open_time},\
CHECK_TAG:{r[1].soup},CHECK_CITY:{r[1].province}%'
except AttributeError as error:
output_before_random += f'STORE:{r[1].store},ADDRESS:{r[1].address},DISCRIPTION:{r[1].discription},TRANSPORT:{r[1].transport},\
MAP_REVIEW:{r[1].map_review},\
LONGITUDE:{r[1].longtitute},LATITUDE:{r[1].latitude},OPEN_TIME:{r[1].open_time},\
CHECK_TAG:{r[1].soup},CHECK_CITY:{r[1].province}%'
return output_before_random
def query_province_soup(p, s):
province_soup_q = db.session.query(Main_store, Store, Post)\
.outerjoin(Post, Post.store_id == Main_store.store_id)\
.outerjoin(Store, Store.store_id == Main_store.store_id)\
.filter(Store.province == p)\
.filter(Store.soup.contains(s))\
.filter(Store.still_there == True)
return province_soup_q
def query_province_direct(p):
province_soup_q = db.session.query(Main_store, Store, Post)\
.outerjoin(Post, Post.store_id == Main_store.store_id)\
.outerjoin(Store, Store.store_id == Main_store.store_id)\
.filter(Store.province == p)\
.filter(Store.still_there == True)
return province_soup_q
#----------------主要用在直接打字query店家的部分-----------------
def query_store(store_k1,store_k2):
store_direct = db.session.query(Main_store, Store, Post)\
.outerjoin(Post, Post.store_id == Main_store.store_id)\
.outerjoin(Store, Store.store_id == Main_store.store_id)\
.filter(Store.store.contains(store_k1))\
.filter(Store.store.contains(store_k2))\
.filter(Store.still_there == True)
return store_direct
#----------------主要用在定位系統GIS的部分-----------------
def query_region_by_store_table(r):
province_soup_q = db.session.query(Main_store, Store)\
.outerjoin(Store, Store.store_id == Main_store.store_id)\
.filter(Store.region == r)\
.filter(Store.still_there == True)
return province_soup_q
#---------------------formation-------------------------------
def convert_string_to_lst(string,c):
li = list(string.split(c))
return li
def divide_map_review(comment_s):
comment_clean = comment_s.replace(" - ", "-").replace("- ", "-").replace(" -", "-")
comment_clean_split = re.split('[ ]',comment_clean)
comment_lst = [i for i in comment_clean_split if i]
if len(comment_lst) > 1:
comment_final_list = []
for i, val in enumerate(comment_lst):
if i != (len(comment_lst)-1) and val[-1].islower() == True and val[0].isupper() == True and comment_lst[i+1][0].isupper() == True:
val = val + comment_lst[i+1]
comment_lst.remove(comment_lst[i+1])
comment_final_list.append(val)
return comment_final_list
else:
return comment_lst
##----------------我的最愛取得userid資料庫設定-----------------
def get_love_list_from_user_id(user_id):
love_list_q = db.session.query(Store,Favorite)\
.outerjoin(Favorite, Favorite.detail_store_id == Store.detail_store_id)\
.filter(Favorite.line_id == user_id)
love_list = ''
for l in love_list_q :
love_list += f'{l[0].store}%'
love_list_clear = love_list.replace(u'\xa0', u' ').replace(' ','')
output_whole_love_list = convert_string_to_lst(love_list_clear,'%')
output_whole_love_list = [i for i in output_whole_love_list if i]
return output_whole_love_list
def count_store_in_table(store_name):
store_id_q = db.session.query(Store)\
.filter(Store.store == store_name)\
.count()
return store_id_q
def get_store_id(store_name):
get_id = ''
store_id_q = db.session.query(Store)\
.filter(Store.store == store_name)
for data in store_id_q:
get_id += data.detail_store_id
return get_id
def store_exist(get_user_line_id, store_name):
store_exist = db.session.query(Store, Favorite)\
.join(Favorite, Favorite.detail_store_id == Store.detail_store_id)\
.filter(Favorite.line_id == get_user_line_id)\
.filter(Store.store == store_name).count()
return store_exist
def count_love_list(user_id):
count_love_list = db.session.query(Favorite)\
.filter(Favorite.line_id == user_id).count()
return count_love_list
##----------------Query love-list by userID----------------
def get_list_from_user_id(user_id):
love_list_q = db.session.query(Store,Favorite)\
.outerjoin(Favorite, Favorite.detail_store_id == Store.detail_store_id)\
.filter(Favorite.line_id == user_id)
return love_list_q
def query_map_review_by_full_name(s):
review = db.session.query(Store).filter(Store.store == s).filter(Store.still_there == True)
love_list = ''
for l in review:
love_list += f'STORE:{l.store},ADDRESS:{l.address},DISCRIPTION:{l.discription},TRANSPORT:{l.transport},MAP_REVIEW:{l.map_review},CITY:{l.province},LONGITUDE:{l.longtitute},LATITUDE:{l.latitude},\
OPEN_TIME:{l.open_time},CHECK_TAG:{l.soup}%'
love_list = love_list.replace(u'\xa0', u' ').replace('\n','')
return love_list
#----------------最愛清單動態的模板設定-----------------
def favorite_list_generator(favorite_list):
button_list = [BoxComponent(
layout="vertical",
margin="sm",
spacing="sm",
contents=[
TextComponent(text="最愛清單",weight="bold",size="xl",margin="sm",wrap=True,),
SeparatorComponent(margin = "xxl")
])]
for i in favorite_list:
favorite_button = ButtonComponent(style="primary", color="#997B66", size="sm", margin="sm",
action=MessageAction(label=i, text=f'搜尋你的清單♡{i}'),)
delete_button = ButtonComponent(style="secondary", color="#F1DCA7", size="sm", margin="sm", flex=0,
action=MessageAction(label="-", text="刪除最愛清單♡"+i),)
button_row = BoxComponent(layout="horizontal", margin="md", spacing="sm",
contents=[favorite_button, delete_button])
button_list.append(button_row)
bubble = BubbleContainer(
director='ltr',
body=BoxComponent(
layout="vertical",
contents=button_list
)
)
return bubble
#----------------tag functions-----------
def tags_button_generator(tag_lst,append_obj,city):
lst_to_append_tags = append_obj["body"]["contents"]
tag_btn_lst = []
for item in tag_lst:
tag_btn = {
"type": "button",
"action": {
"type": "message",
"label": item,
"text": f"{city}:{item}"
},
"color": "#D08C60"
}
tag_btn_lst.append(tag_btn)
tag_btn_group = [tag_btn_lst[2*i:(2*i)+2] for i in range(int((len(tag_btn_lst)/2)) +1)]
tag_btn_group = [sub for sub in tag_btn_group if len(sub) != 0]
for sub in tag_btn_group:
tag_btn_layout = {
"type": "box",
"layout": "vertical",
"margin": "sm",
"contents": []
}
tag_btn_layout["contents"] = sub
lst_to_append_tags.append(tag_btn_layout)
return append_obj
def store_query_tags(s):
store_query_tags = db.session.query(Store).filter(Store.store == s)
result = ''
for r in store_query_tags:
result += f"{r.soup}"
return result
#----------------用來做縣市對應region字典-----------------
north = ["台北市","新北市","基隆市","桃園市","苗栗縣","新竹縣","新竹市","臺北市"]
center = ["台中市","彰化縣","南投縣","雲林縣","臺中市"]
south = ["嘉義市","台南市","高雄市","屏東縣","臺南市"]
east = ["宜蘭縣","花蓮縣","台東縣","臺東縣"]
n_dict = dict.fromkeys(north, ("北","north"))
c_dict = dict.fromkeys(center, ("中","center"))
s_dict = dict.fromkeys(south, ("南","south"))
e_dict = dict.fromkeys(east, ("東","east"))
#----------------官方設定-----------------
@app.route("/", methods=['GET'])
def hello():
return "Hello RAMEN World!"
@app.route("/", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
print("Request body: " + body, "Signature: " + signature)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK RAMEN'
#----------------設定回覆訊息介面-----------------
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
#----------------取得userid-----------------
user_id = event.source.user_id
if user_id == '':
user_id = event.source.user_id
TWregion = ["北部","中部","南部","東部"]
city_name = ["台北市","新北市","基隆市","桃園市","苗栗縣","新竹縣","新竹市","台中市","彰化縣","南投縣","雲林縣","嘉義市","台南市","高雄市","屏東縣","宜蘭縣","花蓮縣","台東縣"]
city_name_dic = {**n_dict, **c_dict, **s_dict, **e_dict}
city_region_dict = dict(zip(["north","center","south","east"], [north,center,south,east]))
#----------------拉麵推薦介面-----------------
if event.message.text == "拉麵推薦":
flex_message0 = Flex_template.main_panel_flex()
line_bot_api.reply_message(event.reply_token,flex_message0)
#----------------不同區域的介面設定-----------------
elif event.message.text in TWregion:
#讀需要的json資料
f_region = open('json_files_for_robot/json_for_app.json', encoding="utf8")
data_region = json.load(f_region)
for i,v in enumerate(TWregion):
if event.message.text == v:
flex_message1 = FlexSendMessage(
alt_text= v + '的縣市',
contents= data_region[i]
)
line_bot_api.reply_message(event.reply_token,flex_message1)
f_region.close()
#----------------選擇湯頭介面-----------------
elif "湯頭推薦:" in event.message.text:
user_choice = event.message.text
city_choice = user_choice[user_choice.index(':')+1:]
#用迴圈去讀湯頭選單
#讀需要的推薦介面json資料
f_city_soup = open('json_files_for_robot/soup_'+city_name_dic[city_choice][1]+'_city.json', encoding="utf8")
data_city_soup = json.load(f_city_soup)
#---------------------get province list----------------#
for i, v in enumerate(city_region_dict[city_name_dic[city_choice][1]]):
if v == city_choice:
flex_message2 = FlexSendMessage(
alt_text='快回來看看我幫你找到的湯頭!',
contents= data_city_soup[i]
)
line_bot_api.reply_message(event.reply_token,flex_message2)
f_city_soup.close()
elif event.message.text in city_name:
flex_message5 = Flex_template.soup_direct_flex(event.message.text)
line_bot_api.reply_message(event.reply_token,flex_message5)
elif event.message.text == "嘉義縣":
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = "抱歉!\uDBC0\uDC7c 這邊尚未有拉麵店,請至附近其他縣市看看!"))
elif ('湯頭推薦:'not in event.message.text and '評論' not in event.message.text and ':' in event.message.text) and ':' not in event.message.text[0] and ':' not in event.message.text[-1] and '最愛清單' not in event.message.text:
user_choice = event.message.text
select_first_param = user_choice[:user_choice.index(':')]
select_second_param = user_choice[user_choice.index(':')+1:]
result = ''
if ((select_first_param == '直接推薦') or (select_first_param == '看更多推薦')) and select_second_param in city_name:
result = query_province_direct(select_second_param)
elif select_first_param in city_name:
result = query_province_soup(select_first_param, select_second_param)
else:
result = ''
# #---------------------------------put all data to a string--------------------------
if result == '':
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = "\uDBC0\uDC7c輸入的字串不合法,查詢不到你想要的東西"))
output_before_random_clear = get_data_str(result)
if output_before_random_clear == None or output_before_random_clear == '':
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = "\uDBC0\uDC7c輸入的字串不合法,查詢不到你想要的東西"))
else:
output_before_random_clear = output_before_random_clear.replace(u'\xa0', u' ').replace('\n','')
#---------------------------------change data to a list of datas--------------------------
output_whole_lst = convert_string_to_lst(output_before_random_clear,'%')
output_whole_lst = [i for i in output_whole_lst if i]
#---------------------------------random(everytime renew can auto random)--------------------------
output_s = random.choice(output_whole_lst)
output_lst = convert_string_to_lst(output_s, ',')
if len(output_lst) == 12 or len(output_lst) == 10:
store_n = output_lst[0][output_lst[0].index(':')+1:]
address = output_lst[1][output_lst[1].index(':')+1:]
descrip = output_lst[2][output_lst[2].index(':')+1:]
trans = output_lst[3][output_lst[3].index(':')+1:]
f_city = output_lst[-1][output_lst[-1].index(':')+1:]
if len(output_lst) == 12:
#FB評論
c1 = output_lst[4][output_lst[4].index(':')+1:]
c2 = output_lst[5][output_lst[5].index(':')+1:]
c3 = output_lst[6][output_lst[6].index(':')+1:]
comment = f'貼文時間:\n{c1}\n\n品項:\n{c2}\n\n評論:\n{c3}'
lon = output_lst[7][output_lst[7].index(':')+1:]
lat = output_lst[8][output_lst[8].index(':')+1:]
op = output_lst[9][output_lst[9].index(':')+1:]
elif len(output_lst) == 10:
#googleMap
comment = output_lst[4][output_lst[4].index(':')+1:]
lon = output_lst[5][output_lst[5].index(':')+1:]
lat = output_lst[6][output_lst[6].index(':')+1:]
op = output_lst[7][output_lst[7].index(':')+1:]
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.error_warning_text('O1')) )
flex_message9 = Flex_template.double_flex("快回來看看我幫你找到的店家!", store_n, address, lon, lat, descrip, trans, op, "看同類推薦", user_choice, f_city, comment, "+到最愛", "加到最愛清單")
line_bot_api.reply_message(event.reply_token,flex_message9)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = f"資料庫有誤"))
elif ' ' in event.message.text and ' ' not in event.message.text[-1] and ' ' not in event.message.text[0]:
user_select = event.message.text
if "有人評論→" in user_select:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.warm_msg()))
elif "正在幫你找到→" in user_select:
text_list = user_select.split("→")
lonti = float(text_list[1])
lati = float(text_list[2])
line_bot_api.reply_message(event.reply_token,LocationSendMessage(title='點擊帶你前往!',address='iRamen',latitude= lati,longitude= lonti))
#----------------weather api logic-----------------
elif "附近天氣搜索中→" in user_select:
text_list = user_select.split("→")
lonti = float(text_list[1])
lati = float(text_list[2])
store_name = str(text_list[0]).replace('搜索中','').replace(' ','')
WEATHER_API_KEY = os.environ.get('WEATHER_API_KEY')
weather_result = Weather.query_local_weather(lonti,lati,WEATHER_API_KEY,store_name)
if weather_result != '':
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = weather_result))
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.error_warning_text('W1'))
)
else: #----------------輸入關鍵字找尋店家-----------------
input_lst = user_select.split()
keyword_result=''
if len(input_lst) == 2 :
count_store = query_store(str(input_lst[0]),str(input_lst[1])).count()
# print(count_store)
if count_store != 0:
keyword_result = query_store(str(input_lst[0]),str(input_lst[1]))
# else:
# keyword_result = ''
# else:
# keyword_result = ''
# else:
# keyword_result = ''
# ---------------------------------put all data to a string--------------------------
if keyword_result == '':
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.keyword_warning_text()))
else:
output_before_random_clear = get_data_str(keyword_result)
if output_before_random_clear == None:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.keyword_warning_text()))
else:
output_before_random_clear = output_before_random_clear.replace(u'\xa0', u' ').replace('\n','')
#---------------------------------change data to a list of datas--------------------------
output_whole_lst = convert_string_to_lst(output_before_random_clear,'%')
output_whole_lst = [i for i in output_whole_lst if i]
output_s = random.choice(output_whole_lst)
output_lst = convert_string_to_lst(output_s, ',')
if len(output_lst) == 12 or len(output_lst) == 10:
store_n = output_lst[0][output_lst[0].index(':')+1:]
address = output_lst[1][output_lst[1].index(':')+1:]
descrip = output_lst[2][output_lst[2].index(':')+1:]
trans = output_lst[3][output_lst[3].index(':')+1:]
f_city = output_lst[-1][output_lst[-1].index(':')+1:]
if len(output_lst) == 12:
#FB評論
c1 = output_lst[4][output_lst[4].index(':')+1:]
c2 = output_lst[5][output_lst[5].index(':')+1:]
c3 = output_lst[6][output_lst[6].index(':')+1:]
comment = f'貼文時間:\n{c1}\n\n品項:\n{c2}\n\n評論:\n{c3}'
lon = output_lst[7][output_lst[7].index(':')+1:]
lat = output_lst[8][output_lst[8].index(':')+1:]
op = output_lst[9][output_lst[9].index(':')+1:]
elif len(output_lst) == 10:
#googleMap
comment = output_lst[4][output_lst[4].index(':')+1:]
lon = output_lst[5][output_lst[5].index(':')+1:]
lat = output_lst[6][output_lst[6].index(':')+1:]
op = output_lst[7][output_lst[7].index(':')+1:]
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.error_warning_text('S1')) )
flex_message3 = Flex_template.double_flex("快來看你搜索到的店!", store_n, address, lon, lat, descrip, trans, op, "再搜索一次", user_select, f_city, comment, "+到最愛", "加到最愛清單")
line_bot_api.reply_message(event.reply_token,flex_message3)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.error_warning_text('S3'))
)
elif ' ' in event.message.text and (' ' in event.message.text[-1] or ' ' in event.message.text[0]):
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.keyword_warning_text()))
elif "輸出評論超連結→" in event.message.text:
text_list = event.message.text.split("→")
store_name = str(text_list[1])
map_review_data = db.session.query(Store.map_review).filter(Store.store == text_list[1]).filter(Store.still_there == True)
map_format = ''
for r in map_review_data:
#抓出來是tuple
r_str = ''.join(list(map(str,r)))
r_str = r_str.replace(u'\xa0', u' ').replace(u'\n', u' ')
map_lst = divide_map_review(r_str)
map_lst = [v+'\n\n' if i%2 != 0 and i != len(map_lst)-1 else v+'\n' for i,v in enumerate(map_lst)]
map_format += ''.join(map(str, map_lst))
map_format = map_format[:-1]
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = f"{store_name}\n\n{map_format}")
)
elif "類別搜索中→" in event.message.text:
group_list = event.message.text.split("→")
store_n = str(group_list[1])
city_n = str(group_list[2])
tags = store_query_tags(store_n)
tag_list = convert_string_to_lst(tags,'#')
tag_list = [i for i in tag_list if i]
contents_tags = {
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": f"{store_n}相關風格",
"weight": "bold",
"align": "start",
"gravity": "center",
"size": "lg",
"color": "#876C5A",
"wrap":True
},
{
"type": "text",
"text": "點擊看類似店家...",
"size": "xs",
"margin": "sm"
},
{
"type": "separator",
"margin": "lg"
}
]
}
}
flex_message_tags = FlexSendMessage(
alt_text='快回來看看我幫你找到的店家!',
contents= tags_button_generator(tag_list, contents_tags, city_n))
line_bot_api.reply_message(event.reply_token,flex_message_tags)
# line_bot_api.reply_message(event.reply_token,TextSendMessage(text = f"{store_n}{city_n}{tag_list}"))
#----------------最愛清單訊息觸發設定-----------------
elif event.message.text == "最愛清單":
user_list_count = count_love_list(user_id)
if user_list_count == 0:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = "尚未有最愛清單,快去加入你喜歡的拉麵吧!\uDBC0\uDC5e"))
elif user_list_count != 0:
ramen_test = get_love_list_from_user_id(user_id)
flex_message6 = FlexSendMessage(
alt_text= '快回來看看我的最愛!',
contents= favorite_list_generator(ramen_test)
)
line_bot_api.reply_message(event.reply_token,flex_message6)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.error_warning_text('L2'))
)
#----------------最愛清單加入資料庫設定與訊息回覆設定-----------------
elif "搜尋你的清單♡" in event.message.text:
text_l = event.message.text.split("♡")
store_name_full = text_l[1]
if store_exist(user_id, store_name_full) != 0:
store_detail = query_map_review_by_full_name(store_name_full)
#---------------------------------change data to a list of datas--------------------------
output_whole_lst = convert_string_to_lst(store_detail,',')
output_whole_lst = [i for i in output_whole_lst if i]
r_store = output_whole_lst[0][output_whole_lst[0].index(':')+1:]
ad = output_whole_lst[1][output_whole_lst[1].index(':')+1:]
dis = output_whole_lst[2][output_whole_lst[2].index(':')+1:]
trans = output_whole_lst[3][output_whole_lst[3].index(':')+1:]
com = output_whole_lst[4][output_whole_lst[4].index(':')+1:]
com_lst = divide_map_review(com)
com_lst = [v+'\n\n' if i%2 != 0 and i != len(com_lst)-1 else v+'\n' for i,v in enumerate(com_lst)]
com_format = ''.join(map(str, com_lst))
city_r = output_whole_lst[5][output_whole_lst[5].index(':')+1:]
lont = output_whole_lst[6][output_whole_lst[6].index(':')+1:]
lati = output_whole_lst[7][output_whole_lst[7].index(':')+1:]
opent = output_whole_lst[8][output_whole_lst[8].index(':')+1:]
flex_message7 = Flex_template.single_flex('快來看看你的清單~', r_store, ad, lont, lati, dis, trans, opent, city_r, com_format,'刪除最愛','刪除最愛清單')
line_bot_api.reply_message(event.reply_token,flex_message7)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = "你已將此店家從最愛清單中刪除")
)
elif "加到最愛清單♡" in event.message.text or "刪除最愛清單♡" in event.message.text:
user_line_id = user_id
text_l = event.message.text.split("♡")
first_love_param = text_l[0]
second_love_param = text_l[1]
if first_love_param == '加到最愛清單':
store_in_table = count_store_in_table(second_love_param) #check if the store name legal
favorite_list_count = count_love_list(user_line_id) #how many items a user save
already_add_store_count = store_exist(user_line_id, second_love_param) #check if the store user want to add already exist in the list
if store_in_table != 0:
if favorite_list_count == 0 or\
favorite_list_count != 0 and already_add_store_count == 0 and favorite_list_count <= 25 :
get_foreign_id = get_store_id(second_love_param)#check the map_id(foreign key) of the store
data = Favorite(user_line_id,get_foreign_id)
while(data.id == None):
try:
db.session.add(data)
db.session.commit()
except IntegrityError:
db.session.rollback()
continue
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text="你剛剛成功把 " + second_love_param + " 加進最愛清單!")
)
elif favorite_list_count > 25:
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text="最愛清單數量超過上限,請刪除部分資料\udbc0\udc7c")
)
else:
line_bot_api.reply_message(event.reply_token,TextSendMessage(text= second_love_param + "已經在最愛清單!"))
else:
line_bot_api.reply_message(event.reply_token,TextSendMessage(text="你輸入的店名資料庫裡沒有啦\udbc0\udc7c"))
elif first_love_param == '刪除最愛清單':
detail_id = get_store_id(second_love_param)
if detail_id != '' and store_exist(user_line_id, second_love_param) != 0:
data = db.session.query(Favorite)\
.filter(Favorite.detail_store_id == detail_id)\
.filter(Favorite.line_id == user_line_id)\
.first()
db.session.delete(data)
db.session.commit()
line_bot_api.reply_message(event.reply_token,TextSendMessage(text="成功刪除"+ second_love_param ))
elif store_exist(user_line_id, second_love_param) == 0: #check if the store user want to rermove already not exist in the list
line_bot_api.reply_message(event.reply_token,TextSendMessage(text= second_love_param + "已不在你的最愛清單囉!" ))
else:
line_bot_api.reply_message(event.reply_token,TextSendMessage(text= "發生錯誤請再試一次" ))
else:
line_bot_api.reply_message(event.reply_token,TextSendMessage(text= "不要亂打字!!!" ))
#----------------定位叫使用者給位置-----------------
elif event.message.text == "定位" :
text_message_location = TextSendMessage(text='偷偷分享位置給我,我才能推薦附近店家給你哦!\uDBC0\uDCB9',
quick_reply=QuickReply(items=[
QuickReplyButton(action=LocationAction(label="我在哪My LOC"))
]))
line_bot_api.reply_message(event.reply_token,text_message_location)
elif "搜尋店家細節♡" in event.message.text:
text_s = event.message.text.split("♡")
store_full_name = text_s[1]
store_detail_for_distance = query_map_review_by_full_name(store_full_name)
output_whole_lst = convert_string_to_lst(store_detail_for_distance,',')
output_whole_lst = [i for i in output_whole_lst if i]
if len(output_whole_lst) == 10:
r_store = output_whole_lst[0][output_whole_lst[0].index(':')+1:]
ad = output_whole_lst[1][output_whole_lst[1].index(':')+1:]
dis = output_whole_lst[2][output_whole_lst[2].index(':')+1:]
trans = output_whole_lst[3][output_whole_lst[3].index(':')+1:]
com = output_whole_lst[4][output_whole_lst[4].index(':')+1:]
com_lst = divide_map_review(com)
com_lst = [v+'\n\n' if i%2 != 0 and i != len(com_lst)-1 else v+'\n' for i,v in enumerate(com_lst)]
com_format = ''.join(map(str, com_lst))
city_r = output_whole_lst[5][output_whole_lst[5].index(':')+1:]
lont = output_whole_lst[6][output_whole_lst[6].index(':')+1:]
lati = output_whole_lst[7][output_whole_lst[7].index(':')+1:]
opent = output_whole_lst[8][output_whole_lst[8].index(':')+1:]
flex_message8 = Flex_template.single_flex('快來看看店家細節~', r_store, ad, lont, lati, dis, trans, opent, city_r, com_format,"+到最愛","加到最愛清單")
line_bot_api.reply_message(event.reply_token,flex_message8)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.error_warning_text('D1'))
)
#----------------問題回報(未來可加donate資訊)----------------
elif event.message.text == "問題回報":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text= Text_template.user_report()))
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text = Text_template.keyword_warning_text()))
@handler.add(MessageEvent, message=LocationMessage)#定位細節
def handle_location(event):
city_name_dic = {**n_dict, **c_dict, **s_dict, **e_dict}
#---------------user info-----------------
u_lat = event.message.latitude
u_long = event.message.longitude
user_address = event.message.address
u_address = user_address.replace(' ', '')
user_location = (u_lat, u_long)
all_store_province = ''
choice_nearby_city_tup = ''
for k, v in city_name_dic.items():
if k in u_address:
region_value = v[0]
all_store_province = query_region_by_store_table(region_value)
break
else:
#search all
all_store_province = province_soup_q = db.session.query(Main_store, Store)\
.outerjoin(Store, Store.store_id == Main_store.store_id)\
.filter(Store.still_there == True)
break
# '''
# 算距離
# '''
if all_store_province == '':
line_bot_api.reply_message(event.reply_token,TextSendMessage(text=Text_template.error_warning_text('P1')))
else:
sorted_city_distance_dic = Gps.caculate_distance(user_location,all_store_province)
if len(sorted_city_distance_dic) >= 10:
choice_nearby_city = Gps.take(10, sorted_city_distance_dic.items())
if choice_nearby_city[0][1][0] > 395:
text_message_foreign_location = TextSendMessage(text="\udbc0\udc7B目前不支援離島與國外拉麵店,請到台灣本島吃拉麵Yeah We only support ramen shops in Taiwan~",
quick_reply=QuickReply(items=[
QuickReplyButton(action=LocationAction(label="再定位一次My LOC"))
]))
line_bot_api.reply_message(event.reply_token,text_message_foreign_location)
else:
choice_nearby_city_tup = choice_nearby_city
else:
line_bot_api.reply_message(event.reply_token,TextSendMessage(text= Text_template.error_warning_text('G2') ))
flex_message_location = FlexSendMessage(
alt_text='快回來看看我幫你找到的店家!',
contents= Gps.distance_template_generator(choice_nearby_city_tup),
quick_reply= QuickReply(items=[QuickReplyButton(action=LocationAction(label="再定位一次My LOC")),
QuickReplyButton(action=URIAction(label="拉麵地圖自己找",uri=f'https://www.google.com/maps/d/u/0/viewer?fbclid=IwAR3O8PKxMuqtqb2wMKoHKe4cCETwnT2RSCZSpsyPPkFsJ6NpstcrDcjhO2k&mid=1I8nWhKMX1j8I2bUkN4qN3-FSyFCCsCh7&ll={u_lat}%2C{u_long}'))
]))
line_bot_api.reply_message(event.reply_token,flex_message_location)
if __name__ == 'main':
app.run(debug=True)
| 48.514145 | 299 | 0.571168 | 2,797 | 0.067788 | 0 | 0 | 27,564 | 0.66804 | 0 | 0 | 8,631 | 0.209181 |