code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ import bisect if not nums: return -1 n = len(nums) k = n for i in range(1, n): if nums[i - 1] > nums[i]: k = i break r = (0, k) if target >= nums[0] else (k, n) idx = bisect.bisect_left(nums, target, *r) if 0 <= idx < n and nums[idx] == target: return idx return -1
[ "bisect.bisect_left" ]
[((439, 475), 'bisect.bisect_left', 'bisect.bisect_left', (['nums', 'target', '*r'], {}), '(nums, target, *r)\n', (457, 475), False, 'import bisect\n')]
import sys from PySide2.QtGui import QGuiApplication from PySide2.QtQml import QQmlApplicationEngine from PySide2.QtCore import QUrl from PySide2.QtCore import QCoreApplication from PySide2.QtCore import QObject, Signal, Slot, Property class Number(QObject): __val = 0 @Signal def numberChanged(self): pass @Slot(int) def set_number(self, val): print("setter func") self.__val = val self.numberChanged.emit() def get_number(self): print("getter func") return self.__val ValueNumber = Property(int, get_number, set_number, notify=numberChanged) if __name__ == '__main__': app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() number = Number() engine.rootContext().setContextProperty("numberVal", number) engine.load(QUrl("./main.qml")) if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
[ "PySide2.QtCore.Slot", "PySide2.QtCore.Property", "PySide2.QtQml.QQmlApplicationEngine", "sys.exit", "PySide2.QtCore.QUrl", "PySide2.QtGui.QGuiApplication" ]
[((334, 343), 'PySide2.QtCore.Slot', 'Slot', (['int'], {}), '(int)\n', (338, 343), False, 'from PySide2.QtCore import QObject, Signal, Slot, Property\n'), ((564, 623), 'PySide2.QtCore.Property', 'Property', (['int', 'get_number', 'set_number'], {'notify': 'numberChanged'}), '(int, get_number, set_number, notify=numberChanged)\n', (572, 623), False, 'from PySide2.QtCore import QObject, Signal, Slot, Property\n'), ((664, 689), 'PySide2.QtGui.QGuiApplication', 'QGuiApplication', (['sys.argv'], {}), '(sys.argv)\n', (679, 689), False, 'from PySide2.QtGui import QGuiApplication\n'), ((703, 726), 'PySide2.QtQml.QQmlApplicationEngine', 'QQmlApplicationEngine', ([], {}), '()\n', (724, 726), False, 'from PySide2.QtQml import QQmlApplicationEngine\n'), ((832, 850), 'PySide2.QtCore.QUrl', 'QUrl', (['"""./main.qml"""'], {}), "('./main.qml')\n", (836, 850), False, 'from PySide2.QtCore import QUrl\n'), ((898, 910), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (906, 910), False, 'import sys\n')]
#!/usr/bin/env python3 import argparse, os, sys, time, shutil, tqdm import warnings, json, gzip import numpy as np import copy from sklearn.model_selection import GroupKFold import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.utils.data import DataLoader, Subset import epi_models import epi_dataset import misc_utils import functools print = functools.partial(print, flush=True) def split_train_valid_test(groups, train_keys, valid_keys, test_keys=None): """ groups: length N, the number of samples train """ assert isinstance(train_keys, list) assert isinstance(valid_keys, list) assert test_keys is None or isinstance(test_keys, list) index = np.arange(len(groups)) train_idx = index[np.isin(groups, train_keys)] valid_idx = index[np.isin(groups, valid_keys)] if test_keys is not None: test_idx = index[np.isin(groups, test_keys)] return train_idx, valid_idx, test_idx else: return train_idx, valid_idx def make_directory(in_dir): if os.path.isfile(in_dir): warnings.warn("{} is a regular file".format(in_dir)) return None outdir = in_dir.rstrip('/') if not os.path.isdir(outdir): os.makedirs(outdir) return outdir def model_summary(model): """ model: pytorch model """ import torch total_param = 0 trainable_param = 0 for i, p in enumerate(model.parameters()): num_p = torch.numel(p) if p.requires_grad: trainable_param += num_p total_param += num_p return {'total_param': total_param, 'trainable_param': trainable_param} def predict(model: nn.Module, data_loader: DataLoader, device=torch.device('cuda')): model.eval() result, true_label = None, None for feats, _, enh_idxs, prom_idxs, labels in data_loader: feats, labels = feats.to(device), labels.to(device) # enh_idxs, prom_idxs = enh_idxs.to(device), prom_idxs.to(device) pred = model(feats, enh_idx=enh_idxs, prom_idx=prom_idxs) pred = pred.detach().cpu().numpy() labels = labels.detach().cpu().numpy() if result is None: result = pred true_label = labels else: result = np.concatenate((result, pred), axis=0) true_label = np.concatenate((true_label, labels), axis=0) return (result.squeeze(), true_label.squeeze()) def train_validate_test( model, optimizer, train_loader, valid_loader, test_loader, num_epoch, patience, outdir, checkpoint_prefix, device, use_scheduler=False) -> nn.Module: bce_loss = nn.BCELoss() mse_loss = nn.MSELoss() wait = 0 best_epoch, best_val_auc, best_val_aupr = -1, -1, -1 if use_scheduler: scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=5, T_mult=2) for epoch_idx in range(num_epoch): model.train() for feats, dists, enh_idxs, prom_idxs, labels in tqdm.tqdm(train_loader): feats, dists, labels = feats.to(device), dists.to(device), labels.to(device) if hasattr(model, "att_C"): pred, pred_dists, att = model(feats, enh_idxs, prom_idxs, return_att=True) attT = att.transpose(1, 2) identity = torch.eye(att.size(1)).to(device) identity = Variable(identity.unsqueeze(0).expand(labels.size(0), att.size(1), att.size(1))) penal = model.l2_matrix_norm(torch.matmul(att, attT) - identity) loss = bce_loss(pred, labels) + (model.att_C * penal / labels.size(0)).type(torch.cuda.FloatTensor) + mse_loss(dists, pred_dists) del penal, identity else: pred = model(feats, dists) loss = bce_loss(pred, labels) optimizer.zero_grad() loss.backward() optimizer.step() if use_scheduler: scheduler.step() model.eval() valid_pred, valid_true = predict(model, valid_loader) val_AUC, val_AUPR = misc_utils.evaluator(valid_true, valid_pred, out_keys=["AUC", "AUPR"]) print("\nvalid_result({})\t{:.4f}\t{:.4f}\t({})".format(epoch_idx, val_AUC, val_AUPR, time.asctime())) if val_AUC + val_AUPR > best_val_auc + best_val_aupr: wait = 0 best_epoch, best_val_auc, best_val_aupr = epoch_idx, val_AUC, val_AUPR test_pred, test_true = predict(model, test_loader) np.savetxt( "{}/test_result.{}.txt.gz".format(outdir, epoch_idx), X=np.concatenate((test_pred.reshape(-1, 1), test_true.reshape(-1, 1)), axis=1), fmt="%.5f", delimiter='\t' ) test_AUC, test_AUPR = misc_utils.evaluator(test_true, test_pred, out_keys=["AUC", "AUPR"]) print("Test_result\t{:.4f}\t{:.4f}\t({})".format(test_AUC, test_AUPR, time.asctime())) if use_scheduler: torch.save({ "model_state_dict": model.state_dict(), "optimizer_state_dict": optimizer.state_dict(), "scheduler_state_dict": scheduler.state_dict() }, "{}/checkpoint.{}.pt".format(outdir, epoch_idx)) else: torch.save({ "model_state_dict": model.state_dict(), "optimizer_state_dict": optimizer.state_dict() }, "{}/checkpoint.{}.pt".format(outdir, epoch_idx)) else: wait += 1 if wait >= patience: print("Early stopped ({})".format(time.asctime())) print("Best epoch/AUC/AUPR: {}\t{:.4f}\t{:.4f}".format(best_epoch, best_val_auc, best_val_aupr)) break else: print("Wait{} ({})".format(wait, time.asctime())) def get_args(): p = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) p.add_argument( '--train', required=True, nargs='+' ) p.add_argument( '--valid', required=True, nargs='+' ) p.add_argument( "--test", nargs='+', default=None, help="Optional test set" ) p.add_argument('-b', "--batch-size", type=int, default=256) p.add_argument('-c', "--config", required=True) p.add_argument('-o', "--outdir", required=True) p.add_argument("--threads", default=32, type=int) p.add_argument('--seed', type=int, default=2020) return p if __name__ == "__main__": p = get_args() args = p.parse_args() np.random.seed(args.seed) torch.manual_seed(args.seed) config = json.load(open(args.config)) # all_data = epi_dataset.EPIDataset(**config["data_opts"]) train_config = config.copy() train_config["data_opts"]["datasets"] = args.train train_config["data_opts"]["use_reverse"] = args.use_reverse train_config["data_opts"]["max_aug"] = args.aug_num train_data = epi_dataset.EPIDataset( **train_config["data_opts"] ) train_loader = DataLoader(train_data, batch_size=args.batch_size, shuffle=True, num_workers=args.threads) if args.test is None: valid_test_config = copy.deepcopy(config) valid_test_config["data_opts"]["datasets"] = args.valid valid_test_data = epi_dataset.EPIDataset( **valid_test_config["data_opts"] ) valid_idx, test_idx = split_train_valid_test( np.array(valid_test_data.metainfo["chrom"]), train_keys=["chr{}".format(i).replace("23", "X") for i in range(1, 24, 2)], valid_keys=["chr{}".format(i) for i in range(2, 22, 2)] ) valid_data = Subset(valid_test_data, indices=valid_idx) test_data = Subset(valid_test_data, indices=test_idx) valid_loader = DataLoader(valid_data, batch_size=args.batch_size, shuffle=False) test_loader = DataLoader(test_data, batch_size=args.batch_size, shuffle=False) else: valid_config = copy.deepcopy(config) valid_config["data_opts"]["datasets"] = args.valid valid_data = epi_dataset.EPIDataset( **valid_config["data_opts"] ) valid_loader = DataLoader(valid_data, batch_size=args.batch_size, shuffle=False, num_workers=args.threads) test_config = copy.deepcopy(config) test_config["data_opts"]["datasets"] = args.test test_data = epi_dataset.EPIDataset( **test_config["data_opts"] ) test_loader = DataLoader(test_data, batch_size=args.batch_size, shuffle=False, num_workers=args.threads) config["model_opts"]["in_dim"] = train_data.feat_dim config["model_opts"]["seq_len"] = config["data_opts"]["seq_len"] // config["data_opts"]["bin_size"] print("##{}".format(time.asctime())) print("##command: {}".format(' '.join(sys.argv))) print("##args: {}".format(args)) print("##config: {}".format(config)) print("##sample size: {}".format(len(train_data))) print("## feature size: {}".format([v.size() for v in train_data.__getitem__(0)])) if args.gpu == -1: device = "cpu" else: os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id) device = "cuda" device = torch.device(device) model_class = getattr(epi_models, config["model_opts"]["model"]) model = model_class(**config["model_opts"]).to(device) optimizer_params = {'lr': config["train_opts"]["learning_rate"], 'weight_decay': 0} optimizer = torch.optim.Adam(model.parameters(), **optimizer_params) print(model) print(model_summary(model)) print(optimizer) if not os.path.isdir(args.outdir): args.outdir = make_directory(args.outdir) train_validate_test( model, optimizer, train_loader, valid_loader, test_loader, num_epoch=config["train_opts"]["num_epoch"], patience=config["train_opts"]["patience"], outdir=args.outdir, checkpoint_prefix="checkpoint", device=device, use_scheduler=config["train_opts"]["use_scheduler"] )
[ "numpy.isin", "numpy.random.seed", "argparse.ArgumentParser", "misc_utils.evaluator", "os.path.isfile", "torch.device", "time.asctime", "torch.nn.MSELoss", "torch.nn.BCELoss", "torch.utils.data.DataLoader", "torch.matmul", "functools.partial", "copy.deepcopy", "tqdm.tqdm", "torch.manual_seed", "numpy.concatenate", "torch.utils.data.Subset", "torch.numel", "os.makedirs", "os.path.isdir", "torch.optim.lr_scheduler.CosineAnnealingWarmRestarts", "epi_dataset.EPIDataset", "numpy.array" ]
[((409, 445), 'functools.partial', 'functools.partial', (['print'], {'flush': '(True)'}), '(print, flush=True)\n', (426, 445), False, 'import functools\n'), ((1081, 1103), 'os.path.isfile', 'os.path.isfile', (['in_dir'], {}), '(in_dir)\n', (1095, 1103), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((1739, 1759), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (1751, 1759), False, 'import torch\n'), ((2675, 2687), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (2685, 2687), True, 'import torch.nn as nn\n'), ((2703, 2715), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2713, 2715), True, 'import torch.nn as nn\n'), ((5975, 6054), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (5998, 6054), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((6773, 6798), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (6787, 6798), True, 'import numpy as np\n'), ((6803, 6831), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (6820, 6831), False, 'import torch\n'), ((7164, 7215), 'epi_dataset.EPIDataset', 'epi_dataset.EPIDataset', ([], {}), "(**train_config['data_opts'])\n", (7186, 7215), False, 'import epi_dataset\n'), ((7249, 7343), 'torch.utils.data.DataLoader', 'DataLoader', (['train_data'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'num_workers': 'args.threads'}), '(train_data, batch_size=args.batch_size, shuffle=True,\n num_workers=args.threads)\n', (7259, 7343), False, 'from torch.utils.data import DataLoader, Subset\n'), ((9448, 9468), 'torch.device', 'torch.device', (['device'], {}), '(device)\n', (9460, 9468), False, 'import torch\n'), ((790, 817), 'numpy.isin', 'np.isin', (['groups', 'train_keys'], {}), '(groups, train_keys)\n', (797, 817), True, 'import numpy as np\n'), ((841, 868), 'numpy.isin', 'np.isin', (['groups', 'valid_keys'], {}), '(groups, valid_keys)\n', (848, 868), True, 'import numpy as np\n'), ((1229, 1250), 'os.path.isdir', 'os.path.isdir', (['outdir'], {}), '(outdir)\n', (1242, 1250), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((1260, 1279), 'os.makedirs', 'os.makedirs', (['outdir'], {}), '(outdir)\n', (1271, 1279), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((1490, 1504), 'torch.numel', 'torch.numel', (['p'], {}), '(p)\n', (1501, 1504), False, 'import torch\n'), ((2830, 2915), 'torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', 'torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', (['optimizer'], {'T_0': '(5)', 'T_mult': '(2)'}), '(optimizer, T_0=5, T_mult=2\n )\n', (2882, 2915), False, 'import torch\n'), ((3030, 3053), 'tqdm.tqdm', 'tqdm.tqdm', (['train_loader'], {}), '(train_loader)\n', (3039, 3053), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((4125, 4195), 'misc_utils.evaluator', 'misc_utils.evaluator', (['valid_true', 'valid_pred'], {'out_keys': "['AUC', 'AUPR']"}), "(valid_true, valid_pred, out_keys=['AUC', 'AUPR'])\n", (4145, 4195), False, 'import misc_utils\n'), ((7395, 7416), 'copy.deepcopy', 'copy.deepcopy', (['config'], {}), '(config)\n', (7408, 7416), False, 'import copy\n'), ((7507, 7563), 'epi_dataset.EPIDataset', 'epi_dataset.EPIDataset', ([], {}), "(**valid_test_config['data_opts'])\n", (7529, 7563), False, 'import epi_dataset\n'), ((7901, 7943), 'torch.utils.data.Subset', 'Subset', (['valid_test_data'], {'indices': 'valid_idx'}), '(valid_test_data, indices=valid_idx)\n', (7907, 7943), False, 'from torch.utils.data import DataLoader, Subset\n'), ((7964, 8005), 'torch.utils.data.Subset', 'Subset', (['valid_test_data'], {'indices': 'test_idx'}), '(valid_test_data, indices=test_idx)\n', (7970, 8005), False, 'from torch.utils.data import DataLoader, Subset\n'), ((8029, 8094), 'torch.utils.data.DataLoader', 'DataLoader', (['valid_data'], {'batch_size': 'args.batch_size', 'shuffle': '(False)'}), '(valid_data, batch_size=args.batch_size, shuffle=False)\n', (8039, 8094), False, 'from torch.utils.data import DataLoader, Subset\n'), ((8117, 8181), 'torch.utils.data.DataLoader', 'DataLoader', (['test_data'], {'batch_size': 'args.batch_size', 'shuffle': '(False)'}), '(test_data, batch_size=args.batch_size, shuffle=False)\n', (8127, 8181), False, 'from torch.utils.data import DataLoader, Subset\n'), ((8215, 8236), 'copy.deepcopy', 'copy.deepcopy', (['config'], {}), '(config)\n', (8228, 8236), False, 'import copy\n'), ((8317, 8368), 'epi_dataset.EPIDataset', 'epi_dataset.EPIDataset', ([], {}), "(**valid_config['data_opts'])\n", (8339, 8368), False, 'import epi_dataset\n'), ((8414, 8509), 'torch.utils.data.DataLoader', 'DataLoader', (['valid_data'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': 'args.threads'}), '(valid_data, batch_size=args.batch_size, shuffle=False,\n num_workers=args.threads)\n', (8424, 8509), False, 'from torch.utils.data import DataLoader, Subset\n'), ((8529, 8550), 'copy.deepcopy', 'copy.deepcopy', (['config'], {}), '(config)\n', (8542, 8550), False, 'import copy\n'), ((8628, 8678), 'epi_dataset.EPIDataset', 'epi_dataset.EPIDataset', ([], {}), "(**test_config['data_opts'])\n", (8650, 8678), False, 'import epi_dataset\n'), ((8723, 8817), 'torch.utils.data.DataLoader', 'DataLoader', (['test_data'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': 'args.threads'}), '(test_data, batch_size=args.batch_size, shuffle=False,\n num_workers=args.threads)\n', (8733, 8817), False, 'from torch.utils.data import DataLoader, Subset\n'), ((9843, 9869), 'os.path.isdir', 'os.path.isdir', (['args.outdir'], {}), '(args.outdir)\n', (9856, 9869), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((925, 951), 'numpy.isin', 'np.isin', (['groups', 'test_keys'], {}), '(groups, test_keys)\n', (932, 951), True, 'import numpy as np\n'), ((2287, 2325), 'numpy.concatenate', 'np.concatenate', (['(result, pred)'], {'axis': '(0)'}), '((result, pred), axis=0)\n', (2301, 2325), True, 'import numpy as np\n'), ((2351, 2395), 'numpy.concatenate', 'np.concatenate', (['(true_label, labels)'], {'axis': '(0)'}), '((true_label, labels), axis=0)\n', (2365, 2395), True, 'import numpy as np\n'), ((4854, 4922), 'misc_utils.evaluator', 'misc_utils.evaluator', (['test_true', 'test_pred'], {'out_keys': "['AUC', 'AUPR']"}), "(test_true, test_pred, out_keys=['AUC', 'AUPR'])\n", (4874, 4922), False, 'import misc_utils\n'), ((7656, 7699), 'numpy.array', 'np.array', (["valid_test_data.metainfo['chrom']"], {}), "(valid_test_data.metainfo['chrom'])\n", (7664, 7699), True, 'import numpy as np\n'), ((9001, 9015), 'time.asctime', 'time.asctime', ([], {}), '()\n', (9013, 9015), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((4290, 4304), 'time.asctime', 'time.asctime', ([], {}), '()\n', (4302, 4304), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((5005, 5019), 'time.asctime', 'time.asctime', ([], {}), '()\n', (5017, 5019), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((3532, 3555), 'torch.matmul', 'torch.matmul', (['att', 'attT'], {}), '(att, attT)\n', (3544, 3555), False, 'import torch\n'), ((5713, 5727), 'time.asctime', 'time.asctime', ([], {}), '()\n', (5725, 5727), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((5932, 5946), 'time.asctime', 'time.asctime', ([], {}), '()\n', (5944, 5946), False, 'import argparse, os, sys, time, shutil, tqdm\n')]
import unittest from app.main.util.data_validation import validate_region_name class TestCorrectRegionValidation(unittest.TestCase): def test_correct_region_validation(self): correct_region_simple = "Argentina" correct_region_with_spaces = "United%20Kingdom" correct_region_with_hiphen = "timor-leste" self.assertTupleEqual( (True, "Argentina", None), validate_region_name(correct_region_simple) ) self.assertTupleEqual( (True, "United Kingdom", None), validate_region_name(correct_region_with_spaces) ) self.assertTupleEqual( (True, "timor-leste", None), validate_region_name(correct_region_with_hiphen) ) class TestIncorrectRegionValidation(unittest.TestCase): def test_incorrect_region_validation(self): no_region_informed = None empty_region = "" region_with_number = "timor-leste123456" self.assertTupleEqual( (False, None, "'region' parameter must be informed"), validate_region_name(no_region_informed) ) self.assertTupleEqual( ( False, "", " ".join([ "'region' must be a non-empty string", "containing a valid country name", "(letters, whitespaces and hiphen only)" ]) ), validate_region_name(empty_region) ) self.assertTupleEqual( ( False, "timor-leste123456", " ".join([ "'region' must be a non-empty string", "containing a valid country name", "(letters, whitespaces and hiphen only)" ]) ), validate_region_name(region_with_number) ) if __name__ == '__main__': unittest.main()
[ "unittest.main", "app.main.util.data_validation.validate_region_name" ]
[((1961, 1976), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1974, 1976), False, 'import unittest\n'), ((418, 461), 'app.main.util.data_validation.validate_region_name', 'validate_region_name', (['correct_region_simple'], {}), '(correct_region_simple)\n', (438, 461), False, 'from app.main.util.data_validation import validate_region_name\n'), ((560, 608), 'app.main.util.data_validation.validate_region_name', 'validate_region_name', (['correct_region_with_spaces'], {}), '(correct_region_with_spaces)\n', (580, 608), False, 'from app.main.util.data_validation import validate_region_name\n'), ((704, 752), 'app.main.util.data_validation.validate_region_name', 'validate_region_name', (['correct_region_with_hiphen'], {}), '(correct_region_with_hiphen)\n', (724, 752), False, 'from app.main.util.data_validation import validate_region_name\n'), ((1090, 1130), 'app.main.util.data_validation.validate_region_name', 'validate_region_name', (['no_region_informed'], {}), '(no_region_informed)\n', (1110, 1130), False, 'from app.main.util.data_validation import validate_region_name\n'), ((1478, 1512), 'app.main.util.data_validation.validate_region_name', 'validate_region_name', (['empty_region'], {}), '(empty_region)\n', (1498, 1512), False, 'from app.main.util.data_validation import validate_region_name\n'), ((1877, 1917), 'app.main.util.data_validation.validate_region_name', 'validate_region_name', (['region_with_number'], {}), '(region_with_number)\n', (1897, 1917), False, 'from app.main.util.data_validation import validate_region_name\n')]
""" TensorMONK :: layers :: Activations """ __all__ = ["Activations"] import torch import torch.nn as nn import torch.nn.functional as F def maxout(tensor: torch.Tensor) -> torch.Tensor: if not tensor.size(1) % 2 == 0: raise ValueError("MaxOut: tensor.size(1) must be divisible by n_splits" ": {}".format(tensor.size(1))) return torch.max(*tensor.split(tensor.size(1)//2, 1)) class Activations(nn.Module): r"""Activation functions. Additional activation functions (other than those available in pytorch) are :obj:`"hsigm"` & :obj:`"hswish"` (`"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244>`_), :obj:`"maxo"` (`"Maxout Networks" <https://arxiv.org/pdf/1302.4389>`_), :obj:`"mish"` (`"Mish: A Self Regularized Non-Monotonic Neural Activation Function" <https://arxiv.org/pdf/1908.08681v1>`_), :obj:`"squash"` (`"Dynamic Routing Between Capsules" <https://arxiv.org/abs/1710.09829>`_) and :obj:`"swish"` (`"SWISH: A Self-Gated Activation Function" <https://arxiv.org/pdf/1710.05941v1>`_). Args: tensor_size (tuple, required): Input tensor shape in BCHW (None/any integer >0, channels, height, width). activation (str, optional): The list of activation options are :obj:`"elu"`, :obj:`"gelu"`, :obj:`"hsigm"`, :obj:`"hswish"`, :obj:`"lklu"`, :obj:`"maxo"`, :obj:`"mish"`, :obj:`"prelu"`, :obj:`"relu"`, :obj:`"relu6"`, :obj:`"rmxo"`, :obj:`"selu"`, :obj:`"sigm"`, :obj:`"squash"`, :obj:`"swish"`, :obj:`"tanh"`. (default: :obj:`"relu"`) elu_alpha (float, optional): (default: :obj:`1.0`) lklu_negslope (float, optional): (default: :obj:`0.01`) .. code-block:: python import torch import tensormonk print(tensormonk.activations.Activations.METHODS) tensor_size = (None, 16, 4, 4) activation = "maxo" maxout = tensormonk.activations.Activations(tensor_size, activation) maxout(torch.randn(1, *tensor_size[1:])) tensor_size = (None, 16, 4) activation = "squash" squash = tensormonk.activations.Activations(tensor_size, activation) squash(torch.randn(1, *tensor_size[1:])) tensor_size = (None, 16) activation = "swish" swish = tensormonk.activations.Activations(tensor_size, activation) swish(torch.randn(1, *tensor_size[1:])) """ METHODS = ["elu", "gelu", "hsigm", "hswish", "lklu", "maxo", "mish", "prelu", "relu", "relu6", "rmxo", "selu", "sigm", "squash", "swish", "tanh"] def __init__(self, tensor_size: tuple, activation: str = "relu", **kwargs): super(Activations, self).__init__() if activation is not None: activation = activation.lower() self.t_size = tensor_size self.activation = activation self.function = None if activation not in self.METHODS: raise ValueError("activation: Invalid activation " + "/".join(self.METHODS) + ": {}".format(activation)) self.function = getattr(self, "_" + activation) if activation == "prelu": self.weight = nn.Parameter(torch.ones(1) * 0.1) if activation == "lklu": self.negslope = kwargs["lklu_negslope"] if "lklu_negslope" in \ kwargs.keys() else 0.01 if activation == "elu": self.alpha = kwargs["elu_alpha"] if "elu_alpha" in \ kwargs.keys() else 1.0 self.tensor_size = tensor_size if activation in ("maxo", "rmxo"): t_size = list(tensor_size) t_size[1] = t_size[1] // 2 self.tensor_size = tuple(t_size) def forward(self, tensor: torch.Tensor) -> torch.Tensor: if self.function is None: return tensor return self.function(tensor) def _relu(self, tensor: torch.Tensor): return F.relu(tensor) def _relu6(self, tensor: torch.Tensor): return F.relu6(tensor) def _lklu(self, tensor: torch.Tensor): return F.leaky_relu(tensor, self.negslope) def _elu(self, tensor: torch.Tensor): return F.elu(tensor, self.alpha) def _gelu(self, tensor: torch.Tensor): return F.gelu(tensor) def _prelu(self, tensor: torch.Tensor): return F.prelu(tensor, self.weight) def _selu(self, tensor: torch.Tensor): return F.selu(tensor) def _tanh(self, tensor: torch.Tensor): return torch.tanh(tensor) def _sigm(self, tensor: torch.Tensor): return torch.sigmoid(tensor) def _maxo(self, tensor: torch.Tensor): if not tensor.size(1) % 2 == 0: raise ValueError("MaxOut: tensor.size(1) must be divisible by 2" ": {}".format(tensor.size(1))) return torch.max(*tensor.split(tensor.size(1)//2, 1)) def _rmxo(self, tensor: torch.Tensor): return self._maxo(F.relu(tensor)) def _swish(self, tensor: torch.Tensor): return tensor * torch.sigmoid(tensor) def _mish(self, tensor: torch.Tensor): return tensor * F.softplus(tensor).tanh() def _squash(self, tensor: torch.Tensor): if not tensor.dim() == 3: raise ValueError("Squash requires 3D tensors: {}".format( tensor.dim())) sum_squares = (tensor ** 2).sum(2, True) return (sum_squares/(1+sum_squares)) * tensor / sum_squares.pow(0.5) def _hsigm(self, tensor: torch.Tensor): return F.relu6(tensor + 3) / 6 def _hswish(self, tensor: torch.Tensor): return self._hsigm(tensor) * tensor def __repr__(self): return self.activation @staticmethod def available() -> list: return Activations.METHODS def flops(self) -> int: import numpy as np flops = 0 numel = np.prod(self.t_size[1:]) if self.activation == "elu": # max(0, x) + min(0, alpha*(exp(x)-1)) flops = numel * 5 elif self.activation in ("lklu", "prelu", "sigm"): flops = numel * 3 elif self.activation == "maxo": # torch.max(*x.split(x.size(1)//2, 1)) flops = numel / 2 elif self.activation == "mish": # x * tanh(ln(1 + e^x)) flops = numel * 5 elif self.activation == "relu": # max(0, x) flops = numel elif self.activation == "relu6": # min(6, max(0, x)) flops = numel * 2 elif self.activation == "rmxo": # maxo(relu(x)) flops = int(numel * 1.5) elif self.activation == "squash": # sum_squares = (tensor**2).sum(2, True) # (sum_squares/(1+sum_squares)) * tensor / sum_squares.pow(0.5) flops = numel * 4 + self.t_size[1] * 2 elif self.activation == "swish": # x * sigm(x) flops = numel * 4 elif self.activation == "tanh": # (exp(x) - exp(-x)) / (exp(x) + exp(-x)) flops = numel * 9 elif self.activation == "hsigm": # min(6, max(0, x + 3)) / 6 flops = numel * 4 elif self.activation == "hswish": # x * min(6, max(0, x + 3)) / 6 flops = numel * 8 return flops
[ "torch.ones", "torch.nn.functional.selu", "torch.nn.functional.prelu", "torch.nn.functional.relu6", "torch.nn.functional.gelu", "torch.sigmoid", "torch.nn.functional.leaky_relu", "torch.nn.functional.relu", "torch.nn.functional.elu", "torch.nn.functional.softplus", "numpy.prod", "torch.tanh" ]
[((4037, 4051), 'torch.nn.functional.relu', 'F.relu', (['tensor'], {}), '(tensor)\n', (4043, 4051), True, 'import torch.nn.functional as F\n'), ((4112, 4127), 'torch.nn.functional.relu6', 'F.relu6', (['tensor'], {}), '(tensor)\n', (4119, 4127), True, 'import torch.nn.functional as F\n'), ((4187, 4222), 'torch.nn.functional.leaky_relu', 'F.leaky_relu', (['tensor', 'self.negslope'], {}), '(tensor, self.negslope)\n', (4199, 4222), True, 'import torch.nn.functional as F\n'), ((4281, 4306), 'torch.nn.functional.elu', 'F.elu', (['tensor', 'self.alpha'], {}), '(tensor, self.alpha)\n', (4286, 4306), True, 'import torch.nn.functional as F\n'), ((4366, 4380), 'torch.nn.functional.gelu', 'F.gelu', (['tensor'], {}), '(tensor)\n', (4372, 4380), True, 'import torch.nn.functional as F\n'), ((4441, 4469), 'torch.nn.functional.prelu', 'F.prelu', (['tensor', 'self.weight'], {}), '(tensor, self.weight)\n', (4448, 4469), True, 'import torch.nn.functional as F\n'), ((4529, 4543), 'torch.nn.functional.selu', 'F.selu', (['tensor'], {}), '(tensor)\n', (4535, 4543), True, 'import torch.nn.functional as F\n'), ((4603, 4621), 'torch.tanh', 'torch.tanh', (['tensor'], {}), '(tensor)\n', (4613, 4621), False, 'import torch\n'), ((4681, 4702), 'torch.sigmoid', 'torch.sigmoid', (['tensor'], {}), '(tensor)\n', (4694, 4702), False, 'import torch\n'), ((5967, 5991), 'numpy.prod', 'np.prod', (['self.t_size[1:]'], {}), '(self.t_size[1:])\n', (5974, 5991), True, 'import numpy as np\n'), ((5056, 5070), 'torch.nn.functional.relu', 'F.relu', (['tensor'], {}), '(tensor)\n', (5062, 5070), True, 'import torch.nn.functional as F\n'), ((5141, 5162), 'torch.sigmoid', 'torch.sigmoid', (['tensor'], {}), '(tensor)\n', (5154, 5162), False, 'import torch\n'), ((5624, 5643), 'torch.nn.functional.relu6', 'F.relu6', (['(tensor + 3)'], {}), '(tensor + 3)\n', (5631, 5643), True, 'import torch.nn.functional as F\n'), ((3307, 3320), 'torch.ones', 'torch.ones', (['(1)'], {}), '(1)\n', (3317, 3320), False, 'import torch\n'), ((5231, 5249), 'torch.nn.functional.softplus', 'F.softplus', (['tensor'], {}), '(tensor)\n', (5241, 5249), True, 'import torch.nn.functional as F\n')]
__author__ = 'luchenhua' EtoF = {'bread': 'du pain', 'wine': 'du vin', 'eats': 'mange', 'drinks': 'bois', 'likes': 'aime', 1: 'un', '6.00': '6.00'} print(EtoF) print(EtoF.keys()) print(EtoF.keys) del EtoF[1] print(EtoF) def translateWord(word, dictionary): if word in dictionary: return dictionary[word] else: return word def translate(sentence): translation = '' word = '' for e in sentence: if e != ' ': word = word + e else: translation = translation + ' ' + translateWord(word, EtoF) word = '' return translation[1:] + ' ' + translateWord(word, EtoF) print(translate('John eats bread')) print(translate('Steve drinks wine')) print(translate('John likes 6.00')) def simpleExp(b, n): if n == 0: return 1 else: return b * simpleExp(b, n - 1) print(simpleExp(2, 10)) def tower(n, f, t, s): if n == 1: print('Move from ' + f + ' to ' + t) else: tower(n - 1, f, s, t) tower(1, f, t, s) tower(n - 1, s, t, f) print(tower(5, 'a', 'b', 'c')) def toChars(s): import string s = string.lower(s) ans = '' for c in s: if c in string.lowercase: ans = ans + c return ans def isPal(s): if len(s) <= 1: return True else: return s[0] == s[-1] and isPal(s[1: -1]) def isPalindraw(s): return isPal(toChars(s)) print(isPalindraw('Guttag')) def isPalPrint(s, indent): if len(s) <= 1: print(indent + 'current: ' + s) return True else: print(indent + 'current: ' + s) return s[0] == s[-1] and isPalPrint(s[1: -1], (indent + ' ')) def isPalindrawPrint(s): return isPalPrint(toChars(s), ' ') print(isPalindrawPrint('Guttag')) def fib(x): assert type(x) == int and x >= 0 if x == 0 or x == 1: return 1 else: return fib(x - 1) + fib(x - 2) print(fib(2)) print(fib(3)) print(fib(4)) print(fib(5))
[ "string.lower" ]
[((1161, 1176), 'string.lower', 'string.lower', (['s'], {}), '(s)\n', (1173, 1176), False, 'import string\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import os class WideResNet: def __init__(self, nk, input_shape, num_classes, weight_decay, keep_prob, data_format='channels_last'): assert len(nk) == 2 assert (nk[0] - 1) % 3 == 0 self.N = (nk[0] - 1) // 3 self.k = nk[1] self.input_shape = input_shape self.num_classes = num_classes self.weight_decay = weight_decay self.prob = 1. - keep_prob assert data_format in ['channels_first', 'channels_last'] self.data_format = data_format self.global_step = tf.train.get_or_create_global_step() self.is_training = True self._define_inputs() self._build_graph() self._init_session() def _define_inputs(self): shape = [None] shape.extend(self.input_shape) self.images = tf.placeholder(dtype=tf.float32, shape=shape, name='images') self.labels = tf.placeholder(dtype=tf.int32, shape=[None, self.num_classes], name='labels') self.lr = tf.placeholder(dtype=tf.float32, shape=[], name='lr') def _build_graph(self): with tf.variable_scope('before_split'): conv1 = self._conv_bn_activation( bottom=self.images, filters=16, kernel_size=3, strides=1, ) with tf.variable_scope('split'): residual_block = conv1 for i in range(self.N): residual_block = self._residual_block(residual_block, 16*self.k, 1, 'group_conv2/conv'+str(i+1)) for i in range(self.N): residual_block = self._residual_block(residual_block, 32*self.k, 2, 'group_conv3/conv'+str(i+1)) for i in range(self.N): residual_block = self._residual_block(residual_block, 64*self.k, 2, 'group_conv4/conv'+str(i+1)) with tf.variable_scope('after_spliting'): bn = self._bn(residual_block) relu = tf.nn.relu(bn) with tf.variable_scope('group_avg_pool'): axes = [1, 2] if self.data_format == 'channels_last' else [2, 3] global_pool = tf.reduce_mean(relu, axis=axes, keepdims=False, name='global_pool') final_dense = tf.layers.dense(global_pool, self.num_classes, name='final_dense') with tf.variable_scope('optimizer'): self.logit = tf.nn.softmax(final_dense, name='logit') self.classifer_loss = tf.losses.softmax_cross_entropy(self.labels, final_dense, label_smoothing=0.1, reduction=tf.losses.Reduction.MEAN) self.l2_loss = self.weight_decay * tf.add_n( [tf.nn.l2_loss(var) for var in tf.trainable_variables()] ) total_loss = self.classifer_loss + self.l2_loss lossavg = tf.train.ExponentialMovingAverage(0.9, name='loss_moveavg') lossavg_op = lossavg.apply([total_loss]) with tf.control_dependencies([lossavg_op]): self.total_loss = tf.identity(total_loss) var_list = tf.trainable_variables() varavg = tf.train.ExponentialMovingAverage(0.9, name='var_moveavg') varavg_op = varavg.apply(var_list) optimizer = tf.train.MomentumOptimizer(self.lr, momentum=0.9) train_op = optimizer.minimize(self.total_loss, global_step=self.global_step) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) self.train_op = tf.group([update_ops, lossavg_op, varavg_op, train_op]) self.accuracy = tf.reduce_mean( tf.cast(tf.equal(tf.argmax(final_dense, 1), tf.argmax(self.labels, 1)), tf.float32), name='accuracy' ) def _init_session(self): self.sess = tf.InteractiveSession() self.sess.run(tf.global_variables_initializer()) self.saver = tf.train.Saver() self.best_saver = tf.train.Saver() def train_one_batch(self, images, labels, lr, sess=None): self.is_training = True if sess is None: sess_ = self.sess else: sess_ = sess _, loss, acc = sess_.run([self.train_op, self.total_loss, self.accuracy], feed_dict={ self.images: images, self.labels: labels, self.lr: lr }) return loss, acc def validate_one_batch(self, images, labels, sess=None): self.is_training = False if sess is None: sess_ = self.sess else: sess_ = sess logit, acc = sess_.run([self.logit, self.accuracy], feed_dict={ self.images: images, self.labels: labels, self.lr: 0. }) return logit, acc def test_one_batch(self, images, sess=None): self.is_training = False if sess is None: sess_ = self.sess else: sess_ = sess logit = sess_.run([self.logit], feed_dict={ self.images: images, self.lr: 0. }) return logit def save_weight(self, mode, path, sess=None): assert(mode in ['latest', 'best']) if sess is None: sess_ = self.sess else: sess_ = sess saver = self.saver if mode == 'latest' else self.best_saver saver.save(sess_, path, global_step=self.global_step) print('save', mode, 'model in', path, 'successfully') def load_weight(self, mode, path, sess=None): assert(mode in ['latest', 'best']) if sess is None: sess_ = self.sess else: sess_ = sess saver = self.saver if mode == 'latest' else self.best_saver ckpt = tf.train.get_checkpoint_state(path) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess_, path) print('load', mode, 'model in', path, 'successfully') else: raise FileNotFoundError('Not Found Model File!') def _bn(self, bottom): bn = tf.layers.batch_normalization( inputs=bottom, axis=3 if self.data_format == 'channels_last' else 1, training=self.is_training ) return bn def _conv_bn_activation(self, bottom, filters, kernel_size, strides, activation=tf.nn.relu): conv = tf.layers.conv2d( inputs=bottom, filters=filters, kernel_size=kernel_size, strides=strides, padding='same', data_format=self.data_format, kernel_initializer=tf.contrib.layers.variance_scaling_initializer() ) bn = self._bn(conv) if activation is not None: return activation(bn) else: return bn def _bn_activation_conv(self, bottom, filters, kernel_size, strides, activation=tf.nn.relu): bn = self._bn(bottom) if activation is not None: bn = activation(bn) conv = tf.layers.conv2d( inputs=bn, filters=filters, kernel_size=kernel_size, strides=strides, padding='same', data_format=self.data_format, kernel_initializer=tf.contrib.layers.variance_scaling_initializer() ) return conv def _residual_block(self, bottom, filters, strides, scope): with tf.variable_scope(scope): with tf.variable_scope('conv_branch'): conv = self._bn_activation_conv(bottom, filters, 3, strides) dropout = self._dropout(conv, 'dropout') conv = self._bn_activation_conv(dropout, filters, 3, 1) with tf.variable_scope('identity_branch'): if strides != 1: shutcut = self._bn_activation_conv(bottom, filters, 1, strides) else: index = 3 if self.data_format == 'channels_last' else 1 if tf.shape(bottom)[index] != filters: shutcut = self._bn_activation_conv(bottom, filters, 1, strides) else: shutcut = bottom return conv + shutcut def _max_pooling(self, bottom, pool_size, strides, name): return tf.layers.max_pooling2d( inputs=bottom, pool_size=pool_size, strides=strides, padding='same', data_format=self.data_format, name=name ) def _avg_pooling(self, bottom, pool_size, strides, name): return tf.layers.average_pooling2d( inputs=bottom, pool_size=pool_size, strides=strides, padding='same', data_format=self.data_format, name=name ) def _dropout(self, bottom, name): return tf.layers.dropout( inputs=bottom, rate=self.prob, training=self.is_training, name=name )
[ "tensorflow.trainable_variables", "tensorflow.get_collection", "tensorflow.identity", "tensorflow.layers.max_pooling2d", "tensorflow.InteractiveSession", "tensorflow.layers.batch_normalization", "tensorflow.nn.softmax", "tensorflow.train.ExponentialMovingAverage", "tensorflow.nn.relu", "tensorflow.train.get_or_create_global_step", "tensorflow.variable_scope", "tensorflow.placeholder", "tensorflow.train.get_checkpoint_state", "tensorflow.control_dependencies", "tensorflow.train.Saver", "tensorflow.global_variables_initializer", "tensorflow.layers.dropout", "tensorflow.reduce_mean", "tensorflow.layers.average_pooling2d", "tensorflow.group", "tensorflow.train.MomentumOptimizer", "tensorflow.contrib.layers.variance_scaling_initializer", "tensorflow.argmax", "tensorflow.layers.dense", "tensorflow.shape", "tensorflow.nn.l2_loss", "tensorflow.losses.softmax_cross_entropy" ]
[((680, 716), 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), '()\n', (714, 716), True, 'import tensorflow as tf\n'), ((952, 1012), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': 'shape', 'name': '"""images"""'}), "(dtype=tf.float32, shape=shape, name='images')\n", (966, 1012), True, 'import tensorflow as tf\n'), ((1035, 1112), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None, self.num_classes]', 'name': '"""labels"""'}), "(dtype=tf.int32, shape=[None, self.num_classes], name='labels')\n", (1049, 1112), True, 'import tensorflow as tf\n'), ((1131, 1184), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[]', 'name': '"""lr"""'}), "(dtype=tf.float32, shape=[], name='lr')\n", (1145, 1184), True, 'import tensorflow as tf\n'), ((3839, 3862), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (3860, 3862), True, 'import tensorflow as tf\n'), ((3941, 3957), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (3955, 3957), True, 'import tensorflow as tf\n'), ((3984, 4000), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (3998, 4000), True, 'import tensorflow as tf\n'), ((6075, 6110), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['path'], {}), '(path)\n', (6104, 6110), True, 'import tensorflow as tf\n'), ((6380, 6509), 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', ([], {'inputs': 'bottom', 'axis': "(3 if self.data_format == 'channels_last' else 1)", 'training': 'self.is_training'}), "(inputs=bottom, axis=3 if self.data_format ==\n 'channels_last' else 1, training=self.is_training)\n", (6409, 6509), True, 'import tensorflow as tf\n'), ((8600, 8737), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', ([], {'inputs': 'bottom', 'pool_size': 'pool_size', 'strides': 'strides', 'padding': '"""same"""', 'data_format': 'self.data_format', 'name': 'name'}), "(inputs=bottom, pool_size=pool_size, strides=strides,\n padding='same', data_format=self.data_format, name=name)\n", (8623, 8737), True, 'import tensorflow as tf\n'), ((8894, 9036), 'tensorflow.layers.average_pooling2d', 'tf.layers.average_pooling2d', ([], {'inputs': 'bottom', 'pool_size': 'pool_size', 'strides': 'strides', 'padding': '"""same"""', 'data_format': 'self.data_format', 'name': 'name'}), "(inputs=bottom, pool_size=pool_size, strides=\n strides, padding='same', data_format=self.data_format, name=name)\n", (8921, 9036), True, 'import tensorflow as tf\n'), ((9168, 9258), 'tensorflow.layers.dropout', 'tf.layers.dropout', ([], {'inputs': 'bottom', 'rate': 'self.prob', 'training': 'self.is_training', 'name': 'name'}), '(inputs=bottom, rate=self.prob, training=self.is_training,\n name=name)\n', (9185, 9258), True, 'import tensorflow as tf\n'), ((1227, 1260), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""before_split"""'], {}), "('before_split')\n", (1244, 1260), True, 'import tensorflow as tf\n'), ((1461, 1487), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""split"""'], {}), "('split')\n", (1478, 1487), True, 'import tensorflow as tf\n'), ((1984, 2019), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""after_spliting"""'], {}), "('after_spliting')\n", (2001, 2019), True, 'import tensorflow as tf\n'), ((2082, 2096), 'tensorflow.nn.relu', 'tf.nn.relu', (['bn'], {}), '(bn)\n', (2092, 2096), True, 'import tensorflow as tf\n'), ((2110, 2145), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""group_avg_pool"""'], {}), "('group_avg_pool')\n", (2127, 2145), True, 'import tensorflow as tf\n'), ((2250, 2317), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['relu'], {'axis': 'axes', 'keepdims': '(False)', 'name': '"""global_pool"""'}), "(relu, axis=axes, keepdims=False, name='global_pool')\n", (2264, 2317), True, 'import tensorflow as tf\n'), ((2344, 2410), 'tensorflow.layers.dense', 'tf.layers.dense', (['global_pool', 'self.num_classes'], {'name': '"""final_dense"""'}), "(global_pool, self.num_classes, name='final_dense')\n", (2359, 2410), True, 'import tensorflow as tf\n'), ((2424, 2454), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""optimizer"""'], {}), "('optimizer')\n", (2441, 2454), True, 'import tensorflow as tf\n'), ((2481, 2521), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['final_dense'], {'name': '"""logit"""'}), "(final_dense, name='logit')\n", (2494, 2521), True, 'import tensorflow as tf\n'), ((2556, 2675), 'tensorflow.losses.softmax_cross_entropy', 'tf.losses.softmax_cross_entropy', (['self.labels', 'final_dense'], {'label_smoothing': '(0.1)', 'reduction': 'tf.losses.Reduction.MEAN'}), '(self.labels, final_dense, label_smoothing=\n 0.1, reduction=tf.losses.Reduction.MEAN)\n', (2587, 2675), True, 'import tensorflow as tf\n'), ((2897, 2956), 'tensorflow.train.ExponentialMovingAverage', 'tf.train.ExponentialMovingAverage', (['(0.9)'], {'name': '"""loss_moveavg"""'}), "(0.9, name='loss_moveavg')\n", (2930, 2956), True, 'import tensorflow as tf\n'), ((3147, 3171), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (3169, 3171), True, 'import tensorflow as tf\n'), ((3193, 3251), 'tensorflow.train.ExponentialMovingAverage', 'tf.train.ExponentialMovingAverage', (['(0.9)'], {'name': '"""var_moveavg"""'}), "(0.9, name='var_moveavg')\n", (3226, 3251), True, 'import tensorflow as tf\n'), ((3323, 3372), 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', (['self.lr'], {'momentum': '(0.9)'}), '(self.lr, momentum=0.9)\n', (3349, 3372), True, 'import tensorflow as tf\n'), ((3487, 3529), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), '(tf.GraphKeys.UPDATE_OPS)\n', (3504, 3529), True, 'import tensorflow as tf\n'), ((3558, 3613), 'tensorflow.group', 'tf.group', (['[update_ops, lossavg_op, varavg_op, train_op]'], {}), '([update_ops, lossavg_op, varavg_op, train_op])\n', (3566, 3613), True, 'import tensorflow as tf\n'), ((3885, 3918), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (3916, 3918), True, 'import tensorflow as tf\n'), ((7720, 7744), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), '(scope)\n', (7737, 7744), True, 'import tensorflow as tf\n'), ((3027, 3064), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[lossavg_op]'], {}), '([lossavg_op])\n', (3050, 3064), True, 'import tensorflow as tf\n'), ((3100, 3123), 'tensorflow.identity', 'tf.identity', (['total_loss'], {}), '(total_loss)\n', (3111, 3123), True, 'import tensorflow as tf\n'), ((6924, 6972), 'tensorflow.contrib.layers.variance_scaling_initializer', 'tf.contrib.layers.variance_scaling_initializer', ([], {}), '()\n', (6970, 6972), True, 'import tensorflow as tf\n'), ((7563, 7611), 'tensorflow.contrib.layers.variance_scaling_initializer', 'tf.contrib.layers.variance_scaling_initializer', ([], {}), '()\n', (7609, 7611), True, 'import tensorflow as tf\n'), ((7763, 7795), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv_branch"""'], {}), "('conv_branch')\n", (7780, 7795), True, 'import tensorflow as tf\n'), ((8020, 8056), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""identity_branch"""'], {}), "('identity_branch')\n", (8037, 8056), True, 'import tensorflow as tf\n'), ((2745, 2763), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['var'], {}), '(var)\n', (2758, 2763), True, 'import tensorflow as tf\n'), ((3691, 3716), 'tensorflow.argmax', 'tf.argmax', (['final_dense', '(1)'], {}), '(final_dense, 1)\n', (3700, 3716), True, 'import tensorflow as tf\n'), ((3718, 3743), 'tensorflow.argmax', 'tf.argmax', (['self.labels', '(1)'], {}), '(self.labels, 1)\n', (3727, 3743), True, 'import tensorflow as tf\n'), ((2775, 2799), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (2797, 2799), True, 'import tensorflow as tf\n'), ((8296, 8312), 'tensorflow.shape', 'tf.shape', (['bottom'], {}), '(bottom)\n', (8304, 8312), True, 'import tensorflow as tf\n')]
# Not currently used; in case I ever turn this into a formal package import setuptools with open('README.md', 'r') as f: long_description = f.read() with open('requirements.txt') as f: install_requires = f.read().split('\n') install_requires = [x for x in install_requires if x != ''] setuptools.setup( name = 'fresh-slack', version = '0.1.0', author = ['<NAME>'], author_email = ['<EMAIL>'], description = 'Like destalinator, but active', long_description = long_description, url = 'https://github.com/anyutils/fresh-slack', packages = setuptools.find_packages(), python_requires = '>= 3.6.*', install_requires = install_requires, extras_require = { 'dev': [ 'pytest >= 5.4.3', 'pytest-cov >= 2.10.0', 'coverage >= 5.2', 'mypy >= 0.782' ] }, classifiers = [ 'Programming Language :: Python :: 3', 'Operating System :: OS Independent', 'License :: MIT' ], entry_points = { 'console_scripts': [ 'freshen-slack = fresh_slack.main:main' ] }, include_package_data = True )
[ "setuptools.find_packages" ]
[((584, 610), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (608, 610), False, 'import setuptools\n')]
#coding:utf-8 ################################# #Copyright(c) 2014 dtysky ################################# import G2R,os class MovieDefine(G2R.DefineSyntax): def Creat(self,Flag,US,FS,DictHash): DictHash=G2R.DefineSyntax.Creat(self,Flag,US,FS,DictHash) if DictHash[Flag]==G2R.DHash(US.Args[Flag]): return DictHash path=US.Args['pathmode']['ScriptPath']+'define/movie.rpy' elepath=US.Args['pathmode']['MoviePath'] Args=US.Args[Flag] so='' for ele in Args: if Args[ele]=='StopMoive': continue so+='define movie_'+os.path.splitext(Args[ele])[0]+' = ' so+="'"+elepath+Args[ele]+"'\n" FS.Open(path,'w') FS.Write(so) FS.Close() return DictHash
[ "G2R.DHash", "G2R.DefineSyntax.Creat", "os.path.splitext" ]
[((209, 261), 'G2R.DefineSyntax.Creat', 'G2R.DefineSyntax.Creat', (['self', 'Flag', 'US', 'FS', 'DictHash'], {}), '(self, Flag, US, FS, DictHash)\n', (231, 261), False, 'import G2R, os\n'), ((279, 303), 'G2R.DHash', 'G2R.DHash', (['US.Args[Flag]'], {}), '(US.Args[Flag])\n', (288, 303), False, 'import G2R, os\n'), ((541, 568), 'os.path.splitext', 'os.path.splitext', (['Args[ele]'], {}), '(Args[ele])\n', (557, 568), False, 'import G2R, os\n')]
from setuptools import setup import os from collections import OrderedDict try: long_description = "" with open('README.md', encoding='utf-8') as f: long_description = f.read() except: print('Curr dir:', os.getcwd()) long_description = open('../../README.md').read() setup(name='geograpy3', version='0.1.24', description='Extract countries, regions and cities from a URL or text', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/somnathrakshit/geograpy3', download_url='https://github.com/somnathrakshit/geograpy3', author='<NAME>', author_email='<EMAIL>', license='Apache', project_urls=OrderedDict( ( ("Documentation", "https://geograpy3.netlify.app"), ("Code", "https://github.com/somnathrakshit/geograpy3"), ("Issue tracker", "https://github.com/somnathrakshit/geograpy3/issues"), ) ), classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8' ], packages=['geograpy'], install_requires=[ 'numpy', 'nltk', 'newspaper3k', 'jellyfish', 'pycountry', 'pylodstorage' ], scripts=['geograpy/bin/geograpy-nltk'], package_data={ 'geograpy': ['data/*.csv'], }, zip_safe=False)
[ "collections.OrderedDict", "os.getcwd" ]
[((734, 937), 'collections.OrderedDict', 'OrderedDict', (["(('Documentation', 'https://geograpy3.netlify.app'), ('Code',\n 'https://github.com/somnathrakshit/geograpy3'), ('Issue tracker',\n 'https://github.com/somnathrakshit/geograpy3/issues'))"], {}), "((('Documentation', 'https://geograpy3.netlify.app'), ('Code',\n 'https://github.com/somnathrakshit/geograpy3'), ('Issue tracker',\n 'https://github.com/somnathrakshit/geograpy3/issues')))\n", (745, 937), False, 'from collections import OrderedDict\n'), ((227, 238), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (236, 238), False, 'import os\n')]
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse('user:create') TOKEN_URL = reverse('user:token') ME_URL = reverse('user:me') def create_user(**params): return get_user_model().objects.create_user(**params) class PublicUserApiTests(TestCase): """Test the users API (public)""" # ------------------------------------------------------ # CREATE USER tests # ------------------------------------------------------ def setUp(self): self.client = APIClient() def test_create_user_success(self): """Test that create user with valid payload is successful""" # Given payload = { 'email': '<EMAIL>', 'password': '<PASSWORD>', 'name': 'MOCK_NAME' } # When response = self.client.post(CREATE_USER_URL, payload) # Then a success response status is returned self.assertEqual(response.status_code, status.HTTP_201_CREATED) # Then the password is stored for the user user = get_user_model().objects.get(**response.data) self.assertTrue(user.check_password(payload['password'])) # Then the password is not returned in the response self.assertNotIn('password', response.data) def test_create_duplicate_user_fails(self): """Test creating a user that already exists fails""" # Given a user that already exists payload = { 'email': '<EMAIL>', 'password': '<PASSWORD>', 'name': 'MOCK_NAME' } create_user(**payload) # When response = self.client.post(CREATE_USER_URL, payload) # Then a bad request status is returned self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_create_user_with_password_too_short(self): """Test creating a user with a password that is not more than 5 characters""" # Given a create user request with a too-short password payload = { 'email': '<EMAIL>', 'password': '<PASSWORD>', 'name': 'MOCK_NAME' } # When response = self.client.post(CREATE_USER_URL, payload) # Then a bad request status is returned self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # Then the user is not created user_exists = get_user_model().objects.filter( email=payload['email'] ).exists() self.assertFalse(user_exists) # ------------------------------------------------------ # TOKEN tests # ------------------------------------------------------ def test_create_token_for_user(self): """Test that a token is created for the user""" # Given payload = {'email': '<EMAIL>', 'password': '<PASSWORD>'} create_user(**payload) # When response = self.client.post(TOKEN_URL, payload) # Then the response is successful self.assertEqual(response.status_code, status.HTTP_200_OK) # Then the response contains a token self.assertIn('token', response.data) def test_create_token_invalid_credentials(self): """Test that token is not created for invalid credentials""" # Given create_user(email='<EMAIL>', password='<PASSWORD>') payload = { 'email': '<EMAIL>', 'password': '<PASSWORD>' } # When response = self.client.post(TOKEN_URL, payload) # Then the response fails self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # Then the response does not contain a token self.assertNotIn('token', response.data) def test_create_token_no_user(self): """Test that token is not created for non-existent user""" # Given payload = {'email': '<EMAIL>', 'password': '<PASSWORD>'} # When response = self.client.post(TOKEN_URL, payload) # Then the response fails self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # Then the response does not contain a token self.assertNotIn('token', response.data) def test_create_token_missing_password(self): """Test that email and password are required""" # Given create_user(email='<EMAIL>', password='<PASSWORD>') payload = {'email': '<EMAIL>', 'password': ''} # When response = self.client.post(TOKEN_URL, payload) # Then the response fails self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # Then the response does not contain a token self.assertNotIn('token', response.data) # ------------------------------------------------------ # ME tests # ------------------------------------------------------ def test_get_me_unauthorised(self): """Test that authentication is required for users""" # Given no authentication token # When response = self.client.get(ME_URL) # Then self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) class PrivateUserApiTests(TestCase): """Test API requests that require authentication""" def setUp(self): self.user = create_user( email='<EMAIL>', password='<PASSWORD>', name='MOCK_NAME' ) self.client = APIClient() self.client.force_authenticate(user=self.user) def test_get_me_success(self): """Test get me for authenticated user""" response = self.client.get(ME_URL) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data, { 'name': self.user.name, 'email': self.user.email }, ) def test_post_me_not_allowed(self): """Test that POST is not allowed on me URL""" # Given / When response = self.client.post(ME_URL, {}) # Then self.assertEqual( response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_update_me_success(self): """Test updating the user profile for authenticated user""" # Given payload = { 'name': 'MOCK_NEW_NAME', 'password': '<PASSWORD>', } # When response = self.client.patch(ME_URL, payload) # Then request is successful self.assertEqual(response.status_code, status.HTTP_200_OK) # Then user is updated self.user.refresh_from_db() self.assertEqual(self.user.name, payload['name']) self.assertTrue(self.user.check_password(payload['password']))
[ "django.urls.reverse", "rest_framework.test.APIClient", "django.contrib.auth.get_user_model" ]
[((209, 231), 'django.urls.reverse', 'reverse', (['"""user:create"""'], {}), "('user:create')\n", (216, 231), False, 'from django.urls import reverse\n'), ((244, 265), 'django.urls.reverse', 'reverse', (['"""user:token"""'], {}), "('user:token')\n", (251, 265), False, 'from django.urls import reverse\n'), ((275, 293), 'django.urls.reverse', 'reverse', (['"""user:me"""'], {}), "('user:me')\n", (282, 293), False, 'from django.urls import reverse\n'), ((648, 659), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (657, 659), False, 'from rest_framework.test import APIClient\n'), ((5596, 5607), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (5605, 5607), False, 'from rest_framework.test import APIClient\n'), ((334, 350), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (348, 350), False, 'from django.contrib.auth import get_user_model\n'), ((1190, 1206), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (1204, 1206), False, 'from django.contrib.auth import get_user_model\n'), ((2549, 2565), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (2563, 2565), False, 'from django.contrib.auth import get_user_model\n')]
from pyowm import OWM import csv from datetime import datetime from os import environ, stat, path, access, R_OK, mkdir API_key = environ.get('API_key') if API_key is None: from creds import API_key fields = ["date", "windspeed", "humidity", "temperature", "status"] now = datetime.now() cities = ["Praha", "Plzen", "<NAME>", "<NAME>", "Usti nad Labem", "Liberec", "<NAME>", "Pardubice", "Jihlava", "Brno", "Olomouc", "Zlin", "Ostrava"] for city in cities: foldername = "data/" filename = foldername + city.lower()+".csv" if not path.isdir(foldername): mkdir(foldername) if not path.isfile(filename) and not access(filename, R_OK): pf = open(filename, "w") if stat(filename).st_size == 0: WriteData = open(filename, "a") WriteData.write("time, windspeed, humidity, temperature, pressure, rain, snow, clouds, status \n") WriteData.close() def getWeatherInfo(city: str): owm = OWM(API_key) mgr = owm.weather_manager() obs = mgr.weather_at_place(city+',CZ') w = obs.weather # Weather details wind = w.wind() humidity = w.humidity temp = w.temperature('celsius') status = w.status.lower() pressure = w.pressure rain = w.rain snow = w.snow clouds = w.clouds def checkFor(objct): if len(objct) == 0: return 0 else: return objct return [now.strftime("%Y.%m.%d"), wind['speed'], humidity, temp['temp'], pressure['press'], checkFor(rain), checkFor(snow), clouds, status] def createString(csvArr): fnlStr = "" for i,el in enumerate(csvArr): fnlStr += str(el) if i != len(csvArr) - 1: fnlStr += "," else: fnlStr += "\n" return fnlStr for city in cities: filename = "data/"+city.lower()+".csv" csvArrIn = getWeatherInfo(city) WriteData = open(filename, "a") WriteData.write(createString(csvArrIn)) WriteData.close()
[ "os.mkdir", "pyowm.OWM", "os.stat", "os.path.isdir", "os.environ.get", "os.path.isfile", "datetime.datetime.now", "os.access" ]
[((131, 153), 'os.environ.get', 'environ.get', (['"""API_key"""'], {}), "('API_key')\n", (142, 153), False, 'from os import environ, stat, path, access, R_OK, mkdir\n'), ((281, 295), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (293, 295), False, 'from datetime import datetime\n'), ((973, 985), 'pyowm.OWM', 'OWM', (['API_key'], {}), '(API_key)\n', (976, 985), False, 'from pyowm import OWM\n'), ((552, 574), 'os.path.isdir', 'path.isdir', (['foldername'], {}), '(foldername)\n', (562, 574), False, 'from os import environ, stat, path, access, R_OK, mkdir\n'), ((584, 601), 'os.mkdir', 'mkdir', (['foldername'], {}), '(foldername)\n', (589, 601), False, 'from os import environ, stat, path, access, R_OK, mkdir\n'), ((613, 634), 'os.path.isfile', 'path.isfile', (['filename'], {}), '(filename)\n', (624, 634), False, 'from os import environ, stat, path, access, R_OK, mkdir\n'), ((643, 665), 'os.access', 'access', (['filename', 'R_OK'], {}), '(filename, R_OK)\n', (649, 665), False, 'from os import environ, stat, path, access, R_OK, mkdir\n'), ((716, 730), 'os.stat', 'stat', (['filename'], {}), '(filename)\n', (720, 730), False, 'from os import environ, stat, path, access, R_OK, mkdir\n')]
from serialize import save_to, load_from from keras.models import Model class GenericModel(object): def __init__( self, inputs, outputs, loss, metrics, optimizer, loss_weights=None, sample_weight_mode=None): """ params: inputs: (tuple) outputs: (tuple) loss: (function) Optimization strategy. metrics: (tuple) optimizer: (optimizer) """ self.model = Model(inputs=inputs, outputs=outputs) self.inputs_shape = [ input._keras_shape[1:] for input in inputs ] self.outputs_shape = [ output._keras_shape[1:] for output in outputs ] self.loss= loss self.metrics = metrics self.optimizer = optimizer self.loss_weights = loss_weights self.sample_weight_mode = sample_weight_mode self.compile() def compile(self): if not self.sample_weight_mode is None: self.model.compile( optimizer=self.optimizer, sample_weight_mode=self.sample_weight_mode, loss=self.loss, metrics=self.metrics ) elif not self.loss_weights is None: self.model.compile( optimizer=self.optimizer, loss_weights=self.loss_weights, loss=self.loss, metrics=self.metrics ) else: self.model.compile( optimizer=self.optimizer, loss=self.loss, metrics=self.metrics ) def save_model(self, name=None): self.name = self.name if name is None else name save_to( self.model,self.name ) def load_model(self, name=None): self.name = self.name if name is None else name self.model = load_from( self.name ) self.compile() def fit( self, x_train, y_train, batch_size=1, epochs=1, cropped=False, **kwargs ): return self.model.fit( x_train, y_train, \ epochs=epochs, batch_size=batch_size, **kwargs) def evaluate( self, x_test, y_test, batch_size=1, cropped=False ): return self.model.evaluate(x_test, y_test, batch_size=batch_size ) def predict( self, x, batch_size=1, verbose=0 ): return self.model.predict( x, batch_size=batch_size, verbose=verbose )
[ "serialize.save_to", "keras.models.Model", "serialize.load_from" ]
[((448, 485), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'outputs'}), '(inputs=inputs, outputs=outputs)\n', (453, 485), False, 'from keras.models import Model\n'), ((1617, 1647), 'serialize.save_to', 'save_to', (['self.model', 'self.name'], {}), '(self.model, self.name)\n', (1624, 1647), False, 'from serialize import save_to, load_from\n'), ((1764, 1784), 'serialize.load_from', 'load_from', (['self.name'], {}), '(self.name)\n', (1773, 1784), False, 'from serialize import save_to, load_from\n')]
from sedac_gpw_parser import population import numpy as np from matplotlib import pyplot as plt import matplotlib.colors as colors import os file_lons = np.arange(-180, 180, 40) file_lats = np.arange(90, -20, -50) DATA_FOLDER = os.path.expanduser("~") + "/.srtm30/" def get_population_data(country_id): pop = population.Population(country_id=country_id) pop.mask_invalid_data(below=0) data = pop.population_array() lat = pop.latitude_range() lon = pop.longitude_range() lonmin = lon.min() lonmax = lon.max() latmax = lat.max() latmin = lat.min() extent = (lonmin, lonmax, latmin, latmax) return data, extent def get_infiles(lonmin, lonmax, latmin, latmax): print(lonmin, lonmax, latmin, latmax) lonmask = (file_lons >= (lonmin - 40)) & (file_lons <= lonmax) latmask = (file_lats >= latmin) & (file_lats <= (latmax + 50)) valid_lons = file_lons[lonmask] valid_lats = file_lats[latmask] latmax = np.round(latmax + 1/120, 8) # Add 1/120 because topographic data is with respect to UPPER LEFT corner latmin = np.round(latmin + 1/120, 8) # Add 1/120 because topographic data is with respect to UPPER LEFT corner lonmin = np.round(lonmin, 8) lonmax = np.round(lonmax, 8) n_lat = int(np.round((latmax - latmin) * 120) + 1) n_lon = int(np.round((lonmax - lonmin) * 120) + 1) full_data = np.zeros((n_lat, n_lon)) lat_offset = 0 for valid_lat in valid_lats: #print(valid_lat, end="\r") file_lat_range = np.round(np.arange(valid_lat, valid_lat-50, -1/120), 8) valid_file_lat_range = (file_lat_range <= latmax) & (file_lat_range >= latmin) n_row = valid_file_lat_range.sum() lon_offset = 0 for valid_lon in valid_lons: file_lon_range = np.round(np.arange(valid_lon, valid_lon+40, +1/120), 8) valid_file_lon_range = (file_lon_range <= lonmax) & (file_lon_range >= lonmin) n_col = valid_file_lon_range.sum() if valid_lon < 0: lon_pref = "W" else: lon_pref = "E" if valid_lat < 0: lat_pref = "S" else: lat_pref = "N" infile = lon_pref + str(abs(valid_lon)).zfill(3) + lat_pref + str(abs(valid_lat)).zfill(2) + ".DEM" with open(DATA_FOLDER+infile) as infile: data = np.fromfile(infile, np.dtype('>i2')).reshape(6000, 4800) print(valid_lat, valid_lon, "cutting data") data = data[valid_file_lat_range] data = data[:, valid_file_lon_range] print("storing data") full_data[lat_offset:lat_offset+n_row,lon_offset:lon_offset+n_col]=data lon_offset += n_col del data lat_offset += n_row return full_data def truncate_colormap(cmap, minval=0.25, maxval=1.0, n=100): new_cmap = colors.LinearSegmentedColormap.from_list( 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, n))) return new_cmap def get_topomap(): colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 2)) colors_land = plt.cm.terrain(np.linspace(0.25, 1, 256)) all_colors = np.vstack((colors_undersea, colors_land)) terrain_map = colors.LinearSegmentedColormap.from_list('terrain_map', all_colors) terrain_map = truncate_colormap(cmap=plt.get_cmap('terrain')) terrain_map.set_under("#254DB3") terrain_map.set_bad("0.5") return terrain_map def main(country_id, plot=True): pop, extent = get_population_data(country_id=country_id) lonmin, lonmax, latmin, latmax = extent print("Getting topography data from disk...") topo_data = get_infiles(lonmin, lonmax, latmin, latmax) print("Removing empty cols") contains_values = [] for col_id in range(pop.shape[1]): print(col_id, pop.shape[1], end="\r") if np.isfinite(pop[:, col_id]).any(): contains_values.append(col_id) print(len(contains_values), pop.shape) pop = pop[:, contains_values] topo_data = topo_data[:, contains_values] print("Removing empty rows") contains_values = [] for row_id in range(pop.shape[0]): print(row_id, pop.shape[1], end="\r") if np.isfinite(pop[row_id]).any(): contains_values.append(row_id) print(len(contains_values), pop.shape) pop = pop[contains_values] topo_data = topo_data[contains_values] print("setting invalid values...") #for i, _pop in enumerate(pop): # print(i, len(pop), end="\r") topo_data[np.isnan(pop)] = np.nan print("Total population:", np.nansum(pop)) if plot: f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 9)) terrain_map = get_topomap() ax1.imshow(topo_data, vmin=0, vmax=4000, cmap=terrain_map, rasterized=True) ax2.imshow(pop, vmin=0, vmax=50) plt.savefig("pop_topo.png") return pop, topo_data def distribution(pop, topo, return_total=False, plot=True, resolution=500, max_elevation=20, add_noise=True): mask = np.isfinite(topo) topo = topo[mask] pop = pop[mask] # Make sure that some artifacts where elevation is negative are set to zero topo[topo <= 0] = 0 #topo[topo == 0] += 0.5 * np.random.random((topo == 0).sum()) #topo[topo >= 0.5] += np.random.random((topo >= 0.5).sum()) - 0.5 if add_noise: topo+= np.random.random(len(topo)) valid_topo = np.linspace(0, max_elevation, resolution) results = np.zeros_like(valid_topo, dtype=float) #total_population = pop.total_population() for i, elevation in enumerate(valid_topo): mask = topo <= elevation #mask = topo == elevation results[i] = pop[mask].sum() total_population = np.sum(pop) results /= total_population #results = results.cumsum() / total_population if plot: f = plt.figure() #plt.semilogy() plt.plot(valid_topo, results) plt.xlabel("Elevation x [m above sea level]") plt.ylabel("Share of population living at or below x") plt.savefig("population_elevation.png") if return_total: return valid_topo, results, total_population else: return valid_topo, results if __name__ == "__main__": pop, topo = main(840, plot=True) distribution(pop, topo, plot=True)
[ "numpy.sum", "numpy.isnan", "matplotlib.pyplot.figure", "numpy.arange", "numpy.round", "matplotlib.colors.LinearSegmentedColormap.from_list", "numpy.zeros_like", "numpy.isfinite", "numpy.linspace", "matplotlib.pyplot.subplots", "numpy.nansum", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.ylabel", "numpy.vstack", "matplotlib.pyplot.plot", "numpy.dtype", "numpy.zeros", "matplotlib.pyplot.xlabel", "os.path.expanduser", "matplotlib.pyplot.savefig", "sedac_gpw_parser.population.Population" ]
[((154, 178), 'numpy.arange', 'np.arange', (['(-180)', '(180)', '(40)'], {}), '(-180, 180, 40)\n', (163, 178), True, 'import numpy as np\n'), ((191, 214), 'numpy.arange', 'np.arange', (['(90)', '(-20)', '(-50)'], {}), '(90, -20, -50)\n', (200, 214), True, 'import numpy as np\n'), ((229, 252), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (247, 252), False, 'import os\n'), ((320, 364), 'sedac_gpw_parser.population.Population', 'population.Population', ([], {'country_id': 'country_id'}), '(country_id=country_id)\n', (341, 364), False, 'from sedac_gpw_parser import population\n'), ((993, 1022), 'numpy.round', 'np.round', (['(latmax + 1 / 120)', '(8)'], {}), '(latmax + 1 / 120, 8)\n', (1001, 1022), True, 'import numpy as np\n'), ((1108, 1137), 'numpy.round', 'np.round', (['(latmin + 1 / 120)', '(8)'], {}), '(latmin + 1 / 120, 8)\n', (1116, 1137), True, 'import numpy as np\n'), ((1223, 1242), 'numpy.round', 'np.round', (['lonmin', '(8)'], {}), '(lonmin, 8)\n', (1231, 1242), True, 'import numpy as np\n'), ((1256, 1275), 'numpy.round', 'np.round', (['lonmax', '(8)'], {}), '(lonmax, 8)\n', (1264, 1275), True, 'import numpy as np\n'), ((1404, 1428), 'numpy.zeros', 'np.zeros', (['(n_lat, n_lon)'], {}), '((n_lat, n_lon))\n', (1412, 1428), True, 'import numpy as np\n'), ((3346, 3387), 'numpy.vstack', 'np.vstack', (['(colors_undersea, colors_land)'], {}), '((colors_undersea, colors_land))\n', (3355, 3387), True, 'import numpy as np\n'), ((3406, 3473), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'colors.LinearSegmentedColormap.from_list', (['"""terrain_map"""', 'all_colors'], {}), "('terrain_map', all_colors)\n", (3446, 3473), True, 'import matplotlib.colors as colors\n'), ((5255, 5272), 'numpy.isfinite', 'np.isfinite', (['topo'], {}), '(topo)\n', (5266, 5272), True, 'import numpy as np\n'), ((5637, 5678), 'numpy.linspace', 'np.linspace', (['(0)', 'max_elevation', 'resolution'], {}), '(0, max_elevation, resolution)\n', (5648, 5678), True, 'import numpy as np\n'), ((5693, 5731), 'numpy.zeros_like', 'np.zeros_like', (['valid_topo'], {'dtype': 'float'}), '(valid_topo, dtype=float)\n', (5706, 5731), True, 'import numpy as np\n'), ((5971, 5982), 'numpy.sum', 'np.sum', (['pop'], {}), '(pop)\n', (5977, 5982), True, 'import numpy as np\n'), ((3244, 3267), 'numpy.linspace', 'np.linspace', (['(0)', '(0.17)', '(2)'], {}), '(0, 0.17, 2)\n', (3255, 3267), True, 'import numpy as np\n'), ((3302, 3327), 'numpy.linspace', 'np.linspace', (['(0.25)', '(1)', '(256)'], {}), '(0.25, 1, 256)\n', (3313, 3327), True, 'import numpy as np\n'), ((4722, 4735), 'numpy.isnan', 'np.isnan', (['pop'], {}), '(pop)\n', (4730, 4735), True, 'import numpy as np\n'), ((4778, 4792), 'numpy.nansum', 'np.nansum', (['pop'], {}), '(pop)\n', (4787, 4792), True, 'import numpy as np\n'), ((4836, 4871), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(12, 9)'}), '(1, 2, figsize=(12, 9))\n', (4848, 4871), True, 'from matplotlib import pyplot as plt\n'), ((5059, 5086), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""pop_topo.png"""'], {}), "('pop_topo.png')\n", (5070, 5086), True, 'from matplotlib import pyplot as plt\n'), ((6093, 6105), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6103, 6105), True, 'from matplotlib import pyplot as plt\n'), ((6134, 6163), 'matplotlib.pyplot.plot', 'plt.plot', (['valid_topo', 'results'], {}), '(valid_topo, results)\n', (6142, 6163), True, 'from matplotlib import pyplot as plt\n'), ((6172, 6217), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Elevation x [m above sea level]"""'], {}), "('Elevation x [m above sea level]')\n", (6182, 6217), True, 'from matplotlib import pyplot as plt\n'), ((6226, 6280), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Share of population living at or below x"""'], {}), "('Share of population living at or below x')\n", (6236, 6280), True, 'from matplotlib import pyplot as plt\n'), ((6289, 6328), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""population_elevation.png"""'], {}), "('population_elevation.png')\n", (6300, 6328), True, 'from matplotlib import pyplot as plt\n'), ((1293, 1326), 'numpy.round', 'np.round', (['((latmax - latmin) * 120)'], {}), '((latmax - latmin) * 120)\n', (1301, 1326), True, 'import numpy as np\n'), ((1348, 1381), 'numpy.round', 'np.round', (['((lonmax - lonmin) * 120)'], {}), '((lonmax - lonmin) * 120)\n', (1356, 1381), True, 'import numpy as np\n'), ((1558, 1604), 'numpy.arange', 'np.arange', (['valid_lat', '(valid_lat - 50)', '(-1 / 120)'], {}), '(valid_lat, valid_lat - 50, -1 / 120)\n', (1567, 1604), True, 'import numpy as np\n'), ((3133, 3163), 'numpy.linspace', 'np.linspace', (['minval', 'maxval', 'n'], {}), '(minval, maxval, n)\n', (3144, 3163), True, 'import numpy as np\n'), ((3516, 3539), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""terrain"""'], {}), "('terrain')\n", (3528, 3539), True, 'from matplotlib import pyplot as plt\n'), ((1847, 1893), 'numpy.arange', 'np.arange', (['valid_lon', '(valid_lon + 40)', '(+1 / 120)'], {}), '(valid_lon, valid_lon + 40, +1 / 120)\n', (1856, 1893), True, 'import numpy as np\n'), ((4044, 4071), 'numpy.isfinite', 'np.isfinite', (['pop[:, col_id]'], {}), '(pop[:, col_id])\n', (4055, 4071), True, 'import numpy as np\n'), ((4401, 4425), 'numpy.isfinite', 'np.isfinite', (['pop[row_id]'], {}), '(pop[row_id])\n', (4412, 4425), True, 'import numpy as np\n'), ((2488, 2503), 'numpy.dtype', 'np.dtype', (['""">i2"""'], {}), "('>i2')\n", (2496, 2503), True, 'import numpy as np\n')]
from moderation_module.guild_logging.commands import guild_logging_control, send_delete_embed, send_edit_embed, \ send_joined_embed, send_remove_embed from moderation_module.storage import GuildLoggingConfig from alento_bot import StorageManager from discord.ext import commands import moderation_module.text import logging import discord logger = logging.getLogger("main_bot") # TODO: Update logging to latest standards, have feature parity of Sx4. class GuildLoggingCog(commands.Cog, name="Logging"): def __init__(self, storage: StorageManager): self.storage: StorageManager = storage self.storage.guilds.register_data_name("guild_logging_config", GuildLoggingConfig) @commands.has_permissions(administrator=True) @commands.command(name="guild_logging_control", aliases=["logging", ]) async def guild_logging_control(self, context: commands.Context, arg1=None, arg2=None): logging_config = self.storage.guilds.get(context.guild.id, "guild_logging_config") await guild_logging_control(logging_config, context, arg1, arg2) @guild_logging_control.error async def missing_permissions_error(self, context, error: Exception): if isinstance(error, commands.MissingPermissions): await context.send(moderation_module.text.MISSING_PERMISSIONS) else: await context.send(f"ERROR:\nType: {type(error)}\n{error}") raise error @commands.Cog.listener() async def on_message_delete(self, message: discord.Message): logging_config: GuildLoggingConfig = self.storage.guilds.get(message.guild.id, "guild_logging_config") if logging_config.toggled_on and logging_config.log_channel_id and \ message.channel.id not in logging_config.exempt_channels and \ (logging_config.log_bots or (not logging_config.log_bots and not message.author.bot)): await send_delete_embed(logging_config, message) @commands.Cog.listener() async def on_message_edit(self, before: discord.Message, after: discord.Message): logging_config: GuildLoggingConfig = self.storage.guilds.get(after.guild.id, "guild_logging_config") if logging_config.toggled_on and logging_config.log_channel_id and \ after.channel.id not in logging_config.exempt_channels and \ (logging_config.log_bots or (not logging_config.log_bots and not after.author.bot)) and \ before.content != after.content: await send_edit_embed(logging_config, before, after) @commands.Cog.listener() async def on_member_join(self, member: discord.Member): logging_config: GuildLoggingConfig = self.storage.guilds.get(member.guild.id, "guild_logging_config") if logging_config.toggled_on and logging_config.log_channel_id: await send_joined_embed(logging_config, member) @commands.Cog.listener() async def on_member_remove(self, member: discord.Member): logging_config: GuildLoggingConfig = self.storage.guilds.get(member.guild.id, "guild_logging_config") if logging_config.toggled_on and logging_config.log_channel_id: await send_remove_embed(logging_config, member)
[ "discord.ext.commands.command", "moderation_module.guild_logging.commands.send_remove_embed", "moderation_module.guild_logging.commands.guild_logging_control", "moderation_module.guild_logging.commands.send_joined_embed", "discord.ext.commands.has_permissions", "discord.ext.commands.Cog.listener", "moderation_module.guild_logging.commands.send_edit_embed", "moderation_module.guild_logging.commands.send_delete_embed", "logging.getLogger" ]
[((354, 383), 'logging.getLogger', 'logging.getLogger', (['"""main_bot"""'], {}), "('main_bot')\n", (371, 383), False, 'import logging\n'), ((706, 750), 'discord.ext.commands.has_permissions', 'commands.has_permissions', ([], {'administrator': '(True)'}), '(administrator=True)\n', (730, 750), False, 'from discord.ext import commands\n'), ((756, 823), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""guild_logging_control"""', 'aliases': "['logging']"}), "(name='guild_logging_control', aliases=['logging'])\n", (772, 823), False, 'from discord.ext import commands\n'), ((1440, 1463), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (1461, 1463), False, 'from discord.ext import commands\n'), ((1967, 1990), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (1988, 1990), False, 'from discord.ext import commands\n'), ((2566, 2589), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (2587, 2589), False, 'from discord.ext import commands\n'), ((2898, 2921), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (2919, 2921), False, 'from discord.ext import commands\n'), ((1023, 1081), 'moderation_module.guild_logging.commands.guild_logging_control', 'guild_logging_control', (['logging_config', 'context', 'arg1', 'arg2'], {}), '(logging_config, context, arg1, arg2)\n', (1044, 1081), False, 'from moderation_module.guild_logging.commands import guild_logging_control, send_delete_embed, send_edit_embed, send_joined_embed, send_remove_embed\n'), ((1918, 1960), 'moderation_module.guild_logging.commands.send_delete_embed', 'send_delete_embed', (['logging_config', 'message'], {}), '(logging_config, message)\n', (1935, 1960), False, 'from moderation_module.guild_logging.commands import guild_logging_control, send_delete_embed, send_edit_embed, send_joined_embed, send_remove_embed\n'), ((2513, 2559), 'moderation_module.guild_logging.commands.send_edit_embed', 'send_edit_embed', (['logging_config', 'before', 'after'], {}), '(logging_config, before, after)\n', (2528, 2559), False, 'from moderation_module.guild_logging.commands import guild_logging_control, send_delete_embed, send_edit_embed, send_joined_embed, send_remove_embed\n'), ((2850, 2891), 'moderation_module.guild_logging.commands.send_joined_embed', 'send_joined_embed', (['logging_config', 'member'], {}), '(logging_config, member)\n', (2867, 2891), False, 'from moderation_module.guild_logging.commands import guild_logging_control, send_delete_embed, send_edit_embed, send_joined_embed, send_remove_embed\n'), ((3184, 3225), 'moderation_module.guild_logging.commands.send_remove_embed', 'send_remove_embed', (['logging_config', 'member'], {}), '(logging_config, member)\n', (3201, 3225), False, 'from moderation_module.guild_logging.commands import guild_logging_control, send_delete_embed, send_edit_embed, send_joined_embed, send_remove_embed\n')]
import os import re from drkns.exception import MissingGenerationTemplateDirectoryException, \ MissingGenerationTemplateException, MultipleGenerationTemplateException _template_directory = '.drknsgeneration' _template_file_re = re.compile(r'^.*\.template\..*$') def get_generation_template_path(from_path: str) -> str: template_directory = os.path.join(from_path, _template_directory) if not os.path.exists(template_directory): error_message = template_directory + ' directory can not be found' raise MissingGenerationTemplateDirectoryException(error_message) contained_files = os.listdir(template_directory) matched_files = [] for contained_file in contained_files: pattern_match = \ _template_file_re.match(contained_file) if pattern_match is None: continue matched_files.append(contained_file) if len(matched_files) == 0: error_message = 'No template found in ' + template_directory raise MissingGenerationTemplateException(error_message) if len(matched_files) > 1: error_message = 'Multiple template found in ' + \ template_directory + ': ' + ', '.join(matched_files) MultipleGenerationTemplateException(error_message) return os.path.join(template_directory, matched_files.pop())
[ "drkns.exception.MissingGenerationTemplateException", "os.path.exists", "drkns.exception.MultipleGenerationTemplateException", "drkns.exception.MissingGenerationTemplateDirectoryException", "os.path.join", "os.listdir", "re.compile" ]
[((235, 269), 're.compile', 're.compile', (['"""^.*\\\\.template\\\\..*$"""'], {}), "('^.*\\\\.template\\\\..*$')\n", (245, 269), False, 'import re\n'), ((353, 397), 'os.path.join', 'os.path.join', (['from_path', '_template_directory'], {}), '(from_path, _template_directory)\n', (365, 397), False, 'import os\n'), ((616, 646), 'os.listdir', 'os.listdir', (['template_directory'], {}), '(template_directory)\n', (626, 646), False, 'import os\n'), ((409, 443), 'os.path.exists', 'os.path.exists', (['template_directory'], {}), '(template_directory)\n', (423, 443), False, 'import os\n'), ((534, 592), 'drkns.exception.MissingGenerationTemplateDirectoryException', 'MissingGenerationTemplateDirectoryException', (['error_message'], {}), '(error_message)\n', (577, 592), False, 'from drkns.exception import MissingGenerationTemplateDirectoryException, MissingGenerationTemplateException, MultipleGenerationTemplateException\n'), ((1009, 1058), 'drkns.exception.MissingGenerationTemplateException', 'MissingGenerationTemplateException', (['error_message'], {}), '(error_message)\n', (1043, 1058), False, 'from drkns.exception import MissingGenerationTemplateDirectoryException, MissingGenerationTemplateException, MultipleGenerationTemplateException\n'), ((1234, 1284), 'drkns.exception.MultipleGenerationTemplateException', 'MultipleGenerationTemplateException', (['error_message'], {}), '(error_message)\n', (1269, 1284), False, 'from drkns.exception import MissingGenerationTemplateDirectoryException, MissingGenerationTemplateException, MultipleGenerationTemplateException\n')]
from __future__ import division, print_function from typing import List, Tuple, Callable import numpy as np import scipy import matplotlib.pyplot as plt class Perceptron: def __init__(self, nb_features=2, max_iteration=10, margin=1e-4): ''' Args : nb_features : Number of features max_iteration : maximum iterations. You algorithm should terminate after this many iterations even if it is not converged margin is the min value, we use this instead of comparing with 0 in the algorithm ''' self.nb_features = nb_features self.w = [0 for i in range(0,nb_features+1)] self.margin = margin self.max_iteration = max_iteration def train(self, features: List[List[float]], labels: List[int]) -> bool: ''' Args : features : List of features. First element of each feature vector is 1 to account for bias labels : label of each feature [-1,1] Returns : True/ False : return True if the algorithm converges else False. ''' seq = [x for x in range(len(features))] threshold = self.margin / 2 converge = False scale = np.linalg.norm(features) for iteration in range(self.max_iteration): if converge: break converge = True np.random.shuffle(seq) for i in seq: pred = np.dot(self.w, features[i]) y = 0 if pred > threshold: y = 1 elif pred < -threshold: y = -1 if y != labels[i]: self.w = np.add(self.w, np.dot(labels[i], features[i])) converge = False self.w = self.w.tolist() return converge def reset(self): self.w = [0 for i in range(0,self.nb_features+1)] def predict(self, features: List[List[float]]) -> List[int]: ''' Args : features : List of features. First element of each feature vector is 1 to account for bias Returns : labels : List of integers of [-1,1] ''' return np.apply_along_axis(lambda x : 1 if np.dot(self.w, x) > 0 else -1, 1, features) def get_weights(self) -> List[float]: return self.w
[ "numpy.dot", "numpy.linalg.norm", "numpy.random.shuffle" ]
[((1280, 1304), 'numpy.linalg.norm', 'np.linalg.norm', (['features'], {}), '(features)\n', (1294, 1304), True, 'import numpy as np\n'), ((1444, 1466), 'numpy.random.shuffle', 'np.random.shuffle', (['seq'], {}), '(seq)\n', (1461, 1466), True, 'import numpy as np\n'), ((1516, 1543), 'numpy.dot', 'np.dot', (['self.w', 'features[i]'], {}), '(self.w, features[i])\n', (1522, 1543), True, 'import numpy as np\n'), ((1775, 1805), 'numpy.dot', 'np.dot', (['labels[i]', 'features[i]'], {}), '(labels[i], features[i])\n', (1781, 1805), True, 'import numpy as np\n'), ((2360, 2377), 'numpy.dot', 'np.dot', (['self.w', 'x'], {}), '(self.w, x)\n', (2366, 2377), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- #!/usr/bin/python3 """ """ # ============================================================================= # Imports # ============================================================================= import cv2 import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt # Matplot-Params # Change size from Plots plt.rcParams['font.size'] = 6 plt.rcParams['figure.dpi']= 100 plt.rcParams['lines.linewidth']= 1 # read img file image = cv2.imread("data/lena_std.tiff") # plot image plt.imshow(image) plt.show() image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image_rgb) plt.show() print(image_rgb[0, 0]) # RGB value at pixel (0,0) print(image_rgb[0, 0, 0]) # Red value (same pixel) # y=250:280, x=250:360 image_rgb[250:280, 250:360] = [255, 255, 255] plt.imshow(image_rgb) plt.show() # image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # bw plt.subplot(1, 2, 1) plt.imshow(image_bw) plt.subplot(1, 2, 2) plt.imshow(image_rgb) # gray plt.subplot(1, 2, 1) plt.imshow(image_gray, 'gray') plt.subplot(1, 2, 2) plt.imshow(image_rgb)
[ "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "cv2.cvtColor", "matplotlib.pyplot.imshow", "cv2.imread" ]
[((481, 513), 'cv2.imread', 'cv2.imread', (['"""data/lena_std.tiff"""'], {}), "('data/lena_std.tiff')\n", (491, 513), False, 'import cv2\n'), ((528, 545), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (538, 545), True, 'from matplotlib import pyplot as plt\n'), ((546, 556), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (554, 556), True, 'from matplotlib import pyplot as plt\n'), ((570, 608), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (582, 608), False, 'import cv2\n'), ((609, 630), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_rgb'], {}), '(image_rgb)\n', (619, 630), True, 'from matplotlib import pyplot as plt\n'), ((631, 641), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (639, 641), True, 'from matplotlib import pyplot as plt\n'), ((814, 835), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_rgb'], {}), '(image_rgb)\n', (824, 835), True, 'from matplotlib import pyplot as plt\n'), ((836, 846), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (844, 846), True, 'from matplotlib import pyplot as plt\n'), ((861, 899), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (873, 899), False, 'import cv2\n'), ((913, 952), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (925, 952), False, 'import cv2\n'), ((959, 979), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (970, 979), True, 'from matplotlib import pyplot as plt\n'), ((980, 1000), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_bw'], {}), '(image_bw)\n', (990, 1000), True, 'from matplotlib import pyplot as plt\n'), ((1001, 1021), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (1012, 1021), True, 'from matplotlib import pyplot as plt\n'), ((1022, 1043), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_rgb'], {}), '(image_rgb)\n', (1032, 1043), True, 'from matplotlib import pyplot as plt\n'), ((1052, 1072), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (1063, 1072), True, 'from matplotlib import pyplot as plt\n'), ((1073, 1103), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_gray', '"""gray"""'], {}), "(image_gray, 'gray')\n", (1083, 1103), True, 'from matplotlib import pyplot as plt\n'), ((1104, 1124), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (1115, 1124), True, 'from matplotlib import pyplot as plt\n'), ((1125, 1146), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_rgb'], {}), '(image_rgb)\n', (1135, 1146), True, 'from matplotlib import pyplot as plt\n')]
import numpy as np import os import time np.set_printoptions(threshold=np.inf) def input(fname): day_dir = os.path.realpath(__file__).split('/')[:-1] fname = os.path.join('/',*day_dir, fname) data = [] with open(fname) as f: for line in f: data.append(line.strip()) return data def count_ele(pairs): elem_count = {e: 0 for e in rules.values()} for pair in pairs: elem_count[pair[0][0]] += 0.5*pair[1] elem_count[pair[0][1]] += 0.5*pair[1] elem_count[seed[0]] += 0.5 elem_count[seed[-1]] += 0.5 return elem_count def do_steps(pairs, rules, n): for i in range(n): new_pairs = [] for pair in pairs: insertion = rules[pair[0]] new_pairs.extend([(pair[0][0]+insertion, pair[1]), (insertion+pair[0][1], pair[1])]) counts = {p: 0 for p in set(np.array(new_pairs)[:,0])} for n in new_pairs: counts[n[0]] += n[1] pairs = [(p, counts[p]) for p in counts] elem_count = count_ele(pairs) min_ele = min(elem_count, key=elem_count.get) max_ele = max(elem_count, key=elem_count.get) print(int(elem_count[max_ele] - elem_count[min_ele])) rules = input('input.txt') # rules = input('test-input.txt') seed = rules[0] rules = {d.split(' ')[0]: d.split(' ')[2] for d in rules[2:]} unique_pairs = set([seed[i]+seed[i+1] for i in range(len(seed)-1)]) pairs = [(p, list(unique_pairs).count(p)) for p in unique_pairs] # part 1 t0 = time.time() print('Part 1:') do_steps(pairs, rules, 10) print('Elapsed time:',time.time()-t0,' sec') # part 2 t0 = time.time() print('\nPart 2:') do_steps(pairs, rules, 40) print('Elapsed time:',time.time()-t0,' sec')
[ "numpy.set_printoptions", "os.path.realpath", "time.time", "numpy.array", "os.path.join" ]
[((42, 79), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (61, 79), True, 'import numpy as np\n'), ((1513, 1524), 'time.time', 'time.time', ([], {}), '()\n', (1522, 1524), False, 'import time\n'), ((1629, 1640), 'time.time', 'time.time', ([], {}), '()\n', (1638, 1640), False, 'import time\n'), ((168, 202), 'os.path.join', 'os.path.join', (['"""/"""', '*day_dir', 'fname'], {}), "('/', *day_dir, fname)\n", (180, 202), False, 'import os\n'), ((1591, 1602), 'time.time', 'time.time', ([], {}), '()\n', (1600, 1602), False, 'import time\n'), ((1709, 1720), 'time.time', 'time.time', ([], {}), '()\n', (1718, 1720), False, 'import time\n'), ((113, 139), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (129, 139), False, 'import os\n'), ((884, 903), 'numpy.array', 'np.array', (['new_pairs'], {}), '(new_pairs)\n', (892, 903), True, 'import numpy as np\n')]
# Copyright 2017-2021 The GPflow Contributors. 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. """ This module is deprecated, and is only provided for backwards compatibility. It will be removed in GPflow 2.3. """ from deprecated import deprecated from . import misc, traversal __all__ = [] def _create_module_redirects(m): for name in m.__all__: func = getattr(m, name) assert callable(func), "all names exported by misc and traversal should be functions" deprecated_func = deprecated( reason="The gpflow.utilities.utilities module is deprecated and will " f"be removed in GPflow 2.3; use gpflow.utilities.{name} instead." )(func) globals()[name] = deprecated_func __all__.append(name) _create_module_redirects(misc) _create_module_redirects(traversal) del _create_module_redirects, misc, traversal
[ "deprecated.deprecated" ]
[((1023, 1178), 'deprecated.deprecated', 'deprecated', ([], {'reason': 'f"""The gpflow.utilities.utilities module is deprecated and will be removed in GPflow 2.3; use gpflow.utilities.{name} instead."""'}), "(reason=\n f'The gpflow.utilities.utilities module is deprecated and will be removed in GPflow 2.3; use gpflow.utilities.{name} instead.'\n )\n", (1033, 1178), False, 'from deprecated import deprecated\n')]
"""Check Python docstrings validate as reStructuredText (RST). This is a plugin for the tool flake8 tool for checking Python soucre code. """ import logging import re import sys import textwrap import tokenize as tk from itertools import chain, dropwhile try: from StringIO import StringIO except ImportError: # Python 3.0 and later from io import StringIO from io import TextIOWrapper ##################################### # Start of backported tokenize code # ##################################### # If possible (python >= 3.2) use tokenize.open to open files, so PEP 263 # encoding markers are interpreted. try: tokenize_open = tk.open except AttributeError: # Fall back on a backport of the encoding aware tokenize open function, # which requires we back port tokenize.detect_encoding to implement. from codecs import lookup, BOM_UTF8 from io import open as io_open cookie_re = re.compile(r"^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)") blank_re = re.compile(br"^[ \t\f]*(?:[#\r\n]|$)") # I don't think 'blank regular expression' is well named, think # it looks for blank line after any Python # comment removed. # Key test case of interest is hashbang lines! assert blank_re.match(b"\n") assert blank_re.match(b"# Comment\n") assert blank_re.match(b"#!/usr/bin/python\n") assert blank_re.match(b"#!/usr/bin/env python\n") assert not blank_re.match(b'"""Welcome\n') assert not blank_re.match(b'"""Welcome"""\n') def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c (PRIVATE).""" # sys.stderr.write("DEBUG: _get_normal_name(%r)\n" % orig_enc) # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or enc.startswith( ("latin-1-", "iso-8859-1-", "iso-latin-1-") ): return "iso-8859-1" return orig_enc def _find_cookie(line, filename, bom_found): """Find encoding string in a line of Python (PRIVATE).""" # sys.stderr.write("DEBUG: _find_cookie(%r, %r, %r)\n" # % (line, filename, bom_found)) match = cookie_re.match(line) if not match: return None encoding = _get_normal_name(match.group(1)) try: lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter raise SyntaxError( "unknown encoding for {!r}: {}".format(filename, encoding) ) if bom_found: if encoding != "utf-8": # This behaviour mimics the Python interpreter raise SyntaxError("encoding problem for {!r}: utf-8".format(filename)) encoding += "-sig" return encoding def tokenize_open(filename): """Simulate opening a Python file read only with the correct encoding. While this was based on the Python 3 standard library function tokenize.open in order to backport it to Python 2.7, this proved painful. Note that because this text will later be fed into ``exex(...)`` we would hit SyntaxError encoding declaration in Unicode string, so the handle returned has the encoding line masked out! Note we don't just remove the line as that would throw off the line numbers, it is replaced with a Python comment. """ # sys.stderr.write("DEBUG: tokenize_open(%r)\n" % filename) # Will check the first & second lines for an encoding # AND REMOVE IT FROM THE TEXT RETURNED with io_open(filename, "rb") as handle: lines = list(handle) # Find the encoding first = lines[0] if lines else b"" second = lines[1] if len(lines) > 1 else b"" default = "utf-8" bom_found = False if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = "utf-8-sig" encoding = _find_cookie(first, filename, bom_found) if encoding: lines[0] = "# original encoding removed\n" if not encoding and blank_re.match(first): # sys.stderr.write("DEBUG: Trying second line %r\n" # % second) encoding = _find_cookie(second, filename, bom_found) if encoding: lines[1] = "# original encoding removed\n" if not encoding: encoding = default # sys.stderr.write("DEBUG: tokenize_open using encoding=%r\n" # % encoding) # Apply the encoding, using StringIO as we removed the # original encoding to help legacy code using exec. # for b in lines: # sys.stderr.write(b"DEBUG: " + b) return StringIO("".join(b.decode(encoding) for b in lines)) ################################### # End of backported tokenize code # ################################### import restructuredtext_lint as rst_lint __version__ = "0.0.13" log = logging.getLogger(__name__) rst_prefix = "RST" rst_fail_load = 900 rst_fail_parse = 901 rst_fail_all = 902 rst_fail_lint = 903 # Level 1 - info code_mapping_info = { "Possible title underline, too short for the title.": 1, "Unexpected possible title overline or transition.": 2, } # Level 2 - warning code_mapping_warning = { # XXX ends without a blank line; unexpected unindent: "Block quote ends without a blank line; unexpected unindent.": 1, "Bullet list ends without a blank line; unexpected unindent.": 2, "Definition list ends without a blank line; unexpected unindent.": 3, "Enumerated list ends without a blank line; unexpected unindent.": 4, "Explicit markup ends without a blank line; unexpected unindent.": 5, "Field list ends without a blank line; unexpected unindent.": 6, "Literal block ends without a blank line; unexpected unindent.": 7, "Option list ends without a blank line; unexpected unindent.": 8, # Other: "Inline strong start-string without end-string.": 10, "Blank line required after table.": 11, "Title underline too short.": 12, "Inline emphasis start-string without end-string.": 13, "Inline literal start-string without end-string.": 14, "Inline interpreted text or phrase reference start-string without end-string.": 15, "Multiple roles in interpreted text (both prefix and suffix present; only one allowed).": 16, # noqa: E501 "Mismatch: both interpreted text role suffix and reference suffix.": 17, "Literal block expected; none found.": 18, "Inline substitution_reference start-string without end-string.": 19, } # Level 3 - error code_mapping_error = { "Unexpected indentation.": 1, "Malformed table.": 2, # e.g. Unknown directive type "req". "Unknown directive type": 3, # e.g. Unknown interpreted text role "need". "Unknown interpreted text role": 4, # e.g. Undefined substitution referenced: "dict". "Undefined substitution referenced:": 5, # e.g. Unknown target name: "license_txt". "Unknown target name:": 6, } # Level 4 - severe code_mapping_severe = {"Unexpected section title.": 1} code_mappings_by_level = { 1: code_mapping_info, 2: code_mapping_warning, 3: code_mapping_error, 4: code_mapping_severe, } def code_mapping(level, msg, extra_directives, extra_roles, default=99): """Return an error code between 0 and 99.""" try: return code_mappings_by_level[level][msg] except KeyError: pass # Following assumes any variable messages take the format # of 'Fixed text "variable text".' only: # e.g. 'Unknown directive type "req".' # ---> 'Unknown directive type' # e.g. 'Unknown interpreted text role "need".' # ---> 'Unknown interpreted text role' if msg.count('"') == 2 and ' "' in msg and msg.endswith('".'): txt = msg[: msg.index(' "')] value = msg.split('"', 2)[1] if txt == "Unknown directive type" and value in extra_directives: return 0 if txt == "Unknown interpreted text role" and value in extra_roles: return 0 return code_mappings_by_level[level].get(txt, default) return default #################################### # Start of code copied from PEP257 # #################################### # This is the reference implementation of the alogrithm # in PEP257 for removing the indentation of a docstring, # which has been placed in the public domain. # # This includes the minor change from sys.maxint to # sys.maxsize for Python 3 compatibility. # # https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation def trim(docstring): """PEP257 docstring indentation trim function.""" if not docstring: return "" # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxsize for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxsize: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return "\n".join(trimmed) ################################## # End of code copied from PEP257 # ################################## def dequote_docstring(text): """Remove the quotes delimiting a docstring.""" # TODO: Process escaped characters unless raw mode? text = text.strip() if len(text) > 6 and text[:3] == text[-3:] == '"""': # Standard case, """...""" return text[3:-3] if len(text) > 7 and text[:4] in ('u"""', 'r"""') and text[-3:] == '"""': # Unicode, u"""...""", or raw r"""...""" return text[4:-3] # Other flake8 tools will report atypical quotes: if len(text) > 6 and text[:3] == text[-3:] == "'''": return text[3:-3] if len(text) > 7 and text[:4] in ("u'''", "r'''") and text[-3:] == "'''": return text[4:-3] if len(text) > 2 and text[0] == text[-1] == '"': return text[1:-1] if len(text) > 3 and text[:2] in ('u"', 'r"') and text[-1] == '"': return text[2:-1] if len(text) > 2 and text[0] == text[-1] == "'": return text[1:-1] if len(text) > 3 and text[:2] in ("u'", "r'") and text[-1] == "'": return text[2:-1] raise ValueError("Bad quotes!") ################################################## # Start of code copied from pydocstyle/parser.py # ################################################## def humanize(string): """Make a string human readable.""" return re.compile(r"(.)([A-Z]+)").sub(r"\1 \2", string).lower() class Value(object): """A generic object with a list of preset fields.""" def __init__(self, *args): """Initialize.""" if len(self._fields) != len(args): raise ValueError( "got {} arguments for {} fields for {}: {}".format( len(args), len(self._fields), self.__class__.__name__, self._fields ) ) vars(self).update(zip(self._fields, args)) def __hash__(self): """Hash.""" return hash(repr(self)) def __eq__(self, other): """Equality.""" return other and vars(self) == vars(other) def __repr__(self): """Representation.""" kwargs = ", ".join( "{}={!r}".format(field, getattr(self, field)) for field in self._fields ) return "{}({})".format(self.__class__.__name__, kwargs) class Definition(Value): """A Python source code definition (could be class, function, etc).""" _fields = ( "name", "_source", "start", "end", "decorators", "docstring", "children", "parent", "skipped_error_codes", ) _human = property(lambda self: humanize(type(self).__name__)) kind = property(lambda self: self._human.split()[-1]) module = property(lambda self: self.parent.module) all = property(lambda self: self.module.all) _slice = property(lambda self: slice(self.start - 1, self.end)) is_class = False def __iter__(self): """Iterate.""" return chain([self], *self.children) @property def _publicity(self): return {True: "public", False: "private"}[self.is_public] @property def source(self): """Return the source code for the definition.""" full_src = self._source[self._slice] def is_empty_or_comment(line): return line.strip() == "" or line.strip().startswith("#") filtered_src = dropwhile(is_empty_or_comment, reversed(full_src)) return "".join(reversed(list(filtered_src))) def __str__(self): """Definition as a string.""" out = "in {} {} `{}`".format(self._publicity, self._human, self.name) if self.skipped_error_codes: out += " (skipping {})".format(self.skipped_error_codes) return out class Module(Definition): """A Python source code module.""" _fields = ( "name", "_source", "start", "end", "decorators", "docstring", "children", "parent", "_all", "future_imports", "skipped_error_codes", ) _nest = staticmethod(lambda s: {"def": Function, "class": Class}[s]) module = property(lambda self: self) all = property(lambda self: self._all) @property def is_public(self): """Is the module public.""" return not self.name.startswith("_") or self.name.startswith("__") def __str__(self): """Definition as a string.""" return "at module level" class Package(Module): """A package is a __init__.py module.""" class Function(Definition): """A Python source code function.""" _nest = staticmethod(lambda s: {"def": NestedFunction, "class": NestedClass}[s]) @property def is_public(self): """Return True iff this function should be considered public.""" if self.all is not None: return self.name in self.all else: return not self.name.startswith("_") @property def is_test(self): """Return True if this function is a test function/method. We exclude tests from the imperative mood check, because to phrase their docstring in the imperative mood, they would have to start with a highly redundant "Test that ...". """ return self.name.startswith("test") or self.name == "runTest" class NestedFunction(Function): """A Python source code nested function.""" is_public = False class Method(Function): """A Python source code method.""" @property def is_magic(self): """Return True iff this method is a magic method (e.g., `__str__`).""" return ( self.name.startswith("__") and self.name.endswith("__") and self.name not in VARIADIC_MAGIC_METHODS ) @property def is_public(self): """Return True iff this method should be considered public.""" # Check if we are a setter/deleter method, and mark as private if so. for decorator in self.decorators: # Given 'foo', match 'foo.bar' but not 'foobar' or 'sfoo' if re.compile(r"^{}\.".format(self.name)).match(decorator.name): return False name_is_public = ( not self.name.startswith("_") or self.name in VARIADIC_MAGIC_METHODS or self.is_magic ) return self.parent.is_public and name_is_public class Class(Definition): """A Python source code class.""" _nest = staticmethod(lambda s: {"def": Method, "class": NestedClass}[s]) is_public = Function.is_public is_class = True class NestedClass(Class): """A Python source code nested class.""" @property def is_public(self): """Return True iff this class should be considered public.""" return ( not self.name.startswith("_") and self.parent.is_class and self.parent.is_public ) class Decorator(Value): """A decorator for function, method or class.""" _fields = "name arguments".split() VARIADIC_MAGIC_METHODS = ("__init__", "__call__", "__new__") class AllError(Exception): """Raised when there is a problem with __all__ when parsing.""" def __init__(self, message): """Initialize the error with a more specific message.""" Exception.__init__( self, message + textwrap.dedent( """ That means pydocstyle cannot decide which definitions are public. Variable __all__ should be present at most once in each file, in form `__all__ = ('a_public_function', 'APublicClass', ...)`. More info on __all__: http://stackoverflow.com/q/44834/. ') """ ), ) class TokenStream(object): """Token stream.""" # A logical newline is where a new expression or statement begins. When # there is a physical new line, but not a logical one, for example: # (x + # y) # The token will be tk.NL, not tk.NEWLINE. LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT} def __init__(self, filelike): """Initialize.""" self._generator = tk.generate_tokens(filelike.readline) self.current = Token(*next(self._generator, None)) self.line = self.current.start[0] self.log = log self.got_logical_newline = True def move(self): """Move.""" previous = self.current current = self._next_from_generator() self.current = None if current is None else Token(*current) self.line = self.current.start[0] if self.current else self.line self.got_logical_newline = previous.kind in self.LOGICAL_NEWLINES return previous def _next_from_generator(self): try: return next(self._generator, None) except (SyntaxError, tk.TokenError): self.log.warning("error generating tokens", exc_info=True) return None def __iter__(self): """Iterate.""" while True: if self.current is not None: yield self.current else: return self.move() class TokenKind(int): """Kind of token.""" def __repr__(self): """Representation.""" return "tk.{}".format(tk.tok_name[self]) class Token(Value): """Token.""" _fields = "kind value start end source".split() def __init__(self, *args): """Initialize.""" super(Token, self).__init__(*args) self.kind = TokenKind(self.kind) class Parser(object): """A Python source code parser.""" def parse(self, filelike, filename): """Parse the given file-like object and return its Module object.""" self.log = log self.source = filelike.readlines() src = "".join(self.source) # This may raise a SyntaxError: compile(src, filename, "exec") self.stream = TokenStream(StringIO(src)) self.filename = filename self.all = None self.future_imports = set() self._accumulated_decorators = [] return self.parse_module() # TODO: remove def __call__(self, *args, **kwargs): """Call the parse method.""" return self.parse(*args, **kwargs) current = property(lambda self: self.stream.current) line = property(lambda self: self.stream.line) def consume(self, kind): """Consume one token and verify it is of the expected kind.""" next_token = self.stream.move() assert next_token.kind == kind def leapfrog(self, kind, value=None): """Skip tokens in the stream until a certain token kind is reached. If `value` is specified, tokens whose values are different will also be skipped. """ while self.current is not None: if self.current.kind == kind and ( value is None or self.current.value == value ): self.consume(kind) return self.stream.move() def parse_docstring(self): """Parse a single docstring and return its value.""" self.log.debug( "parsing docstring, token is %r (%s)", self.current.kind, self.current.value ) while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL): self.stream.move() self.log.debug( "parsing docstring, token is %r (%s)", self.current.kind, self.current.value, ) if self.current.kind == tk.STRING: docstring = self.current.value self.stream.move() return docstring return None def parse_decorators(self): # noqa : D401 """Called after first @ is found. Parse decorators into self._accumulated_decorators. Continue to do so until encountering the 'def' or 'class' start token. """ name = [] arguments = [] at_arguments = False while self.current is not None: self.log.debug( "parsing decorators, current token is %r (%s)", self.current.kind, self.current.value, ) if self.current.kind == tk.NAME and self.current.value in ["def", "class"]: # Done with decorators - found function or class proper break elif self.current.kind == tk.OP and self.current.value == "@": # New decorator found. Store the decorator accumulated so far: self._accumulated_decorators.append( Decorator("".join(name), "".join(arguments)) ) # Now reset to begin accumulating the new decorator: name = [] arguments = [] at_arguments = False elif self.current.kind == tk.OP and self.current.value == "(": at_arguments = True elif self.current.kind == tk.OP and self.current.value == ")": # Ignore close parenthesis pass elif self.current.kind == tk.NEWLINE or self.current.kind == tk.NL: # Ignore newlines pass else: # Keep accumulating current decorator's name or argument. if not at_arguments: name.append(self.current.value) else: arguments.append(self.current.value) self.stream.move() # Add decorator accumulated so far self._accumulated_decorators.append( Decorator("".join(name), "".join(arguments)) ) def parse_definitions(self, class_, all=False): """Parse multiple definitions and yield them.""" while self.current is not None: self.log.debug( "parsing definition list, current token is %r (%s)", self.current.kind, self.current.value, ) self.log.debug("got_newline: %s", self.stream.got_logical_newline) if all and self.current.value == "__all__": self.parse_all() elif ( self.current.kind == tk.OP and self.current.value == "@" and self.stream.got_logical_newline ): self.consume(tk.OP) self.parse_decorators() elif self.current.value in ["def", "class"]: yield self.parse_definition(class_._nest(self.current.value)) elif self.current.kind == tk.INDENT: self.consume(tk.INDENT) for definition in self.parse_definitions(class_): yield definition elif self.current.kind == tk.DEDENT: self.consume(tk.DEDENT) return elif self.current.value == "from": self.parse_from_import_statement() else: self.stream.move() def parse_all(self): """Parse the __all__ definition in a module.""" assert self.current.value == "__all__" self.consume(tk.NAME) if self.current.value != "=": raise AllError("Could not evaluate contents of __all__. ") self.consume(tk.OP) if self.current.value not in "([": raise AllError("Could not evaluate contents of __all__. ") self.consume(tk.OP) self.all = [] all_content = "(" while self.current.kind != tk.OP or self.current.value not in ")]": if self.current.kind in (tk.NL, tk.COMMENT): pass elif self.current.kind == tk.STRING or self.current.value == ",": all_content += self.current.value else: raise AllError( "Unexpected token kind in __all__: {!r}. ".format( self.current.kind ) ) self.stream.move() self.consume(tk.OP) all_content += ")" try: self.all = eval(all_content, {}) except BaseException as e: raise AllError( "Could not evaluate contents of __all__." "\bThe value was {}. The exception was:\n{}".format(all_content, e) ) def parse_module(self): """Parse a module (and its children) and return a Module object.""" self.log.debug("parsing module.") start = self.line docstring = self.parse_docstring() children = list(self.parse_definitions(Module, all=True)) assert self.current is None, self.current end = self.line cls = Module if self.filename.endswith("__init__.py"): cls = Package module = cls( self.filename, self.source, start, end, [], docstring, children, None, self.all, None, "", ) for child in module.children: child.parent = module module.future_imports = self.future_imports self.log.debug("finished parsing module.") return module def parse_definition(self, class_): """Parse a definition and return its value in a `class_` object.""" start = self.line self.consume(tk.NAME) name = self.current.value self.log.debug("parsing %s '%s'", class_.__name__, name) self.stream.move() if self.current.kind == tk.OP and self.current.value == "(": parenthesis_level = 0 while True: if self.current.kind == tk.OP: if self.current.value == "(": parenthesis_level += 1 elif self.current.value == ")": parenthesis_level -= 1 if parenthesis_level == 0: break self.stream.move() if self.current.kind != tk.OP or self.current.value != ":": self.leapfrog(tk.OP, value=":") else: self.consume(tk.OP) if self.current.kind in (tk.NEWLINE, tk.COMMENT): skipped_error_codes = self.parse_skip_comment() self.leapfrog(tk.INDENT) assert self.current.kind != tk.INDENT docstring = self.parse_docstring() decorators = self._accumulated_decorators self.log.debug("current accumulated decorators: %s", decorators) self._accumulated_decorators = [] self.log.debug("parsing nested definitions.") children = list(self.parse_definitions(class_)) self.log.debug("finished parsing nested definitions for '%s'", name) end = self.line - 1 else: # one-liner definition skipped_error_codes = "" docstring = self.parse_docstring() decorators = [] # TODO children = [] end = self.line self.leapfrog(tk.NEWLINE) definition = class_( name, self.source, start, end, decorators, docstring, children, None, skipped_error_codes, ) for child in definition.children: child.parent = definition self.log.debug( "finished parsing %s '%s'. Next token is %r (%s)", class_.__name__, name, self.current.kind, self.current.value, ) return definition def parse_skip_comment(self): """Parse a definition comment for noqa skips.""" skipped_error_codes = "" if self.current.kind == tk.COMMENT: if "noqa: " in self.current.value: skipped_error_codes = "".join(self.current.value.split("noqa: ")[1:]) elif self.current.value.startswith("# noqa"): skipped_error_codes = "all" return skipped_error_codes def check_current(self, kind=None, value=None): """Verify the current token is of type `kind` and equals `value`.""" msg = textwrap.dedent( """ Unexpected token at line {self.line}: In file: {self.filename} Got kind {self.current.kind!r} Got value {self.current.value} """.format( self=self ) ) kind_valid = self.current.kind == kind if kind else True value_valid = self.current.value == value if value else True assert kind_valid and value_valid, msg def parse_from_import_statement(self): """Parse a 'from x import y' statement. The purpose is to find __future__ statements. """ self.log.debug("parsing from/import statement.") is_future_import = self._parse_from_import_source() self._parse_from_import_names(is_future_import) def _parse_from_import_source(self): """Parse the 'from x import' part in a 'from x import y' statement. Return true iff `x` is __future__. """ assert self.current.value == "from", self.current.value self.stream.move() is_future_import = self.current.value == "__future__" self.stream.move() while ( self.current is not None and self.current.kind in (tk.DOT, tk.NAME, tk.OP) and self.current.value != "import" ): self.stream.move() if self.current is None or self.current.value != "import": return False self.check_current(value="import") assert self.current.value == "import", self.current.value self.stream.move() return is_future_import def _parse_from_import_names(self, is_future_import): """Parse the 'y' part in a 'from x import y' statement.""" if self.current.value == "(": self.consume(tk.OP) expected_end_kinds = (tk.OP,) else: expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER) while self.current.kind not in expected_end_kinds and not ( self.current.kind == tk.OP and self.current.value == ";" ): if self.current.kind != tk.NAME: self.stream.move() continue self.log.debug( "parsing import, token is %r (%s)", self.current.kind, self.current.value, ) if is_future_import: self.log.debug("found future import: %s", self.current.value) self.future_imports.add(self.current.value) self.consume(tk.NAME) self.log.debug( "parsing import, token is %r (%s)", self.current.kind, self.current.value, ) if self.current.kind == tk.NAME and self.current.value == "as": self.consume(tk.NAME) # as if self.current.kind == tk.NAME: self.consume(tk.NAME) # new name, irrelevant if self.current.value == ",": self.consume(tk.OP) self.log.debug( "parsing import, token is %r (%s)", self.current.kind, self.current.value, ) ################################################ # End of code copied from pydocstyle/parser.py # ################################################ parse = Parser() class reStructuredTextChecker(object): """Checker of Python docstrings as reStructuredText.""" name = "rst-docstrings" version = __version__ STDIN_NAMES = {"stdin", "-", "(none)", None} def __init__(self, tree, filename="(none)"): """Initialise.""" self.tree = tree self.filename = filename try: self.load_source() self.err = None except Exception as err: self.source = None self.err = err @classmethod def add_options(cls, parser): """Add RST directives and roles options.""" parser.add_option( "--rst-directives", metavar="LIST", default="", parse_from_config=True, comma_separated_list=True, help="Comma-separated list of additional RST directives.", ) parser.add_option( "--rst-roles", metavar="LIST", default="", parse_from_config=True, comma_separated_list=True, help="Comma-separated list of additional RST roles.", ) @classmethod def parse_options(cls, options): """Adding black-config option.""" cls.extra_directives = options.rst_directives cls.extra_roles = options.rst_roles def run(self): """Use docutils to check docstrings are valid RST.""" # Is there any reason not to call load_source here? if self.err is not None: assert self.source is None msg = "%s%03i %s" % ( rst_prefix, rst_fail_load, "Failed to load file: %s" % self.err, ) yield 0, 0, msg, type(self) module = [] try: module = parse(StringIO(self.source), self.filename) except SyntaxError as err: msg = "%s%03i %s" % ( rst_prefix, rst_fail_parse, "Failed to parse file: %s" % err, ) yield 0, 0, msg, type(self) module = [] except AllError: msg = "%s%03i %s" % ( rst_prefix, rst_fail_all, "Failed to parse __all__ entry.", ) yield 0, 0, msg, type(self) module = [] for definition in module: if not definition.docstring: # People can use flake8-docstrings to report missing # docstrings continue try: # Note we use the PEP257 trim algorithm to remove the # leading whitespace from each line - this avoids false # positive severe error "Unexpected section title." unindented = trim(dequote_docstring(definition.docstring)) # Off load RST validation to reStructuredText-lint # which calls docutils internally. # TODO: Should we pass the Python filename as filepath? rst_errors = list(rst_lint.lint(unindented)) except Exception as err: # e.g. UnicodeDecodeError msg = "%s%03i %s" % ( rst_prefix, rst_fail_lint, "Failed to lint docstring: %s - %s" % (definition.name, err), ) yield definition.start, 0, msg, type(self) continue for rst_error in rst_errors: # TODO - make this a configuration option? if rst_error.level <= 1: continue # Levels: # # 0 - debug --> we don't receive these # 1 - info --> RST1## codes # 2 - warning --> RST2## codes # 3 - error --> RST3## codes # 4 - severe --> RST4## codes # # Map the string to a unique code: msg = rst_error.message.split("\n", 1)[0] code = code_mapping( rst_error.level, msg, self.extra_directives, self.extra_roles ) if not code: # We ignored it, e.g. a known Sphinx role continue assert 0 < code < 100, code code += 100 * rst_error.level msg = "%s%03i %s" % (rst_prefix, code, msg) # This will return the line number by combining the # start of the docstring with the offet within it. # We don't know the column number, leaving as zero. yield definition.start + rst_error.line, 0, msg, type(self) def load_source(self): """Load the source for the specified file.""" if self.filename in self.STDIN_NAMES: self.filename = "stdin" if sys.version_info[0] < 3: self.source = sys.stdin.read() else: self.source = TextIOWrapper(sys.stdin.buffer, errors="ignore").read() else: # Could be a Python 2.7 StringIO with no context manager, sigh. # with tokenize_open(self.filename) as fd: # self.source = fd.read() handle = tokenize_open(self.filename) self.source = handle.read() handle.close()
[ "textwrap.dedent", "io.StringIO", "sys.stdin.read", "re.compile", "codecs.lookup", "restructuredtext_lint.lint", "io.TextIOWrapper", "io.open", "itertools.chain", "logging.getLogger", "tokenize.generate_tokens" ]
[((5198, 5225), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (5215, 5225), False, 'import logging\n'), ((926, 982), 're.compile', 're.compile', (['"""^[ \\\\t\\\\f]*#.*?coding[:=][ \\\\t]*([-\\\\w.]+)"""'], {}), "('^[ \\\\t\\\\f]*#.*?coding[:=][ \\\\t]*([-\\\\w.]+)')\n", (936, 982), False, 'import re\n'), ((995, 1036), 're.compile', 're.compile', (["b'^[ \\\\t\\\\f]*(?:[#\\\\r\\\\n]|$)'"], {}), "(b'^[ \\\\t\\\\f]*(?:[#\\\\r\\\\n]|$)')\n", (1005, 1036), False, 'import re\n'), ((12795, 12824), 'itertools.chain', 'chain', (['[self]', '*self.children'], {}), '([self], *self.children)\n', (12800, 12824), False, 'from itertools import chain, dropwhile\n'), ((18035, 18072), 'tokenize.generate_tokens', 'tk.generate_tokens', (['filelike.readline'], {}), '(filelike.readline)\n', (18053, 18072), True, 'import tokenize as tk\n'), ((19824, 19837), 'io.StringIO', 'StringIO', (['src'], {}), '(src)\n', (19832, 19837), False, 'from io import StringIO\n'), ((2455, 2471), 'codecs.lookup', 'lookup', (['encoding'], {}), '(encoding)\n', (2461, 2471), False, 'from codecs import lookup, BOM_UTF8\n'), ((3764, 3787), 'io.open', 'io_open', (['filename', '"""rb"""'], {}), "(filename, 'rb')\n", (3771, 3787), True, 'from io import open as io_open\n'), ((17206, 17588), 'textwrap.dedent', 'textwrap.dedent', (['"""\n That means pydocstyle cannot decide which definitions are\n public. Variable __all__ should be present at most once in\n each file, in form\n `__all__ = (\'a_public_function\', \'APublicClass\', ...)`.\n More info on __all__: http://stackoverflow.com/q/44834/. \')\n """'], {}), '(\n """\n That means pydocstyle cannot decide which definitions are\n public. Variable __all__ should be present at most once in\n each file, in form\n `__all__ = (\'a_public_function\', \'APublicClass\', ...)`.\n More info on __all__: http://stackoverflow.com/q/44834/. \')\n """\n )\n', (17221, 17588), False, 'import textwrap\n'), ((35281, 35302), 'io.StringIO', 'StringIO', (['self.source'], {}), '(self.source)\n', (35289, 35302), False, 'from io import StringIO\n'), ((38447, 38463), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (38461, 38463), False, 'import sys\n'), ((11180, 11205), 're.compile', 're.compile', (['"""(.)([A-Z]+)"""'], {}), "('(.)([A-Z]+)')\n", (11190, 11205), False, 'import re\n'), ((36545, 36570), 'restructuredtext_lint.lint', 'rst_lint.lint', (['unindented'], {}), '(unindented)\n', (36558, 36570), True, 'import restructuredtext_lint as rst_lint\n'), ((38512, 38560), 'io.TextIOWrapper', 'TextIOWrapper', (['sys.stdin.buffer'], {'errors': '"""ignore"""'}), "(sys.stdin.buffer, errors='ignore')\n", (38525, 38560), False, 'from io import TextIOWrapper\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `youtube_sm_parser` package.""" import pytest import unittest.mock import deepdiff import collections import os import xmltodict import json from youtube_sm_parser import youtube_sm_parser def rel_fn(fn): dir_name = os.path.dirname(os.path.realpath(__file__)) return os.path.join(dir_name, fn) def mock_xml(fn): with open(rel_fn(fn)) as f: return xmltodict.parse(f.read()) def mock_xml_raw(fn): with open(rel_fn(fn)) as f: return f.read() def mock_json(fn): with open(rel_fn(fn)) as f: return json.load(f, object_pairs_hook=collections.OrderedDict) @pytest.fixture def subs_file(): return mock_xml('subscription_manager.xml') @pytest.fixture def feed(): return mock_xml('feed.xml') @pytest.fixture def feed_raw(): return mock_xml_raw('feed.xml') @pytest.fixture def entry_dict(): return { 'id': 'id', 'title': 'video title', 'link': 'video_url', 'uploader': 'author name', 'published': '2019-05-14T11:00:01+00:00', 'thumbnail': 'thumb_url' } def test_extract_feeds(subs_file): expected = ['test_chan_url', 'test_chan_url_2'] parsed_urls = youtube_sm_parser.extract_feeds(subs_file) assert parsed_urls == expected def test_get_entries(feed): expected = [mock_json(i) for i in ['entry1.json', 'entry2.json']] entries = youtube_sm_parser.get_entries(feed) assert deepdiff.DeepDiff(entries, expected) == {} def test_get_entries_empty(): expected = [] entries = youtube_sm_parser.get_entries({'feed': {}}) assert entries == expected def test_entry_to_dict(entry_dict): entry = mock_json('entry1.json') expected = youtube_sm_parser.entry_to_dict(entry) assert deepdiff.DeepDiff(entry_dict, expected) == {} def test_format_dict(entry_dict): format_string = '{title},{link}' expected = 'video title,video_url' formatted = youtube_sm_parser.format_dict(entry_dict, format_string) assert formatted == expected def test_feed_to_dicts(feed_raw, entry_dict): class r(): content = feed_raw entry_dicts = youtube_sm_parser.feed_to_dicts(r).data assert entry_dicts[0] == entry_dict @pytest.mark.parametrize('f', ['json', 'lines', 'yaml']) def test_parse_args_format(f): args = youtube_sm_parser.parse_args(['--format', f]) assert args.format == f def test_invalid_format(): with pytest.raises(SystemExit): args = youtube_sm_parser.parse_args('--format invalid'.split()) def test_line_format_valid(): args = youtube_sm_parser.parse_args('-l {title}'.split()) assert args.line_format == '{title}' def test_line_format_invalid(): with pytest.raises(SystemExit): args = youtube_sm_parser.parse_args('-l {invalid}'.split()) @unittest.mock.patch('youtube_sm_parser.youtube_sm_parser.FuturesSession') def test_get_subscriptions(mock_fs, feed): mock_fs.return_value.get.return_value.content = feed subs = youtube_sm_parser.get_subscriptions(['blah'], 10) @pytest.mark.parametrize('out_format, expected, line_format', [ ['json', '[\n {\n "a": "b"\n }\n]', None], ['lines', 'b', '{a}'], ['yaml', '- a: b\n', None] ]) def test_get_output(out_format, expected, line_format): entries = [{'a': 'b'}] output = youtube_sm_parser.get_output(entries, out_format, line_format) assert expected == output
[ "json.load", "youtube_sm_parser.youtube_sm_parser.get_entries", "os.path.realpath", "youtube_sm_parser.youtube_sm_parser.extract_feeds", "youtube_sm_parser.youtube_sm_parser.parse_args", "youtube_sm_parser.youtube_sm_parser.format_dict", "youtube_sm_parser.youtube_sm_parser.feed_to_dicts", "pytest.raises", "youtube_sm_parser.youtube_sm_parser.get_subscriptions", "deepdiff.DeepDiff", "youtube_sm_parser.youtube_sm_parser.get_output", "pytest.mark.parametrize", "os.path.join", "youtube_sm_parser.youtube_sm_parser.entry_to_dict" ]
[((2265, 2320), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""f"""', "['json', 'lines', 'yaml']"], {}), "('f', ['json', 'lines', 'yaml'])\n", (2288, 2320), False, 'import pytest\n'), ((3089, 3267), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""out_format, expected, line_format"""', '[[\'json\', """[\n {\n "a": "b"\n }\n]""", None], [\'lines\', \'b\',\n \'{a}\'], [\'yaml\', \'- a: b\\n\', None]]'], {}), '(\'out_format, expected, line_format\', [[\'json\',\n """[\n {\n "a": "b"\n }\n]""", None], [\'lines\', \'b\', \'{a}\'], [\n \'yaml\', \'- a: b\\n\', None]])\n', (3112, 3267), False, 'import pytest\n'), ((341, 367), 'os.path.join', 'os.path.join', (['dir_name', 'fn'], {}), '(dir_name, fn)\n', (353, 367), False, 'import os\n'), ((1241, 1283), 'youtube_sm_parser.youtube_sm_parser.extract_feeds', 'youtube_sm_parser.extract_feeds', (['subs_file'], {}), '(subs_file)\n', (1272, 1283), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((1435, 1470), 'youtube_sm_parser.youtube_sm_parser.get_entries', 'youtube_sm_parser.get_entries', (['feed'], {}), '(feed)\n', (1464, 1470), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((1590, 1633), 'youtube_sm_parser.youtube_sm_parser.get_entries', 'youtube_sm_parser.get_entries', (["{'feed': {}}"], {}), "({'feed': {}})\n", (1619, 1633), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((1756, 1794), 'youtube_sm_parser.youtube_sm_parser.entry_to_dict', 'youtube_sm_parser.entry_to_dict', (['entry'], {}), '(entry)\n', (1787, 1794), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((1981, 2037), 'youtube_sm_parser.youtube_sm_parser.format_dict', 'youtube_sm_parser.format_dict', (['entry_dict', 'format_string'], {}), '(entry_dict, format_string)\n', (2010, 2037), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((2363, 2408), 'youtube_sm_parser.youtube_sm_parser.parse_args', 'youtube_sm_parser.parse_args', (["['--format', f]"], {}), "(['--format', f])\n", (2391, 2408), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((3036, 3085), 'youtube_sm_parser.youtube_sm_parser.get_subscriptions', 'youtube_sm_parser.get_subscriptions', (["['blah']", '(10)'], {}), "(['blah'], 10)\n", (3071, 3085), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((3370, 3432), 'youtube_sm_parser.youtube_sm_parser.get_output', 'youtube_sm_parser.get_output', (['entries', 'out_format', 'line_format'], {}), '(entries, out_format, line_format)\n', (3398, 3432), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((302, 328), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (318, 328), False, 'import os\n'), ((609, 664), 'json.load', 'json.load', (['f'], {'object_pairs_hook': 'collections.OrderedDict'}), '(f, object_pairs_hook=collections.OrderedDict)\n', (618, 664), False, 'import json\n'), ((1483, 1519), 'deepdiff.DeepDiff', 'deepdiff.DeepDiff', (['entries', 'expected'], {}), '(entries, expected)\n', (1500, 1519), False, 'import deepdiff\n'), ((1807, 1846), 'deepdiff.DeepDiff', 'deepdiff.DeepDiff', (['entry_dict', 'expected'], {}), '(entry_dict, expected)\n', (1824, 1846), False, 'import deepdiff\n'), ((2181, 2215), 'youtube_sm_parser.youtube_sm_parser.feed_to_dicts', 'youtube_sm_parser.feed_to_dicts', (['r'], {}), '(r)\n', (2212, 2215), False, 'from youtube_sm_parser import youtube_sm_parser\n'), ((2475, 2500), 'pytest.raises', 'pytest.raises', (['SystemExit'], {}), '(SystemExit)\n', (2488, 2500), False, 'import pytest\n'), ((2752, 2777), 'pytest.raises', 'pytest.raises', (['SystemExit'], {}), '(SystemExit)\n', (2765, 2777), False, 'import pytest\n')]
"""Quantum Router.""" import collections class Router: # TODO: Remove this when we have more methods # pylint:disable=too-few-public-methods """A quantum router. A quantum router object represents a quantum router that is part of a quantum network. Quantum routers are interconnected by quantum links.""" def __init__(self, network, name): """Initialize a quantum router. Args: network (Network): The network in which the router is created. name (str): The name of quantum router; uniquely identifies the router within the quantum network. Raises: AssertionError if there is already a router with the same name in the network.""" self.network = network self.name = name self._next_available_port = 0 self.links = collections.OrderedDict() # Link objects indexed by local port network.add_router(self) def add_link(self, link): """Add a link to the router. The link is attached to the next available port. The number of that port is returned. Args: link (Link): The link to be attached. Returns: The port to which the link was attached. Raises: AssertionError if there is already a router with the same name in the network.""" assert self in [link.router_1, link.router_2], \ f"Attempt to add link to router {self.name} which is not an end-point of the link" port = self._next_available_port self._next_available_port += 1 self.links[port] = link return port
[ "collections.OrderedDict" ]
[((846, 871), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (869, 871), False, 'import collections\n')]
from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework.schemas import get_schema_view from ai4all_api import views schema_view = get_schema_view(title='AI4All backend API') # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'submit-camera-items', views.SubmitCameraItemViewSet) # The API URLs are now determined automatically by the router. # Additionally, we include the login URLs for the browsable API. urlpatterns = [ url(r'^schema/$', schema_view), url(r'^api/', include(router.urls)), ]
[ "django.conf.urls.include", "django.conf.urls.url", "rest_framework.routers.DefaultRouter", "rest_framework.schemas.get_schema_view" ]
[((187, 230), 'rest_framework.schemas.get_schema_view', 'get_schema_view', ([], {'title': '"""AI4All backend API"""'}), "(title='AI4All backend API')\n", (202, 230), False, 'from rest_framework.schemas import get_schema_view\n'), ((294, 309), 'rest_framework.routers.DefaultRouter', 'DefaultRouter', ([], {}), '()\n', (307, 309), False, 'from rest_framework.routers import DefaultRouter\n'), ((530, 559), 'django.conf.urls.url', 'url', (['"""^schema/$"""', 'schema_view'], {}), "('^schema/$', schema_view)\n", (533, 559), False, 'from django.conf.urls import url, include\n'), ((580, 600), 'django.conf.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (587, 600), False, 'from django.conf.urls import url, include\n')]
from keras.models import load_model # from matplotlib.font_manager import FontProperties import cv2 import numpy as np import exptBikeNYC size =10 model = exptBikeNYC.build_model(False) model.load_weights('MODEL/c3.p3.t3.resunit4.lr0.0002.best.h5') f = open("area.csv", "r") # 临时存储某时间的人数 person_num = [] # 存储各时间的人数尺寸(n,3,3) imgs = [] i, l = 0, 0 for line in f: l += 1 if l == 1: continue i += 1 line = line.strip().split(',') # 将人数转化为小于1的数,后面求实际人数需转化过来 number = (float(line[2]) - 0) / (3073 - 0) * 2 - 1 person_num.append(number) # 每次读16个数据 if i % (128) == 0: # 转化成一维数组 person_num = np.array(person_num) # 改变形状,类似图像形式 person_num = person_num.reshape(16, 8) imgs.append(person_num) i = 0 person_num = [] # 训练数据(输入三种类型的数据,并各自转化为多通道形式) train_x1, train_x2, train_x3, train_y = [], [], [], [] for i in range(1300, 1305): # 取短期、周期、趋势三组件数据,各不同长度序列 image1 = [imgs[i - 3], imgs[i - 2], imgs[i - 1]] image2 = [imgs[i - 72], imgs[i - 48], imgs[i - 24]] image3 = [imgs[i - 484], imgs[i - 336], imgs[i - 168]] train_x1.append(image1) train_x2.append(image2) train_x3.append(image3) lab = [imgs[i]] train_y.append(lab) # 最终输出 train_x = [np.array(train_x1), np.array(train_x2), np.array(train_x3)] train_y = np.array(train_y) # X_test, Y_test=exptBikeNYC.main() predict_y = model.predict(train_x) print((train_y+1)/2*3073) print(((predict_y+1)/2*3073).astype(int)) # print((predict_y*(60923+192687)-192687))
[ "exptBikeNYC.build_model", "numpy.array" ]
[((156, 186), 'exptBikeNYC.build_model', 'exptBikeNYC.build_model', (['(False)'], {}), '(False)\n', (179, 186), False, 'import exptBikeNYC\n'), ((1330, 1347), 'numpy.array', 'np.array', (['train_y'], {}), '(train_y)\n', (1338, 1347), True, 'import numpy as np\n'), ((1260, 1278), 'numpy.array', 'np.array', (['train_x1'], {}), '(train_x1)\n', (1268, 1278), True, 'import numpy as np\n'), ((1280, 1298), 'numpy.array', 'np.array', (['train_x2'], {}), '(train_x2)\n', (1288, 1298), True, 'import numpy as np\n'), ((1300, 1318), 'numpy.array', 'np.array', (['train_x3'], {}), '(train_x3)\n', (1308, 1318), True, 'import numpy as np\n'), ((646, 666), 'numpy.array', 'np.array', (['person_num'], {}), '(person_num)\n', (654, 666), True, 'import numpy as np\n')]
# Generated by Django 2.1.5 on 2019-02-14 13:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('places', '0037_hostel'), ('article', '0002_textarticle_place'), ] operations = [ migrations.RenameField( model_name='imagearticle', old_name='user', new_name='created_by', ), migrations.RenameField( model_name='textarticle', old_name='user', new_name='created_by', ), migrations.AddField( model_name='imagearticle', name='place', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='places.Place'), preserve_default=False, ), migrations.AlterField( model_name='imagearticle', name='picture', field=models.ImageField(help_text='Picture of your place', upload_to='%Y/%m/%d/'), ), ]
[ "django.db.models.ForeignKey", "django.db.models.ImageField", "django.db.migrations.RenameField" ]
[((301, 395), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""imagearticle"""', 'old_name': '"""user"""', 'new_name': '"""created_by"""'}), "(model_name='imagearticle', old_name='user', new_name\n ='created_by')\n", (323, 395), False, 'from django.db import migrations, models\n'), ((447, 540), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""textarticle"""', 'old_name': '"""user"""', 'new_name': '"""created_by"""'}), "(model_name='textarticle', old_name='user', new_name=\n 'created_by')\n", (469, 540), False, 'from django.db import migrations, models\n'), ((696, 792), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'default': '(1)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""places.Place"""'}), "(default=1, on_delete=django.db.models.deletion.CASCADE,\n to='places.Place')\n", (713, 792), False, 'from django.db import migrations, models\n'), ((953, 1028), 'django.db.models.ImageField', 'models.ImageField', ([], {'help_text': '"""Picture of your place"""', 'upload_to': '"""%Y/%m/%d/"""'}), "(help_text='Picture of your place', upload_to='%Y/%m/%d/')\n", (970, 1028), False, 'from django.db import migrations, models\n')]
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data from datetime import datetime LOGDIR = '/tmp/17springAI/mnist/objectiveFunc/' + datetime.now().strftime('%Y%m%d-%H%M%S') + '/' def activation(act_func, logit): if act_func == "relu": return tf.nn.relu(logit) else: return tf.nn.sigmoid(logit) def logits(input, size_in, size_out): w = tf.Variable(tf.truncated_normal([size_in, size_out], stddev=0.1), name="W") b = tf.Variable(tf.constant(0.1, shape=[size_out]), name="B") logit = (tf.matmul(input, w) + b) tf.summary.histogram("weights", w) tf.summary.histogram("biases", b) tf.summary.histogram("logits", logit) return logit, w, b # fully conected layer def fc_layer(input, size_in, size_out,act_func, name="fc" ): with tf.name_scope(name): logit, w, b = logits(input, size_in, size_out) act = activation(act_func, logit) tf.summary.histogram("weights", w) tf.summary.histogram("biases", b) tf.summary.histogram("activations", act) return act, w, b # runs different model each time, hparam is a string specification for the model # hpram is also used in the created tensorboard summary def mnist_model(learning_rate, objectiveFunc, hparam, act_func): tf.reset_default_graph() sess = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.4))) # input layer x = tf.placeholder(tf.float32, [None, 784], name="x") x_image = tf.reshape(x, [-1, 28, 28, 1]) # to view images on tensorboard tf.summary.image('input', x_image, 3) # label to compare y_ = tf.placeholder(tf.float32, [None, 10], name="labels") keep_prob = tf.placeholder(tf.float32) h1, W1, B1 = fc_layer(x, 784, 100, act_func, "h1") logit, W2, B2 = logits(h1, 100, 10) Y = tf.nn.softmax(logit) ## changing loss function if objectiveFunc == "mean_sq_err": with tf.name_scope("mean_sq_err"): mean_sq_err = tf.reduce_mean(tf.contrib.keras.losses.mean_squared_error(Y, y_)) tf.summary.scalar("mean_sq_err", mean_sq_err) loss = mean_sq_err elif objectiveFunc == "L2_norm": with tf.name_scope("L2_norm"): xent = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( logits=logit, labels=y_), name="xent") L2_lambda = 0.05 L2_norm = xent + \ L2_lambda * (tf.nn.l2_loss(W1) + tf.nn.l2_loss(B1) + tf.nn.l2_loss(W2) + tf.nn.l2_loss(B2)) tf.summary.scalar("L2_norm", L2_norm) loss = L2_norm else: with tf.name_scope("xent"): xent = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( logits=logit, labels=y_), name="xent") tf.summary.scalar("xent", xent) loss = xent with tf.name_scope("train"): train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) with tf.name_scope("accuracy"): correct_prediction = tf.equal(tf.argmax(logit, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar("accuracy", accuracy) summ = tf.summary.merge_all() sess.run(tf.global_variables_initializer()) writer_train = tf.summary.FileWriter(LOGDIR + hparam + "_train") writer_train.add_graph(sess.graph) writer_test = tf.summary.FileWriter(LOGDIR + hparam + "_test") writer_test.add_graph(sess.graph) num_epochs = 200 # training accuracy list_vacc = list() for k in range(num_epochs): print(str(k) + "th epoch") for i in range(550): if i % 100 == 0: batch_xs, batch_ys = mnist.train.next_batch(100) [train_accuracy, s_train] = sess.run([accuracy, summ], feed_dict={x: batch_xs, y_: batch_ys}) writer_train.add_summary(s_train, k * 550 + i) [test_accuracy, s_test] = sess.run([accuracy, summ], feed_dict={x: mnist.test.images, y_: mnist.test.labels}) writer_test.add_summary(s_test, k * 550 + i) print('Step {:d}, training accuracy {:g}'.format(k * 550 + i, train_accuracy)) print('Step {:d}, test accuracy {:g}'.format(k * 550 + i, test_accuracy)) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5}) vacc = accuracy.eval(feed_dict={x: mnist.validation.images, y_: mnist.validation.labels, keep_prob: 1}) list_vacc.append(vacc) if k > 10 and np.mean(list_vacc[-10:-5]) > np.mean(list_vacc[-5:]): print("Seems like it starts to overfit, aborting the training") break mnist = input_data.read_data_sets('./MNIST_data', one_hot=True) def make_hparam_string(act_func, learning_rate, objective): return "%s,lr_%.0E,%s" % (act_func, learning_rate, objective) def main(): for act_func in ["sigmoid", "relu"]: # You can try adding some more learning rates for learning_rate in [1E-4]: # Include "False" as a value to try different model architectures: for objective in ["xent", "mean_sq_err", "L2_norm"]: # def mnist_model(learning_rate, regularization, hparam): hparam = make_hparam_string(act_func, learning_rate, objective) print('Starting run for %s' % hparam) # Actually run with the new settings mnist_model(learning_rate, objective, hparam, act_func) if __name__ == '__main__': main()
[ "tensorflow.contrib.keras.losses.mean_squared_error", "tensorflow.reset_default_graph", "tensorflow.reshape", "tensorflow.train.AdamOptimizer", "tensorflow.matmul", "numpy.mean", "tensorflow.GPUOptions", "tensorflow.truncated_normal", "tensorflow.nn.softmax", "tensorflow.nn.relu", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.placeholder", "tensorflow.cast", "tensorflow.summary.histogram", "tensorflow.summary.FileWriter", "tensorflow.name_scope", "datetime.datetime.now", "tensorflow.summary.merge_all", "tensorflow.summary.image", "tensorflow.summary.scalar", "tensorflow.global_variables_initializer", "tensorflow.constant", "tensorflow.argmax", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "tensorflow.nn.l2_loss", "tensorflow.nn.sigmoid" ]
[((4916, 4971), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""./MNIST_data"""'], {'one_hot': '(True)'}), "('./MNIST_data', one_hot=True)\n", (4941, 4971), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((601, 635), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""weights"""', 'w'], {}), "('weights', w)\n", (621, 635), True, 'import tensorflow as tf\n'), ((640, 673), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""biases"""', 'b'], {}), "('biases', b)\n", (660, 673), True, 'import tensorflow as tf\n'), ((678, 715), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""logits"""', 'logit'], {}), "('logits', logit)\n", (698, 715), True, 'import tensorflow as tf\n'), ((1317, 1341), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (1339, 1341), True, 'import tensorflow as tf\n'), ((1489, 1538), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 784]'], {'name': '"""x"""'}), "(tf.float32, [None, 784], name='x')\n", (1503, 1538), True, 'import tensorflow as tf\n'), ((1553, 1583), 'tensorflow.reshape', 'tf.reshape', (['x', '[-1, 28, 28, 1]'], {}), '(x, [-1, 28, 28, 1])\n', (1563, 1583), True, 'import tensorflow as tf\n'), ((1624, 1661), 'tensorflow.summary.image', 'tf.summary.image', (['"""input"""', 'x_image', '(3)'], {}), "('input', x_image, 3)\n", (1640, 1661), True, 'import tensorflow as tf\n'), ((1695, 1748), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 10]'], {'name': '"""labels"""'}), "(tf.float32, [None, 10], name='labels')\n", (1709, 1748), True, 'import tensorflow as tf\n'), ((1765, 1791), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (1779, 1791), True, 'import tensorflow as tf\n'), ((1896, 1916), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logit'], {}), '(logit)\n', (1909, 1916), True, 'import tensorflow as tf\n'), ((3312, 3334), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (3332, 3334), True, 'import tensorflow as tf\n'), ((3403, 3452), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (["(LOGDIR + hparam + '_train')"], {}), "(LOGDIR + hparam + '_train')\n", (3424, 3452), True, 'import tensorflow as tf\n'), ((3510, 3558), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (["(LOGDIR + hparam + '_test')"], {}), "(LOGDIR + hparam + '_test')\n", (3531, 3558), True, 'import tensorflow as tf\n'), ((306, 323), 'tensorflow.nn.relu', 'tf.nn.relu', (['logit'], {}), '(logit)\n', (316, 323), True, 'import tensorflow as tf\n'), ((349, 369), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['logit'], {}), '(logit)\n', (362, 369), True, 'import tensorflow as tf\n'), ((429, 481), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[size_in, size_out]'], {'stddev': '(0.1)'}), '([size_in, size_out], stddev=0.1)\n', (448, 481), True, 'import tensorflow as tf\n'), ((513, 547), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': '[size_out]'}), '(0.1, shape=[size_out])\n', (524, 547), True, 'import tensorflow as tf\n'), ((572, 591), 'tensorflow.matmul', 'tf.matmul', (['input', 'w'], {}), '(input, w)\n', (581, 591), True, 'import tensorflow as tf\n'), ((833, 852), 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), '(name)\n', (846, 852), True, 'import tensorflow as tf\n'), ((959, 993), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""weights"""', 'w'], {}), "('weights', w)\n", (979, 993), True, 'import tensorflow as tf\n'), ((1002, 1035), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""biases"""', 'b'], {}), "('biases', b)\n", (1022, 1035), True, 'import tensorflow as tf\n'), ((1044, 1084), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""activations"""', 'act'], {}), "('activations', act)\n", (1064, 1084), True, 'import tensorflow as tf\n'), ((2965, 2987), 'tensorflow.name_scope', 'tf.name_scope', (['"""train"""'], {}), "('train')\n", (2978, 2987), True, 'import tensorflow as tf\n'), ((3073, 3098), 'tensorflow.name_scope', 'tf.name_scope', (['"""accuracy"""'], {}), "('accuracy')\n", (3086, 3098), True, 'import tensorflow as tf\n'), ((3260, 3299), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""accuracy"""', 'accuracy'], {}), "('accuracy', accuracy)\n", (3277, 3299), True, 'import tensorflow as tf\n'), ((3349, 3382), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (3380, 3382), True, 'import tensorflow as tf\n'), ((2000, 2028), 'tensorflow.name_scope', 'tf.name_scope', (['"""mean_sq_err"""'], {}), "('mean_sq_err')\n", (2013, 2028), True, 'import tensorflow as tf\n'), ((2134, 2179), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""mean_sq_err"""', 'mean_sq_err'], {}), "('mean_sq_err', mean_sq_err)\n", (2151, 2179), True, 'import tensorflow as tf\n'), ((3138, 3157), 'tensorflow.argmax', 'tf.argmax', (['logit', '(1)'], {}), '(logit, 1)\n', (3147, 3157), True, 'import tensorflow as tf\n'), ((3159, 3175), 'tensorflow.argmax', 'tf.argmax', (['y_', '(1)'], {}), '(y_, 1)\n', (3168, 3175), True, 'import tensorflow as tf\n'), ((3211, 3250), 'tensorflow.cast', 'tf.cast', (['correct_prediction', 'tf.float32'], {}), '(correct_prediction, tf.float32)\n', (3218, 3250), True, 'import tensorflow as tf\n'), ((183, 197), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (195, 197), False, 'from datetime import datetime\n'), ((2071, 2120), 'tensorflow.contrib.keras.losses.mean_squared_error', 'tf.contrib.keras.losses.mean_squared_error', (['Y', 'y_'], {}), '(Y, y_)\n', (2113, 2120), True, 'import tensorflow as tf\n'), ((2261, 2285), 'tensorflow.name_scope', 'tf.name_scope', (['"""L2_norm"""'], {}), "('L2_norm')\n", (2274, 2285), True, 'import tensorflow as tf\n'), ((2624, 2661), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""L2_norm"""', 'L2_norm'], {}), "('L2_norm', L2_norm)\n", (2641, 2661), True, 'import tensorflow as tf\n'), ((2712, 2733), 'tensorflow.name_scope', 'tf.name_scope', (['"""xent"""'], {}), "('xent')\n", (2725, 2733), True, 'import tensorflow as tf\n'), ((2898, 2929), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""xent"""', 'xent'], {}), "('xent', xent)\n", (2915, 2929), True, 'import tensorflow as tf\n'), ((3010, 3047), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {}), '(learning_rate)\n', (3032, 3047), True, 'import tensorflow as tf\n'), ((4759, 4785), 'numpy.mean', 'np.mean', (['list_vacc[-10:-5]'], {}), '(list_vacc[-10:-5])\n', (4766, 4785), True, 'import numpy as np\n'), ((4788, 4811), 'numpy.mean', 'np.mean', (['list_vacc[-5:]'], {}), '(list_vacc[-5:])\n', (4795, 4811), True, 'import numpy as np\n'), ((1409, 1459), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': '(0.4)'}), '(per_process_gpu_memory_fraction=0.4)\n', (1422, 1459), True, 'import tensorflow as tf\n'), ((2338, 2402), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'logit', 'labels': 'y_'}), '(logits=logit, labels=y_)\n', (2377, 2402), True, 'import tensorflow as tf\n'), ((2786, 2850), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'logit', 'labels': 'y_'}), '(logits=logit, labels=y_)\n', (2825, 2850), True, 'import tensorflow as tf\n'), ((2593, 2610), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['B2'], {}), '(B2)\n', (2606, 2610), True, 'import tensorflow as tf\n'), ((2573, 2590), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['W2'], {}), '(W2)\n', (2586, 2590), True, 'import tensorflow as tf\n'), ((2533, 2550), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['W1'], {}), '(W1)\n', (2546, 2550), True, 'import tensorflow as tf\n'), ((2553, 2570), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['B1'], {}), '(B1)\n', (2566, 2570), True, 'import tensorflow as tf\n')]
import copy # for copying something in Python import unicodedata import multiprocessing as mp from multiprocessing import Manager import gc import numpy as np class WSUtils(): def __init__(self, VNDict): ################################################################################################## ''' The dictionary bellow is normalizing map which is inherited from Dat Quoc Nguyen (https://github.com/datquocnguyen/RDRsegmenter) (https://github.com/datquocnguyen/VnMarMoT/blob/master/Utility.py) ''' self.normalize_map = { "òa": "oà", "óa": "oá", "ỏa": "oả", "õa": "oã", "ọa": "oạ", "òe": "oè", "óe": "oé", "ỏe": "oẻ", "õe": "oẽ", "ọe": "oẹ", "ùy": "uỳ", "úy": "uý", "ủy": "uỷ", "ũy": "uỹ", "ụy": "uỵ", "Ủy": "Uỷ" } ################################################################################################## ''' The RDR_VNDict, VNFamilyName, and VNMiddle are inherited from the work of Dat Quoc Nguyen (https://github.com/datquocnguyen/RDRsegmenter) The UET_VNDict is inherited from the work of Tuan-Phong Nguyen (https://github.com/phongnt570/UETsegmenter/blob/master/dictionary/VNDictObject) ''' ################################################################################################## self.VNDict = set(self.read_lines('./dict/' + VNDict + '.txt')) self.VNFamilyName = set(self.read_lines('./dict/VNFamilyName.txt')) self.VNMiddle = set(self.read_lines('./dict/VNMiddle.txt')) ################################################################################################## self.lower = '🄰' # this string indicates for "lower" token style self.upper = '🄱' # this string indicates for "upper" token style self.bos = '🄲' # this string indicates for "begin of sentence" token style self.eos = '🄳' # this string indicates for "end of sentence" token style self.allupper = '🄴' # this string indicates for "all characters are upper" token style self.other = '🄵' # this string indicates for "other" token style (not in of all style above) ################################################################################################## def pop_seen_words_sfx(self, train_stns, ratios): seen_words = set() seen_words_sfx = set() for stn in train_stns: wrds = stn.lower().split(' ') for w in wrds: seen_words.update({w}) syl = w.split('_') sfx = syl[-1] if len(syl) in [3, 4] and sfx in ratios['sfx'] and not self.inVNFamilyName(syl[0]): seen_words_sfx.update({w}) seen_words.update(self.VNDict) for word in seen_words_sfx: if self.inVNDict(word.replace('_', ' ')): self.VNDict.discard(word.replace('_', ' ')) return seen_words, seen_words_sfx def get_unseenwords_sfx(self, test_stns, seen_words, ratios): unseen_words_sfx = set() for stn in test_stns: wrds = stn.lower().split(' ') for w in wrds: syl = w.split('_') sfx = syl[-1] if len(syl) in [3, 4] and sfx in ratios['sfx'] and not self.inVNFamilyName(syl[0]): if ' '.join(syl) not in seen_words: unseen_words_sfx.update({w}) return unseen_words_sfx def normalize_accent(self, line_pos): for key in self.normalize_map.keys(): line_pos = line_pos.replace(key, self.normalize_map[key]) return unicodedata.normalize('NFC', u'' + line_pos) def possible_tag(self, stns_train, POSs): possible_lbl = {} for idx, line in enumerate(stns_train): lbl = POSs[idx] for j, word in enumerate(line): word_lower = word.lower() if word not in possible_lbl: possible_lbl[word_lower] = [lbl[j]] else: if lbl[j] not in possible_lbl[word_lower]: possible_lbl[word_lower].append(lbl[j]) return possible_lbl def read_lines(self, file_path): ''' Input: The path of the text file. Output: The list in which each line of the list according to each line in the input text file ''' lines = [] f = open(file_path, 'r', encoding='utf8') for line in f.readlines(): line_pos = line.replace('\n', '') lines.append(self.normalize_accent(line_pos)) f.close() return lines def read_ws_corpus(self, file_path): ''' Input: The path of the text file. Output: The list in which each line of the list according to each line in the input text file ''' lines = [] f = open(file_path, 'r', encoding='utf8') for line in f.readlines(): line_pos = line.replace('\n', '') ''' The "underscore" character has the task to concatenate continuous tokens into a work The "space" character has the task to segment work (to mark the boundary of two words) "Two lines" of code bellow has the task to fix the little errors in the VLSP 2013 for Word Segmentation dataset These errors occur only "four times" in the "testing set" of the VLSP 2013 for Word Segmentation dataset Therefore, that errors will be not affected on all results because of it very very very very very small than total ''' ###################################### line_pos = line_pos.replace('_ ', ' ') line_pos = line_pos.replace(' _', ' ') ###################################### lines.append(self.normalize_accent(line_pos)) f.close() return lines def read_pos_training_corpus(self, file_path): ''' Input: Output: ''' f = open(file_path, 'r', encoding='utf8') list_stns, list_POSs = [], [] words_tmp, POSs_tmp = [], [] lbls, id2lbl = {}, {} for line in f.readlines(): if len(line.replace('\n', '')) == 0: list_stns.append(words_tmp) list_POSs.append(POSs_tmp) words_tmp, POSs_tmp = [], [] continue line_split = line.replace('\n', '').split('\t') words_tmp.append(self.normalize_accent(line_split[0])) lbl = self.normalize_accent(line_split[1]) if lbl not in lbls: lbls[lbl] = len(lbls) POSs_tmp.append(lbls[lbl]) f.close() for key in lbls.keys(): id2lbl[lbls[key]] = key return list_stns, list_POSs, lbls, id2lbl def read_pos_test_corpus(self, file_path): ''' Input: Output: ''' f = open(file_path, 'r', encoding='utf8') list_stns, list_POSs = [], [] words_tmp, POSs_tmp = [], [] for line in f.readlines(): if len(line.replace('\n', '')) == 0: list_stns.append(words_tmp) list_POSs.append(POSs_tmp) words_tmp, POSs_tmp = [], [] continue line_split = line.replace('\n', '').split('\t') words_tmp.append(self.normalize_accent(line_split[0])) POSs_tmp.append(self.normalize_accent(line_split[1])) f.close() return list_stns, list_POSs def add_string_to_dict(self, vocab, string): ''' Put a string to a dictionary and update the counters of keys ''' if string not in vocab: vocab[string] = 1 else: vocab[string] += 1 def syl_type(self, s): ''' Return style of an input token by using "utils" object (All styles are described above) ''' if s == self.bos: return self.bos if s == self.eos: return self.eos if s.islower(): return self.lower if s.isupper(): return self.allupper if len(s) > 1 and s[0].isupper() and s[1:].islower(): return self.upper return self.other def inVNDict(self, syl): ''' Input: a string Output: True or False (Check whether a string in the Vietnamese dictionary) ''' return syl in self.VNDict def inVNFamilyName(self, syl): ''' Input: a string Output: True or False (Check whether a string is a Vietnamese family name) ''' return syl in self.VNFamilyName def inVNMiddle(self, syl): ''' Input: a string Output: True or False (Check whether a string is a Vietnamese middle name) ''' return syl in self.VNMiddle def compute_ratios(self, training_sentences): # Counters of some n-grams patterns n_gram_1 = {'e1_gram-1_gram_n0_pre': {}, 'e2_gram-1_gram_n0': {}} pos_1_gram = {} head_sfx = {} # Counting for some n-grams patterns for line in training_sentences: n_grams = line.split(' ') n_grams_N = len(n_grams) for idx, n_gram in enumerate(n_grams): tokens = n_gram.lower().split('_') tokens_original = n_gram.split('_') if 4 < len(tokens) and len(tokens) < 10: self.VNDict.update({n_gram.replace('_', ' ').lower()}) if len(tokens) == 1: if idx < n_grams_N - 1: next_word = n_grams[idx + 1] if len(next_word.split('_')) > 1: if self.syl_type(tokens_original[0]) == self.lower: self.add_string_to_dict(n_gram_1['e1_gram-1_gram_n0_pre'], tokens[0]) elif self.syl_type(next_word) in [self.lower, self.allupper, self.upper]: if self.syl_type(tokens_original[0]) == self.lower: self.add_string_to_dict(n_gram_1['e1_gram-1_gram_n0_pre'], tokens[0]) if len(tokens) > 1: if self.syl_type(tokens_original[0]) == self.lower: self.add_string_to_dict(n_gram_1['e2_gram-1_gram_n0'], tokens[0]) if len(tokens) == 3 or len(tokens) == 4: head = ' '.join(tokens[:-1]) sfx = tokens[-1] if self.inVNDict(head) and not self.inVNDict(' '.join(tokens)): if all(self.syl_type(t_original) == self.lower for t_original in tokens_original): if not self.inVNFamilyName(tokens[0]): self.add_string_to_dict(pos_1_gram, sfx) if sfx not in head_sfx: head_sfx[sfx] = {head} else: head_sfx[sfx].update({head}) avg_pos_1_gram = 0 for key in pos_1_gram: avg_pos_1_gram += pos_1_gram[key] pos_final = [] if len(pos_1_gram) > 0: avg_pos_1_gram = avg_pos_1_gram/len(pos_1_gram) for key in pos_1_gram: if pos_1_gram[key] > avg_pos_1_gram and len(head_sfx[key]) > 1: pos_final.append(key) tmp_ratios_2 = {} avg_ratios_2 = 0 ratios_2 = {} for key in n_gram_1['e1_gram-1_gram_n0_pre'].keys(): if key in n_gram_1['e2_gram-1_gram_n0']: quantity = n_gram_1['e1_gram-1_gram_n0_pre'][key]+n_gram_1['e2_gram-1_gram_n0'][key] tmp_ratios_2[key] = [n_gram_1['e1_gram-1_gram_n0_pre'][key]>n_gram_1['e2_gram-1_gram_n0'][key],quantity] avg_ratios_2 += quantity if len(tmp_ratios_2) > 0: avg_ratios_2 = avg_ratios_2/len(tmp_ratios_2) for key in tmp_ratios_2: if tmp_ratios_2[key][1] > avg_ratios_2: if tmp_ratios_2[key][0]: ratios_2[key] = tmp_ratios_2[key][0] return {'sep': ratios_2, 'sfx': pos_final} def extract_training_sentence(self, sentence): ''' Input: a sentence (with "underscores" character) Output: the list of syllabus and labels (0 for "space" and 1 for "underscore" after each token) For instance: + Input: bùng_phát việc khai_thác tự_do mỏ sắt Trại_Bò + Output: - syls: ['bùng', 'phát', 'việc', 'khai', 'thác', 'tự', 'do', 'mỏ', 'sắt', 'Trại', 'Bò'] - lbls: [1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0] We have noted that the "label" at the end of a sentence always is "space"! (And no "label" at the begin of sentence) ''' syls, lbls, cur_idx = [], [], 0 stn = sentence + ' ' for idx, character in enumerate(stn): if character == ' ' or character == '_': if character == ' ': lbls.append(0) else: lbls.append(1) syls.append(stn[cur_idx:idx]) cur_idx = idx + 1 return syls, lbls def extract_syls_windows(self, syls, lbls, window_size=8): ''' Input: the list of syllabus and labels of training sentence Output: all syllabus windows (by padding at the begin and end of sentence and sliding!) ''' bi_lbl = copy.deepcopy(lbls) for i in range(window_size): syls = [self.bos] + syls + [self.eos] bi_lbl = [0] + bi_lbl + [0] return [[syls[i-window_size:i+window_size+1], bi_lbl[i-window_size:i+window_size+1]]\ for i in range(window_size, len(syls)-window_size)] def extract_syls_test_windows(self, syls, window_size=8): ''' Input: the list of syllabus of testing sentence Output: all syllabus windows (by padding at the begin and end of sentence and sliding!) ''' for i in range(window_size): syls = [self.bos] + syls + [self.eos] return [syls[i-window_size:i+window_size+1] for i in range(window_size, len(syls)-window_size)] def get_support(self, true_line, pred_line): ''' Input: + The dictionary of "true" and "predicted" line + The format of key is: [the begin position of word]_[the end position of word] + The format of value is: string of word Output: + Corrected prediction satisfies: both the predicted and true pair have the same key and value + Number of corrected words are segmented, number of words in "predicted" line, and number of word in "true" line ''' nb_correctly_segmented = 0 for key in pred_line.keys(): if key in true_line and pred_line[key] == true_line[key]: nb_correctly_segmented += 1 return nb_correctly_segmented, len(pred_line), len(true_line) def get_support_details(self, true_line, pred_line, unseen_words_sfx): ''' Input: + The dictionary of "true" and "predicted" line + The format of key is: [the begin position of word]_[the end position of word] + The format of value is: string of word Output: + Corrected prediction satisfies: both the predicted and true pair have the same key and value + Number of corrected words are segmented, number of words in "predicted" line, and number of word in "true" line ''' nb_correctly_segmented = {'1': 0, '2': 0, '3a': 0, '3b': 0, '4a': 0, '4b': 0, '5-9': 0, '10-': 0} nb_pred = {'1': 0, '2': 0, '3a': 0, '3b': 0, '4a': 0, '4b': 0, '5-9': 0, '10-': 0} nb_true = {'1': 0, '2': 0, '3a': 0, '3b': 0, '4a': 0, '4b': 0, '5-9': 0, '10-': 0} for key in pred_line.keys(): nb_syls = len(pred_line[key].split('_')) if 10 <= nb_syls: nb_syls = '10-' elif 5 <= nb_syls and nb_syls <= 9: nb_syls = '5-9' elif nb_syls in [3,4]: if pred_line[key].lower() in unseen_words_sfx: nb_syls = str(nb_syls) + 'b' else: nb_syls = str(nb_syls) + 'a' else: nb_syls = str(nb_syls) nb_pred[nb_syls] += 1 for key in true_line.keys(): nb_syls = len(true_line[key].split('_')) if 10 <= nb_syls: nb_syls = '10-' elif 5 <= nb_syls and nb_syls <= 9: nb_syls = '5-9' elif nb_syls in [3,4]: if true_line[key].lower() in unseen_words_sfx: nb_syls = str(nb_syls) + 'b' else: nb_syls = str(nb_syls) + 'a' else: nb_syls = str(nb_syls) nb_true[nb_syls] += 1 for key in true_line.keys(): nb_syls = len(true_line[key].split('_')) if 10 <= nb_syls: nb_syls = '10-' elif 5 <= nb_syls and nb_syls <= 9: nb_syls = '5-9' elif nb_syls in [3,4]: if true_line[key].lower() in unseen_words_sfx: nb_syls = str(nb_syls) + 'b' else: nb_syls = str(nb_syls) + 'a' else: nb_syls = str(nb_syls) if key in pred_line and pred_line[key] == true_line[key]: nb_correctly_segmented[nb_syls] += 1 return nb_correctly_segmented, nb_pred, nb_true def compute_score_details(self, list_stn, list_predict, unseen_words_sfx): nb_correct, nb_output, nb_ref = 0, 0, 0 nb_correct = {'1': 0, '2': 0, '3a': 0, '3b': 0, '4a': 0, '4b': 0, '5-9': 0, '10-': 0} nb_output = {'1': 0, '2': 0, '3a': 0, '3b': 0, '4a': 0, '4b': 0, '5-9': 0, '10-': 0} nb_ref = {'1': 0, '2': 0, '3a': 0, '3b': 0, '4a': 0, '4b': 0, '5-9': 0, '10-': 0} precision = {} recall = {} f1_score = {} for idx, stn in enumerate(list_stn): pred_sentence = list_predict[idx] n_c, n_p, n_r = self.get_support_details(self.exact_wordboundary(stn), self.exact_wordboundary(pred_sentence),\ unseen_words_sfx) for key in nb_correct.keys(): nb_correct[key] += n_c[key] nb_output[key] += n_p[key] nb_ref[key] += n_r[key] for key in nb_correct.keys(): if nb_output[key] > 0: precision[key] = 100*nb_correct[key]/nb_output[key] else: precision[key] = 0 if precision[key] > 0: recall[key] = 100*nb_correct[key]/nb_ref[key] else: recall[key] = 0 if precision[key]+recall[key] > 0: f1_score[key] = 2*precision[key]*recall[key]/(precision[key]+recall[key]) else: f1_score[key] = 0 performance_detail = {'precision': precision, 'recall': recall, 'f1_score': f1_score,\ 'nb_correct': nb_correct, 'nb_output': nb_output, 'nb_ref': nb_ref} nb_correct_total = sum(nb_correct.values()) nb_output_total = sum(nb_output.values()) nb_ref_total = sum(nb_ref.values()) precision_total = 100*nb_correct_total/nb_output_total recall_total = 100*nb_correct_total/nb_ref_total f1_score_total = 2*precision_total*recall_total/(precision_total+recall_total) performance_total = {'precision': precision_total, 'recall': recall_total, 'f1_score': f1_score_total} return performance_detail, performance_total def exact_wordboundary(self, line): ''' Input: + A sentence contains underscore characters Output: + The dictionary of the input line + The format of key is: [the begin position of word]_[the end position of word] + The format of value is: string of word ''' tokens = line.split() words = {} idx = 1 for token in tokens: length = len(token.split('_')) if length > 1: words[str(idx) + '-' + str(idx + length - 1)] = token else: words[str(idx + length - 1)] = token idx = idx + length return words def fill_underscore(self, syls, lbls): ''' This process is opposite with "extract_training_sentence" function We fill "underscore" or "space" base on their labels ''' output = '' for idx, word in enumerate(syls): output = output + word if lbls[idx] == 0: output = output + ' ' elif lbls[idx] == 1: output = output + '_' return output[:-1] def B_I_O_to_underscore_space(self, id2lbl, pos, stn): two_lbl = [] for idx, lbl in enumerate(pos): if idx == len(pos) - 1: two_lbl.append(0) else: if id2lbl[lbl] in ['B_W', 'I_W'] and id2lbl[pos[idx + 1]] == 'I_W': two_lbl.append(1) else: two_lbl.append(0) return self.fill_underscore(stn, two_lbl) def extract_training_pairs(self, training_sentences): X, Y = [], [] for sentence in training_sentences: syls, lbls = self.extract_training_sentence(sentence) syls_windows = self.extract_syls_windows(syls, lbls) X.extend(syls_windows) Y.extend(lbls) return X, Y def predict_list_of_sentence_ws(self, ws, NUM_PROCESSES, list_stn, get_support, has_underscore=False): NUM_JOBS = len(list_stn) nor_list = [self.normalize_accent(line) for line in list_stn] predicted_sentences = [None for i in range(NUM_JOBS)] if has_underscore: nb_correct, nb_output, nb_ref = 0, 0, 0 nb_stn_correct = 0 raw_list = [line.replace('_',' ') for line in nor_list] else: raw_list = nor_list def work(begin, end, return_dict): for i in range(begin, end): sentence = raw_list[i] syls = sentence.split(' ') syls_windows = self.extract_syls_test_windows(syls) y, y_lbl = [], [0, 0, 0, 0, 0, 0, 0, 0] for j in range(len(syls_windows)): y_tmp = ws['model'].predict(ws['vectorizer'].transform([[syls_windows[j], y_lbl]])) y_lbl.extend(y_tmp) y.extend(y_tmp) y_lbl = y_lbl[1:] return_dict[i] = self.fill_underscore(syls, y) if NUM_PROCESSES > 0: with Manager() as manager: return_dict = manager.dict() processes = [] batch_size = int(NUM_JOBS/NUM_PROCESSES) for i in range(NUM_PROCESSES): begin = i*batch_size end = begin + batch_size if i == NUM_PROCESSES - 1: end = NUM_JOBS processes.append(mp.Process(target=work, args=(begin, end, return_dict))) for p in processes: p.daemon = True p.start() for p in processes: p.join() p.terminate() for k, v in return_dict.items(): predicted_sentences[k] = v else: return_dict = {} work(0, NUM_JOBS, return_dict) for k, v in return_dict.items(): predicted_sentences[k] = v for idx, p_sentence in enumerate(predicted_sentences): if has_underscore: n_c, n_p, n_r = self.get_support(self.exact_wordboundary(nor_list[idx]), self.exact_wordboundary(p_sentence)) nb_correct += n_c nb_output += n_p nb_ref += n_r if n_c == n_p and n_c == n_r: nb_stn_correct += 1 if has_underscore: precision = nb_correct/nb_output recall = nb_correct/nb_ref if precision+recall > 0: f1_score = 2*precision*recall/(precision+recall) else: f1_score = 0 if get_support: return predicted_sentences, [nb_output, nb_ref, nb_correct] else: return predicted_sentences, [precision, recall, f1_score] return predicted_sentences
[ "unicodedata.normalize", "copy.deepcopy", "multiprocessing.Manager", "multiprocessing.Process" ]
[((3859, 3903), 'unicodedata.normalize', 'unicodedata.normalize', (['"""NFC"""', "(u'' + line_pos)"], {}), "('NFC', u'' + line_pos)\n", (3880, 3903), False, 'import unicodedata\n'), ((14261, 14280), 'copy.deepcopy', 'copy.deepcopy', (['lbls'], {}), '(lbls)\n', (14274, 14280), False, 'import copy\n'), ((24148, 24157), 'multiprocessing.Manager', 'Manager', ([], {}), '()\n', (24155, 24157), False, 'from multiprocessing import Manager\n'), ((24561, 24616), 'multiprocessing.Process', 'mp.Process', ([], {'target': 'work', 'args': '(begin, end, return_dict)'}), '(target=work, args=(begin, end, return_dict))\n', (24571, 24616), True, 'import multiprocessing as mp\n')]
import unittest import numpy as np from rastervision.core.class_map import (ClassItem, ClassMap) from rastervision.evaluations.segmentation_evaluation import ( SegmentationEvaluation) from rastervision.label_stores.segmentation_raster_file import ( SegmentationInputRasterFile) from rastervision.label_stores.segmentation_raster_file_test import ( TestingRasterSource) class TestSegmentationEvaluation(unittest.TestCase): def test_compute(self): class_map = ClassMap( [ClassItem(id=1, name='one'), ClassItem(id=2, name='two')]) raster_class_map = {'#010101': 1, '#020202': 2} gt_array = np.ones((5, 5, 3), dtype=np.uint8) gt_array[0, 0, :] = 0 gt_array[2, 2, :] = 2 gt_raster = TestingRasterSource(data=gt_array) gt_label_store = SegmentationInputRasterFile( source=gt_raster, raster_class_map=raster_class_map) p_array = np.ones((4, 4, 3), dtype=np.uint8) p_array[1, 1, :] = 0 p_raster = TestingRasterSource(data=p_array) p_label_store = SegmentationInputRasterFile( source=p_raster, raster_class_map=raster_class_map) seval = SegmentationEvaluation() seval.compute(class_map, gt_label_store, p_label_store) tp1 = 16 - 3 # 4*4 - 3 true positives for class 1 fp1 = 1 # 1 false positive (2,2) and one don't care at (0,0) fn1 = 1 # one false negative (1,1) precision1 = float(tp1) / (tp1 + fp1) recall1 = float(tp1) / (tp1 + fn1) tp2 = 0 # 0 true positives for class 2 fn2 = 1 # one false negative (2,2) precision2 = None # float(tp2) / (tp2 + fp2) where fp2 == 0 recall2 = float(tp2) / (tp2 + fn2) self.assertAlmostEqual(precision1, seval.class_to_eval_item[1].precision) self.assertAlmostEqual(recall1, seval.class_to_eval_item[1].recall) self.assertEqual(precision2, seval.class_to_eval_item[2].precision) self.assertAlmostEqual(recall2, seval.class_to_eval_item[2].recall) if __name__ == "__main__": unittest.main()
[ "unittest.main", "numpy.ones", "rastervision.core.class_map.ClassItem", "rastervision.label_stores.segmentation_raster_file.SegmentationInputRasterFile", "rastervision.label_stores.segmentation_raster_file_test.TestingRasterSource", "rastervision.evaluations.segmentation_evaluation.SegmentationEvaluation" ]
[((2129, 2144), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2142, 2144), False, 'import unittest\n'), ((658, 692), 'numpy.ones', 'np.ones', (['(5, 5, 3)'], {'dtype': 'np.uint8'}), '((5, 5, 3), dtype=np.uint8)\n', (665, 692), True, 'import numpy as np\n'), ((773, 807), 'rastervision.label_stores.segmentation_raster_file_test.TestingRasterSource', 'TestingRasterSource', ([], {'data': 'gt_array'}), '(data=gt_array)\n', (792, 807), False, 'from rastervision.label_stores.segmentation_raster_file_test import TestingRasterSource\n'), ((833, 918), 'rastervision.label_stores.segmentation_raster_file.SegmentationInputRasterFile', 'SegmentationInputRasterFile', ([], {'source': 'gt_raster', 'raster_class_map': 'raster_class_map'}), '(source=gt_raster, raster_class_map=raster_class_map\n )\n', (860, 918), False, 'from rastervision.label_stores.segmentation_raster_file import SegmentationInputRasterFile\n'), ((946, 980), 'numpy.ones', 'np.ones', (['(4, 4, 3)'], {'dtype': 'np.uint8'}), '((4, 4, 3), dtype=np.uint8)\n', (953, 980), True, 'import numpy as np\n'), ((1029, 1062), 'rastervision.label_stores.segmentation_raster_file_test.TestingRasterSource', 'TestingRasterSource', ([], {'data': 'p_array'}), '(data=p_array)\n', (1048, 1062), False, 'from rastervision.label_stores.segmentation_raster_file_test import TestingRasterSource\n'), ((1087, 1166), 'rastervision.label_stores.segmentation_raster_file.SegmentationInputRasterFile', 'SegmentationInputRasterFile', ([], {'source': 'p_raster', 'raster_class_map': 'raster_class_map'}), '(source=p_raster, raster_class_map=raster_class_map)\n', (1114, 1166), False, 'from rastervision.label_stores.segmentation_raster_file import SegmentationInputRasterFile\n'), ((1197, 1221), 'rastervision.evaluations.segmentation_evaluation.SegmentationEvaluation', 'SegmentationEvaluation', ([], {}), '()\n', (1219, 1221), False, 'from rastervision.evaluations.segmentation_evaluation import SegmentationEvaluation\n'), ((509, 536), 'rastervision.core.class_map.ClassItem', 'ClassItem', ([], {'id': '(1)', 'name': '"""one"""'}), "(id=1, name='one')\n", (518, 536), False, 'from rastervision.core.class_map import ClassItem, ClassMap\n'), ((551, 578), 'rastervision.core.class_map.ClassItem', 'ClassItem', ([], {'id': '(2)', 'name': '"""two"""'}), "(id=2, name='two')\n", (560, 578), False, 'from rastervision.core.class_map import ClassItem, ClassMap\n')]
from importlib.metadata import version try: __version__ = version(__name__) except: pass
[ "importlib.metadata.version" ]
[((63, 80), 'importlib.metadata.version', 'version', (['__name__'], {}), '(__name__)\n', (70, 80), False, 'from importlib.metadata import version\n')]
# Plot / Form # Display a plot inside a form. # --- from synth import FakeCategoricalSeries from h2o_wave import site, data, ui page = site['/demo'] n = 20 f = FakeCategoricalSeries() v = page.add('example', ui.form_card( box='1 1 4 5', items=[ ui.text_xl('Example 1'), ui.visualization( plot=ui.plot([ui.mark(type='interval', x='=product', y='=price', y_min=0)]), data=data(fields='product price', rows=[(c, x) for c, x, _ in [f.next() for _ in range(n)]], pack=True), ), ui.text_xl('Example 2'), ui.visualization( plot=ui.plot([ui.mark(type='interval', x='=product', y='=price', y_min=0)]), data=data(fields='product price', rows=[(c, x) for c, x, _ in [f.next() for _ in range(n)]], pack=True), ), ], )) page.save()
[ "h2o_wave.ui.text_xl", "synth.FakeCategoricalSeries", "h2o_wave.ui.mark" ]
[((162, 185), 'synth.FakeCategoricalSeries', 'FakeCategoricalSeries', ([], {}), '()\n', (183, 185), False, 'from synth import FakeCategoricalSeries\n'), ((263, 286), 'h2o_wave.ui.text_xl', 'ui.text_xl', (['"""Example 1"""'], {}), "('Example 1')\n", (273, 286), False, 'from h2o_wave import site, data, ui\n'), ((539, 562), 'h2o_wave.ui.text_xl', 'ui.text_xl', (['"""Example 2"""'], {}), "('Example 2')\n", (549, 562), False, 'from h2o_wave import site, data, ui\n'), ((340, 399), 'h2o_wave.ui.mark', 'ui.mark', ([], {'type': '"""interval"""', 'x': '"""=product"""', 'y': '"""=price"""', 'y_min': '(0)'}), "(type='interval', x='=product', y='=price', y_min=0)\n", (347, 399), False, 'from h2o_wave import site, data, ui\n'), ((616, 675), 'h2o_wave.ui.mark', 'ui.mark', ([], {'type': '"""interval"""', 'x': '"""=product"""', 'y': '"""=price"""', 'y_min': '(0)'}), "(type='interval', x='=product', y='=price', y_min=0)\n", (623, 675), False, 'from h2o_wave import site, data, ui\n')]
from django.db.models import Q from model_utils.models import now from rest_framework.filters import BaseFilterBackend class OwnerFilter(BaseFilterBackend): """过滤属于当前用户的数据""" def filter_queryset(self, request, queryset, view): current = request.user return queryset.filter(owner=current) class TimeRangeFilter(BaseFilterBackend): """时间区间过滤器""" def filter_queryset(self, request, queryset, view): return queryset.filter( Q(start__isnull=True) | Q(end__isnull=True) | Q(start__lte=now) | Q(end__gte=now)).filter( ~Q(start__gt=now)).filter(~Q(end__lt=now))
[ "django.db.models.Q" ]
[((608, 622), 'django.db.models.Q', 'Q', ([], {'end__lt': 'now'}), '(end__lt=now)\n', (609, 622), False, 'from django.db.models import Q\n'), ((582, 598), 'django.db.models.Q', 'Q', ([], {'start__gt': 'now'}), '(start__gt=now)\n', (583, 598), False, 'from django.db.models import Q\n'), ((544, 559), 'django.db.models.Q', 'Q', ([], {'end__gte': 'now'}), '(end__gte=now)\n', (545, 559), False, 'from django.db.models import Q\n'), ((524, 541), 'django.db.models.Q', 'Q', ([], {'start__lte': 'now'}), '(start__lte=now)\n', (525, 541), False, 'from django.db.models import Q\n'), ((478, 499), 'django.db.models.Q', 'Q', ([], {'start__isnull': '(True)'}), '(start__isnull=True)\n', (479, 499), False, 'from django.db.models import Q\n'), ((502, 521), 'django.db.models.Q', 'Q', ([], {'end__isnull': '(True)'}), '(end__isnull=True)\n', (503, 521), False, 'from django.db.models import Q\n')]
import math from scrollingtext import ScrollingText from widget import Widget class TextList(Widget): _text_margin = 1 _selected = None # type: None | int def __init__(self, position, size, font, empty_items_text): super(TextList, self).__init__(position, size) self._font = font self._emtpy_items_text = empty_items_text width = size[0] height = size[1] assert width > 0 assert height > 0 text_height = font.getsize("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")[1] assert text_height > 0 num_lines = int(math.ceil(float(height) / (text_height + self._text_margin))) self._lines = [] for i in range(0, num_lines): line_y = i * (text_height + self._text_margin) self._lines.append(ScrollingText( (self._text_margin, line_y), (width - 2 * self._text_margin, text_height), font, "" )) self._items = [] self._selected_item = None self._on_empty_items() def _middle_line(self): return self._lines[(len(self._lines) - 1) / 2] def _on_empty_items(self): self._reset_lines() self._middle_line().set_text(self._emtpy_items_text) self._middle_line().set_scroll(True) self._top_line_idx = None self._selected = None def _reset_lines(self): for l in self._lines: l.set_text("") l.set_invert(False) l.set_draw_border(False) l.set_scroll(False) @property def selected(self): return self._selected def set_selected(self, selected): self._selected = max(0, min(selected, len(self._items) - 1)) def set_items(self, items): self._items = items if len(items) == 0: self._selected = None self._on_empty_items() else: # noinspection PyTypeChecker if self._selected is None: self._selected = 0 elif self._selected >= len(items): self._selected = len(items) - 1 self._update_lines() self._need_refresh = True def select_next(self): if self._selected is not None: self._selected = (self._selected + 1) % len(self._items) self._update_lines() self._need_refresh = True def select_previous(self): if self._selected is not None: self._selected -= 1 if self._selected < 0: self._selected = len(self._items) + self._selected self._update_lines() self._need_refresh = True def tick(self): if self._selected_item is not None: self._selected_item.tick() def need_refresh(self): if super(TextList, self).need_refresh(): return True return self._selected_item is not None and self._selected_item.need_refresh() def _update_lines(self): self._reset_lines() # 0, 1, 2, ..., k-1 # 0 <= n <= k // window size # 0 <= i <= k # find 0 <= s <= k such that: # (s + n/2) mod k == i # s + n/2 = x*k + i k = len(self._items) n = min(k, len(self._lines)) s = self._selected - n / 2 + 1 # if s < 0: # s += k if s < 0: s = 0 elif s + n > k: s = k - n # make bottom line fully visible if it is selected text_height = self._lines[0].size[1] num_lines = len(self._lines) if k * (text_height + self._text_margin) > self.size[1]: if self._selected == k - 1: y = self.size[1] - text_height for i in range(0, num_lines): line = self._lines[num_lines - i - 1] line.set_position((self._text_margin, y)) y -= text_height y -= self._text_margin else: for i in range(0, num_lines): y = i * (text_height + self._text_margin) line = self._lines[i] line.set_position((self._text_margin, y)) for i in range(0, n): line = self._lines[i] line.set_text(self._items[s]) line.set_scroll(s == self._selected) line.set_invert(s == self._selected) if s == self._selected: self._selected_item = line s = (s + 1) % k def _draw(self, img, draw): super(TextList, self)._draw(img, draw) for l in self._lines: l.refresh(img, draw)
[ "scrollingtext.ScrollingText" ]
[((829, 931), 'scrollingtext.ScrollingText', 'ScrollingText', (['(self._text_margin, line_y)', '(width - 2 * self._text_margin, text_height)', 'font', '""""""'], {}), "((self._text_margin, line_y), (width - 2 * self._text_margin,\n text_height), font, '')\n", (842, 931), False, 'from scrollingtext import ScrollingText\n')]
"""Monty hall paradox Wiki: https://en.wikipedia.org/wiki/Fermat_primality_test """ import math import random def ferma(number: int, k: int = 100) -> bool: """Тест простоты Ферма Wiki: https://en.wikipedia.org/wiki/Fermat_primality_test :param number: проверяемое число :type number: int :param k: количество тестов :type k: int, default 100 :return: True если число псевдопростое, False если составное :rtype: bool """ if number == 2: return True for _ in range(1, k + 1): random_number = (random.randint(1, number) % (number - 2)) + 2 # проверка на взаимную простоту чисел random_number и number if math.gcd(random_number, number) != 1: return False # проверка условия теоремы Ферма, с использованием возведения # числа в степень по модулю if pow(random_number, number - 1, number) != 1: return False return True
[ "random.randint", "math.gcd" ]
[((696, 727), 'math.gcd', 'math.gcd', (['random_number', 'number'], {}), '(random_number, number)\n', (704, 727), False, 'import math\n'), ((570, 595), 'random.randint', 'random.randint', (['(1)', 'number'], {}), '(1, number)\n', (584, 595), False, 'import random\n')]
"""Snakemake wrapper for PALADIN alignment""" __author__ = "<NAME>" __copyright__ = "Copyright 2019, <NAME>" __email__ = "<EMAIL>" __license__ = "MIT" from os import path from snakemake.shell import shell extra = snakemake.params.get("extra", "") log = snakemake.log_fmt_shell(stdout=False, stderr=True) r = snakemake.input.get("r") assert r is not None, "reads are required as input" index = snakemake.input.get("index") assert index is not None, "please index your assembly and provide the basename (with'.bwt' extension) via the 'index' input param" index_base = str(index).rsplit('.bwt')[0] outfile = snakemake.output # if bam output, pipe to bam! output_cmd = " | samtools view -Sb - > " if str(outfile).endswith('.bam') else " -o " min_orf_len = snakemake.params.get('f', '250') shell("paladin align -f {min_orf_len} -t {snakemake.threads} {extra} {index_base} {r} {output_cmd} {outfile}")
[ "snakemake.shell.shell" ]
[((796, 916), 'snakemake.shell.shell', 'shell', (['"""paladin align -f {min_orf_len} -t {snakemake.threads} {extra} {index_base} {r} {output_cmd} {outfile}"""'], {}), "(\n 'paladin align -f {min_orf_len} -t {snakemake.threads} {extra} {index_base} {r} {output_cmd} {outfile}'\n )\n", (801, 916), False, 'from snakemake.shell import shell\n')]
import numpy as np import matplotlib.pyplot as plt # %matplotlib inline 缩放 plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (12, 8) # Normal distributed x and y vector with mean 0 and standard deviation 1 x = np.random.normal(0, 1, 200) y = np.random.normal(0, 1, 200) X = np.vstack((x, y)) # 2xn # 缩放 sx, sy = 0.5, 2.0 Scale = np.array([[sx, 0], [0, sy]]) Y = Scale.dot(X) # 原始点集 plt.scatter(X[0, :], X[1, :]) # 缩放后点 plt.scatter(Y[0, :], Y[1, :]) plt.title('Generated Data') plt.axis('equal') plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.scatter", "matplotlib.pyplot.axis", "matplotlib.pyplot.style.use", "numpy.array", "numpy.random.normal", "numpy.vstack" ]
[((76, 99), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (89, 99), True, 'import matplotlib.pyplot as plt\n'), ((219, 246), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(200)'], {}), '(0, 1, 200)\n', (235, 246), True, 'import numpy as np\n'), ((251, 278), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(200)'], {}), '(0, 1, 200)\n', (267, 278), True, 'import numpy as np\n'), ((283, 300), 'numpy.vstack', 'np.vstack', (['(x, y)'], {}), '((x, y))\n', (292, 300), True, 'import numpy as np\n'), ((339, 367), 'numpy.array', 'np.array', (['[[sx, 0], [0, sy]]'], {}), '([[sx, 0], [0, sy]])\n', (347, 367), True, 'import numpy as np\n'), ((393, 422), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X[0, :]', 'X[1, :]'], {}), '(X[0, :], X[1, :])\n', (404, 422), True, 'import matplotlib.pyplot as plt\n'), ((430, 459), 'matplotlib.pyplot.scatter', 'plt.scatter', (['Y[0, :]', 'Y[1, :]'], {}), '(Y[0, :], Y[1, :])\n', (441, 459), True, 'import matplotlib.pyplot as plt\n'), ((460, 487), 'matplotlib.pyplot.title', 'plt.title', (['"""Generated Data"""'], {}), "('Generated Data')\n", (469, 487), True, 'import matplotlib.pyplot as plt\n'), ((488, 505), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (496, 505), True, 'import matplotlib.pyplot as plt\n'), ((506, 516), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (514, 516), True, 'import matplotlib.pyplot as plt\n')]
import mock from six import StringIO from grab import GrabTimeoutError, Grab from grab.spider import Spider, Task from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL # That URLs breaks Grab's URL normalization process # with error "label empty or too long" INVALID_URL = 'http://13354&altProductId=6423589&productId=6423589'\ '&altProductStoreId=13713&catalogId=10001'\ '&categoryId=28678&productStoreId=13713'\ 'http://www.textbooksnow.com/webapp/wcs/stores'\ '/servlet/ProductDisplay?langId=-1&storeId=' class SpiderErrorTestCase(BaseGrabTestCase): def setUp(self): self.server.reset() def test_generator_with_invalid_url(self): class SomeSpider(Spider): def task_generator(self): yield Task('page', url=INVALID_URL) bot = build_spider(SomeSpider) bot.run() def test_redirect_with_invalid_url(self): server = self.server class TestSpider(Spider): def task_generator(self): # pylint: disable=attribute-defined-outside-init self.done_counter = 0 # pylint: enable=attribute-defined-outside-init yield Task('page', url=server.get_url()) def task_page(self, grab, task): pass self.server.response_once['code'] = 301 self.server.response_once['headers'] = [ ('Location', INVALID_URL), ] bot = build_spider(TestSpider, network_try_limit=1) bot.run() # FIXME: fix # That test case ruins the spider instance :( #def test_redirect_with_invalid_byte(self): # url = self.server.get_url() # invalid_url = b'http://\xa0' + url.encode('ascii') # def callback(server): # server.set_status(301) # server.add_header('Location', invalid_url) # server.write('') # server.finish() # class TestSpider(Spider): # def task_generator(self): # #yield Task('page', url='http://www.tripadvisor.com/ShowUrl? # #&excludeFromVS=false&odc=BusinessListingsUrl&d=4289178&url=1') # #yield Task('page', invalid_url) # yield Task('page', url) # # def task_page(self, grab, task): # pass # # self.server.response['callback'] = callback # bot = build_spider(TestSpider) # bot.run() def test_no_warning(self): """Simple spider should not generate any warnings (warning module sends messages to stderr) """ out = StringIO() with mock.patch('sys.stderr', out): server = self.server server.response['data'] = b'<div>test</div>' class SimpleSpider(Spider): # pylint: disable=unused-argument initial_urls = [server.get_url()] def task_initial(self, grab, task): yield Task('more', url=server.get_url()) def task_more(self, grab, task): #print(grab.doc.url) grab.doc('//div').text() bot = build_spider(SimpleSpider) bot.run() self.assertTrue(out.getvalue() == '') def test_grab_attribute_exception(self): server = self.server server.response['sleep'] = 2 class SimpleSpider(Spider): def task_generator(self): grab = Grab() grab.setup(url=server.get_url(), timeout=1) yield Task('page', grab=grab, raw=True) def task_page(self, grab, unused_task): self.meta['exc'] = grab.exception bot = build_spider(SimpleSpider) bot.run() self.assertTrue(isinstance(bot.meta['exc'], GrabTimeoutError)) @run_test_if(lambda: (GLOBAL['network_service'] == 'multicurl' and GLOBAL['grab_transport'] == 'pycurl'), 'multicurl & pycurl') def test_stat_error_name_multi_pycurl(self): server = self.server server.response['sleep'] = 2 class SimpleSpider(Spider): def prepare(self): self.network_try_limit = 1 def task_generator(self): grab = Grab(url=server.get_url(), timeout=1) yield Task('page', grab=grab) def task_page(self, grab, unused_task): pass bot = build_spider(SimpleSpider) bot.run() self.assertTrue('error:operation-timeouted' in bot.stat.counters) @run_test_if(lambda: (GLOBAL['network_service'] == 'threaded' and GLOBAL['grab_transport'] == 'pycurl'), 'threaded & pycurl') def test_stat_error_name_threaded_pycurl(self): server = self.server server.response['sleep'] = 2 class SimpleSpider(Spider): def prepare(self): self.network_try_limit = 1 def task_generator(self): grab = Grab(url=server.get_url(), timeout=1) yield Task('page', grab=grab) def task_page(self, grab, unused_task): pass bot = build_spider(SimpleSpider) bot.run() print(bot.stat.counters) self.assertTrue('error:grab-timeout-error' in bot.stat.counters) @run_test_if(lambda: (GLOBAL['network_service'] == 'threaded' and GLOBAL['grab_transport'] == 'urllib3'), 'threaded & urllib3') def test_stat_error_name_threaded_urllib3(self): server = self.server server.response['sleep'] = 2 class SimpleSpider(Spider): def prepare(self): self.network_try_limit = 1 def task_generator(self): grab = Grab(url=server.get_url(), timeout=1) yield Task('page', grab=grab) def task_page(self, grab, unused_task): pass bot = build_spider(SimpleSpider) bot.run() self.assertTrue('error:read-timeout-error' in bot.stat.counters)
[ "grab.Grab", "tests.util.build_spider", "mock.patch", "six.StringIO", "grab.spider.Task", "tests.util.run_test_if" ]
[((3930, 4060), 'tests.util.run_test_if', 'run_test_if', (["(lambda : GLOBAL['network_service'] == 'multicurl' and GLOBAL[\n 'grab_transport'] == 'pycurl')", '"""multicurl & pycurl"""'], {}), "(lambda : GLOBAL['network_service'] == 'multicurl' and GLOBAL[\n 'grab_transport'] == 'pycurl', 'multicurl & pycurl')\n", (3941, 4060), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((4687, 4815), 'tests.util.run_test_if', 'run_test_if', (["(lambda : GLOBAL['network_service'] == 'threaded' and GLOBAL[\n 'grab_transport'] == 'pycurl')", '"""threaded & pycurl"""'], {}), "(lambda : GLOBAL['network_service'] == 'threaded' and GLOBAL[\n 'grab_transport'] == 'pycurl', 'threaded & pycurl')\n", (4698, 4815), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((5477, 5607), 'tests.util.run_test_if', 'run_test_if', (["(lambda : GLOBAL['network_service'] == 'threaded' and GLOBAL[\n 'grab_transport'] == 'urllib3')", '"""threaded & urllib3"""'], {}), "(lambda : GLOBAL['network_service'] == 'threaded' and GLOBAL[\n 'grab_transport'] == 'urllib3', 'threaded & urllib3')\n", (5488, 5607), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((872, 896), 'tests.util.build_spider', 'build_spider', (['SomeSpider'], {}), '(SomeSpider)\n', (884, 896), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((1517, 1562), 'tests.util.build_spider', 'build_spider', (['TestSpider'], {'network_try_limit': '(1)'}), '(TestSpider, network_try_limit=1)\n', (1529, 1562), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((2652, 2662), 'six.StringIO', 'StringIO', ([], {}), '()\n', (2660, 2662), False, 'from six import StringIO\n'), ((3808, 3834), 'tests.util.build_spider', 'build_spider', (['SimpleSpider'], {}), '(SimpleSpider)\n', (3820, 3834), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((4562, 4588), 'tests.util.build_spider', 'build_spider', (['SimpleSpider'], {}), '(SimpleSpider)\n', (4574, 4588), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((5320, 5346), 'tests.util.build_spider', 'build_spider', (['SimpleSpider'], {}), '(SimpleSpider)\n', (5332, 5346), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((6113, 6139), 'tests.util.build_spider', 'build_spider', (['SimpleSpider'], {}), '(SimpleSpider)\n', (6125, 6139), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((2676, 2705), 'mock.patch', 'mock.patch', (['"""sys.stderr"""', 'out'], {}), "('sys.stderr', out)\n", (2686, 2705), False, 'import mock\n'), ((3207, 3233), 'tests.util.build_spider', 'build_spider', (['SimpleSpider'], {}), '(SimpleSpider)\n', (3219, 3233), False, 'from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL\n'), ((3513, 3519), 'grab.Grab', 'Grab', ([], {}), '()\n', (3517, 3519), False, 'from grab import GrabTimeoutError, Grab\n'), ((827, 856), 'grab.spider.Task', 'Task', (['"""page"""'], {'url': 'INVALID_URL'}), "('page', url=INVALID_URL)\n", (831, 856), False, 'from grab.spider import Spider, Task\n'), ((3629, 3662), 'grab.spider.Task', 'Task', (['"""page"""'], {'grab': 'grab', 'raw': '(True)'}), "('page', grab=grab, raw=True)\n", (3633, 3662), False, 'from grab.spider import Spider, Task\n'), ((4449, 4472), 'grab.spider.Task', 'Task', (['"""page"""'], {'grab': 'grab'}), "('page', grab=grab)\n", (4453, 4472), False, 'from grab.spider import Spider, Task\n'), ((5207, 5230), 'grab.spider.Task', 'Task', (['"""page"""'], {'grab': 'grab'}), "('page', grab=grab)\n", (5211, 5230), False, 'from grab.spider import Spider, Task\n'), ((6000, 6023), 'grab.spider.Task', 'Task', (['"""page"""'], {'grab': 'grab'}), "('page', grab=grab)\n", (6004, 6023), False, 'from grab.spider import Spider, Task\n')]
from flask_wtf import FlaskForm from wtforms import StringField,PasswordField,SubmitField,BooleanField from wtforms.validators import DataRequired,EqualTo,Email from ..models import User from wtforms import ValidationError class RegistrationForm(FlaskForm): email=StringField('Your email address',validators=[DataRequired(),Email()]) username=StringField('your username',validators=[DataRequired()]) password=PasswordField('Your password',validators=[DataRequired(),EqualTo('password_confirm',message='password must match')]) password_confirm=PasswordField('Confirm Passwords',validators=[DataRequired()]) submit=SubmitField('submit') def validate_email(self,data_field): if User.query.filter_by(email=data_field.data).first(): raise ValidationError("email already exists") def validate_username(self,data_field): if User.query.filter_by(username=data_field.data).first(): raise ValidationError("username already exists") class LoginForm(FlaskForm): email=StringField('Your email address',validators=[DataRequired(),Email()]) password=PasswordField('Password',validators=[DataRequired()]) remember=BooleanField('remember me') submit=SubmitField('submit') class BlogForm(FlaskForm): title=StringField('Your Title',validators=[DataRequired()]) content=StringField('Content',validators=[DataRequired()]) submit = SubmitField('submit') class CommentForm(FlaskForm): comment=StringField('comment',validators=[DataRequired()]) submit = SubmitField('submit') class SubscriberForm(FlaskForm): email = StringField('Your email address', validators=[DataRequired(), Email()]) submit = SubmitField('submit')
[ "wtforms.ValidationError", "wtforms.validators.Email", "wtforms.BooleanField", "wtforms.SubmitField", "wtforms.validators.EqualTo", "wtforms.validators.DataRequired" ]
[((635, 656), 'wtforms.SubmitField', 'SubmitField', (['"""submit"""'], {}), "('submit')\n", (646, 656), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1184, 1211), 'wtforms.BooleanField', 'BooleanField', (['"""remember me"""'], {}), "('remember me')\n", (1196, 1211), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1223, 1244), 'wtforms.SubmitField', 'SubmitField', (['"""submit"""'], {}), "('submit')\n", (1234, 1244), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1413, 1434), 'wtforms.SubmitField', 'SubmitField', (['"""submit"""'], {}), "('submit')\n", (1424, 1434), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1541, 1562), 'wtforms.SubmitField', 'SubmitField', (['"""submit"""'], {}), "('submit')\n", (1552, 1562), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1693, 1714), 'wtforms.SubmitField', 'SubmitField', (['"""submit"""'], {}), "('submit')\n", (1704, 1714), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((782, 821), 'wtforms.ValidationError', 'ValidationError', (['"""email already exists"""'], {}), "('email already exists')\n", (797, 821), False, 'from wtforms import ValidationError\n'), ((952, 994), 'wtforms.ValidationError', 'ValidationError', (['"""username already exists"""'], {}), "('username already exists')\n", (967, 994), False, 'from wtforms import ValidationError\n'), ((315, 329), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (327, 329), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((330, 337), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (335, 337), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((393, 407), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (405, 407), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((465, 479), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (477, 479), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((480, 538), 'wtforms.validators.EqualTo', 'EqualTo', (['"""password_confirm"""'], {'message': '"""password must match"""'}), "('password_confirm', message='password must match')\n", (487, 538), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((607, 621), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (619, 621), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((1079, 1093), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1091, 1093), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((1094, 1101), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (1099, 1101), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((1154, 1168), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1166, 1168), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((1320, 1334), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1332, 1334), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((1383, 1397), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1395, 1397), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((1511, 1525), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1523, 1525), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((1654, 1668), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1666, 1668), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n'), ((1670, 1677), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (1675, 1677), False, 'from wtforms.validators import DataRequired, EqualTo, Email\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 11 16:22:17 2021 @author: mike_ubuntu """ import numpy as np from functools import reduce import copy import gc import time import datetime import pickle import warnings import epde.globals as global_var import torch from epde.decorators import History_Extender, Reset_equation_status from epde.interface.token_family import TF_Pool from epde.factor import Factor from epde.supplementary import Filter_powers, Population_Sort, flatten import epde.moeadd.moeadd_stc as moeadd def Check_Unqueness(obj, background): return not any([elem == obj for elem in background]) def normalize_ts(Input): # print('normalize_ts Input:', Input) matrix = np.copy(Input) # print(Matrix.shape) if np.ndim(matrix) == 0: raise ValueError('Incorrect input to the normalizaton: the data has 0 dimensions') elif np.ndim(matrix) == 1: return matrix else: for i in np.arange(matrix.shape[0]): # print(matrix[i].shape) std = np.std(matrix[i]) if std != 0: matrix[i] = (matrix[i] - np.mean(matrix[i])) / std else: matrix[i] = 1 return matrix class Complex_Structure(object): def __init__(self, interelement_operator = np.add, *params): self._history = '' self.structure = None self.interelement_operator = interelement_operator def __eq__(self, other): if type(other) != type(self): raise ValueError('Type of self and other are different') return (all([any([other_elem == self_elem for other_elem in other.structure]) for self_elem in self.structure]) and all([any([other_elem == self_elem for self_elem in self.structure]) for other_elem in other.structure]) and len(other.structure) == len(self.structure)) def set_evaluator(self, evaluator): raise NotImplementedError('Functionality of this method has been moved to the evolutionary operator declaration') def evaluate(self, structural = False): assert len(self.structure) > 0, 'Attempt to evaluate an empty complex structure' if len(self.structure) == 1: return self.structure[0].evaluate(structural) else: # print([type(elem) for elem in self.structure]) return reduce(lambda x, y: self.interelement_operator(x, y.evaluate(structural)), self.structure[1:], self.structure[0].evaluate(structural)) def reset_saved_state(self): self.saved = {True:False, False:False} self.saved_as = {True:None, False:None} for elem in self.structure: elem.reset_saved_state() @property def name(self): pass class Term(Complex_Structure): __slots__ = ['_history', 'structure', 'interelement_operator', 'saved', 'saved_as', 'pool', 'max_factors_in_term', 'cache_linked', 'occupied_tokens_labels'] def __init__(self, pool, passed_term = None, max_factors_in_term = 1, forbidden_tokens = None, interelement_operator = np.multiply): super().__init__(interelement_operator) self.pool = pool self.max_factors_in_term = max_factors_in_term if type(passed_term) == type(None): self.Randomize(forbidden_tokens) else: self.Defined(passed_term) if type(global_var.tensor_cache) != type(None): self.use_cache() self.reset_saved_state() # key - state of normalization, value - if the variable is saved in cache @property def cache_label(self): if len(self.structure) > 1: structure_sorted = sorted(self.structure, key = lambda x: x.cache_label) cache_label = tuple([elem.cache_label for elem in structure_sorted])#reduce(form_label, structure_sorted, '') else: cache_label = self.structure[0].cache_label return cache_label def use_cache(self): self.cache_linked = True # print('structure:', self.structure) for idx, _ in enumerate(self.structure): if not self.structure[idx].cache_linked: self.structure[idx].use_cache() def Defined(self, passed_term): self.structure = [] print('passed_term:', passed_term) if isinstance(passed_term, (list, tuple)): #type(passed_term) == list or type(passed_term) == tuple: for i, factor in enumerate(passed_term): if type(factor) == str: _, temp_f = self.pool.create(label = factor) self.structure.append(temp_f)#; raise NotImplementedError elif type(factor) == Factor: self.structure.append(factor) else: raise ValueError('The structure of a term should be declared with str or factor.Factor obj, instead got', type(factor)) else: # Случай, если подается лишь 1 токен if type(passed_term) == str: _, temp_f = self.pool.create(label = passed_term) self.structure.append(temp_f)#; raise NotImplementedError elif type(passed_term) == Factor: self.structure.append(passed_term) else: raise ValueError('The structure of a term should be declared with str or factor.Factor obj, instead got', type(passed_term)) def Randomize(self, forbidden_factors = None, **kwargs): if np.sum(self.pool.families_cardinality(meaningful_only = True)) == 0: raise ValueError('No token families are declared as meaningful for the process of the system search') factors_num = np.random.randint(1, self.max_factors_in_term +1) while True: self.occupied_tokens_labels = [] occupied_by_factor, factor = self.pool.create(label = None, create_meaningful = True, occupied = self.occupied_tokens_labels, **kwargs) self.structure = [factor,] self.occupied_tokens_labels.extend(occupied_by_factor) factors_powers = {factor.label : 1} for i in np.arange(1, factors_num): occupied_by_factor, factor = self.pool.create(label = None, create_meaningful = False, occupied = self.occupied_tokens_labels, def_term_tokens = [token.label for token in self.structure], **kwargs) if factor.label in factors_powers: factors_powers[factor.label] += 1 else: factors_powers[factor.label] = 1 for param_idx, param_descr in factor.params_description.items(): if param_descr['name'] == 'power': power_param_idx = param_idx if factors_powers[factor.label] == factor.params_description[power_param_idx]['bounds'][1]: self.occupied_tokens_labels.append(factor.label) self.structure.append(factor) self.occupied_tokens_labels.extend(occupied_by_factor) self.structure = Filter_powers(self.structure) if type(forbidden_factors) == type(None): break elif all([(Check_Unqueness(factor, forbidden_factors) or not factor.status['unique_for_right_part']) for factor in self.structure]): break def evaluate(self, structural): assert type(global_var.tensor_cache) != type(None), 'Currently working only with connected cache' normalize = structural if self.saved[structural] or (self.cache_label, normalize) in global_var.tensor_cache: # value = global_var.tensor_cache.get(self.cache_label, normalized = normalize, saved_as = self.saved_as[normalize]) value = value.reshape(value.size) return value else: self.prev_normalized = normalize value = super().evaluate(structural) if normalize and np.ndim(value) != 1: value = normalize_ts(value) elif normalize and np.ndim(value) == 1 and np.std(value) != 0: value = (value - np.mean(value))/np.std(value) elif normalize and np.ndim(value) == 1 and np.std(value) == 0: value = (value - np.mean(value)) if np.all([len(factor.params) == 1 for factor in self.structure]): self.saved[normalize] = global_var.tensor_cache.add(self.cache_label, value, normalized = normalize) # Место возможных проблем: сохранение/загрузка нормализованных данных if self.saved[normalize]: self.saved_as[normalize] = self.cache_label value = value.reshape(value.size) return value def Filter_tokens_by_right_part(self, reference_target, equation, equation_position): taken_tokens = [factor.label for factor in reference_target.structure if factor.status['unique_for_right_part']] meaningful_taken = any([factor.status['meaningful'] for factor in reference_target.structure if factor.status['unique_for_right_part']]) accept_term_try = 0 while True: accept_term_try += 1 new_term = copy.deepcopy(self) for factor_idx, factor in enumerate(new_term.structure): if factor.label in taken_tokens: new_term.Reset_occupied_tokens() _, new_term.structure[factor_idx] = self.pool.create(create_meaningful=meaningful_taken, occupied = new_term.occupied_tokens_labels + taken_tokens) # print('try:', accept_term_try, 'suggested:', new_term.name) #Возможная ошибка из-за (не) использования "create meaningful" if Check_Unqueness(new_term, equation.structure[:equation_position] + equation.structure[equation_position + 1 :]): self.structure = new_term.structure self.structure = Filter_powers(self.structure) self.reset_saved_state() break if accept_term_try == 10: warnings.warn('Can not create unique term, while filtering equation tokens in regards to the right part.') if accept_term_try >= 10: self.Randomize(forbidden_factors = new_term.occupied_tokens_labels + taken_tokens) if accept_term_try == 100: print('Something wrong with the random generation of term while running "Filter_tokens_by_right_part"') print('proposed', new_term.name, 'for ', equation.text_form, 'with respect to', reference_target.name) def Reset_occupied_tokens(self): occupied_tokens_new = [] for factor in self.structure: for token_family in self.pool.families: if factor in token_family.tokens and factor.status['unique_token_type']: occupied_tokens_new.extend([token for token in token_family.tokens]) elif factor.status['unique_specific_token']: occupied_tokens_new.append(factor.label) self.occupied_tokens_labels = occupied_tokens_new @property def available_tokens(self): #Переделать, т.к. меняется пул токенов: старая имплементация через лист available_tokens = [] for token in self.pool.families: if not all([label in self.occupied_tokens_labels for label in token.tokens]): token_new = copy.deepcopy(token) token_new.tokens = [label for label in token.tokens if label not in self.occupied_tokens_labels] available_tokens.append(token_new) return available_tokens @property def total_params(self): return max(sum([len(element.params) - 1 for element in self.structure]), 1) @property def name(self): form = '' for token_idx in range(len(self.structure)): form += self.structure[token_idx].name if token_idx < len(self.structure) - 1: form += ' * ' return form @property def contains_deriv(self): return any([factor.is_deriv and factor.deriv_code != [None,] for factor in self.structure]) @property def solver_form(self): deriv_orders = [] deriv_powers = [] try: coeff_tensor = np.ones_like(global_var.grid_cache.get('0')) except KeyError: raise NotImplementedError('No cache implemented') for factor in self.structure: if factor.is_deriv: for param_idx, param_descr in factor.params_description.items(): if param_descr['name'] == 'power': power_param_idx = param_idx deriv_orders.append(factor.deriv_code); deriv_powers.append(factor.params[power_param_idx]) else: coeff_tensor = coeff_tensor * factor.evaluate() # deriv_orders.append(factor.deriv_code); deriv_powers.append(1) if len(deriv_powers) == 1: deriv_powers = deriv_powers[0] deriv_orders = deriv_orders[0] coeff_tensor = torch.from_numpy(coeff_tensor) return [coeff_tensor, deriv_orders, deriv_powers] def __eq__(self, other): return (all([any([other_elem == self_elem for other_elem in other.structure]) for self_elem in self.structure]) and all([any([other_elem == self_elem for self_elem in self.structure]) for other_elem in other.structure]) and len(other.structure) == len(self.structure)) class Equation(Complex_Structure): __slots__ = ['_history', 'structure', 'interelement_operator', 'saved', 'saved_as', 'n_immutable', 'pool', 'terms_number', 'max_factors_in_term', 'operator', '_target', 'target_idx', '_features', 'right_part_selected', '_weights_final', 'weights_final_evald', '_weights_internal', 'weights_internal_evald', 'fitness_calculated', 'solver_form_defined', '_solver_form', '_fitness_value', 'crossover_selected_times', 'elite'] def __init__(self, pool, basic_structure, terms_number = 6, max_factors_in_term = 2, interelement_operator = np.add): #eq_weights_eval """ Class for the single equation for the dynamic system. attributes: structure : list of Term objects \r\n List, containing all terms of the equation; first 2 terms are reserved for constant value and the input function; target_idx : int \r\n Index of the target term, selected in the Split phase; target : 1-d array of float \r\n values of the Term object, reshaped into 1-d array, designated as target for application in sparse regression; features : matrix of float \r\n matrix, composed of terms, not included in target, value columns, designated as features for application in sparse regression; fitness_value : float \r\n Inverse value of squared error for the selected target 2function and features and discovered weights; estimator : sklearn estimator of selected type \r\n parameters: Matrix of derivatives: first axis through various orders/coordinates in order: ['1', 'f', all derivatives by one coordinate axis in increasing order, ...]; second axis: time, further - spatial coordinates; tokens : list of strings \r\n Symbolic forms of functions, including derivatives; terms_number : int, base value of 6 \r\n Maximum number of terms in the discovered equation; max_factors_in_term : int, base value of 2\r\n Maximum number of factors, that can form a term (e.g. with 2: df/dx_1 * df/dx_2) """ super().__init__(interelement_operator) self.reset_state() self.n_immutable = len(basic_structure) # print('n_immutable', self.n_immutable) self.pool = pool self.structure = [] self.terms_number = terms_number; self.max_factors_in_term = max_factors_in_term self.operator = None if (terms_number < self.n_immutable): raise Exception('Number of terms ({}) is too low to even contain all of the pre-determined ones'.format(terms_number)) for passed_term in basic_structure: if isinstance(passed_term, Term): self.structure.append(passed_term) elif isinstance(passed_term, str): self.structure.append(Term(self.pool, passed_term = passed_term, max_factors_in_term = self.max_factors_in_term)) for i in range(len(basic_structure), terms_number): check_test = 0 while True: check_test += 1 new_term = Term(self.pool, max_factors_in_term = self.max_factors_in_term, passed_term = None) if Check_Unqueness(new_term, self.structure): break self.structure.append(new_term) for idx, _ in enumerate(self.structure): self.structure[idx].use_cache() @property def contains_deriv(self): return any([term.contains_deriv for term in self.structure]) @property def forbidden_token_labels(self): target_symbolic = [factor.label for factor in self.structure[self.target_idx].structure] forbidden_tokens = set() for token_family in self.pool.families: for token in token_family.tokens: if token in target_symbolic and token_family.status['unique_for_right_part']: forbidden_tokens.add(token) return forbidden_tokens def reconstruct_to_contain_deriv(self): while True: replacement_idx = np.random.randint(low = 0, high = len(self.structure)) temp = Term(self.pool, max_factors_in_term=self.max_factors_in_term) # , forbidden_tokens=self.forbidden_token_labels if temp.contains_deriv: self.structure[replacement_idx] = temp break def reconstruct_by_right_part(self, right_part_idx): new_eq = copy.deepcopy(self) self.copy_properties_to(new_eq) new_eq.target_idx = right_part_idx if any([factor.status['unique_for_right_part'] for factor in new_eq.structure[right_part_idx].structure]): for term_idx, term in enumerate(new_eq.structure): if term_idx != right_part_idx: term.Filter_tokens_by_right_part(new_eq.structure[right_part_idx], self, term_idx) new_eq.reset_saved_state() return new_eq def evaluate(self, normalize = True, return_val = False, save = True): self._target = self.structure[self.target_idx].evaluate(normalize) feature_indexes = list(range(len(self.structure))) feature_indexes.remove(self.target_idx) for feat_idx in range(len(feature_indexes)): if feat_idx == 0: self._features = self.structure[feature_indexes[feat_idx]].evaluate(normalize) elif feat_idx != 0: temp = self.structure[feature_indexes[feat_idx]].evaluate(normalize) self._features = np.vstack([self._features, temp]) else: continue if self._features.ndim == 1: self._features = np.expand_dims(self._features, 1) temp_feats = np.vstack([self._features, np.ones(self._features.shape[1])]) self._features = np.transpose(self._features); temp_feats = np.transpose(temp_feats) if return_val: self.prev_normalized = normalize if normalize: elem1 = np.expand_dims(self._target, axis = 1) value = np.add(elem1, - reduce(lambda x,y: np.add(x, y), [np.multiply(weight, temp_feats[:,feature_idx]) for feature_idx, weight in np.ndenumerate(self.weights_internal)])) else: elem1 = np.expand_dims(self._target, axis = 1) value = np.add(elem1, - reduce(lambda x,y: np.add(x, y), [np.multiply(weight, temp_feats[:,feature_idx]) for feature_idx, weight in np.ndenumerate(self.weights_final)])) return value, self._target, self._features else: return None, self._target, self._features def reset_state(self, reset_right_part : bool = True): if reset_right_part: self.right_part_selected = False self.weights_internal_evald = False self.weights_final_evald = False self.fitness_calculated = False self.solver_form_defined = False @Reset_equation_status(reset_input = False, reset_output = True) @History_Extender('\n -> was copied by deepcopy(self)', 'n') def __deepcopy__(self, memo = None): clss = self.__class__ new_struct = clss.__new__(clss) memo[id(self)] = new_struct attrs_to_avoid_copy = ['_features', '_target'] # print(self.__slots__) for k in self.__slots__: try: # print('successful writing', k, getattr(self, k)) if k not in attrs_to_avoid_copy: setattr(new_struct, k, copy.deepcopy(getattr(self, k), memo)) else: setattr(new_struct, k, None) except AttributeError: # print('unsuccessful writing', k) pass # new_struct.__dict__.update(self.__dict__) # new_struct.structure = copy.deepcopy(self.structure) return new_struct def copy_properties_to(self, new_equation): new_equation.weights_internal_evald = self.weights_internal_evald new_equation.weights_final_evald = self.weights_final_evald new_equation.right_part_selected = self.right_part_selected new_equation.fitness_calculated = self.fitness_calculated new_equation.solver_form_defined = self.solver_form_defined try: new_equation._fitness_value = self._fitness_value except AttributeError: pass def add_history(self, add): self._history += add @property def history(self): return self._history @property def fitness_value(self): return self._fitness_value @fitness_value.setter def fitness_value(self, val): self._fitness_value = val def penalize_fitness(self, coeff = 1.): self._fitness_value = self._fitness_value*coeff @property def weights_internal(self): if self.weights_internal_evald: return self._weights_internal else: raise AttributeError('Internal weights called before initialization') @weights_internal.setter def weights_internal(self, weights): self._weights_internal = weights self.weights_internal_evald = True self.weights_final_evald = False @property def weights_final(self): if self.weights_final_evald: return self._weights_final else: raise AttributeError('Final weights called before initialization') @weights_final.setter def weights_final(self, weights): self._weights_final = weights self.weights_final_evald = True @property def latex_form(self): form = r"" for term_idx in range(len(self.structure)): if term_idx != self.target_idx: form += str(self.weights_final[term_idx]) if term_idx < self.target_idx else str(self.weights_final[term_idx-1]) form += ' * ' + self.structure[term_idx].latex_form + ' + ' form += str(self.weights_final[-1]) + ' = ' + self.structure[self.target_idx].text_form return form @property def text_form(self): form = '' if self.weights_final_evald: for term_idx in range(len(self.structure)): if term_idx != self.target_idx: form += str(self.weights_final[term_idx]) if term_idx < self.target_idx else str(self.weights_final[term_idx-1]) form += ' * ' + self.structure[term_idx].name + ' + ' form += str(self.weights_final[-1]) + ' = ' + self.structure[self.target_idx].name else: for term_idx in range(len(self.structure)): form += 'k_'+ str(term_idx) + ' ' + self.structure[term_idx].name + ' + ' form += 'k_' + str(len(self.structure)) + ' = 0' return form def solver_form(self): if self.solver_form_defined: return self._solver_form else: self._solver_form = [] for term_idx in range(len(self.structure)): if term_idx != self.target_idx: term_form = self.structure[term_idx].solver_form weight = self.weights_final[term_idx] if term_idx < self.target_idx else self.weights_final[term_idx-1] term_form[0] = term_form[0] * weight term_form[0] = torch.flatten(term_form[0]).unsqueeze(1).type(torch.FloatTensor) self._solver_form.append(term_form) free_coeff_weight = torch.from_numpy(np.full_like(a = global_var.grid_cache.get('0'), fill_value = self.weights_final[-1])) free_coeff_weight = torch.flatten(free_coeff_weight).unsqueeze(1).type(torch.FloatTensor) target_weight = torch.from_numpy(np.full_like(a = global_var.grid_cache.get('0'), fill_value = -1)) target_form = self.structure[self.target_idx].solver_form target_form[0] = target_form[0] * target_weight target_form[0] = torch.flatten(target_form[0]).unsqueeze(1).type(torch.FloatTensor) self._solver_form.append([free_coeff_weight, [None,], 0]) self._solver_form.append(target_form) self.solver_form_defined = True return self._solver_form @property def state(self): return self.text_form @property def described_variables(self): eps=1e-7 described = set() for term_idx, term in enumerate(self.structure): if term_idx == self.target_idx: described.update({factor.type for factor in term.structure}) else: weight_idx = term_idx if term_idx < term_idx else term_idx - 1 if np.abs(self.weights_final[weight_idx]) > eps: described.update({factor.type for factor in term.structure}) described = frozenset(described) return described def max_deriv_orders(self): solver_form = self.solver_form() max_orders = np.zeros(global_var.grid_cache.get('0').ndim) def count_order(obj, deriv_ax): if obj is None: return 0 else: return obj.count(deriv_ax) for term in solver_form: if isinstance(term[2], list): for deriv_factor in term[1]: orders = np.array([count_order(deriv_factor, ax) for ax #deriv_factor.count(ax) in np.arange(max_orders.size)]) max_orders = np.maximum(max_orders, orders) else: orders = np.array([count_order(term[1], ax) for ax # term[1].count(ax) in np.arange(max_orders.size)]) max_orders = np.maximum(max_orders, orders) if np.max(max_orders) > 2: raise NotImplementedError('The current implementation allows does not allow higher orders of equation, than 2.') return max_orders def boundary_conditions(self, main_var_key = ('u', (1.0,))): required_bc_ord = self.max_deriv_orders() # We assume, that the maximum order of the equation here is 2 if global_var.grid_cache is None: raise NameError('Grid cache has not been initialized yet.') bconds = [] hardcoded_bc_relative_locations = {0 : None, 1 : (0,), 2 : (0, 1)} tensor_shape = global_var.grid_cache.get('0').shape def get_boundary_ind(tensor_shape, axis, rel_loc): return tuple(np.meshgrid(*[np.arange(shape) if dim_idx != axis else min(int(rel_loc * shape), shape-1) for dim_idx, shape in enumerate(tensor_shape)], indexing = 'ij')) for ax_idx, ax_ord in enumerate(required_bc_ord): for loc_fraction in hardcoded_bc_relative_locations[ax_ord]: indexes = get_boundary_ind(tensor_shape, axis = ax_idx, rel_loc = loc_fraction) coords = np.squeeze(np.array([global_var.grid_cache.get(str(idx))[indexes] for idx in np.arange(len(tensor_shape))])).T vals = np.squeeze(global_var.tensor_cache.get(main_var_key)[indexes]).T coords = torch.from_numpy(coords).type(torch.FloatTensor) vals = torch.from_numpy(vals).type(torch.FloatTensor) bconds.append([coords, vals]) print('shape of the grid', global_var.grid_cache.get('0').shape) print('Obtained boundary conditions', len(bconds[0])) return bconds def standalone_boundary_conditions(max_deriv_orders, main_var_key = ('u', (1.0,))): required_bc_ord = max_deriv_orders # We assume, that the maximum order of the equation here is 2 if global_var.grid_cache is None: raise NameError('Grid cache has not been initialized yet.') bconds = [] hardcoded_bc_relative_locations = {0 : None, 1 : (0,), 2 : (0, 1)} tensor_shape = global_var.grid_cache.get('0').shape def get_boundary_ind(tensor_shape, axis, rel_loc, old_way = False): return tuple(np.meshgrid(*[np.arange(shape) if dim_idx != axis else min(int(rel_loc * shape), shape-1) for dim_idx, shape in enumerate(tensor_shape)], indexing = 'ij')) for ax_idx, ax_ord in enumerate(required_bc_ord): for loc_fraction in hardcoded_bc_relative_locations[ax_ord]: indexes = get_boundary_ind(tensor_shape, axis = ax_idx, rel_loc = loc_fraction) coords = np.array([global_var.grid_cache.get(str(idx))[indexes] for idx in np.arange(len(tensor_shape))]) vals = global_var.tensor_cache.get(main_var_key)[indexes] coords = torch.from_numpy(coords) vals = torch.from_numpy(vals) bconds.append([coords, vals]) return bconds class SoEq(Complex_Structure, moeadd.moeadd_solution): # __slots__ = ['tokens_indep', 'tokens_dep', 'equation_number'] def __init__(self, pool, terms_number, max_factors_in_term, sparcity = None, eq_search_iters = 100): self.tokens_indep = TF_Pool(pool.families_meaningful) #[family for family in token_families if family.status['meaningful']] self.tokens_dep = TF_Pool(pool.families_supplementary) #[family for family in token_families if not family.status['meaningful']] self.equation_number = np.size(self.tokens_indep.families_cardinality()) if type(sparcity) != None: self.vals = sparcity self.max_terms_number = terms_number; self.max_factors_in_term = max_factors_in_term self.moeadd_set = False; self.eq_search_operator_set = False# ; self.evaluated = False self.def_eq_search_iters = eq_search_iters def use_default_objective_function(self): from epde.eq_mo_objectives import system_discrepancy, system_complexity_by_terms self.set_objective_functions([system_discrepancy, system_complexity_by_terms]) def set_objective_functions(self, obj_funs): ''' Method to set the objective functions to evaluate the "quality" of the system of equations. Parameters: ----------- obj_funs - callable or list of callables; function/functions to evaluate quality metrics of system of equations. Can return a single metric (for example, quality of the process modelling with specific system), or a list of metrics (for example, number of terms for each equation in the system). The function results will be flattened after their application. ''' assert callable(obj_funs) or all([callable(fun) for fun in obj_funs]) self.obj_funs = obj_funs # import time # print(len(self.obj_funs)) # time.sleep(10) def set_eq_search_evolutionary(self, evolutionary): # raise NotImplementedError('In current version, the evolutionary operatorshall be taken from global variables') # assert type(evolutionary.coeff_calculator) != type(None), 'Defined evolutionary operator lacks coefficient calculator' self.eq_search_evolutionary_strategy = evolutionary self.eq_search_operator_set = True def create_equations(self, population_size = 16, sparcity = None, eq_search_iters = None, EA_kwargs = dict()): # if type(eq_search_iters) == type(None) and type(self.def_eq_search_iters) == type(None): # raise ValueError('Number of iterations is not defied both in method parameter or in object attribute') assert self.eq_search_operator_set if type(eq_search_iters) == type(None): eq_search_iters = self.def_eq_search_iters if type(sparcity) == type(None): sparcity = self.vals else: self.vals = sparcity self.population_size = population_size self.eq_search_evolutionary_strategy.modify_block_params(block_label = 'truncation', param_label = 'population_size', value = population_size) self.structure = []; self.eq_search_iters = eq_search_iters token_selection = self.tokens_indep self.vars_to_describe = {token_family.type for token_family in self.tokens_dep.families} self.vars_to_describe = self.vars_to_describe.union({token_family.type for token_family in self.tokens_indep.families}) self.separated_vars = set() for eq_idx in range(self.equation_number): current_tokens = token_selection + self.tokens_dep # print('Equation index', eq_idx, self.vals) self.eq_search_evolutionary_strategy.modify_block_params(block_label = 'rps1', param_label = 'sparsity', value = self.vals[eq_idx], suboperator_sequence = ['eq_level_rps', 'fitness_calculation', 'sparsity'])#(sparcity_value = self.vals[eq_idx]) self.eq_search_evolutionary_strategy.modify_block_params(block_label = 'rps2', param_label = 'sparsity', value = self.vals[eq_idx], suboperator_sequence = ['eq_level_rps', 'fitness_calculation', 'sparsity'])#(sparcity_value = self.vals[eq_idx]) cur_equation, cur_eq_operator_error_abs, cur_eq_operator_error_structural = self.optimize_equation(pool = current_tokens, strategy = self.eq_search_evolutionary_strategy, population_size = self.population_size, separate_vars = self.separated_vars, EA_kwargs = EA_kwargs) self.vars_to_describe.difference_update(cur_equation.described_variables) self.separated_vars.add(frozenset(cur_equation.described_variables)) self.structure.append(cur_equation) # self.single_vars_in_equation.update() # cache.clear(full = False) if not eq_idx == self.equation_number - 1: global_var.tensor_cache.change_variables(cur_eq_operator_error_abs, cur_eq_operator_error_structural) # for idx, _ in enumerate(token_selection): # token_selection[idx].change_variables(cur_eq_operator_error) # obj_funs = np.array(flatten([func(self) for func in self.obj_funs])) # np.array([self.evaluate(normalize = False),] + [eq.L0_norm for eq in self.structure]) moeadd.moeadd_solution.__init__(self, self.vals, self.obj_funs) # , return_val = True, self) super( self.moeadd_set = True def optimize_equation(self, pool, strategy, population_size, basic_terms : list = [], separate_vars : set = None, EA_kwargs = dict()): population = [Equation(pool, basic_terms, self.max_terms_number, self.max_factors_in_term) for i in range(population_size)] EA_kwargs['separate_vars'] = separate_vars strategy.run(initial_population = population, EA_kwargs = EA_kwargs) result = strategy.result return result[0], result[0].evaluate(normalize = False, return_val=True)[0], result[0].evaluate(normalize = True, return_val=True)[0] @staticmethod def equation_opt_iteration(population, evol_operator, population_size, iter_index, separate_vars, strict_restrictions = True): for equation in population: if equation.described_variables in separate_vars: equation.penalize_fitness(coeff = 0.) population = Population_Sort(population) population = population[:population_size] gc.collect() population = evol_operator.apply(population, separate_vars) return population def evaluate(self, normalize = True): if len(self.structure) == 1: value = self.structure[0].evaluate(normalize = normalize, return_val = True)[0] else: value = np.sum([equation.evaluate(normalize, return_val = True)[0] for equation in self.structure]) value = np.sum(np.abs(value)) return value @property def obj_fun(self): # print('objective functions:', self.obj_funs) # print('objective function values:', [func(self) for func in self.obj_funs], flatten([func(self) for func in self.obj_funs])) return np.array(flatten([func(self) for func in self.obj_funs])) def __call__(self): assert self.moeadd_set, 'The structure of the equation is not defined, therefore no moeadd operations can be called' return self.obj_fun @property def text_form(self): form = '' if len(self.structure) > 1: for eq_idx, equation in enumerate(self.structure): if eq_idx == 0: form += '/ ' + equation.text_form + '\n' elif eq_idx == len(self.structure) - 1: form += '\ ' + equation.text_form + '\n' else: form += '| ' + equation.text_form + '\n' else: form += self.structure[0].text_form + '\n' return form def __eq__(self, other): assert self.moeadd_set, 'The structure of the equation is not defined, therefore no moeadd operations can be called' # eps = 1e-9 return (all([any([other_elem == self_elem for other_elem in other.structure]) for self_elem in self.structure]) and all([any([other_elem == self_elem for self_elem in self.structure]) for other_elem in other.structure]) and len(other.structure) == len(self.structure)) or all(np.isclose(self.obj_fun, other.obj_fun)) @property def latex_form(self): form = r"\begin{eqnarray*}" for equation in self.structure: form += equation.latex_form + r", \\ " form += r"\end{eqnarray*}" def __hash__(self): return hash(tuple(self.vals))
[ "epde.interface.token_family.TF_Pool", "numpy.abs", "numpy.maximum", "epde.supplementary.Population_Sort", "numpy.ones", "gc.collect", "numpy.isclose", "numpy.random.randint", "numpy.arange", "numpy.mean", "torch.flatten", "numpy.multiply", "numpy.copy", "numpy.std", "numpy.ndim", "numpy.transpose", "epde.globals.tensor_cache.add", "numpy.max", "numpy.add", "epde.moeadd.moeadd_stc.moeadd_solution.__init__", "epde.globals.tensor_cache.get", "copy.deepcopy", "numpy.ndenumerate", "epde.globals.tensor_cache.change_variables", "epde.supplementary.Filter_powers", "epde.globals.grid_cache.get", "numpy.vstack", "torch.from_numpy", "epde.decorators.History_Extender", "numpy.expand_dims", "epde.decorators.Reset_equation_status", "warnings.warn" ]
[((728, 742), 'numpy.copy', 'np.copy', (['Input'], {}), '(Input)\n', (735, 742), True, 'import numpy as np\n'), ((21638, 21697), 'epde.decorators.Reset_equation_status', 'Reset_equation_status', ([], {'reset_input': '(False)', 'reset_output': '(True)'}), '(reset_input=False, reset_output=True)\n', (21659, 21697), False, 'from epde.decorators import History_Extender, Reset_equation_status\n'), ((21707, 21769), 'epde.decorators.History_Extender', 'History_Extender', (['"""\n -> was copied by deepcopy(self)"""', '"""n"""'], {}), '("""\n -> was copied by deepcopy(self)""", \'n\')\n', (21723, 21769), False, 'from epde.decorators import History_Extender, Reset_equation_status\n'), ((775, 790), 'numpy.ndim', 'np.ndim', (['matrix'], {}), '(matrix)\n', (782, 790), True, 'import numpy as np\n'), ((5841, 5891), 'numpy.random.randint', 'np.random.randint', (['(1)', '(self.max_factors_in_term + 1)'], {}), '(1, self.max_factors_in_term + 1)\n', (5858, 5891), True, 'import numpy as np\n'), ((13770, 13800), 'torch.from_numpy', 'torch.from_numpy', (['coeff_tensor'], {}), '(coeff_tensor)\n', (13786, 13800), False, 'import torch\n'), ((19061, 19080), 'copy.deepcopy', 'copy.deepcopy', (['self'], {}), '(self)\n', (19074, 19080), False, 'import copy\n'), ((20421, 20449), 'numpy.transpose', 'np.transpose', (['self._features'], {}), '(self._features)\n', (20433, 20449), True, 'import numpy as np\n'), ((20464, 20488), 'numpy.transpose', 'np.transpose', (['temp_feats'], {}), '(temp_feats)\n', (20476, 20488), True, 'import numpy as np\n'), ((30989, 31019), 'epde.globals.grid_cache.get', 'global_var.grid_cache.get', (['"""0"""'], {}), "('0')\n", (31014, 31019), True, 'import epde.globals as global_var\n'), ((32146, 32179), 'epde.interface.token_family.TF_Pool', 'TF_Pool', (['pool.families_meaningful'], {}), '(pool.families_meaningful)\n', (32153, 32179), False, 'from epde.interface.token_family import TF_Pool\n'), ((32276, 32312), 'epde.interface.token_family.TF_Pool', 'TF_Pool', (['pool.families_supplementary'], {}), '(pool.families_supplementary)\n', (32283, 32312), False, 'from epde.interface.token_family import TF_Pool\n'), ((37692, 37755), 'epde.moeadd.moeadd_stc.moeadd_solution.__init__', 'moeadd.moeadd_solution.__init__', (['self', 'self.vals', 'self.obj_funs'], {}), '(self, self.vals, self.obj_funs)\n', (37723, 37755), True, 'import epde.moeadd.moeadd_stc as moeadd\n'), ((38813, 38840), 'epde.supplementary.Population_Sort', 'Population_Sort', (['population'], {}), '(population)\n', (38828, 38840), False, 'from epde.supplementary import Filter_powers, Population_Sort, flatten\n'), ((38899, 38911), 'gc.collect', 'gc.collect', ([], {}), '()\n', (38909, 38911), False, 'import gc\n'), ((897, 912), 'numpy.ndim', 'np.ndim', (['matrix'], {}), '(matrix)\n', (904, 912), True, 'import numpy as np\n'), ((968, 994), 'numpy.arange', 'np.arange', (['matrix.shape[0]'], {}), '(matrix.shape[0])\n', (977, 994), True, 'import numpy as np\n'), ((6352, 6377), 'numpy.arange', 'np.arange', (['(1)', 'factors_num'], {}), '(1, factors_num)\n', (6361, 6377), True, 'import numpy as np\n'), ((7515, 7544), 'epde.supplementary.Filter_powers', 'Filter_powers', (['self.structure'], {}), '(self.structure)\n', (7528, 7544), False, 'from epde.supplementary import Filter_powers, Population_Sort, flatten\n'), ((8094, 8200), 'epde.globals.tensor_cache.get', 'global_var.tensor_cache.get', (['self.cache_label'], {'normalized': 'normalize', 'saved_as': 'self.saved_as[normalize]'}), '(self.cache_label, normalized=normalize,\n saved_as=self.saved_as[normalize])\n', (8121, 8200), True, 'import epde.globals as global_var\n'), ((9725, 9744), 'copy.deepcopy', 'copy.deepcopy', (['self'], {}), '(self)\n', (9738, 9744), False, 'import copy\n'), ((20279, 20312), 'numpy.expand_dims', 'np.expand_dims', (['self._features', '(1)'], {}), '(self._features, 1)\n', (20293, 20312), True, 'import numpy as np\n'), ((28856, 28874), 'numpy.max', 'np.max', (['max_orders'], {}), '(max_orders)\n', (28862, 28874), True, 'import numpy as np\n'), ((29456, 29486), 'epde.globals.grid_cache.get', 'global_var.grid_cache.get', (['"""0"""'], {}), "('0')\n", (29481, 29486), True, 'import epde.globals as global_var\n'), ((31737, 31761), 'torch.from_numpy', 'torch.from_numpy', (['coords'], {}), '(coords)\n', (31753, 31761), False, 'import torch\n'), ((31781, 31803), 'torch.from_numpy', 'torch.from_numpy', (['vals'], {}), '(vals)\n', (31797, 31803), False, 'import torch\n'), ((39335, 39348), 'numpy.abs', 'np.abs', (['value'], {}), '(value)\n', (39341, 39348), True, 'import numpy as np\n'), ((1051, 1068), 'numpy.std', 'np.std', (['matrix[i]'], {}), '(matrix[i])\n', (1057, 1068), True, 'import numpy as np\n'), ((8911, 8985), 'epde.globals.tensor_cache.add', 'global_var.tensor_cache.add', (['self.cache_label', 'value'], {'normalized': 'normalize'}), '(self.cache_label, value, normalized=normalize)\n', (8938, 8985), True, 'import epde.globals as global_var\n'), ((10578, 10607), 'epde.supplementary.Filter_powers', 'Filter_powers', (['self.structure'], {}), '(self.structure)\n', (10591, 10607), False, 'from epde.supplementary import Filter_powers, Population_Sort, flatten\n'), ((10725, 10841), 'warnings.warn', 'warnings.warn', (['"""Can not create unique term, while filtering equation tokens in regards to the right part."""'], {}), "(\n 'Can not create unique term, while filtering equation tokens in regards to the right part.'\n )\n", (10738, 10841), False, 'import warnings\n'), ((12074, 12094), 'copy.deepcopy', 'copy.deepcopy', (['token'], {}), '(token)\n', (12087, 12094), False, 'import copy\n'), ((12990, 13020), 'epde.globals.grid_cache.get', 'global_var.grid_cache.get', (['"""0"""'], {}), "('0')\n", (13015, 13020), True, 'import epde.globals as global_var\n'), ((20361, 20393), 'numpy.ones', 'np.ones', (['self._features.shape[1]'], {}), '(self._features.shape[1])\n', (20368, 20393), True, 'import numpy as np\n'), ((20607, 20643), 'numpy.expand_dims', 'np.expand_dims', (['self._target'], {'axis': '(1)'}), '(self._target, axis=1)\n', (20621, 20643), True, 'import numpy as np\n'), ((20930, 20966), 'numpy.expand_dims', 'np.expand_dims', (['self._target'], {'axis': '(1)'}), '(self._target, axis=1)\n', (20944, 20966), True, 'import numpy as np\n'), ((28041, 28071), 'epde.globals.grid_cache.get', 'global_var.grid_cache.get', (['"""0"""'], {}), "('0')\n", (28066, 28071), True, 'import epde.globals as global_var\n'), ((28814, 28844), 'numpy.maximum', 'np.maximum', (['max_orders', 'orders'], {}), '(max_orders, orders)\n', (28824, 28844), True, 'import numpy as np\n'), ((30457, 30487), 'epde.globals.grid_cache.get', 'global_var.grid_cache.get', (['"""0"""'], {}), "('0')\n", (30482, 30487), True, 'import epde.globals as global_var\n'), ((31652, 31693), 'epde.globals.tensor_cache.get', 'global_var.tensor_cache.get', (['main_var_key'], {}), '(main_var_key)\n', (31679, 31693), True, 'import epde.globals as global_var\n'), ((37193, 37298), 'epde.globals.tensor_cache.change_variables', 'global_var.tensor_cache.change_variables', (['cur_eq_operator_error_abs', 'cur_eq_operator_error_structural'], {}), '(cur_eq_operator_error_abs,\n cur_eq_operator_error_structural)\n', (37233, 37298), True, 'import epde.globals as global_var\n'), ((40936, 40975), 'numpy.isclose', 'np.isclose', (['self.obj_fun', 'other.obj_fun'], {}), '(self.obj_fun, other.obj_fun)\n', (40946, 40975), True, 'import numpy as np\n'), ((8458, 8472), 'numpy.ndim', 'np.ndim', (['value'], {}), '(value)\n', (8465, 8472), True, 'import numpy as np\n'), ((20136, 20169), 'numpy.vstack', 'np.vstack', (['[self._features, temp]'], {}), '([self._features, temp])\n', (20145, 20169), True, 'import numpy as np\n'), ((27740, 27778), 'numpy.abs', 'np.abs', (['self.weights_final[weight_idx]'], {}), '(self.weights_final[weight_idx])\n', (27746, 27778), True, 'import numpy as np\n'), ((28582, 28612), 'numpy.maximum', 'np.maximum', (['max_orders', 'orders'], {}), '(max_orders, orders)\n', (28592, 28612), True, 'import numpy as np\n'), ((8558, 8572), 'numpy.ndim', 'np.ndim', (['value'], {}), '(value)\n', (8565, 8572), True, 'import numpy as np\n'), ((8582, 8595), 'numpy.std', 'np.std', (['value'], {}), '(value)\n', (8588, 8595), True, 'import numpy as np\n'), ((8651, 8664), 'numpy.std', 'np.std', (['value'], {}), '(value)\n', (8657, 8664), True, 'import numpy as np\n'), ((26401, 26431), 'epde.globals.grid_cache.get', 'global_var.grid_cache.get', (['"""0"""'], {}), "('0')\n", (26426, 26431), True, 'import epde.globals as global_var\n'), ((26698, 26728), 'epde.globals.grid_cache.get', 'global_var.grid_cache.get', (['"""0"""'], {}), "('0')\n", (26723, 26728), True, 'import epde.globals as global_var\n'), ((30252, 30276), 'torch.from_numpy', 'torch.from_numpy', (['coords'], {}), '(coords)\n', (30268, 30276), False, 'import torch\n'), ((30324, 30346), 'torch.from_numpy', 'torch.from_numpy', (['vals'], {}), '(vals)\n', (30340, 30346), False, 'import torch\n'), ((1135, 1153), 'numpy.mean', 'np.mean', (['matrix[i]'], {}), '(matrix[i])\n', (1142, 1153), True, 'import numpy as np\n'), ((8635, 8649), 'numpy.mean', 'np.mean', (['value'], {}), '(value)\n', (8642, 8649), True, 'import numpy as np\n'), ((8696, 8710), 'numpy.ndim', 'np.ndim', (['value'], {}), '(value)\n', (8703, 8710), True, 'import numpy as np\n'), ((8720, 8733), 'numpy.std', 'np.std', (['value'], {}), '(value)\n', (8726, 8733), True, 'import numpy as np\n'), ((8773, 8787), 'numpy.mean', 'np.mean', (['value'], {}), '(value)\n', (8780, 8787), True, 'import numpy as np\n'), ((26566, 26598), 'torch.flatten', 'torch.flatten', (['free_coeff_weight'], {}), '(free_coeff_weight)\n', (26579, 26598), False, 'import torch\n'), ((26982, 27011), 'torch.flatten', 'torch.flatten', (['target_form[0]'], {}), '(target_form[0])\n', (26995, 27011), False, 'import torch\n'), ((28756, 28782), 'numpy.arange', 'np.arange', (['max_orders.size'], {}), '(max_orders.size)\n', (28765, 28782), True, 'import numpy as np\n'), ((30156, 30197), 'epde.globals.tensor_cache.get', 'global_var.tensor_cache.get', (['main_var_key'], {}), '(main_var_key)\n', (30183, 30197), True, 'import epde.globals as global_var\n'), ((31134, 31150), 'numpy.arange', 'np.arange', (['shape'], {}), '(shape)\n', (31143, 31150), True, 'import numpy as np\n'), ((20705, 20717), 'numpy.add', 'np.add', (['x', 'y'], {}), '(x, y)\n', (20711, 20717), True, 'import numpy as np\n'), ((20720, 20767), 'numpy.multiply', 'np.multiply', (['weight', 'temp_feats[:, feature_idx]'], {}), '(weight, temp_feats[:, feature_idx])\n', (20731, 20767), True, 'import numpy as np\n'), ((21029, 21041), 'numpy.add', 'np.add', (['x', 'y'], {}), '(x, y)\n', (21035, 21041), True, 'import numpy as np\n'), ((21044, 21091), 'numpy.multiply', 'np.multiply', (['weight', 'temp_feats[:, feature_idx]'], {}), '(weight, temp_feats[:, feature_idx])\n', (21055, 21091), True, 'import numpy as np\n'), ((28520, 28546), 'numpy.arange', 'np.arange', (['max_orders.size'], {}), '(max_orders.size)\n', (28529, 28546), True, 'import numpy as np\n'), ((29592, 29608), 'numpy.arange', 'np.arange', (['shape'], {}), '(shape)\n', (29601, 29608), True, 'import numpy as np\n'), ((20846, 20883), 'numpy.ndenumerate', 'np.ndenumerate', (['self.weights_internal'], {}), '(self.weights_internal)\n', (20860, 20883), True, 'import numpy as np\n'), ((21170, 21204), 'numpy.ndenumerate', 'np.ndenumerate', (['self.weights_final'], {}), '(self.weights_final)\n', (21184, 21204), True, 'import numpy as np\n'), ((26193, 26220), 'torch.flatten', 'torch.flatten', (['term_form[0]'], {}), '(term_form[0])\n', (26206, 26220), False, 'import torch\n')]
from django.contrib import admin from members.models import Member # Register your models here. class MemberAdmin(admin.ModelAdmin): ''' Admin View for Member ''' list_display = ('full_name', 'email', 'phone_number',) admin.site.register(Member, MemberAdmin)
[ "django.contrib.admin.site.register" ]
[((240, 280), 'django.contrib.admin.site.register', 'admin.site.register', (['Member', 'MemberAdmin'], {}), '(Member, MemberAdmin)\n', (259, 280), False, 'from django.contrib import admin\n')]
# encoding: utf-8 from __future__ import print_function import term import humanfriendly class RequestStorage(object): """ Stores statistics about single request """ def __init__(self): self.queryset_stats = [] def add_queryset_storage_instance(self, queryset_storage): self.queryset_stats.append(queryset_storage) @property def total_wasted_memory(self): wasted_memory = 0 for qs_storage in self.queryset_stats: wasted_memory += qs_storage.total_wasted_memory return wasted_memory # Stats print methods def print_stats(self): """ Display statistics of current request """ if not self.queryset_stats: return term.writeLine("\n\t ERASERHEAD STATS \n", term.bold, term.reverse) for queryset_storage in self.queryset_stats: queryset_storage.print_stats() print() term.write("\t TOTAL WASTED MEMORY: ", term.bold, term.reverse) term.write(" {}".format(humanfriendly.format_size(self.total_wasted_memory)), term.red) print()
[ "term.writeLine", "humanfriendly.format_size", "term.write" ]
[((733, 801), 'term.writeLine', 'term.writeLine', (['"""\n\t ERASERHEAD STATS \n"""', 'term.bold', 'term.reverse'], {}), '("""\n\t ERASERHEAD STATS \n""", term.bold, term.reverse)\n', (747, 801), False, 'import term\n'), ((921, 984), 'term.write', 'term.write', (['"""\t TOTAL WASTED MEMORY: """', 'term.bold', 'term.reverse'], {}), "('\\t TOTAL WASTED MEMORY: ', term.bold, term.reverse)\n", (931, 984), False, 'import term\n'), ((1018, 1069), 'humanfriendly.format_size', 'humanfriendly.format_size', (['self.total_wasted_memory'], {}), '(self.total_wasted_memory)\n', (1043, 1069), False, 'import humanfriendly\n')]
from easydict import EasyDict as edict # init __C_SHHA = edict() cfg_data = __C_SHHA __C_SHHA.TRAIN_SIZE = (512,1024) __C_SHHA.DATA_PATH = '../ProcessedData/SHHA/' __C_SHHA.TRAIN_LST = 'train.txt' __C_SHHA.VAL_LST = 'val.txt' __C_SHHA.VAL4EVAL = 'val_gt_loc.txt' __C_SHHA.MEAN_STD = ([0.410824894905, 0.370634973049, 0.359682112932], [0.278580576181, 0.26925137639, 0.27156367898]) __C_SHHA.LABEL_FACTOR = 1 __C_SHHA.LOG_PARA = 1. __C_SHHA.RESUME_MODEL = ''#model path __C_SHHA.TRAIN_BATCH_SIZE = 6 #imgs __C_SHHA.VAL_BATCH_SIZE = 1 # must be 1
[ "easydict.EasyDict" ]
[((59, 66), 'easydict.EasyDict', 'edict', ([], {}), '()\n', (64, 66), True, 'from easydict import EasyDict as edict\n')]
# -*- coding: utf-8 -*- # @Author: <NAME> # @Date: 2021-02-25 20:06:08 # @Last Modified by: <NAME> # @Last Modified time: 2021-02-25 20:06:12 import json import logging import socket from os import environ from monitoring.constants import ( ARM_AWAY, ARM_STAY, LOG_IPC, MONITOR_ARM_AWAY, MONITOR_ARM_STAY, MONITOR_DISARM, MONITOR_REGISTER_CARD, POWER_GET_STATE, MONITOR_SET_CLOCK, MONITOR_SYNC_CLOCK, MONITOR_UPDATE_CONFIG, UPDATE_SECURE_CONNECTION, MONITOR_UPDATE_KEYPAD, MONITOR_GET_STATE, MONITOR_GET_ARM, UPDATE_SSH, ) class IPCClient(object): """ Sending IPC messages from the REST API to the monitoring service """ _socket = None def __init__(self): self._logger = logging.getLogger(LOG_IPC) if not self._socket: self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: self._socket.connect(environ["MONITOR_INPUT_SOCKET"]) except (ConnectionRefusedError, FileNotFoundError): self._socket = None def disarm(self, user_id): return self._send_message({"action": MONITOR_DISARM, "user_id": user_id}) def get_arm(self): return self._send_message({"action": MONITOR_GET_ARM}) def arm(self, arm_type, user_id): if arm_type == ARM_AWAY: return self._send_message({"action": MONITOR_ARM_AWAY, "user_id": user_id}) elif arm_type == ARM_STAY: return self._send_message({"action": MONITOR_ARM_STAY, "user_id": user_id}) else: print("Unknown arm type: %s" % arm_type) def get_state(self): return self._send_message({"action": MONITOR_GET_STATE}) def get_power_state(self): return self._send_message({"action": POWER_GET_STATE}) def update_configuration(self): return self._send_message({"action": MONITOR_UPDATE_CONFIG}) def update_keypad(self): return self._send_message({"action": MONITOR_UPDATE_KEYPAD}) def register_card(self): return self._send_message({"action": MONITOR_REGISTER_CARD}) def update_dyndns(self): return self._send_message({"action": UPDATE_SECURE_CONNECTION}) def update_ssh(self): return self._send_message({"action": UPDATE_SSH}) def sync_clock(self): return self._send_message({"action": MONITOR_SYNC_CLOCK}) def set_clock(self, settings): message = {"action": MONITOR_SET_CLOCK} message = {**message, **settings} return self._send_message(message) def _send_message(self, message): if self._socket: self._socket.send(json.dumps(message).encode()) data = self._socket.recv(1024) return json.loads(data.decode())
[ "socket.socket", "logging.getLogger", "json.dumps" ]
[((772, 798), 'logging.getLogger', 'logging.getLogger', (['LOG_IPC'], {}), '(LOG_IPC)\n', (789, 798), False, 'import logging\n'), ((855, 904), 'socket.socket', 'socket.socket', (['socket.AF_UNIX', 'socket.SOCK_STREAM'], {}), '(socket.AF_UNIX, socket.SOCK_STREAM)\n', (868, 904), False, 'import socket\n'), ((2676, 2695), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (2686, 2695), False, 'import json\n')]
""" Functionality to analyse bias triangles @author: amjzwerver """ #%% import numpy as np import qcodes import qtt import qtt.pgeometry import matplotlib.pyplot as plt from qcodes.plots.qcmatplotlib import MatPlot from qtt.data import diffDataset def plotAnalysedLines(clicked_pts, linePoints1_2, linePt3_vert, linePt3_horz, linePt3_ints, intersect_point): """ Plots lines based on three points clicked Args: clicked_pts (array): lines between the three points (1-2), (2-3) linePoints1_2 (array): line fitted through points 1 and 2 linePt3_vert (array): vertical line through point 3 linePt3_horz (array): horizontal line through point 3 linePt3_ints (array): line through point 3 and its vert/horz intersection with the line through point 1,2 intersect_point (array): intersection point point 3, line1_2 """ qtt.pgeometry.plot2Dline(linePoints1_2, ':c', alpha = .5) qtt.pgeometry.plot2Dline(linePt3_vert, ':b', alpha=.4) qtt.pgeometry.plot2Dline(linePt3_horz, ':b', alpha=.4) qtt.pgeometry.plot2Dline(linePt3_ints, ':b', alpha=.4) qtt.pgeometry.plotPoints(intersect_point, '.b') qtt.pgeometry.plotPoints(clicked_pts[:,2:3], '.b') linePt3_ints_short = np.column_stack((intersect_point, clicked_pts[:,2:3])) qtt.pgeometry.plotPoints(linePt3_ints_short, 'b') def perpLineIntersect(ds, description, vertical = True, points=None): """ Takes three points in a graph and calculates the length of a linepiece between a line through points 1,2 and a vertical/horizontal line through the third point. Uses the currently active figure. Args: ds (dataset): dataset with charge stability diagram and gate voltage in mV vertical (bool): find intersection of point with line vertically (True) or horizontally (False) description: Returns: (dict): 'intersection_point' = intersetcion point 'distance' = length of line from 3rd clicked point to line through clicked points 1 and 2 'clicked_points' = coordinates of the three clicked points """ diffDataset(ds, diff_dir='xy') plt.figure(588); plt.clf() MatPlot(ds.diff_dir_xy, num = 588) ax = plt.gca() ax.set_autoscale_on(False) ax.set_xlabel(ax.get_xlabel()[:2]) ax.set_ylabel(ax.get_ylabel()[:2]) # ax = plt.gca() # ax.set_autoscale_on(False) if description == 'lever_arm' and vertical == True: print('''Please click three points; Point 1: on the addition line for the dot represented on the vertical axis Point 2: further on the addition line for the dot represented on the vertical axis Point 3: on the triple point at the addition line for the dot represented on the horizontal axis where both dot levels are aligned''') elif description == 'lever_arm' and vertical == False: print('''Please click three points; Point 1: on the addition line for the dot represented on the horizontal axis Point 2: further on the addition line for the dot represented on the horizontal axis Point 3: on the triple point at the addition line for the dot represented on the horizontal axis where both dot levels are aligned''') elif description == 'E_charging': print('''Please click three points; Point 1: on the (0, 1) - (0,2) addition line Point 2: further on the (0, 1) - (0,2) addition line Point 3: on the (0, 0) - (0, 1) addition line ''') else: # Do something here such that no three points need to be clicked print('''Please make sure that the descirption argument of this function is either 'lever_arm' or 'E_charging' ''') if points is not None: clicked_pts = points else: clicked_pts=qtt.pgeometry.ginput(3, '.c') qtt.pgeometry.plotPoints(clicked_pts, ':c') qtt.pgeometry.plotLabels(clicked_pts) linePoints1_2 = qtt.pgeometry.fitPlane( clicked_pts[:, 0:2].T ) yy = clicked_pts[:,[2, 2]]; yy[1, -1] += 1 line_vertical = qtt.pgeometry.fitPlane( yy.T ) xx = clicked_pts[:,[2, 2]]; xx[0, -1] += 1 line_horizontal = qtt.pgeometry.fitPlane( xx.T ) if vertical == True: i = qtt.pgeometry.intersect2lines(linePoints1_2, line_vertical) intersectPoint = qtt.pgeometry.dehom(i) line = intersectPoint[:,[0,0]]; line[0,-1]+=1 else: i = qtt.pgeometry.intersect2lines(linePoints1_2, line_horizontal) intersectPoint = qtt.pgeometry.dehom(i) line = intersectPoint[:,[0,0]]; line[1,-1]+=1 linePt3_ints = qtt.pgeometry.fitPlane(line.T) line_length = np.linalg.norm(intersectPoint - clicked_pts[:,2:3]) # visualize plotAnalysedLines(clicked_pts, linePoints1_2, line_vertical, line_horizontal, linePt3_ints, intersectPoint) return {'intersection_point': intersectPoint, 'distance': line_length, 'clicked_points': clicked_pts} #def intersect2lines(l1, l2): # """ Caculate intersection between 2 lines """ # r = qtt.pgeometry.null(np.vstack( (l1, l2)) ) # a = qtt.pgeometry.dehom(r[1]) # return a def lever_arm(bias, results, fig = None): """ Calculates the lever arm of a dot by using bias triangles in charge sensing. Uses currently active figure. Args: bias (float): bias in uV between source and drain while taking the bias triangles results (dict): dictionary returned from the function perpLineIntersect containing three points, the intersection point between a line through 1,2 and the third point and the length from points 3 to the intersection (horz/vert) fig (bool): adds lever arm to title of already existing figure with points Returns: lev_arm (float): the lever arm of the assigned dot in uV/mV """ line_length = results['distance'] #in uV/mV lev_arm = abs(bias/line_length) if fig and len(plt.get_fignums()) != 0: ax = plt.gca() ax.set_autoscale_on(False) if np.round(results['clicked_points'][0,2],2) == np.round(results['intersection_point'][0],2): gate = ax.get_ylabel()[:2] else: gate = ax.get_xlabel()[:2] title = 'Lever arm %s: %.2f $\mu$eV/mV'%(gate, lev_arm) plt.annotate('Length %s: %.2f mV'%(gate, line_length), xy = (0.05, 0.1), xycoords='axes fraction', color = 'k') plt.annotate(title, xy = (0.05, 0.05), xycoords='axes fraction', color = 'k') ax.set_title(title) return lev_arm def E_charging(lev_arm, results, fig = None): """ Calculates the charging energy of a dot by using charge stability diagrams. Uses currently active figure. Args: lev_arm (float): lever arm for the gate to the dot results (dict): dictionary returned from the function perpLineIntersect containing three points, the intersection point between a line through 1,2 and the third point and the length from points 3 to the intersection (horz/vert) fig (bool): adds charging energy to title of already existing figure with points Returns: E_charging (float): the charging energy for the dot """ line_length = results['distance'] E_c = line_length * lev_arm if fig and len(plt.get_fignums()) != 0: ax = plt.gca() ax.set_autoscale_on(False) if np.round(results['clicked_points'][0,2],2) == np.round(results['intersection_point'][0],2): gate = ax.get_ylabel()[:2] else: gate = ax.get_xlabel()[:2] title = 'E_charging %s: %.2f meV'%(gate, E_c/1000) plt.annotate('Length %s: %.2f mV'%(gate, line_length), xy = (0.05, 0.1), xycoords='axes fraction', color = 'k') plt.annotate(title, xy = (0.05, 0.05), xycoords='axes fraction', color = 'k') ax.set_title(title) return E_c def test_lever_arm(): lever_arm_fit = {'clicked_points': np.array([[ 24., 38., 40.], [135., 128., 111.]]), 'distance': 15., 'intersection_point': np.array([[ 40.4],[127.]])} r=lever_arm(-800, lever_arm_fit) assert(np.abs(r-53.3)<1e-1)
[ "numpy.abs", "matplotlib.pyplot.clf", "matplotlib.pyplot.figure", "numpy.linalg.norm", "matplotlib.pyplot.gca", "numpy.round", "qtt.pgeometry.intersect2lines", "qtt.pgeometry.plot2Dline", "qtt.pgeometry.dehom", "qtt.pgeometry.fitPlane", "qtt.data.diffDataset", "matplotlib.pyplot.get_fignums", "qtt.pgeometry.plotLabels", "qcodes.plots.qcmatplotlib.MatPlot", "matplotlib.pyplot.annotate", "qtt.pgeometry.ginput", "numpy.array", "numpy.column_stack", "qtt.pgeometry.plotPoints" ]
[((918, 974), 'qtt.pgeometry.plot2Dline', 'qtt.pgeometry.plot2Dline', (['linePoints1_2', '""":c"""'], {'alpha': '(0.5)'}), "(linePoints1_2, ':c', alpha=0.5)\n", (942, 974), False, 'import qtt\n'), ((980, 1035), 'qtt.pgeometry.plot2Dline', 'qtt.pgeometry.plot2Dline', (['linePt3_vert', '""":b"""'], {'alpha': '(0.4)'}), "(linePt3_vert, ':b', alpha=0.4)\n", (1004, 1035), False, 'import qtt\n'), ((1039, 1094), 'qtt.pgeometry.plot2Dline', 'qtt.pgeometry.plot2Dline', (['linePt3_horz', '""":b"""'], {'alpha': '(0.4)'}), "(linePt3_horz, ':b', alpha=0.4)\n", (1063, 1094), False, 'import qtt\n'), ((1098, 1153), 'qtt.pgeometry.plot2Dline', 'qtt.pgeometry.plot2Dline', (['linePt3_ints', '""":b"""'], {'alpha': '(0.4)'}), "(linePt3_ints, ':b', alpha=0.4)\n", (1122, 1153), False, 'import qtt\n'), ((1162, 1209), 'qtt.pgeometry.plotPoints', 'qtt.pgeometry.plotPoints', (['intersect_point', '""".b"""'], {}), "(intersect_point, '.b')\n", (1186, 1209), False, 'import qtt\n'), ((1214, 1265), 'qtt.pgeometry.plotPoints', 'qtt.pgeometry.plotPoints', (['clicked_pts[:, 2:3]', '""".b"""'], {}), "(clicked_pts[:, 2:3], '.b')\n", (1238, 1265), False, 'import qtt\n'), ((1295, 1350), 'numpy.column_stack', 'np.column_stack', (['(intersect_point, clicked_pts[:, 2:3])'], {}), '((intersect_point, clicked_pts[:, 2:3]))\n', (1310, 1350), True, 'import numpy as np\n'), ((1354, 1403), 'qtt.pgeometry.plotPoints', 'qtt.pgeometry.plotPoints', (['linePt3_ints_short', '"""b"""'], {}), "(linePt3_ints_short, 'b')\n", (1378, 1403), False, 'import qtt\n'), ((2271, 2301), 'qtt.data.diffDataset', 'diffDataset', (['ds'], {'diff_dir': '"""xy"""'}), "(ds, diff_dir='xy')\n", (2282, 2301), False, 'from qtt.data import diffDataset\n'), ((2306, 2321), 'matplotlib.pyplot.figure', 'plt.figure', (['(588)'], {}), '(588)\n', (2316, 2321), True, 'import matplotlib.pyplot as plt\n'), ((2323, 2332), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2330, 2332), True, 'import matplotlib.pyplot as plt\n'), ((2337, 2369), 'qcodes.plots.qcmatplotlib.MatPlot', 'MatPlot', (['ds.diff_dir_xy'], {'num': '(588)'}), '(ds.diff_dir_xy, num=588)\n', (2344, 2369), False, 'from qcodes.plots.qcmatplotlib import MatPlot\n'), ((2381, 2390), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2388, 2390), True, 'import matplotlib.pyplot as plt\n'), ((4064, 4107), 'qtt.pgeometry.plotPoints', 'qtt.pgeometry.plotPoints', (['clicked_pts', '""":c"""'], {}), "(clicked_pts, ':c')\n", (4088, 4107), False, 'import qtt\n'), ((4112, 4149), 'qtt.pgeometry.plotLabels', 'qtt.pgeometry.plotLabels', (['clicked_pts'], {}), '(clicked_pts)\n', (4136, 4149), False, 'import qtt\n'), ((4175, 4220), 'qtt.pgeometry.fitPlane', 'qtt.pgeometry.fitPlane', (['clicked_pts[:, 0:2].T'], {}), '(clicked_pts[:, 0:2].T)\n', (4197, 4220), False, 'import qtt\n'), ((4295, 4323), 'qtt.pgeometry.fitPlane', 'qtt.pgeometry.fitPlane', (['yy.T'], {}), '(yy.T)\n', (4317, 4323), False, 'import qtt\n'), ((4396, 4424), 'qtt.pgeometry.fitPlane', 'qtt.pgeometry.fitPlane', (['xx.T'], {}), '(xx.T)\n', (4418, 4424), False, 'import qtt\n'), ((4845, 4875), 'qtt.pgeometry.fitPlane', 'qtt.pgeometry.fitPlane', (['line.T'], {}), '(line.T)\n', (4867, 4875), False, 'import qtt\n'), ((4894, 4946), 'numpy.linalg.norm', 'np.linalg.norm', (['(intersectPoint - clicked_pts[:, 2:3])'], {}), '(intersectPoint - clicked_pts[:, 2:3])\n', (4908, 4946), True, 'import numpy as np\n'), ((4025, 4054), 'qtt.pgeometry.ginput', 'qtt.pgeometry.ginput', (['(3)', '""".c"""'], {}), "(3, '.c')\n", (4045, 4054), False, 'import qtt\n'), ((4473, 4532), 'qtt.pgeometry.intersect2lines', 'qtt.pgeometry.intersect2lines', (['linePoints1_2', 'line_vertical'], {}), '(linePoints1_2, line_vertical)\n', (4502, 4532), False, 'import qtt\n'), ((4558, 4580), 'qtt.pgeometry.dehom', 'qtt.pgeometry.dehom', (['i'], {}), '(i)\n', (4577, 4580), False, 'import qtt\n'), ((4657, 4718), 'qtt.pgeometry.intersect2lines', 'qtt.pgeometry.intersect2lines', (['linePoints1_2', 'line_horizontal'], {}), '(linePoints1_2, line_horizontal)\n', (4686, 4718), False, 'import qtt\n'), ((4744, 4766), 'qtt.pgeometry.dehom', 'qtt.pgeometry.dehom', (['i'], {}), '(i)\n', (4763, 4766), False, 'import qtt\n'), ((6280, 6289), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (6287, 6289), True, 'import matplotlib.pyplot as plt\n'), ((6594, 6707), 'matplotlib.pyplot.annotate', 'plt.annotate', (["('Length %s: %.2f mV' % (gate, line_length))"], {'xy': '(0.05, 0.1)', 'xycoords': '"""axes fraction"""', 'color': '"""k"""'}), "('Length %s: %.2f mV' % (gate, line_length), xy=(0.05, 0.1),\n xycoords='axes fraction', color='k')\n", (6606, 6707), True, 'import matplotlib.pyplot as plt\n'), ((6714, 6787), 'matplotlib.pyplot.annotate', 'plt.annotate', (['title'], {'xy': '(0.05, 0.05)', 'xycoords': '"""axes fraction"""', 'color': '"""k"""'}), "(title, xy=(0.05, 0.05), xycoords='axes fraction', color='k')\n", (6726, 6787), True, 'import matplotlib.pyplot as plt\n'), ((7711, 7720), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (7718, 7720), True, 'import matplotlib.pyplot as plt\n'), ((8018, 8132), 'matplotlib.pyplot.annotate', 'plt.annotate', (["('Length %s: %.2f mV' % (gate, line_length))"], {'xy': '(0.05, 0.1)', 'xycoords': '"""axes fraction"""', 'color': '"""k"""'}), "('Length %s: %.2f mV' % (gate, line_length), xy=(0.05, 0.1),\n xycoords='axes fraction', color='k')\n", (8030, 8132), True, 'import matplotlib.pyplot as plt\n'), ((8139, 8212), 'matplotlib.pyplot.annotate', 'plt.annotate', (['title'], {'xy': '(0.05, 0.05)', 'xycoords': '"""axes fraction"""', 'color': '"""k"""'}), "(title, xy=(0.05, 0.05), xycoords='axes fraction', color='k')\n", (8151, 8212), True, 'import matplotlib.pyplot as plt\n'), ((8331, 8384), 'numpy.array', 'np.array', (['[[24.0, 38.0, 40.0], [135.0, 128.0, 111.0]]'], {}), '([[24.0, 38.0, 40.0], [135.0, 128.0, 111.0]])\n', (8339, 8384), True, 'import numpy as np\n'), ((8422, 8449), 'numpy.array', 'np.array', (['[[40.4], [127.0]]'], {}), '([[40.4], [127.0]])\n', (8430, 8449), True, 'import numpy as np\n'), ((8499, 8515), 'numpy.abs', 'np.abs', (['(r - 53.3)'], {}), '(r - 53.3)\n', (8505, 8515), True, 'import numpy as np\n'), ((6336, 6380), 'numpy.round', 'np.round', (["results['clicked_points'][0, 2]", '(2)'], {}), "(results['clicked_points'][0, 2], 2)\n", (6344, 6380), True, 'import numpy as np\n'), ((6382, 6427), 'numpy.round', 'np.round', (["results['intersection_point'][0]", '(2)'], {}), "(results['intersection_point'][0], 2)\n", (6390, 6427), True, 'import numpy as np\n'), ((7767, 7811), 'numpy.round', 'np.round', (["results['clicked_points'][0, 2]", '(2)'], {}), "(results['clicked_points'][0, 2], 2)\n", (7775, 7811), True, 'import numpy as np\n'), ((7813, 7858), 'numpy.round', 'np.round', (["results['intersection_point'][0]", '(2)'], {}), "(results['intersection_point'][0], 2)\n", (7821, 7858), True, 'import numpy as np\n'), ((6242, 6259), 'matplotlib.pyplot.get_fignums', 'plt.get_fignums', ([], {}), '()\n', (6257, 6259), True, 'import matplotlib.pyplot as plt\n'), ((7673, 7690), 'matplotlib.pyplot.get_fignums', 'plt.get_fignums', ([], {}), '()\n', (7688, 7690), True, 'import matplotlib.pyplot as plt\n')]
from django.db import models import iipimage.fields import iipimage.storage import sculpture.constants from .base_model import BaseModel from .contributor import Contributor from .image_status import ImageStatus class BaseImage (BaseModel): """Abstract model for all images.""" SOURCE_FORMATS = (('analogue', 'Analogue'), ('digital', 'Digital')) image = iipimage.fields.ImageField( height_field='height', width_field='width', storage=iipimage.storage.image_storage, upload_to=iipimage.storage.get_image_path, help_text='Accepts RAW, TIFF and JPEG files', blank=True, null=True) status = models.ForeignKey( ImageStatus, related_name='%(app_label)s_%(class)s_images', blank=True) photographer = models.ForeignKey( Contributor, blank=True, null=True, related_name='%(app_label)s_%(class)s_images') caption = models.CharField(blank=True, max_length=256) description = models.TextField(blank=True) source_format = models.CharField(blank=True, choices=SOURCE_FORMATS, max_length=12) upload_file_format = models.CharField(blank=True, max_length=10) upload_filename = models.CharField(blank=True, max_length=128) resolution = models.IntegerField(blank=True, help_text='Pixels per inch.', null=True) # width and height are automatically set (via height_field and # width_field on self.image). The information may still be useful # to see, so do not set editable=False. width = models.IntegerField(help_text='Width in pixels.', blank=True) height = models.IntegerField(help_text='Height in pixels.', blank=True) bit_depth = models.CharField(blank=True, max_length=12) colour_mode = models.CharField(blank=True, max_length=12) camera_details = models.CharField(blank=True, max_length=256) photo_date = models.CharField( blank=True, help_text='Date the photo was taken (eg: 01 Jan 2013).', max_length=32) editing_software = models.CharField(blank=True, max_length=128) editing_notes = models.TextField(blank=True) order = models.IntegerField(default=2) copyright = models.TextField(blank=True, verbose_name="Copyright Information") class Meta: abstract = True app_label = 'sculpture' ordering = ['order'] def __str__ (self): return self.caption def save (self, *args, **kwargs): # Automatically populate various metadata fields based on the # image file. if not self.id: # Set a status for the image. self.status = ImageStatus.objects.get( name=sculpture.constants.IMAGE_STATUS_GOOD) super(BaseImage, self).save(*args, **kwargs) def get_metadata (self, site): """Returns a dictionary of metadata for this image.""" metadata = {'filename': self.image.name, 'caption': self.caption, 'date': self.photo_date, 'visit date': site.visit_date} contributors = '; '.join([author.name for author in site.authors.all()]) metadata['fieldworkers'] = contributors if self.photographer: metadata['photographer'] = self.photographer.name for field, value in metadata.items(): if value is not None: metadata[field] = value.encode('utf-8') return metadata # Linked thumbnail for use in the admin. # Adapted from http://djangosnippets.org/snippets/162/ def linked_thumbnail (self): """Displays thumbnail-size image linked to the full image.""" html = '' if self.id: html = '<a href="%s">%s</a>' % (self.image.url, self.thumbnail(70)) return html linked_thumbnail.allow_tags = True def thumbnail (self, height=500): """Displays thumbnail-size image.""" html = '' if self.id: image = self.image thumbnail_url = image.thumbnail_url(height=height) html = '<div overflow: hidden;"><img height="%d" src="%s"></div>' % (height, thumbnail_url) return html thumbnail.allow_tags = True # Linked thumbnail for use in the admin. # Adapted from http://djangosnippets.org/snippets/162/ def thumbnail_site (self): """Displays thumbnail-size image linked to the full image.""" html = '' if self.id: html = '<a href="%s" title="Photograph by: %s">%s</a>' % (self.image.url, self.photographer, self.thumbnail(640)) return html
[ "django.db.models.ForeignKey", "django.db.models.TextField", "django.db.models.IntegerField", "django.db.models.CharField" ]
[((659, 753), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ImageStatus'], {'related_name': '"""%(app_label)s_%(class)s_images"""', 'blank': '(True)'}), "(ImageStatus, related_name=\n '%(app_label)s_%(class)s_images', blank=True)\n", (676, 753), False, 'from django.db import models\n'), ((777, 882), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Contributor'], {'blank': '(True)', 'null': '(True)', 'related_name': '"""%(app_label)s_%(class)s_images"""'}), "(Contributor, blank=True, null=True, related_name=\n '%(app_label)s_%(class)s_images')\n", (794, 882), False, 'from django.db import models\n'), ((909, 953), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(256)'}), '(blank=True, max_length=256)\n', (925, 953), False, 'from django.db import models\n'), ((972, 1000), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)'}), '(blank=True)\n', (988, 1000), False, 'from django.db import models\n'), ((1021, 1088), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': 'SOURCE_FORMATS', 'max_length': '(12)'}), '(blank=True, choices=SOURCE_FORMATS, max_length=12)\n', (1037, 1088), False, 'from django.db import models\n'), ((1151, 1194), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(10)'}), '(blank=True, max_length=10)\n', (1167, 1194), False, 'from django.db import models\n'), ((1217, 1261), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(128)'}), '(blank=True, max_length=128)\n', (1233, 1261), False, 'from django.db import models\n'), ((1279, 1351), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'blank': '(True)', 'help_text': '"""Pixels per inch."""', 'null': '(True)'}), "(blank=True, help_text='Pixels per inch.', null=True)\n", (1298, 1351), False, 'from django.db import models\n'), ((1582, 1643), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'help_text': '"""Width in pixels."""', 'blank': '(True)'}), "(help_text='Width in pixels.', blank=True)\n", (1601, 1643), False, 'from django.db import models\n'), ((1657, 1719), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'help_text': '"""Height in pixels."""', 'blank': '(True)'}), "(help_text='Height in pixels.', blank=True)\n", (1676, 1719), False, 'from django.db import models\n'), ((1736, 1779), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(12)'}), '(blank=True, max_length=12)\n', (1752, 1779), False, 'from django.db import models\n'), ((1798, 1841), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(12)'}), '(blank=True, max_length=12)\n', (1814, 1841), False, 'from django.db import models\n'), ((1863, 1907), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(256)'}), '(blank=True, max_length=256)\n', (1879, 1907), False, 'from django.db import models\n'), ((1925, 2030), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'help_text': '"""Date the photo was taken (eg: 01 Jan 2013)."""', 'max_length': '(32)'}), "(blank=True, help_text=\n 'Date the photo was taken (eg: 01 Jan 2013).', max_length=32)\n", (1941, 2030), False, 'from django.db import models\n'), ((2066, 2110), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(128)'}), '(blank=True, max_length=128)\n', (2082, 2110), False, 'from django.db import models\n'), ((2131, 2159), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)'}), '(blank=True)\n', (2147, 2159), False, 'from django.db import models\n'), ((2172, 2202), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(2)'}), '(default=2)\n', (2191, 2202), False, 'from django.db import models\n'), ((2219, 2285), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'verbose_name': '"""Copyright Information"""'}), "(blank=True, verbose_name='Copyright Information')\n", (2235, 2285), False, 'from django.db import models\n')]
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='isobar', version='0.1.1', description='A Python library to express and manipulate musical patterns', long_description = open("README.md", "r").read(), long_description_content_type = "text/markdown", author='<NAME>', author_email='<EMAIL>', url='https://github.com/ideoforms/isobar', packages=find_packages(), install_requires=['python-osc', 'mido', 'python-rtmidi'], keywords=['sound', 'music', 'composition'], classifiers=[ 'Topic :: Multimedia :: Sound/Audio', 'Topic :: Artistic Software', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers' ], setup_requires=['pytest-runner'], tests_require=['pytest', 'pytest-timeout'] )
[ "setuptools.find_packages" ]
[((410, 425), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (423, 425), False, 'from setuptools import setup, find_packages\n')]
# Copyright 2015 <NAME> # # 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 sys import math from vector import Vector from config import DPI, TAU, TIGHT_LARGE_BOLT_RADIUS, WALL_ANCHOR_RADIUS, WALL_ANCHOR_OFFSET import draw PADDING = DPI*1 CORNER_RADIUS = DPI*0.25 CORNER_POINTS = 32 FOOT_WIDTH = PADDING - 2*CORNER_RADIUS ADD_FEET = False ADD_WALL_ANCHOR_HOLES = False def generate(data, color): # Deduce size and position of frame, and its holes, from the existing data. minX = DPI*100 minY = DPI*100 maxX = -DPI*100 maxY = -DPI*100 floorY = -DPI*100 holes = [] for piece in data["pieces"]: cx = piece["cx"] cy = piece["cy"] minX = min(minX, cx) minY = min(minY, cy) maxX = max(maxX, cx) maxY = max(maxY, cy) for v in piece["points"]: floorY = max(floorY, cy + v.y) for hole in holes: if hole["cx"] == cx and hole["cy"] == cy: break else: holes.append({ "cx": cx, "cy": cy, "r": TIGHT_LARGE_BOLT_RADIUS, }) # Add hole in lower-left since there are no axles there. holes.append({ "cx": minX, "cy": maxY, "r": TIGHT_LARGE_BOLT_RADIUS, }) sys.stderr.write("The frame has %d holes.\n" % len(holes)) # Expand margin. minX -= PADDING minY -= PADDING maxX += PADDING maxY += PADDING floorY += PADDING # Draw frame. P = [] P.append(Vector(minX, minY)) P.append(Vector(maxX, minY)) if ADD_FEET: P.append(Vector(maxX, floorY)) P.append(Vector(maxX - FOOT_WIDTH, floorY)) P.append(Vector(maxX - FOOT_WIDTH, maxY)) P.append(Vector(minX + FOOT_WIDTH, maxY)) P.append(Vector(minX + FOOT_WIDTH, floorY)) P.append(Vector(minX, floorY)) else: P.append(Vector(maxX, maxY)) P.append(Vector(minX, maxY)) # Do not close this, the round_corners() function does it. P = draw.round_corners(P, CORNER_RADIUS, CORNER_POINTS) width = (maxX - minX)/DPI height = ((floorY if ADD_FEET else maxY) - minY)/DPI sys.stderr.write("Frame is %.1fx%.1f inches\n" % (width, height)) if width > 24 or height > 18: sys.stderr.write("------------------ FRAME TOO LARGE -----------------------\n") # Front piece. piece = { "cx": 0, "cy": 0, "cz": 9, "type": "frame", "color": color, "speed": 0, "points": P, "holes": holes, } data["pieces"].append(piece) # Back piece. piece = piece.copy() # Add holes for hanging frame to wall. holes = holes[:] if ADD_WALL_ANCHOR_HOLES: # XXX Can probably delete this. piece["holes"] = holes holes.append({ "cx": minX + WALL_ANCHOR_OFFSET + PADDING, "cy": minY + PADDING, "r": WALL_ANCHOR_RADIUS, }) holes.append({ "cx": maxX - WALL_ANCHOR_OFFSET - PADDING, "cy": minY + PADDING, "r": WALL_ANCHOR_RADIUS, }) holes.append({ "cx": minX + WALL_ANCHOR_OFFSET + PADDING, "cy": maxY - PADDING, "r": WALL_ANCHOR_RADIUS, }) holes.append({ "cx": maxX - WALL_ANCHOR_OFFSET - PADDING, "cy": maxY - PADDING, "r": WALL_ANCHOR_RADIUS, }) piece["cz"] = -3 data["pieces"].append(piece)
[ "sys.stderr.write", "vector.Vector", "draw.round_corners" ]
[((2554, 2605), 'draw.round_corners', 'draw.round_corners', (['P', 'CORNER_RADIUS', 'CORNER_POINTS'], {}), '(P, CORNER_RADIUS, CORNER_POINTS)\n', (2572, 2605), False, 'import draw\n'), ((2698, 2763), 'sys.stderr.write', 'sys.stderr.write', (["('Frame is %.1fx%.1f inches\\n' % (width, height))"], {}), "('Frame is %.1fx%.1f inches\\n' % (width, height))\n", (2714, 2763), False, 'import sys\n'), ((2046, 2064), 'vector.Vector', 'Vector', (['minX', 'minY'], {}), '(minX, minY)\n', (2052, 2064), False, 'from vector import Vector\n'), ((2079, 2097), 'vector.Vector', 'Vector', (['maxX', 'minY'], {}), '(maxX, minY)\n', (2085, 2097), False, 'from vector import Vector\n'), ((2806, 2891), 'sys.stderr.write', 'sys.stderr.write', (['"""------------------ FRAME TOO LARGE -----------------------\n"""'], {}), "('------------------ FRAME TOO LARGE -----------------------\\n'\n )\n", (2822, 2891), False, 'import sys\n'), ((2133, 2153), 'vector.Vector', 'Vector', (['maxX', 'floorY'], {}), '(maxX, floorY)\n', (2139, 2153), False, 'from vector import Vector\n'), ((2172, 2205), 'vector.Vector', 'Vector', (['(maxX - FOOT_WIDTH)', 'floorY'], {}), '(maxX - FOOT_WIDTH, floorY)\n', (2178, 2205), False, 'from vector import Vector\n'), ((2224, 2255), 'vector.Vector', 'Vector', (['(maxX - FOOT_WIDTH)', 'maxY'], {}), '(maxX - FOOT_WIDTH, maxY)\n', (2230, 2255), False, 'from vector import Vector\n'), ((2274, 2305), 'vector.Vector', 'Vector', (['(minX + FOOT_WIDTH)', 'maxY'], {}), '(minX + FOOT_WIDTH, maxY)\n', (2280, 2305), False, 'from vector import Vector\n'), ((2324, 2357), 'vector.Vector', 'Vector', (['(minX + FOOT_WIDTH)', 'floorY'], {}), '(minX + FOOT_WIDTH, floorY)\n', (2330, 2357), False, 'from vector import Vector\n'), ((2376, 2396), 'vector.Vector', 'Vector', (['minX', 'floorY'], {}), '(minX, floorY)\n', (2382, 2396), False, 'from vector import Vector\n'), ((2425, 2443), 'vector.Vector', 'Vector', (['maxX', 'maxY'], {}), '(maxX, maxY)\n', (2431, 2443), False, 'from vector import Vector\n'), ((2462, 2480), 'vector.Vector', 'Vector', (['minX', 'maxY'], {}), '(minX, maxY)\n', (2468, 2480), False, 'from vector import Vector\n')]
import json from django.test import TestCase, Client from django.urls import reverse from django.utils import timezone from rest_framework import status from .models import User, SignUpCode from .auth import auth_token, passwd_token class UserTestCase(TestCase): """User test case""" def setUp(self): self.user = User( firstName='User', middleName='User', lastName='User', username='user', password='<PASSWORD>', birthday='1986-05-12', phone='55 4351 8691' ) self.user.set_password('<PASSWORD>') self.user.save() self.signup_code = SignUpCode.objects.create(email='<EMAIL>') self.client = Client() def tearDown(self): self.user.delete() self.signup_code.delete() def test_password_hash(self): self.assertTrue(self.user.password.startswith('<PASSWORD>')) self.assertEqual(len(self.user.password), 78) def test_signup_available(self): path = reverse('signup-available') response = self.client.post(path, json.dumps({ 'username': 'user2' }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_signup_mail(self): path = reverse('signup-mail') response = self.client.post(path, json.dumps({ 'email': '<EMAIL>' }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_signup_check(self): path = reverse('signup-check') response = self.client.post(path, json.dumps({ 'email': '<EMAIL>', 'code': self.signup_code.code }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_signup(self): path = reverse('accounts-signup') response = self.client.post(path, json.dumps({ 'firstName': 'User 2', 'middleName': 'User 2', 'lastName': 'User 2', 'username': 'user2', 'password': '<PASSWORD>', 'email': '<EMAIL>', 'birthday': '1987-06-20', 'phone': '55 4530 2942', 'code': self.signup_code.code }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_signin(self): path = reverse('accounts-signin') response = self.client.post(path, json.dumps({ 'username': 'user', 'password': '<PASSWORD>' }), content_type='application/json') data = response.json() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('token' in data.keys()) def test_passwd_change(self): path = reverse('passwd-change') token = auth_token(self.user) response = self.client.post(path, json.dumps({ 'current': 'p455w0rd', 'password': '<PASSWORD>' }), content_type='application/json', HTTP_AUTHORIZATION='Token %s' % token ) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_passwd_mail(self): path = reverse('passwd-mail') response = self.client.post(path, json.dumps({ 'username': 'user' }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_passwd_check(self): path = reverse('passwd-check') token = passwd_token(self.user) response = self.client.post(path, content_type='application/json', HTTP_AUTHORIZATION='Token %s' % token ) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_passwd_reset(self): path = reverse('passwd-reset') token = passwd_token(self.user) response = self.client.post(path, json.dumps({ 'password': '<PASSWORD>' }), content_type='application/json', HTTP_AUTHORIZATION='Token %s' % token ) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_me_profile_update(self): path = reverse('me-profile') token = auth_token(self.user) response = self.client.patch(path, json.dumps({ 'firstName': 'User', 'middleName': 'User', 'lastName': 'User', 'birthday': '1994-08-14' }), content_type='application/json', HTTP_AUTHORIZATION='Token %s' % token ) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_user_list(self): path = reverse('user-list') token = auth_token(self.user) response = self.client.get( path, content_type='application/json', HTTP_AUTHORIZATION='Token %s' % token ) data = response.json() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('results' in data.keys()) self.assertTrue(isinstance(data['results'], list))
[ "django.urls.reverse", "json.dumps", "django.test.Client" ]
[((735, 743), 'django.test.Client', 'Client', ([], {}), '()\n', (741, 743), False, 'from django.test import TestCase, Client\n'), ((1041, 1068), 'django.urls.reverse', 'reverse', (['"""signup-available"""'], {}), "('signup-available')\n", (1048, 1068), False, 'from django.urls import reverse\n'), ((1318, 1340), 'django.urls.reverse', 'reverse', (['"""signup-mail"""'], {}), "('signup-mail')\n", (1325, 1340), False, 'from django.urls import reverse\n'), ((1590, 1613), 'django.urls.reverse', 'reverse', (['"""signup-check"""'], {}), "('signup-check')\n", (1597, 1613), False, 'from django.urls import reverse\n'), ((1900, 1926), 'django.urls.reverse', 'reverse', (['"""accounts-signup"""'], {}), "('accounts-signup')\n", (1907, 1926), False, 'from django.urls import reverse\n'), ((2469, 2495), 'django.urls.reverse', 'reverse', (['"""accounts-signin"""'], {}), "('accounts-signin')\n", (2476, 2495), False, 'from django.urls import reverse\n'), ((2852, 2876), 'django.urls.reverse', 'reverse', (['"""passwd-change"""'], {}), "('passwd-change')\n", (2859, 2876), False, 'from django.urls import reverse\n'), ((3252, 3274), 'django.urls.reverse', 'reverse', (['"""passwd-mail"""'], {}), "('passwd-mail')\n", (3259, 3274), False, 'from django.urls import reverse\n'), ((3524, 3547), 'django.urls.reverse', 'reverse', (['"""passwd-check"""'], {}), "('passwd-check')\n", (3531, 3547), False, 'from django.urls import reverse\n'), ((3853, 3876), 'django.urls.reverse', 'reverse', (['"""passwd-reset"""'], {}), "('passwd-reset')\n", (3860, 3876), False, 'from django.urls import reverse\n'), ((4237, 4258), 'django.urls.reverse', 'reverse', (['"""me-profile"""'], {}), "('me-profile')\n", (4244, 4258), False, 'from django.urls import reverse\n'), ((4709, 4729), 'django.urls.reverse', 'reverse', (['"""user-list"""'], {}), "('user-list')\n", (4716, 4729), False, 'from django.urls import reverse\n'), ((1112, 1145), 'json.dumps', 'json.dumps', (["{'username': 'user2'}"], {}), "({'username': 'user2'})\n", (1122, 1145), False, 'import json\n'), ((1384, 1416), 'json.dumps', 'json.dumps', (["{'email': '<EMAIL>'}"], {}), "({'email': '<EMAIL>'})\n", (1394, 1416), False, 'import json\n'), ((1657, 1720), 'json.dumps', 'json.dumps', (["{'email': '<EMAIL>', 'code': self.signup_code.code}"], {}), "({'email': '<EMAIL>', 'code': self.signup_code.code})\n", (1667, 1720), False, 'import json\n'), ((1970, 2212), 'json.dumps', 'json.dumps', (["{'firstName': 'User 2', 'middleName': 'User 2', 'lastName': 'User 2',\n 'username': 'user2', 'password': '<PASSWORD>', 'email': '<EMAIL>',\n 'birthday': '1987-06-20', 'phone': '55 4530 2942', 'code': self.\n signup_code.code}"], {}), "({'firstName': 'User 2', 'middleName': 'User 2', 'lastName':\n 'User 2', 'username': 'user2', 'password': '<PASSWORD>', 'email':\n '<EMAIL>', 'birthday': '1987-06-20', 'phone': '55 4530 2942', 'code':\n self.signup_code.code})\n", (1980, 2212), False, 'import json\n'), ((2539, 2597), 'json.dumps', 'json.dumps', (["{'username': 'user', 'password': '<PASSWORD>'}"], {}), "({'username': 'user', 'password': '<PASSWORD>'})\n", (2549, 2597), False, 'import json\n'), ((2958, 3019), 'json.dumps', 'json.dumps', (["{'current': 'p455w0rd', 'password': '<PASSWORD>'}"], {}), "({'current': 'p455w0rd', 'password': '<PASSWORD>'})\n", (2968, 3019), False, 'import json\n'), ((3318, 3350), 'json.dumps', 'json.dumps', (["{'username': 'user'}"], {}), "({'username': 'user'})\n", (3328, 3350), False, 'import json\n'), ((3960, 3998), 'json.dumps', 'json.dumps', (["{'password': '<PASSWORD>'}"], {}), "({'password': '<PASSWORD>'})\n", (3970, 3998), False, 'import json\n'), ((4341, 4446), 'json.dumps', 'json.dumps', (["{'firstName': 'User', 'middleName': 'User', 'lastName': 'User', 'birthday':\n '1994-08-14'}"], {}), "({'firstName': 'User', 'middleName': 'User', 'lastName': 'User',\n 'birthday': '1994-08-14'})\n", (4351, 4446), False, 'import json\n')]
""" Ship Graveyard Simulator Prologue """ #pylint: disable=C0103 from protonfixes import util def main(): """ needs builtin vulkan-1 """ util.set_environment('WINEDLLOVERRIDES','vulkan-1=b')
[ "protonfixes.util.set_environment" ]
[((152, 206), 'protonfixes.util.set_environment', 'util.set_environment', (['"""WINEDLLOVERRIDES"""', '"""vulkan-1=b"""'], {}), "('WINEDLLOVERRIDES', 'vulkan-1=b')\n", (172, 206), False, 'from protonfixes import util\n')]
from tests.utils import W3CTestCase class TestFlexbox_Flex110Unitless(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'flexbox_flex-1-1-0-unitless'))
[ "tests.utils.W3CTestCase.find_tests" ]
[((103, 166), 'tests.utils.W3CTestCase.find_tests', 'W3CTestCase.find_tests', (['__file__', '"""flexbox_flex-1-1-0-unitless"""'], {}), "(__file__, 'flexbox_flex-1-1-0-unitless')\n", (125, 166), False, 'from tests.utils import W3CTestCase\n')]
import setuptools setuptools.setup( name='pynetem', version='0.1', author='<NAME>', author_email='<EMAIL>', url='https://github.com/manojrege/pynetem', description='A Python wrapper library for network emulation on MacOS', long_description=open('README.md').read(), license=open('LICENSE').read(), packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "LICENSE :: OSI APPROVED :: BSD LICENSE", ], package_data = {'pynetem': ['data/dummynet.conf.j2']}, include_package_data = True, )
[ "setuptools.find_packages" ]
[((344, 370), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (368, 370), False, 'import setuptools\n')]
import face_recognition import cv2 import numpy as np import os import re from itertools import chain known_people_folder='./database' def scan_known_people(known_people_folder): known_names = [] known_face_encodings = [] for file in image_files_in_folder(known_people_folder): basename = os.path.splitext(os.path.basename(file))[0] img = face_recognition.load_image_file(file) encodings = face_recognition.face_encodings(img) print('in face finding function') if len(encodings) > 1: click.echo("WARNING: More than one face found in {}. Only considering the first face.".format(file)) if len(encodings) == 0: click.echo("WARNING: No faces found in {}. Ignoring file.".format(file)) else: known_names.append(basename) known_face_encodings.append(encodings[0]) def main(known_people_folder, image_to_check, cpus, tolerance, show_distance): print('in second main') known_face_encodings.append(encodings[0]) return known_names, known_face_encodings def image_files_in_folder(folder): print('in image files in folder fucntion') return [os.path.join(folder, f) for f in os.listdir(folder) if re.match(r'.*\.(jpg|jpeg|png)', f, flags=re.I)] #improved:- # 1. Process each video frame at 1/4 resolution (though still display it at full resolution) # 2. Only detect faces in every other frame of video. #There you go, i pulled a little sneaky on you. known_people_folder='./database' # Get a reference to webcam #0 (the default one) video_capture = cv2.VideoCapture(0) # Create arrays of known face encodings and their names known_face_names,known_face_encodings = scan_known_people(known_people_folder) # Initialize some variables face_locations = [] face_encodings = [] face_names = [] process_this_frame = True while True: # Grab a single frame of video ret, frame = video_capture.read() #Converting the imgage to HLS for brightness(Light intersity) Detection imgHLS = cv2.cvtColor(frame, cv2.COLOR_BGR2HLS) Lchannel = imgHLS[:,:,1] a=list(chain.from_iterable(Lchannel)) brightness=sum(a)/len(a) if(brightness<=75): condition="Very Poor" if(brightness<=85 and brightness >75): condition=" Poor" if(brightness<=95 and brightness >85): condition="Good" if(brightness <=105 and brightness >95): condition="Very Poor" if(brightness >105): condition="Excellent" print(condition) #print(brightness) #np.array(Lchannel).tolist() #print(type(Lchannel)) # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] # Only process every other frame of video to save time if process_this_frame: # Find all the faces and face encodings in the current frame of video face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: # See if the face is a match for the known face(s) matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" # # If a match was found in known_face_encodings, just use the first one. # if True in matches: # first_match_index = matches.index(True) # name = known_face_names[first_match_index] # Or instead, use the known face with the smallest distance to the new face face_distances = face_recognition.face_distance(known_face_encodings, face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = known_face_names[best_match_index] face_names.append(name) process_this_frame = not process_this_frame # Display the results for (top, right, bottom, left), name in zip(face_locations, face_names): # Scale back up face locations since the frame we detected in was scaled to 1/4 size top *= 4 right *= 4 bottom *= 4 left *= 4 # Draw a box around the face cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) # Draw a label with a name below the face cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) cv2.putText(frame,'Brightness/Visiblity: '+condition,(80,30), font,1,(255,255,255),1,cv2.LINE_AA) cv2.putText(frame,'Press Q to Quit',(5,470), font,0.5,(255,255,255),1,cv2.LINE_AA) # Display the resulting image cv2.imshow('Video', frame) # Hit 'q' on the keyboard to quit! if cv2.waitKey(1) & 0xFF == ord('q'): break # Release handle to the webcam video_capture.release() cv2.destroyAllWindows()
[ "face_recognition.compare_faces", "numpy.argmin", "cv2.rectangle", "cv2.imshow", "os.path.join", "cv2.cvtColor", "face_recognition.face_encodings", "cv2.destroyAllWindows", "cv2.resize", "face_recognition.face_distance", "os.path.basename", "cv2.waitKey", "re.match", "os.listdir", "cv2.putText", "cv2.VideoCapture", "face_recognition.face_locations", "face_recognition.load_image_file", "itertools.chain.from_iterable" ]
[((1610, 1629), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1626, 1629), False, 'import cv2\n'), ((5245, 5268), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5266, 5268), False, 'import cv2\n'), ((2053, 2091), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HLS'], {}), '(frame, cv2.COLOR_BGR2HLS)\n', (2065, 2091), False, 'import cv2\n'), ((2732, 2775), 'cv2.resize', 'cv2.resize', (['frame', '(0, 0)'], {'fx': '(0.25)', 'fy': '(0.25)'}), '(frame, (0, 0), fx=0.25, fy=0.25)\n', (2742, 2775), False, 'import cv2\n'), ((5066, 5092), 'cv2.imshow', 'cv2.imshow', (['"""Video"""', 'frame'], {}), "('Video', frame)\n", (5076, 5092), False, 'import cv2\n'), ((370, 408), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['file'], {}), '(file)\n', (402, 408), False, 'import face_recognition\n'), ((429, 465), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['img'], {}), '(img)\n', (460, 465), False, 'import face_recognition\n'), ((1193, 1216), 'os.path.join', 'os.path.join', (['folder', 'f'], {}), '(folder, f)\n', (1205, 1216), False, 'import os\n'), ((2137, 2166), 'itertools.chain.from_iterable', 'chain.from_iterable', (['Lchannel'], {}), '(Lchannel)\n', (2156, 2166), False, 'from itertools import chain\n'), ((3115, 3163), 'face_recognition.face_locations', 'face_recognition.face_locations', (['rgb_small_frame'], {}), '(rgb_small_frame)\n', (3146, 3163), False, 'import face_recognition\n'), ((3189, 3253), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['rgb_small_frame', 'face_locations'], {}), '(rgb_small_frame, face_locations)\n', (3220, 3253), False, 'import face_recognition\n'), ((4493, 4559), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(left, top)', '(right, bottom)', '(0, 0, 255)', '(2)'], {}), '(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n', (4506, 4559), False, 'import cv2\n'), ((4619, 4707), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(left, bottom - 35)', '(right, bottom)', '(0, 0, 255)', 'cv2.FILLED'], {}), '(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2\n .FILLED)\n', (4632, 4707), False, 'import cv2\n'), ((4750, 4829), 'cv2.putText', 'cv2.putText', (['frame', 'name', '(left + 6, bottom - 6)', 'font', '(1.0)', '(255, 255, 255)', '(1)'], {}), '(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n', (4761, 4829), False, 'import cv2\n'), ((4838, 4950), 'cv2.putText', 'cv2.putText', (['frame', "('Brightness/Visiblity: ' + condition)", '(80, 30)', 'font', '(1)', '(255, 255, 255)', '(1)', 'cv2.LINE_AA'], {}), "(frame, 'Brightness/Visiblity: ' + condition, (80, 30), font, 1,\n (255, 255, 255), 1, cv2.LINE_AA)\n", (4849, 4950), False, 'import cv2\n'), ((4944, 5039), 'cv2.putText', 'cv2.putText', (['frame', '"""Press Q to Quit"""', '(5, 470)', 'font', '(0.5)', '(255, 255, 255)', '(1)', 'cv2.LINE_AA'], {}), "(frame, 'Press Q to Quit', (5, 470), font, 0.5, (255, 255, 255),\n 1, cv2.LINE_AA)\n", (4955, 5039), False, 'import cv2\n'), ((1226, 1244), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (1236, 1244), False, 'import os\n'), ((1248, 1294), 're.match', 're.match', (['""".*\\\\.(jpg|jpeg|png)"""', 'f'], {'flags': 're.I'}), "('.*\\\\.(jpg|jpeg|png)', f, flags=re.I)\n", (1256, 1294), False, 'import re\n'), ((3409, 3476), 'face_recognition.compare_faces', 'face_recognition.compare_faces', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (3439, 3476), False, 'import face_recognition\n'), ((3864, 3931), 'face_recognition.face_distance', 'face_recognition.face_distance', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (3894, 3931), False, 'import face_recognition\n'), ((3963, 3988), 'numpy.argmin', 'np.argmin', (['face_distances'], {}), '(face_distances)\n', (3972, 3988), True, 'import numpy as np\n'), ((5140, 5154), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5151, 5154), False, 'import cv2\n'), ((329, 351), 'os.path.basename', 'os.path.basename', (['file'], {}), '(file)\n', (345, 351), False, 'import os\n')]
from socketclient import Client import socketio import csv from random import randrange import threading import time def toni(car_id): sio = None try: sio = socketio.Client(ssl_verify=False) sio.connect('http://localhost:3003/') except socketio.exceptions.ConnectionError: print('[ERROR] Server is off') @sio.event def notification(data): print('[INFO] Notification: ', data) @sio.event def message(data): print('[INFO] Message: ', data) @sio.event def bad_status(data): print('[ERROR] Bad status:', data) @sio.event def bad_notify(data): print('[ERROR] Bad notify:', data) @sio.event def connect(): socket.isConnected = True socket.send('id', socket.id) print("[INFO] Connected!") @sio.event def connect_error(): print("[ERROR] The connection failed!") @sio.event def disconnect(): socket.isConnected = False print("[INFO] Disconnected!") socket = Client(sio, car_id) pos = randrange(469) with open('cami.csv', 'r') as file: reader = list(csv.reader(file)) for i in range(pos, len(reader), 2): row = reader[i] socket.update_position(int(row[0]), int(row[1][1:])) time.sleep(3) for i in range(0, len(reader), 2): row = reader[i] socket.update_position(int(row[0]), int(row[1][1:])) time.sleep(3) socket.disconnect() print('End car ', car_id) threads = list() for index in range(1, 6): car = threading.Thread(target=toni, args=("CH000" + str(index),), daemon=True) threads.append(car) car.start() for thread in threads: thread.join() print("Main End")
[ "csv.reader", "socketio.Client", "socketclient.Client", "time.sleep", "random.randrange" ]
[((1035, 1054), 'socketclient.Client', 'Client', (['sio', 'car_id'], {}), '(sio, car_id)\n', (1041, 1054), False, 'from socketclient import Client\n'), ((1066, 1080), 'random.randrange', 'randrange', (['(469)'], {}), '(469)\n', (1075, 1080), False, 'from random import randrange\n'), ((175, 208), 'socketio.Client', 'socketio.Client', ([], {'ssl_verify': '(False)'}), '(ssl_verify=False)\n', (190, 208), False, 'import socketio\n'), ((1143, 1159), 'csv.reader', 'csv.reader', (['file'], {}), '(file)\n', (1153, 1159), False, 'import csv\n'), ((1311, 1324), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (1321, 1324), False, 'import time\n'), ((1474, 1487), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (1484, 1487), False, 'import time\n')]
# SpeechToText of multiple audio files in a directory # Using this code snippet you can convert multiple audio files from specific directory to the text format # It will make seperate .txt files for each audio file into the given directory path and will save the transcriptions of all audio files into those .txt files import symbl from os import listdir from os.path import isfile, join # returns lambda function with fileName which is under processing def save_transcriptions_in_file(fileName): return lambda conversation_object: on_success(conversation_object, fileName) # returns actual callback to save the transcriptions of a conversation in a file def on_success(conversation_object, fileName): transcriptions = conversation_object.get_messages() file = open(fileName + ".txt","w+") file.write(str(transcriptions)) file.close() # An ‘r’ preceding a string denotes a raw, (almost) un-escaped string. # The escape character is backslash, that is why a normal string will not work as a Windows path string. # If you are using Mac or Linux, no need to append `r` before <directory path> directory_path = r'<directory_path>' files = [join(directory_path, file) for file in listdir(directory_path) if isfile(join(directory_path, file))] # Process audio files in the above mentioned directory for file in files: job = symbl.Audio.process_file( # credentials={app_id: <app_id>, app_secret: <app_secret>}, #Optional, Don't add this parameter if you have symbl.conf file in your home directory file_path=file, wait=False).on_complete(save_transcriptions_in_file(file))
[ "symbl.Audio.process_file", "os.path.join", "os.listdir" ]
[((1164, 1190), 'os.path.join', 'join', (['directory_path', 'file'], {}), '(directory_path, file)\n', (1168, 1190), False, 'from os.path import isfile, join\n'), ((1203, 1226), 'os.listdir', 'listdir', (['directory_path'], {}), '(directory_path)\n', (1210, 1226), False, 'from os import listdir\n'), ((1237, 1263), 'os.path.join', 'join', (['directory_path', 'file'], {}), '(directory_path, file)\n', (1241, 1263), False, 'from os.path import isfile, join\n'), ((1351, 1403), 'symbl.Audio.process_file', 'symbl.Audio.process_file', ([], {'file_path': 'file', 'wait': '(False)'}), '(file_path=file, wait=False)\n', (1375, 1403), False, 'import symbl\n')]
import os import sys import h5py import argparse import numpy as np parser = argparse.ArgumentParser() parser.add_argument('--root', help='path to root directory') args = parser.parse_args() root = args.root fname = os.path.join(root, 'metadata/train.txt') flist = [os.path.join(root, 'h5', line.strip()) for line in open(fname, 'r')] fname = os.path.join(root, 'metadata', 'classes.txt') classes = [line.strip() for line in open(fname, 'r')] num_classes = len(classes) sizes = np.zeros(num_classes) total = np.zeros(num_classes) for fname in flist: print('> Processing {}...'.format(fname)) fin = h5py.File(fname) coords = fin['coords'][:] points = fin['points'][:] labels = fin['labels'][:] labels = labels.reshape(-1, 2) num_points = labels.shape[0] for i in range(num_classes): indices = (labels[:, 0] == i) size = np.sum(indices) sizes[i] += size if size == 0: continue total[i] += num_points freq = sizes / total weight = np.median(freq) / freq fname = os.path.join(root, 'metadata', 'weight.txt') print('> Saving statistics to {}...'.format(fname)) np.savetxt(fname, weight, fmt='%f')
[ "h5py.File", "numpy.sum", "argparse.ArgumentParser", "numpy.median", "numpy.savetxt", "numpy.zeros", "os.path.join" ]
[((79, 104), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (102, 104), False, 'import argparse\n'), ((220, 260), 'os.path.join', 'os.path.join', (['root', '"""metadata/train.txt"""'], {}), "(root, 'metadata/train.txt')\n", (232, 260), False, 'import os\n'), ((357, 402), 'os.path.join', 'os.path.join', (['root', '"""metadata"""', '"""classes.txt"""'], {}), "(root, 'metadata', 'classes.txt')\n", (369, 402), False, 'import os\n'), ((492, 513), 'numpy.zeros', 'np.zeros', (['num_classes'], {}), '(num_classes)\n', (500, 513), True, 'import numpy as np\n'), ((522, 543), 'numpy.zeros', 'np.zeros', (['num_classes'], {}), '(num_classes)\n', (530, 543), True, 'import numpy as np\n'), ((1049, 1093), 'os.path.join', 'os.path.join', (['root', '"""metadata"""', '"""weight.txt"""'], {}), "(root, 'metadata', 'weight.txt')\n", (1061, 1093), False, 'import os\n'), ((1146, 1181), 'numpy.savetxt', 'np.savetxt', (['fname', 'weight'], {'fmt': '"""%f"""'}), "(fname, weight, fmt='%f')\n", (1156, 1181), True, 'import numpy as np\n'), ((621, 637), 'h5py.File', 'h5py.File', (['fname'], {}), '(fname)\n', (630, 637), False, 'import h5py\n'), ((1017, 1032), 'numpy.median', 'np.median', (['freq'], {}), '(freq)\n', (1026, 1032), True, 'import numpy as np\n'), ((883, 898), 'numpy.sum', 'np.sum', (['indices'], {}), '(indices)\n', (889, 898), True, 'import numpy as np\n')]
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=import-error,print-statement,relative-import,protected-access """Unit tests for name_style_converter.py.""" import unittest from name_style_converter import NameStyleConverter from name_style_converter import tokenize_name class SmartTokenizerTest(unittest.TestCase): def test_simple_cases(self): self.assertEqual(tokenize_name('foo'), ['foo']) self.assertEqual(tokenize_name('fooBar'), ['foo', 'Bar']) self.assertEqual(tokenize_name('fooBarBaz'), ['foo', 'Bar', 'Baz']) self.assertEqual(tokenize_name('Baz'), ['Baz']) self.assertEqual(tokenize_name(''), []) self.assertEqual(tokenize_name('FOO'), ['FOO']) self.assertEqual(tokenize_name('foo2'), ['foo', '2']) def test_tricky_cases(self): self.assertEqual(tokenize_name('XMLHttpRequest'), ['XML', 'Http', 'Request']) self.assertEqual(tokenize_name('HTMLElement'), ['HTML', 'Element']) self.assertEqual(tokenize_name('WebGLRenderingContext'), ['WebGL', 'Rendering', 'Context']) self.assertEqual(tokenize_name('CanvasRenderingContext2D'), ['Canvas', 'Rendering', 'Context', '2D']) self.assertEqual(tokenize_name('CanvasRenderingContext2DAPITest'), ['Canvas', 'Rendering', 'Context', '2D', 'API', 'Test']) self.assertEqual(tokenize_name('SVGSVGElement'), ['SVG', 'SVG', 'Element']) self.assertEqual(tokenize_name('CanvasRenderingContext2D'), ['Canvas', 'Rendering', 'Context', '2D']) self.assertEqual(tokenize_name('CSSURLImageValue'), ['CSS', 'URL', 'Image', 'Value']) self.assertEqual(tokenize_name('CSSPropertyAPID'), ['CSS', 'Property', 'API', 'D']) self.assertEqual(tokenize_name('AXARIAGridCell'), ['AX', 'ARIA', 'Grid', 'Cell']) self.assertEqual(tokenize_name('CDATASection'), ['CDATA', 'Section']) self.assertEqual(tokenize_name('ASCIICType'), ['ASCII', 'CType']) self.assertEqual(tokenize_name('CString'), ['CString']) self.assertEqual(tokenize_name('HTMLDListElement'), ['HTML', 'DList', 'Element']) self.assertEqual(tokenize_name('HTMLOListElement'), ['HTML', 'OList', 'Element']) self.assertEqual(tokenize_name('HTMLIFrameElement'), ['HTML', 'IFrame', 'Element']) self.assertEqual(tokenize_name('HTMLPlugInElement'), ['HTML', 'PlugIn', 'Element']) # No special handling for OptGroup, FieldSet, and TextArea. self.assertEqual(tokenize_name('HTMLOptGroupElement'), ['HTML', 'Opt', 'Group', 'Element']) self.assertEqual(tokenize_name('HTMLFieldSetElement'), ['HTML', 'Field', 'Set', 'Element']) self.assertEqual(tokenize_name('HTMLTextAreaElement'), ['HTML', 'Text', 'Area', 'Element']) self.assertEqual(tokenize_name('Path2D'), ['Path', '2D']) self.assertEqual(tokenize_name('Point2D'), ['Point', '2D']) self.assertEqual(tokenize_name('CanvasRenderingContext2DState'), ['Canvas', 'Rendering', 'Context', '2D', 'State']) self.assertEqual(tokenize_name('Accelerated2dCanvas'), ['Accelerated', '2d', 'Canvas']) self.assertEqual(tokenize_name('RTCDTMFSender'), ['RTC', 'DTMF', 'Sender']) self.assertEqual(tokenize_name('WebGLCompressedTextureS3TCsRGB'), ['WebGL', 'Compressed', 'Texture', 'S3TC', 'sRGB']) self.assertEqual(tokenize_name('WebGL2CompressedTextureETC1'), ['WebGL2', 'Compressed', 'Texture', 'ETC1']) self.assertEqual(tokenize_name('EXTsRGB'), ['EXT', 'sRGB']) # 'PVRTC' contains a special token 'RTC', but it should be a # single token. self.assertEqual(tokenize_name('WebGLCompressedTexturePVRTC'), ['WebGL', 'Compressed', 'Texture', 'PVRTC']) self.assertEqual(tokenize_name('SVGFEBlendElement'), ['SVG', 'FE', 'Blend', 'Element']) self.assertEqual(tokenize_name('SVGMPathElement'), ['SVG', 'MPath', 'Element']) self.assertEqual(tokenize_name('SVGTSpanElement'), ['SVG', 'TSpan', 'Element']) self.assertEqual(tokenize_name('SVGURIReference'), ['SVG', 'URI', 'Reference']) self.assertEqual(tokenize_name('UTF16TextIterator'), ['UTF16', 'Text', 'Iterator']) self.assertEqual(tokenize_name('UTF8Decoder'), ['UTF8', 'Decoder']) self.assertEqual(tokenize_name('Uint8Array'), ['Uint8', 'Array']) self.assertEqual(tokenize_name('DOMWindowBase64'), ['DOM', 'Window', 'Base64']) self.assertEqual(tokenize_name('TextCodecLatin1'), ['Text', 'Codec', 'Latin1']) self.assertEqual(tokenize_name('V8BindingForCore'), ['V8', 'Binding', 'For', 'Core']) self.assertEqual(tokenize_name('V8DOMRect'), ['V8', 'DOM', 'Rect']) self.assertEqual(tokenize_name('String16MojomTraits'), ['String16', 'Mojom', 'Traits']) self.assertEqual(tokenize_name('V0InsertionPoint'), ['V0', 'Insertion', 'Point']) self.assertEqual(tokenize_name('ShadowDOMV0Test'), ['Shadow', 'DOM', 'V0', 'Test']) self.assertEqual(tokenize_name('ElementShadowV0'), ['Element', 'Shadow', 'V0']) self.assertEqual(tokenize_name('StubChromeClientForSPv2'), ['Stub', 'Chrome', 'Client', 'For', 'SPv2']) self.assertEqual(tokenize_name('SQLiteAuthorizer'), ['SQLite', 'Authorizer']) self.assertEqual(tokenize_name('XPathEvaluator'), ['XPath', 'Evaluator']) self.assertEqual(tokenize_name('IsXHTMLDocument'), ['Is', 'XHTML', 'Document']) self.assertEqual(tokenize_name('isHTMLDocument'), ['is', 'HTML', 'Document']) self.assertEqual(tokenize_name('matrix3d'), ['matrix', '3d']) def test_ignoring_characters(self): self.assertEqual(tokenize_name('Animation.idl'), ['Animation', 'idl']) self.assertEqual(tokenize_name('-webkit-appearance'), ['webkit', 'appearance']) self.assertEqual(tokenize_name(' foo_bar!#"$'), ['foo', 'bar']) class NameStyleConverterTest(unittest.TestCase): def test_snake_case(self): converter = NameStyleConverter('HTMLElement') self.assertEqual(converter.to_snake_case(), 'html_element') def test_upper_camel_case(self): converter = NameStyleConverter('someSuperThing') self.assertEqual(converter.to_upper_camel_case(), 'SomeSuperThing') converter = NameStyleConverter('SVGElement') self.assertEqual(converter.to_upper_camel_case(), 'SVGElement') converter = NameStyleConverter('cssExternalScannerPreload') self.assertEqual(converter.to_upper_camel_case(), 'CSSExternalScannerPreload') converter = NameStyleConverter('xpathExpression') self.assertEqual(converter.to_upper_camel_case(), 'XPathExpression') converter = NameStyleConverter('feDropShadow') self.assertEqual(converter.to_upper_camel_case(), 'FEDropShadow') def test_lower_camel_case(self): converter = NameStyleConverter('someSuperThing') self.assertEqual(converter.to_lower_camel_case(), 'someSuperThing') converter = NameStyleConverter('SVGElement') self.assertEqual(converter.to_lower_camel_case(), 'svgElement') converter = NameStyleConverter('documentURI') self.assertEqual(converter.to_lower_camel_case(), 'documentURI') converter = NameStyleConverter('-webkit-margin-start') self.assertEqual(converter.to_lower_camel_case(), 'webkitMarginStart') converter = NameStyleConverter('Accelerated2dCanvas') self.assertEqual(converter.to_lower_camel_case(), 'accelerated2dCanvas') def test_macro_case(self): converter = NameStyleConverter('WebGLBaz2D') self.assertEqual(converter.to_macro_case(), 'WEBGL_BAZ_2D') def test_all_cases(self): converter = NameStyleConverter('SVGScriptElement') self.assertEqual(converter.to_all_cases(), { 'snake_case': 'svg_script_element', 'upper_camel_case': 'SVGScriptElement', 'macro_case': 'SVG_SCRIPT_ELEMENT', })
[ "name_style_converter.NameStyleConverter", "name_style_converter.tokenize_name" ]
[((6291, 6324), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""HTMLElement"""'], {}), "('HTMLElement')\n", (6309, 6324), False, 'from name_style_converter import NameStyleConverter\n'), ((6451, 6487), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""someSuperThing"""'], {}), "('someSuperThing')\n", (6469, 6487), False, 'from name_style_converter import NameStyleConverter\n'), ((6584, 6616), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""SVGElement"""'], {}), "('SVGElement')\n", (6602, 6616), False, 'from name_style_converter import NameStyleConverter\n'), ((6709, 6756), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""cssExternalScannerPreload"""'], {}), "('cssExternalScannerPreload')\n", (6727, 6756), False, 'from name_style_converter import NameStyleConverter\n'), ((6864, 6901), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""xpathExpression"""'], {}), "('xpathExpression')\n", (6882, 6901), False, 'from name_style_converter import NameStyleConverter\n'), ((6999, 7033), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""feDropShadow"""'], {}), "('feDropShadow')\n", (7017, 7033), False, 'from name_style_converter import NameStyleConverter\n'), ((7166, 7202), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""someSuperThing"""'], {}), "('someSuperThing')\n", (7184, 7202), False, 'from name_style_converter import NameStyleConverter\n'), ((7299, 7331), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""SVGElement"""'], {}), "('SVGElement')\n", (7317, 7331), False, 'from name_style_converter import NameStyleConverter\n'), ((7424, 7457), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""documentURI"""'], {}), "('documentURI')\n", (7442, 7457), False, 'from name_style_converter import NameStyleConverter\n'), ((7551, 7593), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""-webkit-margin-start"""'], {}), "('-webkit-margin-start')\n", (7569, 7593), False, 'from name_style_converter import NameStyleConverter\n'), ((7693, 7734), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""Accelerated2dCanvas"""'], {}), "('Accelerated2dCanvas')\n", (7711, 7734), False, 'from name_style_converter import NameStyleConverter\n'), ((7868, 7900), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""WebGLBaz2D"""'], {}), "('WebGLBaz2D')\n", (7886, 7900), False, 'from name_style_converter import NameStyleConverter\n'), ((8020, 8058), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""SVGScriptElement"""'], {}), "('SVGScriptElement')\n", (8038, 8058), False, 'from name_style_converter import NameStyleConverter\n'), ((512, 532), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""foo"""'], {}), "('foo')\n", (525, 532), False, 'from name_style_converter import tokenize_name\n'), ((569, 592), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""fooBar"""'], {}), "('fooBar')\n", (582, 592), False, 'from name_style_converter import tokenize_name\n'), ((636, 662), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""fooBarBaz"""'], {}), "('fooBarBaz')\n", (649, 662), False, 'from name_style_converter import tokenize_name\n'), ((713, 733), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""Baz"""'], {}), "('Baz')\n", (726, 733), False, 'from name_style_converter import tokenize_name\n'), ((770, 787), 'name_style_converter.tokenize_name', 'tokenize_name', (['""""""'], {}), "('')\n", (783, 787), False, 'from name_style_converter import tokenize_name\n'), ((819, 839), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""FOO"""'], {}), "('FOO')\n", (832, 839), False, 'from name_style_converter import tokenize_name\n'), ((876, 897), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""foo2"""'], {}), "('foo2')\n", (889, 897), False, 'from name_style_converter import tokenize_name\n'), ((972, 1003), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""XMLHttpRequest"""'], {}), "('XMLHttpRequest')\n", (985, 1003), False, 'from name_style_converter import tokenize_name\n'), ((1059, 1087), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""HTMLElement"""'], {}), "('HTMLElement')\n", (1072, 1087), False, 'from name_style_converter import tokenize_name\n'), ((1136, 1174), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""WebGLRenderingContext"""'], {}), "('WebGLRenderingContext')\n", (1149, 1174), False, 'from name_style_converter import tokenize_name\n'), ((1262, 1303), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""CanvasRenderingContext2D"""'], {}), "('CanvasRenderingContext2D')\n", (1275, 1303), False, 'from name_style_converter import tokenize_name\n'), ((1397, 1445), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""CanvasRenderingContext2DAPITest"""'], {}), "('CanvasRenderingContext2DAPITest')\n", (1410, 1445), False, 'from name_style_converter import tokenize_name\n'), ((1555, 1585), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""SVGSVGElement"""'], {}), "('SVGSVGElement')\n", (1568, 1585), False, 'from name_style_converter import tokenize_name\n'), ((1640, 1681), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""CanvasRenderingContext2D"""'], {}), "('CanvasRenderingContext2D')\n", (1653, 1681), False, 'from name_style_converter import tokenize_name\n'), ((1776, 1809), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""CSSURLImageValue"""'], {}), "('CSSURLImageValue')\n", (1789, 1809), False, 'from name_style_converter import tokenize_name\n'), ((1870, 1902), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""CSSPropertyAPID"""'], {}), "('CSSPropertyAPID')\n", (1883, 1902), False, 'from name_style_converter import tokenize_name\n'), ((1962, 1993), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""AXARIAGridCell"""'], {}), "('AXARIAGridCell')\n", (1975, 1993), False, 'from name_style_converter import tokenize_name\n'), ((2053, 2082), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""CDATASection"""'], {}), "('CDATASection')\n", (2066, 2082), False, 'from name_style_converter import tokenize_name\n'), ((2132, 2159), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""ASCIICType"""'], {}), "('ASCIICType')\n", (2145, 2159), False, 'from name_style_converter import tokenize_name\n'), ((2206, 2230), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""CString"""'], {}), "('CString')\n", (2219, 2230), False, 'from name_style_converter import tokenize_name\n'), ((2271, 2304), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""HTMLDListElement"""'], {}), "('HTMLDListElement')\n", (2284, 2304), False, 'from name_style_converter import tokenize_name\n'), ((2361, 2394), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""HTMLOListElement"""'], {}), "('HTMLOListElement')\n", (2374, 2394), False, 'from name_style_converter import tokenize_name\n'), ((2451, 2485), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""HTMLIFrameElement"""'], {}), "('HTMLIFrameElement')\n", (2464, 2485), False, 'from name_style_converter import tokenize_name\n'), ((2543, 2577), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""HTMLPlugInElement"""'], {}), "('HTMLPlugInElement')\n", (2556, 2577), False, 'from name_style_converter import tokenize_name\n'), ((2704, 2740), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""HTMLOptGroupElement"""'], {}), "('HTMLOptGroupElement')\n", (2717, 2740), False, 'from name_style_converter import tokenize_name\n'), ((2804, 2840), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""HTMLFieldSetElement"""'], {}), "('HTMLFieldSetElement')\n", (2817, 2840), False, 'from name_style_converter import tokenize_name\n'), ((2904, 2940), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""HTMLTextAreaElement"""'], {}), "('HTMLTextAreaElement')\n", (2917, 2940), False, 'from name_style_converter import tokenize_name\n'), ((3005, 3028), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""Path2D"""'], {}), "('Path2D')\n", (3018, 3028), False, 'from name_style_converter import tokenize_name\n'), ((3071, 3095), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""Point2D"""'], {}), "('Point2D')\n", (3084, 3095), False, 'from name_style_converter import tokenize_name\n'), ((3139, 3185), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""CanvasRenderingContext2DState"""'], {}), "('CanvasRenderingContext2DState')\n", (3152, 3185), False, 'from name_style_converter import tokenize_name\n'), ((3288, 3324), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""Accelerated2dCanvas"""'], {}), "('Accelerated2dCanvas')\n", (3301, 3324), False, 'from name_style_converter import tokenize_name\n'), ((3385, 3415), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""RTCDTMFSender"""'], {}), "('RTCDTMFSender')\n", (3398, 3415), False, 'from name_style_converter import tokenize_name\n'), ((3470, 3517), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""WebGLCompressedTextureS3TCsRGB"""'], {}), "('WebGLCompressedTextureS3TCsRGB')\n", (3483, 3517), False, 'from name_style_converter import tokenize_name\n'), ((3621, 3665), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""WebGL2CompressedTextureETC1"""'], {}), "('WebGL2CompressedTextureETC1')\n", (3634, 3665), False, 'from name_style_converter import tokenize_name\n'), ((3762, 3786), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""EXTsRGB"""'], {}), "('EXTsRGB')\n", (3775, 3786), False, 'from name_style_converter import tokenize_name\n'), ((3923, 3967), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""WebGLCompressedTexturePVRTC"""'], {}), "('WebGLCompressedTexturePVRTC')\n", (3936, 3967), False, 'from name_style_converter import tokenize_name\n'), ((4065, 4099), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""SVGFEBlendElement"""'], {}), "('SVGFEBlendElement')\n", (4078, 4099), False, 'from name_style_converter import tokenize_name\n'), ((4161, 4193), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""SVGMPathElement"""'], {}), "('SVGMPathElement')\n", (4174, 4193), False, 'from name_style_converter import tokenize_name\n'), ((4249, 4281), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""SVGTSpanElement"""'], {}), "('SVGTSpanElement')\n", (4262, 4281), False, 'from name_style_converter import tokenize_name\n'), ((4337, 4369), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""SVGURIReference"""'], {}), "('SVGURIReference')\n", (4350, 4369), False, 'from name_style_converter import tokenize_name\n'), ((4426, 4460), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""UTF16TextIterator"""'], {}), "('UTF16TextIterator')\n", (4439, 4460), False, 'from name_style_converter import tokenize_name\n'), ((4518, 4546), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""UTF8Decoder"""'], {}), "('UTF8Decoder')\n", (4531, 4546), False, 'from name_style_converter import tokenize_name\n'), ((4594, 4621), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""Uint8Array"""'], {}), "('Uint8Array')\n", (4607, 4621), False, 'from name_style_converter import tokenize_name\n'), ((4668, 4700), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""DOMWindowBase64"""'], {}), "('DOMWindowBase64')\n", (4681, 4700), False, 'from name_style_converter import tokenize_name\n'), ((4756, 4788), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""TextCodecLatin1"""'], {}), "('TextCodecLatin1')\n", (4769, 4788), False, 'from name_style_converter import tokenize_name\n'), ((4844, 4877), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""V8BindingForCore"""'], {}), "('V8BindingForCore')\n", (4857, 4877), False, 'from name_style_converter import tokenize_name\n'), ((4938, 4964), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""V8DOMRect"""'], {}), "('V8DOMRect')\n", (4951, 4964), False, 'from name_style_converter import tokenize_name\n'), ((5014, 5050), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""String16MojomTraits"""'], {}), "('String16MojomTraits')\n", (5027, 5050), False, 'from name_style_converter import tokenize_name\n'), ((5111, 5144), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""V0InsertionPoint"""'], {}), "('V0InsertionPoint')\n", (5124, 5144), False, 'from name_style_converter import tokenize_name\n'), ((5201, 5233), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""ShadowDOMV0Test"""'], {}), "('ShadowDOMV0Test')\n", (5214, 5233), False, 'from name_style_converter import tokenize_name\n'), ((5293, 5325), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""ElementShadowV0"""'], {}), "('ElementShadowV0')\n", (5306, 5325), False, 'from name_style_converter import tokenize_name\n'), ((5381, 5421), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""StubChromeClientForSPv2"""'], {}), "('StubChromeClientForSPv2')\n", (5394, 5421), False, 'from name_style_converter import tokenize_name\n'), ((5519, 5552), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""SQLiteAuthorizer"""'], {}), "('SQLiteAuthorizer')\n", (5532, 5552), False, 'from name_style_converter import tokenize_name\n'), ((5605, 5636), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""XPathEvaluator"""'], {}), "('XPathEvaluator')\n", (5618, 5636), False, 'from name_style_converter import tokenize_name\n'), ((5688, 5720), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""IsXHTMLDocument"""'], {}), "('IsXHTMLDocument')\n", (5701, 5720), False, 'from name_style_converter import tokenize_name\n'), ((5776, 5807), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""isHTMLDocument"""'], {}), "('isHTMLDocument')\n", (5789, 5807), False, 'from name_style_converter import tokenize_name\n'), ((5863, 5888), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""matrix3d"""'], {}), "('matrix3d')\n", (5876, 5888), False, 'from name_style_converter import tokenize_name\n'), ((5974, 6004), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""Animation.idl"""'], {}), "('Animation.idl')\n", (5987, 6004), False, 'from name_style_converter import tokenize_name\n'), ((6053, 6088), 'name_style_converter.tokenize_name', 'tokenize_name', (['"""-webkit-appearance"""'], {}), "('-webkit-appearance')\n", (6066, 6088), False, 'from name_style_converter import tokenize_name\n'), ((6141, 6171), 'name_style_converter.tokenize_name', 'tokenize_name', (['""" foo_bar!#"$"""'], {}), '(\' foo_bar!#"$\')\n', (6154, 6171), False, 'from name_style_converter import tokenize_name\n')]
from django.conf.urls import url from product.views import CategoryView, CategoryIndexView urlpatterns = [ url(r'^(?P<parent_slugs>([-\w]+/)*)?(?P<slug>[-\w]+)/$', CategoryView.as_view(), name='satchmo_category'), url(r'^$', CategoryIndexView.as_view(), name='satchmo_category_index'), ]
[ "product.views.CategoryIndexView.as_view", "product.views.CategoryView.as_view" ]
[((170, 192), 'product.views.CategoryView.as_view', 'CategoryView.as_view', ([], {}), '()\n', (190, 192), False, 'from product.views import CategoryView, CategoryIndexView\n'), ((235, 262), 'product.views.CategoryIndexView.as_view', 'CategoryIndexView.as_view', ([], {}), '()\n', (260, 262), False, 'from product.views import CategoryView, CategoryIndexView\n')]
import socket from enum import IntEnum from typing import Dict, List from base64 import b64decode, b64encode UTF_8 = 'utf-8' class Stage(IntEnum): START = 1 TRANSFER = 2 CHECKID = 3 CHECK = 4 SHOW = 5 SEND = 6 class BaseMsg: def get_bytes(self) -> bytes: return str(self).encode() class Transfer(BaseMsg): def __init__(self): self.to: str = '' self.from_: str = '' self.value: float = -1 self.comment: str = '' def __str__(self) -> str: return f'transfer {self.to} {self.from_} {self.value} {self.comment}' class CheckId(BaseMsg): def __init__(self): self.id: int = -1 def __str__(self) -> str: return f'checkid {self.id}' class Check(BaseMsg): def __init__(self): self.encrypt_bytes: bytes = b'' def __str__(self) -> str: return f'check {self.encrypt_bytes}' def get_bytes(self) -> bytes: return 'check '.encode() + self.encrypt_bytes class Show(BaseMsg): def __init__(self): self.offset: int = -1 self.limit: int = -1 def __str__(self) -> str: return f'show {self.offset} {self.limit}' class Sender: def __init__(self, stage: Stage, msg: BaseMsg): self.prev_stage: Stage = stage self.msg: BaseMsg = msg self.host = '0.0.0.0' self.port = 5051 @staticmethod def print_transfer_answer(data: bytes): split_data = data.strip(b'\x00').split(b'\n') print(f'id: {split_data[0].decode(UTF_8)} {b64encode(split_data[1]).decode(UTF_8)}') @staticmethod def print_check_id_answer(data: bytes): print(data.strip(b'\x00').decode(UTF_8)) @staticmethod def print_check_answer(data: bytes): print(data.strip(b'\x00').decode(UTF_8)) @staticmethod def print_show_answer(data: bytes): split_data = data.strip(b'\x00').split('separator'.encode()) print('encrypted transactions:') for el in split_data: print(b64encode(el).decode(UTF_8)) def handle_message(self): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((self.host, self.port)) sock.sendall(self.msg.get_bytes()) data: bytes = sock.recv(1488) if self.prev_stage == Stage.TRANSFER: self.print_transfer_answer(data) elif self.prev_stage == Stage.CHECKID: self.print_check_id_answer(data) elif self.prev_stage == Stage.CHECK: self.print_check_answer(data) elif self.prev_stage == Stage.SHOW: self.print_show_answer(data) class MachineGun: START_COMMANDS: List[str] = ['transfer', 'checkid', 'check', 'show'] STRING_TO_STAGE: Dict[str, Stage] = { 'transfer': Stage.TRANSFER, 'checkid': Stage.CHECKID, 'check': Stage.CHECK, 'show': Stage.SHOW } def __init__(self): self.stage: Stage = Stage.START self.prev_stage: Stage = Stage.START self.msg = None @staticmethod def _validate_string(input_msg: str) -> str: res = input(input_msg) while res == '': res = input(input_msg) return res @staticmethod def _validate_num(input_msg: str, num_type: type): value = -1 while value <= 0: try: value = num_type(input(input_msg)) except ValueError: print('enter the number > 0') value = -1 return value @staticmethod def _validate_bytes(input_msg: str) -> bytes: res = input(input_msg) while res == '': res = input(input_msg) return b64decode(res) def handle_start(self): possible_commands = "; ".join(self.START_COMMANDS) command = input(f'possible commands: {possible_commands}\n') while command not in self.START_COMMANDS: command = input(f'possible commands: {possible_commands}\n') self.prev_stage = self.stage self.stage = self.STRING_TO_STAGE[command] def handle_transfer(self): transfer = Transfer() transfer.to = self._validate_string('to:\n') transfer.from_ = self._validate_string('from:\n') transfer.value = self._validate_num('value:\n', float) transfer.comment = self._validate_string('comment:\n') self.prev_stage = self.stage self.stage = Stage.SEND self.msg = transfer def handle_check_id(self): check_id = CheckId() check_id.id = self._validate_num('id:\n', int) self.prev_stage = self.stage self.stage = Stage.SEND self.msg = check_id def handle_check(self): check = Check() check.encrypt_bytes = self._validate_bytes('encrypt bytes in base64:\n') self.prev_stage = self.stage self.stage = Stage.SEND self.msg = check def handle_show(self): show = Show() show.offset = self._validate_num('offset:\n', int) show.limit = self._validate_num('limit:\n', int) self.prev_stage = self.stage self.stage = Stage.SEND self.msg = show def run(self): while True: try: if self.stage == Stage.START: self.handle_start() elif self.stage == Stage.TRANSFER: self.handle_transfer() elif self.stage == Stage.CHECKID: self.handle_check_id() elif self.stage == Stage.CHECK: self.handle_check() elif self.stage == Stage.SHOW: self.handle_show() elif self.stage == Stage.SEND: sender = Sender(self.prev_stage, self.msg) sender.handle_message() self.stage = Stage.START self.prev_stage = Stage.START except Exception: print('kernel panic') self.stage = Stage.START def main(): try: gun = MachineGun() gun.run() except KeyboardInterrupt: exit(0) if __name__ == '__main__': main() # thread_pool = ThreadPool(processes=7) # # # def main(): # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # addr = ('0.0.0.0', 5051) # sock.connect(addr) # sock.sendall('transfer a v 100 '.encode() + ('a'*3).encode()) # 'transfer <from> <to> <value> <comment>' # answ = sock.recv(1488).strip(b'\x00').split(b'\n') # разделитель \n # _id = int(answ[0].decode('utf-8')) # id транзакции # print(_id) # print(answ[1]) # [int(x) for x in answ[1]] # sock.sendall('checkid '.encode() + str(_id).encode()) # 'checkid <id>' # print(sock.recv(1488).strip(b'\x00').decode('utf-8')) # тело транзакции или not found # sock.sendall('show 0 1'.encode()) # 'show' # transactions = sock.recv(1488).strip(b'\x00').split(b'\n') # список транзакций # print(answ[1] in transactions) # проверка сеществования транзакции в бд # sock.sendall('check '.encode() + transactions[0][:-1] + b'x\23') # 'check <шифротекст>' # print(sock.recv(1488).strip(b'\x00').decode('utf-8')) # ok или error # sock.close() # for _ in range(100): # thread_pool.apply_async(main) # thread_pool.close() # thread_pool.join()
[ "socket.socket", "base64.b64encode", "base64.b64decode" ]
[((3752, 3766), 'base64.b64decode', 'b64decode', (['res'], {}), '(res)\n', (3761, 3766), False, 'from base64 import b64decode, b64encode\n'), ((2101, 2150), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (2114, 2150), False, 'import socket\n'), ((2028, 2041), 'base64.b64encode', 'b64encode', (['el'], {}), '(el)\n', (2037, 2041), False, 'from base64 import b64decode, b64encode\n'), ((1548, 1572), 'base64.b64encode', 'b64encode', (['split_data[1]'], {}), '(split_data[1])\n', (1557, 1572), False, 'from base64 import b64decode, b64encode\n')]
import time import datetime import itertools from wtforms import fields#, widgets try: from wtforms.fields import _unset_value as unset_value except ImportError: from wtforms.utils import unset_value from .widgets import ( DateTimePickerWidget, TimePickerWidget, Select2Widget, Select2TagsWidget, InlineFieldListWidget, InlineFormWidget, AjaxSelect2Widget, XEditableWidget, ) from mytrade.utils import _ """ An understanding of WTForms's Custom Widgets is helpful for understanding this code: http://wtforms.simplecodes.com/docs/0.6.2/widgets.html#custom-widgets """ class DateTimeField(fields.DateTimeField): """ Allows modifying the datetime format of a DateTimeField using form_args. """ widget = DateTimePickerWidget() def __init__(self, label=None, validators=None, format=None, **kwargs): """ Constructor :param label: Label :param validators: Field validators :param format: Format for text to date conversion. Defaults to '%Y-%m-%d %H:%M:%S' :param kwargs: Any additional parameters """ super(DateTimeField, self).__init__(label, validators, **kwargs) self.format = format or '%Y-%m-%d %H:%M:%S' class TimeField(fields.Field): """ A text field which stores a `datetime.time` object. Accepts time string in multiple formats: 20:10, 20:10:00, 10:00 am, 9:30pm, etc. """ widget = TimePickerWidget() def __init__(self, label=None, validators=None, formats=None, default_format=None, widget_format=None, **kwargs): """ Constructor :param label: Label :param validators: Field validators :param formats: Supported time formats, as a enumerable. :param default_format: Default time format. Defaults to '%H:%M:%S' :param kwargs: Any additional parameters """ super(TimeField, self).__init__(label, validators, **kwargs) self.formats = formats or ('%H:%M:%S', '%H:%M', '%I:%M:%S%p', '%I:%M%p', '%I:%M:%S %p', '%I:%M %p') self.default_format = default_format or '%H:%M:%S' def _value(self): if self.raw_data: return u' '.join(self.raw_data) elif self.data is not None: return self.data.strftime(self.default_format) else: return u'' def process_formdata(self, valuelist): if valuelist: date_str = u' '.join(valuelist) if date_str.strip(): for format in self.formats: try: timetuple = time.strptime(date_str, format) self.data = datetime.time(timetuple.tm_hour, timetuple.tm_min, timetuple.tm_sec) return except ValueError: pass raise ValueError(_('Invalid time format')) else: self.data = None class Select2Field(fields.SelectField): """ `Select2 <https://github.com/ivaynberg/select2>`_ styled select widget. You must include select2.js, form-x.x.x.js and select2 stylesheet for it to work. """ widget = Select2Widget() def __init__(self, label=None, validators=None, coerce=str, choices=None, allow_blank=False, blank_text=None, **kwargs): super(Select2Field, self).__init__( label, validators, coerce, choices, **kwargs ) self.allow_blank = allow_blank self.blank_text = blank_text or ' ' def iter_choices(self): if self.allow_blank: yield (u'__None', self.blank_text, self.data is None) if self.choices: for value, label in self.choices: yield (value, label, self.coerce(value) == self.data) def process_data(self, value): if value is None: self.data = None else: try: self.data = self.coerce(value) except (ValueError, TypeError): self.data = None def process_formdata(self, valuelist): if valuelist: if valuelist[0] == '__None': self.data = None else: try: self.data = self.coerce(valuelist[0]) except ValueError: raise ValueError(self.gettext(u'Invalid Choice: could not coerce')) def pre_validate(self, form): if self.allow_blank and self.data is None: return super(Select2Field, self).pre_validate(form) class Select2TagsField(fields.StringField): """`Select2 <http://ivaynberg.github.com/select2/#tags>`_ styled text field. You must include select2.js, form-x.x.x.js and select2 stylesheet for it to work. """ widget = Select2TagsWidget() def __init__(self, label=None, validators=None, save_as_list=False, coerce=str, **kwargs): """Initialization :param save_as_list: If `True` then populate ``obj`` using list else string """ self.save_as_list = save_as_list self.coerce = coerce super(Select2TagsField, self).__init__(label, validators, **kwargs) def process_formdata(self, valuelist): if self.save_as_list: self.data = [self.coerce(v.strip()) for v in valuelist[0].split(',') if v.strip()] else: self.data = self.coerce(valuelist[0]) def _value(self): if isinstance(self.data, (list, tuple)): return u','.join(v for v in self.data) elif self.data: return self.data else: return u'' class InlineFieldList(fields.FieldList): widget = InlineFieldListWidget() def __init__(self, *args, **kwargs): super(InlineFieldList, self).__init__(*args, **kwargs) def __call__(self, **kwargs): # Create template meta = getattr(self, 'meta', None) if meta: template = self.unbound_field.bind(form=None, name='', _meta=meta) else: template = self.unbound_field.bind(form=None, name='') # Small hack to remove separator from FormField if isinstance(template, fields.FormField): template.separator = '' template.process(None) return self.widget(self, template=template, check=self.display_row_controls, **kwargs) def display_row_controls(self, field): return True def process(self, formdata, data=None): res = super(InlineFieldList, self).process(formdata, data) # Postprocess - contribute flag if formdata: for f in self.entries: key = 'del-%s' % f.id f._should_delete = key in formdata return res def validate(self, form, extra_validators=tuple()): """ Validate this FieldList. Note that FieldList validation differs from normal field validation in that FieldList validates all its enclosed fields first before running any of its own validators. """ self.errors = [] # Run validators on all entries within for subfield in self.entries: if not self.should_delete(subfield) and not subfield.validate(form): self.errors.append(subfield.errors) chain = itertools.chain(self.validators, extra_validators) self._run_validation_chain(form, chain) return len(self.errors) == 0 def should_delete(self, field): return getattr(field, '_should_delete', False) def populate_obj(self, obj, name): values = getattr(obj, name, None) try: ivalues = iter(values) except TypeError: ivalues = iter([]) candidates = itertools.chain(ivalues, itertools.repeat(None)) _fake = type(str('_fake'), (object, ), {}) output = [] for field, data in zip(self.entries, candidates): if not self.should_delete(field): fake_obj = _fake() fake_obj.data = data field.populate_obj(fake_obj, 'data') output.append(fake_obj.data) setattr(obj, name, output) class InlineFormField(fields.FormField): """ Inline version of the ``FormField`` widget. """ widget = InlineFormWidget() class InlineModelFormField(fields.FormField): """ Customized ``FormField``. Excludes model primary key from the `populate_obj` and handles `should_delete` flag. """ widget = InlineFormWidget() def __init__(self, form_class, pk, form_opts=None, **kwargs): super(InlineModelFormField, self).__init__(form_class, **kwargs) self._pk = pk self.form_opts = form_opts def get_pk(self): return getattr(self.form, self._pk).data def populate_obj(self, obj, name): for name, field in iteritems(self.form._fields): if name != self._pk: field.populate_obj(obj, name) class ListEditableFieldList(fields.FieldList): """ Modified FieldList to allow for alphanumeric primary keys. Used in the editable list view. """ widget = XEditableWidget() def __init__(self, *args, **kwargs): super(ListEditableFieldList, self).__init__(*args, **kwargs) # min_entries = 1 is required for the widget to determine the type self.min_entries = 1 def _extract_indices(self, prefix, formdata): offset = len(prefix) + 1 for name in formdata: # selects only relevant field (not CSRF, other fields, etc) if name.startswith(prefix): # exclude offset (prefix-), remaining text is the index yield name[offset:] def _add_entry(self, formdata=None, data=unset_value, index=None): assert not self.max_entries or len(self.entries) < self.max_entries, \ 'You cannot have more than max_entries entries in this FieldList' if index is None: index = self.last_index + 1 self.last_index = index # '%s-%s' instead of '%s-%d' to allow alphanumeric name = '%s-%s' % (self.short_name, index) id = '%s-%s' % (self.id, index) # support both wtforms 1 and 2 meta = getattr(self, 'meta', None) if meta: field = self.unbound_field.bind( form=None, name=name, prefix=self._prefix, id=id, _meta=meta ) else: field = self.unbound_field.bind( form=None, name=name, prefix=self._prefix, id=id ) field.process(formdata, data) self.entries.append(field) return field def populate_obj(self, obj, name): # return data from first item, instead of a list of items setattr(obj, name, self.data.pop()) class AjaxSelectField(fields.SelectFieldBase): """ Ajax Model Select Field """ widget = AjaxSelect2Widget() separator = ',' def __init__(self, loader, label=None, validators=None, allow_blank=False, blank_text=u'', **kwargs): super(AjaxSelectField, self).__init__(label, validators, **kwargs) self.loader = loader self.allow_blank = allow_blank self.blank_text = blank_text def _get_data(self): if self._formdata: model = self.loader.get_one(self._formdata) if model is not None: self._set_data(model) return self._data def _set_data(self, data): self._data = data self._formdata = None data = property(_get_data, _set_data) def _format_item(self, item): value = self.loader.format(self.data) return (value[0], value[1], True) def process_formdata(self, valuelist): if valuelist: if self.allow_blank and valuelist[0] == u'__None': self.data = None else: self._data = None self._formdata = valuelist[0] def pre_validate(self, form): if not self.allow_blank and self.data is None: raise ValidationError(self.gettext(u'Not a valid choice')) class AjaxSelectMultipleField(AjaxSelectField): """ Ajax-enabled model multi-select field. """ widget = AjaxSelect2Widget(multiple=True) def __init__(self, loader, label=None, validators=None, default=None, **kwargs): if default is None: default = [] super(AjaxSelectMultipleField, self).__init__(loader, label, validators, default=default, **kwargs) self._invalid_formdata = False def _get_data(self): formdata = self._formdata if formdata: data = [] # TODO: Optimize? for item in formdata: model = self.loader.get_one(item) if item else None if model: data.append(model) else: self._invalid_formdata = True self._set_data(data) return self._data def _set_data(self, data): self._data = data self._formdata = None data = property(_get_data, _set_data) def process_formdata(self, valuelist): self._formdata = set() for field in valuelist: for n in field.split(self.separator): self._formdata.add(n) def pre_validate(self, form): if self._invalid_formdata: raise ValidationError(self.gettext(u'Not a valid choice'))
[ "itertools.chain", "datetime.time", "time.strptime", "mytrade.utils._", "itertools.repeat" ]
[((7843, 7893), 'itertools.chain', 'itertools.chain', (['self.validators', 'extra_validators'], {}), '(self.validators, extra_validators)\n', (7858, 7893), False, 'import itertools\n'), ((8306, 8328), 'itertools.repeat', 'itertools.repeat', (['None'], {}), '(None)\n', (8322, 8328), False, 'import itertools\n'), ((3262, 3286), 'mytrade.utils._', '_', (['"""Invalid time format"""'], {}), "('Invalid time format')\n", (3263, 3286), False, 'from mytrade.utils import _\n'), ((2892, 2923), 'time.strptime', 'time.strptime', (['date_str', 'format'], {}), '(date_str, format)\n', (2905, 2923), False, 'import time\n'), ((2960, 3028), 'datetime.time', 'datetime.time', (['timetuple.tm_hour', 'timetuple.tm_min', 'timetuple.tm_sec'], {}), '(timetuple.tm_hour, timetuple.tm_min, timetuple.tm_sec)\n', (2973, 3028), False, 'import datetime\n')]
from pathlib import Path from novel_tools.framework import Processor from novel_tools.common import NovelData, ACC, FieldMetadata class PathTransformer(Processor, ACC): """ Given `in_dir`, this transformer will replace all `Path` fields with the paths relative to its `in_dir`. """ @staticmethod def required_fields() -> list[FieldMetadata]: return [ FieldMetadata('in_dir', 'Path', description='The parent directory for all the novel data.'), FieldMetadata('fields', 'list[str]', default=['source'], description='A list of fields of type `Path` to transform.') ] def __init__(self, args): args = self.extract_fields(args) self.in_dir = args['in_dir'] self.fields = args['fields'] def process(self, data: NovelData) -> NovelData: for field in self.fields: path = data.get(field, None) if isinstance(path, Path): data.set(**{field: path.relative_to(self.in_dir)}) return data
[ "novel_tools.common.FieldMetadata" ]
[((394, 490), 'novel_tools.common.FieldMetadata', 'FieldMetadata', (['"""in_dir"""', '"""Path"""'], {'description': '"""The parent directory for all the novel data."""'}), "('in_dir', 'Path', description=\n 'The parent directory for all the novel data.')\n", (407, 490), False, 'from novel_tools.common import NovelData, ACC, FieldMetadata\n'), ((525, 647), 'novel_tools.common.FieldMetadata', 'FieldMetadata', (['"""fields"""', '"""list[str]"""'], {'default': "['source']", 'description': '"""A list of fields of type `Path` to transform."""'}), "('fields', 'list[str]', default=['source'], description=\n 'A list of fields of type `Path` to transform.')\n", (538, 647), False, 'from novel_tools.common import NovelData, ACC, FieldMetadata\n')]
import pandas as pd def values_to_df(values): data = [] for n, v in values.items(): data.append([ n.localname, v.to_value().get_value(), v.unit ]) return pd.DataFrame( data, columns = ["name", "value", "unit"] ) def instance_to_df(inst): columns = ["name", "value", "unit", "entity", "scheme", "start", "end", "instant"] columnset = set(columns) data = [] for c in inst.contexts.values(): for v in c.values.values(): row = { "name": v.name.localname, "value": str(v.to_value().get_value()), "unit": v.to_value().get_unit(), } if c.entity: row["entity"] = c.entity.id row["scheme"] = c.entity.scheme if c.period: row["start"] = c.period.start row["end"] = c.period.end if c.instant: row["instant"] = c.instant.instant for dim in c.dimensions: d = dim.dimension.localname v = dim.value.localname if d not in columnset: columns.append(d) columnset.add(d) row[d] = v data.append(row) return pd.DataFrame(data, columns=columns)
[ "pandas.DataFrame" ]
[((199, 252), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['name', 'value', 'unit']"}), "(data, columns=['name', 'value', 'unit'])\n", (211, 252), True, 'import pandas as pd\n'), ((1326, 1361), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'columns'}), '(data, columns=columns)\n', (1338, 1361), True, 'import pandas as pd\n')]
import flask import pyodbc # Initializes app and database connection app = flask.Flask('biosphere', template_folder='templates') db_conn = conn = pyodbc.connect( 'Driver={SQL Server};' 'Server=DESKTOP-QR078NF\SQLEXPRESS;' 'Database=BIOSPHERE;' 'Trusted_Connection=yes;' ) # Function to handle the root path '/' @app.route('/') @app.route('/home') def home(): my_user = {'first': 'Luciano', 'last': 'Santos'} return flask.render_template('home.html', user=my_user) # given a result row, extracts and returns the species data def extract_species(row): species = {} species['id'] = row[0] species['genus'] = row[1] species['species'] = row[2] species['subspecies'] = row[3] species['name'] = species['genus'] + ' ' + species['species'] if species['subspecies'] is not None: species['name'] += ' ' + species['subspecies'] return species # Function to handle the species path '/species' @app.route('/species', defaults={'id': None}) @app.route('/species/<id>') def species(id): cursor = db_conn.cursor() if id is None: cursor.execute('SELECT * FROM Bio.Species') all_species = [] for row in cursor: data = extract_species(row) all_species.append(data) return flask.render_template('species.html', species=all_species) else: cursor.execute('SELECT * FROM Bio.Species WHERE sp_id=' + id) row = cursor.fetchone() if row is None: return flask.render_template('error.html', message='Species not found!') data = extract_species(row) return flask.render_template('species_detail.html', species=data) # given a result row, extracts and returns the author data def extract_author(row): author = {} author['id'] = row[0] author['first_name'] = row[1] author['middle_name'] = row[2] author['last_name'] = row[3] author['birthdate'] = row[4] author['name'] = author['first_name'] + ' ' if author['middle_name'] is not None: author['name'] += author['middle_name'] + ' ' author['name'] += author['last_name'] return author @app.route('/authors', defaults={'id': None}) @app.route('/authors/<id>') def authors(id): cursor = db_conn.cursor() if id is None: cursor.execute('SELECT * FROM Bio.Author') all_authors = [] for row in cursor: data = extract_author(row) all_authors.append(data) return flask.render_template('authors.html', authors=all_authors) else: cursor.execute('SELECT * FROM Bio.Author WHERE au_id=' + id) all_authors = [] row = cursor.fetchone() if row is None: return flask.render_template('error.html', message='Author not found!') data = extract_author(row) return flask.render_template('author_detail.html', author=data) # given a result row, extracts and returns the species data def extract_species1(row): species = {} species['id'] = row[0] species['genus'] = row[1] species['species'] = row[2] species['subspecies'] = row[3] species['name'] = species['genus'] + ' ' + species['species'] if species['subspecies'] is not None: species['name'] += ' ' + species['subspecies'] return species # Function to handle the species path '/species' @app.route('/species1', defaults={'id': None}) @app.route('/species1/<id>') def speciescom(id): cursor = db_conn.cursor() if id is None: cursor.execute('SELECT * FROM Bio.Species') all_species = [] for row in cursor: data = extract_species1(row) all_species.append(data) return flask.render_template('species1.html', species=all_species) else: cursor.execute('SELECT * FROM Bio.Species' +id ) row = cursor.fetchone() if row is None: return flask.render_template('error.html', message='Species not found!') data = extract_species1(row) return flask.render_template('species_detail.html', species=data) def extract_publication(row): publication = {} publication['id'] = row[0] publication['year'] = row[1] publication['title'] = row[2] publication['startPubli'] = row[3] publication['endPubli'] = row[4] publication['fname'] = row[5] publication['lname'] = row[6] publication['name'] = publication['title'] return publication def extract_publication2(row): publication = {} publication['id'] = row[0] publication['year'] = row[1] publication['title'] = row[2] publication['start'] = row[3] publication['end'] = row[4] publication['fname'] = row[5] publication['lname'] = row[6] return publication @app.route('/publication', defaults={'id': None}) @app.route('/publication/<id>') def publication(id): cursor = db_conn.cursor() if id is None: cursor.execute("SELECT * FROM Bio.Publication") all_publication = [] for row in cursor: data = extract_publication(row) all_publication.append(data) return flask.render_template('publication.html', publication=all_publication) else: cursor.execute("""\ SELECT p.pu_id, p.pu_year, p.pu_title, p.pu_page_start, p.pu_page_end, a.au_fname, a.au_lname FROM Bio.Publication p, Bio.Au_Writes_Pu w, Bio.Author a WHERE p.pu_id = w.pu_id AND w.au_id = a.au_id and p.pu_id = """ + id) all_publication = [] row = cursor.fetchone() if row is None: return flask.render_template('error.html', message='Publication not found!') data = extract_publication2(row) return flask.render_template('publication_details.html', publication=data) # Starts listening for requests... app.run(port=8080, use_reloader=True)
[ "flask.Flask", "flask.render_template", "pyodbc.connect" ]
[((80, 133), 'flask.Flask', 'flask.Flask', (['"""biosphere"""'], {'template_folder': '"""templates"""'}), "('biosphere', template_folder='templates')\n", (91, 133), False, 'import flask\n'), ((152, 277), 'pyodbc.connect', 'pyodbc.connect', (['"""Driver={SQL Server};Server=DESKTOP-QR078NF\\\\SQLEXPRESS;Database=BIOSPHERE;Trusted_Connection=yes;"""'], {}), "(\n 'Driver={SQL Server};Server=DESKTOP-QR078NF\\\\SQLEXPRESS;Database=BIOSPHERE;Trusted_Connection=yes;'\n )\n", (166, 277), False, 'import pyodbc\n'), ((458, 506), 'flask.render_template', 'flask.render_template', (['"""home.html"""'], {'user': 'my_user'}), "('home.html', user=my_user)\n", (479, 506), False, 'import flask\n'), ((1334, 1392), 'flask.render_template', 'flask.render_template', (['"""species.html"""'], {'species': 'all_species'}), "('species.html', species=all_species)\n", (1355, 1392), False, 'import flask\n'), ((1672, 1730), 'flask.render_template', 'flask.render_template', (['"""species_detail.html"""'], {'species': 'data'}), "('species_detail.html', species=data)\n", (1693, 1730), False, 'import flask\n'), ((2568, 2626), 'flask.render_template', 'flask.render_template', (['"""authors.html"""'], {'authors': 'all_authors'}), "('authors.html', authors=all_authors)\n", (2589, 2626), False, 'import flask\n'), ((2929, 2985), 'flask.render_template', 'flask.render_template', (['"""author_detail.html"""'], {'author': 'data'}), "('author_detail.html', author=data)\n", (2950, 2985), False, 'import flask\n'), ((3832, 3891), 'flask.render_template', 'flask.render_template', (['"""species1.html"""'], {'species': 'all_species'}), "('species1.html', species=all_species)\n", (3853, 3891), False, 'import flask\n'), ((4159, 4217), 'flask.render_template', 'flask.render_template', (['"""species_detail.html"""'], {'species': 'data'}), "('species_detail.html', species=data)\n", (4180, 4217), False, 'import flask\n'), ((5302, 5372), 'flask.render_template', 'flask.render_template', (['"""publication.html"""'], {'publication': 'all_publication'}), "('publication.html', publication=all_publication)\n", (5323, 5372), False, 'import flask\n'), ((5918, 5985), 'flask.render_template', 'flask.render_template', (['"""publication_details.html"""'], {'publication': 'data'}), "('publication_details.html', publication=data)\n", (5939, 5985), False, 'import flask\n'), ((1553, 1618), 'flask.render_template', 'flask.render_template', (['"""error.html"""'], {'message': '"""Species not found!"""'}), "('error.html', message='Species not found!')\n", (1574, 1618), False, 'import flask\n'), ((2812, 2876), 'flask.render_template', 'flask.render_template', (['"""error.html"""'], {'message': '"""Author not found!"""'}), "('error.html', message='Author not found!')\n", (2833, 2876), False, 'import flask\n'), ((4039, 4104), 'flask.render_template', 'flask.render_template', (['"""error.html"""'], {'message': '"""Species not found!"""'}), "('error.html', message='Species not found!')\n", (4060, 4104), False, 'import flask\n'), ((5790, 5859), 'flask.render_template', 'flask.render_template', (['"""error.html"""'], {'message': '"""Publication not found!"""'}), "('error.html', message='Publication not found!')\n", (5811, 5859), False, 'import flask\n')]
import argparse import time import numpy as np import pyvisa # Parse folder path, file name, and measurement parameters from command line # arguments. Remember to include the "python" keyword before the call to the # python file from the command line, e.g. python example.py "arg1" "arg2". # Folder paths must use forward slashes to separate subfolders. parser = argparse.ArgumentParser( description='Measure and save max power point tracking data') parser.add_argument( 'folder_path', metavar='folder_path', type=str, help='Absolute path to the folder containing max P stabilisation data') parser.add_argument( 'file_name', metavar='file_name', type=str, help='Name of the file to save the data to') parser.add_argument( 'V_start', metavar='V_start', type=float, help='Seed voltage for maximum power point tracker (V)') parser.add_argument( 'nplc', metavar='nplc', type=float, help='Integration filter in number of power line cycles (NPLC)') parser.add_argument( 't_settling', metavar='t_settling', type=float, help='Settling delay (ms)') parser.add_argument( 't_track', metavar='t_track', type=float, help='Time to track maximum power point for (s)') parser.add_argument('A', metavar='A', type=float, help='Device area (cm^2)') parser.add_argument( 'num_of_suns', metavar='num_of_suns', type=float, help='Number of suns equivalent illumination intensity') args = parser.parse_args() # Assign argparse arguments to variables folderpath = args.folder_path filename = args.file_name V_start = args.V_start A = args.A nplc = args.nplc t_settling = args.t_settling t_track = args.t_track suns = args.num_of_suns V_range = np.absolute(V_start) # Set current measurement range to 10 times SQ limit for 0.5 eV # bandgap for the given area I_range = 10 * 0.065 * A # Assign the VISA resource to a variable rm = pyvisa.ResourceManager() keithley2400 = rm.open_resource('GPIfdf8:f53e:61e4::18::INSTR') keithley2400.query('*IDN?') keithley2400.write('*RST') keithley2400.encoding = 'latin-1' # Disable the output keithley2400.write('OUTP OFF') # Enable 4-wire sense keithley2400.write(':SYST:RSEN 1') # Don't auto-off source after measurement keithley2400.write(':SOUR:CLE:AUTO OFF') # Set source mode to voltage keithley2400.write(':SOUR:FUNC VOLT') # Set output-off mode to high impedance keithley2400.write(':OUTP:SMOD HIMP') # Set the voltage range keithley2400.write(':SOUR:VOLT:RANG {}'.format(V_range)) # Set the current range keithley2400.write(':SOUR:CURR:RANG {}'.format(I_range)) # Set the delay keithley2400.write(':SOUR:DEL {}'.format(t_settling)) # Set the integration filter keithley2400.write(':SENS:CURR:NPLC {}'.format(nplc)) # Disable autozero keithley2400.write(':SYST:AZER OFF') def track_max_power(V, t_track): """Maximum power point stabilizer. Holding at a fixed voltage (V), measure the power output for a fixed amount of time (t_track), taking as many measurements as possible. Parameters ---------- V : float Seed voltage for the maximum power point tracker (V) t_track : float Time to track the maximum power point for (s) Returns ------- ts : list of float Timestamps for every measurement (UTC) Vs : list of float Vs (V) Is : list of float Is (A) Ps : list of float Ps (W) Js : list of float Current densities (mA / cm^2) PCEs : list of float Power conversion PCEs (%) """ # Initialise empty lists for storing data ts = [] Vs = [] Is = [] Js = [] Ps = [] PCEs = [] # Turn on the Keithley output at zero volts and measure for 4s in the dark keithley2400.write(':SOUR:VOLT {}'.format(V)) keithley2400.write('OUTP ON') # Start timing t_start = time.time() t = time.time() # Measure Jsc in the dark for 3s while t - t_start < 3: ts.append(t - t_start) data = keithley2400.query(':MEAS:CURR?') # Measure the current data = data.split(',') data = [float(item) for item in data] Vs.append(data[0]) Is.append(data[1]) Js.append(data[1] * 1000 / A) Ps.append(data[0] * data[1]) PCEs.append(np.absolute(data[0] * data[1] * 1000 / (suns * A))) t = time.time() # Open the shutter of the solar simulator keithley2400.write(':SOUR2:TTL 0') # Measure at V in the light for t_track i = len(Vs) - 1 while t - t_start < t_track + 3: ts.append(t - t_start) data = keithley2400.query(':MEAS:CURR?') # Measure the current data = data.split(',') data = [float(item) for item in data] Vs.append(data[0]) Is.append(data[1]) Js.append(data[1] * 1000 / A) Ps.append(data[0] * data[1]) PCEs.append(np.absolute(data[0] * data[1] * 1000 / (suns * A))) t = time.time() i += 1 return ts, Vs, Is, Js, Ps, PCEs # Turn off display keithley2400.write(':DISP:ENAB 0') # Manually reset zero reference values keithley2400.write(':SYST:AZER ONCE') # Track max power mppt_results = track_max_power(V_start, t_track) # Disable output keithley2400.write('OUTP OFF') # Close shutter keithley2400.write(':SOUR2:TTL 1') # Turn off display keithley2400.write(':DISP:ENAB 1') # Format and save the results np.savetxt( folderpath + filename, np.transpose(np.array(mppt_results)), fmt='%.9f', delimiter='\t', newline='\r\n', header='Time (s)\tV\tI (A)\tJ (mA/cm^2)\tP (W)\tPCE (%)', comments='') # Close the visa resource manager keithley2400.close()
[ "numpy.absolute", "pyvisa.ResourceManager", "argparse.ArgumentParser", "time.time", "numpy.array" ]
[((366, 456), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Measure and save max power point tracking data"""'}), "(description=\n 'Measure and save max power point tracking data')\n", (389, 456), False, 'import argparse\n'), ((1727, 1747), 'numpy.absolute', 'np.absolute', (['V_start'], {}), '(V_start)\n', (1738, 1747), True, 'import numpy as np\n'), ((1914, 1938), 'pyvisa.ResourceManager', 'pyvisa.ResourceManager', ([], {}), '()\n', (1936, 1938), False, 'import pyvisa\n'), ((3865, 3876), 'time.time', 'time.time', ([], {}), '()\n', (3874, 3876), False, 'import time\n'), ((3885, 3896), 'time.time', 'time.time', ([], {}), '()\n', (3894, 3896), False, 'import time\n'), ((4355, 4366), 'time.time', 'time.time', ([], {}), '()\n', (4364, 4366), False, 'import time\n'), ((4948, 4959), 'time.time', 'time.time', ([], {}), '()\n', (4957, 4959), False, 'import time\n'), ((5457, 5479), 'numpy.array', 'np.array', (['mppt_results'], {}), '(mppt_results)\n', (5465, 5479), True, 'import numpy as np\n'), ((4291, 4341), 'numpy.absolute', 'np.absolute', (['(data[0] * data[1] * 1000 / (suns * A))'], {}), '(data[0] * data[1] * 1000 / (suns * A))\n', (4302, 4341), True, 'import numpy as np\n'), ((4884, 4934), 'numpy.absolute', 'np.absolute', (['(data[0] * data[1] * 1000 / (suns * A))'], {}), '(data[0] * data[1] * 1000 / (suns * A))\n', (4895, 4934), True, 'import numpy as np\n')]
#!/usr/local/bin/python3.6 #-*- coding: utf-8 -*- #Author WangJiang@2019 15810438848 <EMAIL> #All rights reserved ################################################################################################################ from colorama import init, Fore, Back, Style ################################################################################################################ ### 输出类 class Cls_Color: ### 初始化 def __init__(self): """ Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Style: DIM, NORMAL, BRIGHT, RESET_ALL """ init(autoreset=True) # 初始化,并且设置颜色设置自动恢复 ### 字体红色 def fore_red(self, content): return Fore.RED + content
[ "colorama.init" ]
[((691, 711), 'colorama.init', 'init', ([], {'autoreset': '(True)'}), '(autoreset=True)\n', (695, 711), False, 'from colorama import init, Fore, Back, Style\n')]
from unittest import TestCase from unittest.mock import patch from nose.tools import istest from convertfrom.main import convert, main class EntryPointTest(TestCase): @istest @patch('convertfrom.main.sys') @patch('convertfrom.main.print') @patch('convertfrom.main.convert') def prints_converted_result(self, mock_convert, mock_print, mock_sys): mock_sys.argv = ['convertfrom', '2a', 'to', 'b'] mock_convert.return_value = '2b' main() mock_print.assert_called_once_with('2b') mock_convert.assert_called_once_with(['2a', 'to', 'b']) @istest @patch('convertfrom.main.convert') def exits_on_exceptions(self, mock_convert): exception = RuntimeError('oops') mock_convert.side_effect = exception with self.assertRaises(SystemExit): main() class ConvertTest(TestCase): @istest def converts_10m_to_1000cm(self): result = convert(['10m', 'to', 'cm']) self.assertEqual(result, '1000.0cm') @istest def converts_1m_to_100cm(self): result = convert(['1m', 'to', 'cm']) self.assertEqual(result, '100.0cm') @istest def converts_1m_to_1000mm(self): result = convert(['1m', 'to', 'mm']) self.assertEqual(result, '1000.0mm') @istest def converts_200cm_to_2m(self): result = convert(['200cm', 'to', 'm']) self.assertEqual(result, '2.0m') @istest def converts_1meter_to_100cm(self): result = convert(['1meter', 'to', 'cm']) self.assertEqual(result, '100.0cm') @istest def converts_1_meter_to_100cm(self): result = convert(['1', 'meter', 'to', 'cm']) self.assertEqual(result, '100.0cm') @istest def converts_1_meter_to_1m(self): result = convert(['1', 'meter', 'to', 'meters']) self.assertEqual(result, '1.0meters')
[ "unittest.mock.patch", "convertfrom.main.main", "convertfrom.main.convert" ]
[((188, 217), 'unittest.mock.patch', 'patch', (['"""convertfrom.main.sys"""'], {}), "('convertfrom.main.sys')\n", (193, 217), False, 'from unittest.mock import patch\n'), ((223, 254), 'unittest.mock.patch', 'patch', (['"""convertfrom.main.print"""'], {}), "('convertfrom.main.print')\n", (228, 254), False, 'from unittest.mock import patch\n'), ((260, 293), 'unittest.mock.patch', 'patch', (['"""convertfrom.main.convert"""'], {}), "('convertfrom.main.convert')\n", (265, 293), False, 'from unittest.mock import patch\n'), ((615, 648), 'unittest.mock.patch', 'patch', (['"""convertfrom.main.convert"""'], {}), "('convertfrom.main.convert')\n", (620, 648), False, 'from unittest.mock import patch\n'), ((476, 482), 'convertfrom.main.main', 'main', ([], {}), '()\n', (480, 482), False, 'from convertfrom.main import convert, main\n'), ((946, 974), 'convertfrom.main.convert', 'convert', (["['10m', 'to', 'cm']"], {}), "(['10m', 'to', 'cm'])\n", (953, 974), False, 'from convertfrom.main import convert, main\n'), ((1087, 1114), 'convertfrom.main.convert', 'convert', (["['1m', 'to', 'cm']"], {}), "(['1m', 'to', 'cm'])\n", (1094, 1114), False, 'from convertfrom.main import convert, main\n'), ((1227, 1254), 'convertfrom.main.convert', 'convert', (["['1m', 'to', 'mm']"], {}), "(['1m', 'to', 'mm'])\n", (1234, 1254), False, 'from convertfrom.main import convert, main\n'), ((1367, 1396), 'convertfrom.main.convert', 'convert', (["['200cm', 'to', 'm']"], {}), "(['200cm', 'to', 'm'])\n", (1374, 1396), False, 'from convertfrom.main import convert, main\n'), ((1509, 1540), 'convertfrom.main.convert', 'convert', (["['1meter', 'to', 'cm']"], {}), "(['1meter', 'to', 'cm'])\n", (1516, 1540), False, 'from convertfrom.main import convert, main\n'), ((1657, 1692), 'convertfrom.main.convert', 'convert', (["['1', 'meter', 'to', 'cm']"], {}), "(['1', 'meter', 'to', 'cm'])\n", (1664, 1692), False, 'from convertfrom.main import convert, main\n'), ((1806, 1845), 'convertfrom.main.convert', 'convert', (["['1', 'meter', 'to', 'meters']"], {}), "(['1', 'meter', 'to', 'meters'])\n", (1813, 1845), False, 'from convertfrom.main import convert, main\n'), ((841, 847), 'convertfrom.main.main', 'main', ([], {}), '()\n', (845, 847), False, 'from convertfrom.main import convert, main\n')]
import os import boto3 from slackclient import SlackClient from lunchbot import logging logger = logging.getLogger(__name__) class Slack(object): client = None @staticmethod def get_client(): if Slack.client is not None: logger.debug("Using cached Slack client") return Slack.client logger.debug("Creating fresh Slack client") slack_token = os.environ["SLACK_API_TOKEN"] Slack.client = SlackClient(slack_token) return Slack.client class Dynamo(object): table = None @staticmethod def get_table(): if Dynamo.table is not None: logger.debug("Using cached DynamoDB client") return Dynamo.table logger.debug("Creating fresh DynamoDB client") dynamo_resource = boto3.resource("dynamodb") Dynamo.table = dynamo_resource.Table(os.environ["DYNAMODB_TABLE"]) return Dynamo.table
[ "boto3.resource", "lunchbot.logging.getLogger", "slackclient.SlackClient" ]
[((101, 128), 'lunchbot.logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (118, 128), False, 'from lunchbot import logging\n'), ((462, 486), 'slackclient.SlackClient', 'SlackClient', (['slack_token'], {}), '(slack_token)\n', (473, 486), False, 'from slackclient import SlackClient\n'), ((804, 830), 'boto3.resource', 'boto3.resource', (['"""dynamodb"""'], {}), "('dynamodb')\n", (818, 830), False, 'import boto3\n')]
from __future__ import division from __future__ import print_function from evaluation import get_roc_score, clustering_latent_space from input_data import load_adj_feature from kcore import compute_kcore, expand_embedding from model import * from optimizer import OptimizerAE, OptimizerVAE from preprocessing import * import numpy as np import os import scipy.sparse as sp import tensorflow as tf import time os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) flags = tf.app.flags FLAGS = flags.FLAGS # Select graph dataset flags.DEFINE_string('dataset', 'Cross-talk', 'Name of the graph dataset') # Select machine learning task to perform on graph flags.DEFINE_string('task', 'link_prediction', 'Name of the learning task') # Model flags.DEFINE_string('model', 'linear_vae', 'Name of the model') # Model parameters flags.DEFINE_float('dropout', 0., 'Dropout rate (1 - keep probability).') flags.DEFINE_integer('epochs', 1000, 'Number of epochs in training.') flags.DEFINE_boolean('features', True, 'Include node features or not in encoder') flags.DEFINE_float('learning_rate', 0.05, 'Initial learning rate (with Adam)') flags.DEFINE_integer('hidden', 64, 'Number of units in GCN hidden layer(s).') flags.DEFINE_integer('dimension', 128, 'Dimension of encoder output, i.e. \ embedding dimension') # Experimental setup parameters flags.DEFINE_integer('nb_run', 1, 'Number of model run + test') flags.DEFINE_float('prop_val', 5., 'Proportion of edges in validation set \ (for Link Prediction task)') flags.DEFINE_float('prop_test', 10., 'Proportion of edges in test set \ (for Link Prediction task)') flags.DEFINE_boolean('validation', False, 'Whether to report validation \ results at each epoch (for \ Link Prediction task)') flags.DEFINE_boolean('verbose', True, 'Whether to print comments details.') flags.DEFINE_boolean('kcore', False, 'Whether to run k-core decomposition \ and use the framework. False = model \ will be trained on the entire graph') flags.DEFINE_integer('k', 2, 'Which k-core to use. Higher k => smaller graphs\ and faster (but maybe less accurate) training') flags.DEFINE_integer('nb_iterations', 10, 'Number of fix point iterations in \ algorithm 2 of IJCAI paper. See \ kcore.py file for details') # Lists to collect average results if FLAGS.task == 'link_prediction': mean_roc = [] mean_ap = [] if FLAGS.kcore: mean_time_kcore = [] mean_time_train = [] mean_time_expand = [] mean_core_size = [] mean_time = [] # Load graph dataset if FLAGS.verbose: print("Loading data...") if FLAGS.dataset == 'Cross-talk': adj_init, features_init = load_adj_feature('../Cross-talk/Fegs_1.npy', '../Cross-talk/Cross-talk_Matrix.txt') else: adj_init, features_init = load_data(FLAGS.dataset) print(type(adj_init), type(features_init)) # The entire training+test process is repeated FLAGS.nb_run times for i in range(FLAGS.nb_run): if FLAGS.task == 'link_prediction': if FLAGS.verbose: print("Masking test edges...") # Edge Masking for Link Prediction: compute Train/Validation/Test set adj, val_edges, val_edges_false, test_edges, test_edges_false = \ mask_test_edges(adj_init, FLAGS.prop_test, FLAGS.prop_val) elif FLAGS.task == 'node_clustering': adj_tri = sp.triu(adj_init) adj = adj_tri + adj_tri.T else: raise ValueError('Undefined task!') # Start computation of running times t_start = time.time() # Degeneracy Framework / K-Core Decomposition if FLAGS.kcore: if FLAGS.verbose: print("Starting k-core decomposition of the graph") # Save adjacency matrix of un-decomposed graph # (needed to embed nodes that are not in k-core, after GAE training) adj_orig = adj # Get the (smaller) adjacency matrix of the k-core subgraph, # and the corresponding nodes adj, nodes_kcore = compute_kcore(adj, FLAGS.k) # Get the (smaller) feature matrix of the nb_core graph if FLAGS.features: features = features_init[nodes_kcore, :] # Flag to compute k-core decomposition's running time t_core = time.time() elif FLAGS.features: features = features_init # Preprocessing and initialization if FLAGS.verbose: print("Preprocessing and Initializing...") # Compute number of nodes num_nodes = adj.shape[0] # If features are not used, replace feature matrix by identity matrix if not FLAGS.features: features = sp.identity(adj.shape[0]) # Preprocessing on node features features = sparse_to_tuple(features) num_features = features[2][1] features_nonzero = features[1].shape[0] # Define placeholders placeholders = { 'features': tf.sparse_placeholder(tf.float32), 'adj': tf.sparse_placeholder(tf.float32), 'adj_orig': tf.sparse_placeholder(tf.float32), 'dropout': tf.placeholder_with_default(0., shape=()) } # Create model model = None # Linear Graph Variational Autoencoder model = LinearModelVAE(placeholders, num_features, num_nodes, features_nonzero) # Optimizer pos_weight = float(adj.shape[0] * adj.shape[0] - adj.sum()) / adj.sum() norm = adj.shape[0] * adj.shape[0] / float((adj.shape[0] * adj.shape[0] - adj.sum()) * 2) with tf.name_scope('optimizer'): # Optimizer for Non-Variational Autoencoders opt = OptimizerVAE(preds=model.reconstructions, labels=tf.reshape(tf.sparse_tensor_to_dense(placeholders['adj_orig'], validate_indices=False), [-1]), model=model, num_nodes=num_nodes, pos_weight=pos_weight, norm=norm) # Normalization and preprocessing on adjacency matrix adj_norm = preprocess_graph(adj) adj_label = sparse_to_tuple(adj + sp.eye(adj.shape[0])) # Initialize TF session sess = tf.Session() sess.run(tf.global_variables_initializer()) # Model training if FLAGS.verbose: print("Training...") for epoch in range(FLAGS.epochs): # Flag to compute running time for each epoch t = time.time() # Construct feed dictionary feed_dict = construct_feed_dict(adj_norm, adj_label, features, placeholders) feed_dict.update({placeholders['dropout']: FLAGS.dropout}) # Weights update outs = sess.run([opt.opt_op, opt.cost, opt.accuracy], feed_dict=feed_dict) # Compute average loss avg_cost = outs[1] if FLAGS.verbose: # Display epoch information print("Epoch:", '%04d' % (epoch + 1), "train_loss=", "{:.5f}".format(avg_cost), "time=", "{:.5f}".format(time.time() - t)) # Validation, for Link Prediction if not FLAGS.kcore and FLAGS.validation and FLAGS.task == 'link_prediction': feed_dict.update({placeholders['dropout']: 0}) emb = sess.run(model.z_mean, feed_dict=feed_dict) feed_dict.update({placeholders['dropout']: FLAGS.dropout}) val_roc, val_ap = get_roc_score(val_edges, val_edges_false, emb) print("val_roc=", "{:.5f}".format(val_roc), "val_ap=", "{:.5f}".format(val_ap)) # Flag to compute Graph AE/VAE training time t_model = time.time() # Compute embedding # Get embedding from model emb = sess.run(model.z_mean, feed_dict=feed_dict) # If k-core is used, only part of the nodes from the original # graph are embedded. The remaining ones are projected in the # latent space via the expand_embedding heuristic if FLAGS.kcore: if FLAGS.verbose: print("Propagation to remaining nodes...") # Project remaining nodes in latent space emb = expand_embedding(adj_orig, emb, nodes_kcore, FLAGS.nb_iterations) # Compute mean running times for K-Core, GAE Train and Propagation steps mean_time_expand.append(time.time() - t_model) mean_time_train.append(t_model - t_core) mean_time_kcore.append(t_core - t_start) # Compute mean size of K-Core graph # Note: size is fixed if task is node clustering, but will vary if # task is link prediction due to edge masking mean_core_size.append(len(nodes_kcore)) # Compute mean total running time mean_time.append(time.time() - t_start) print(type(emb)) np.save('../Cross-talk/Cross_talk_gcn_features128_FEGS.npy', emb) # Test model if FLAGS.verbose: print("Testing model...") # Link Prediction: classification edges/non-edges # Get ROC and AP scores roc_score, ap_score = get_roc_score(test_edges, test_edges_false, emb) # Report scores mean_roc.append(roc_score) mean_ap.append(ap_score) ###### Report Final Results ###### # Report final results print("\nTest results for", FLAGS.model, "model on", FLAGS.dataset, "on", FLAGS.task, "\n", "___________________________________________________\n") if FLAGS.task == 'link_prediction': print("AUC scores\n", mean_roc) print("Mean AUC score: ", np.mean(mean_roc), "\nStd of AUC scores: ", np.std(mean_roc), "\n \n") print("AP scores\n", mean_ap) print("Mean AP score: ", np.mean(mean_ap), "\nStd of AP scores: ", np.std(mean_ap), "\n \n") else: print("Adjusted MI scores\n", mean_mutual_info) print("Mean Adjusted MI score: ", np.mean(mean_mutual_info), "\nStd of Adjusted MI scores: ", np.std(mean_mutual_info), "\n \n") print("Total Running times\n", mean_time) print("Mean total running time: ", np.mean(mean_time), "\nStd of total running time: ", np.std(mean_time), "\n \n")
[ "numpy.save", "kcore.expand_embedding", "numpy.std", "tensorflow.global_variables_initializer", "tensorflow.placeholder_with_default", "tensorflow.sparse_tensor_to_dense", "tensorflow.Session", "kcore.compute_kcore", "time.time", "scipy.sparse.triu", "numpy.mean", "input_data.load_adj_feature", "scipy.sparse.identity", "evaluation.get_roc_score", "tensorflow.sparse_placeholder", "tensorflow.name_scope", "scipy.sparse.eye" ]
[((3122, 3209), 'input_data.load_adj_feature', 'load_adj_feature', (['"""../Cross-talk/Fegs_1.npy"""', '"""../Cross-talk/Cross-talk_Matrix.txt"""'], {}), "('../Cross-talk/Fegs_1.npy',\n '../Cross-talk/Cross-talk_Matrix.txt')\n", (3138, 3209), False, 'from input_data import load_adj_feature\n'), ((4033, 4044), 'time.time', 'time.time', ([], {}), '()\n', (4042, 4044), False, 'import time\n'), ((6779, 6791), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (6789, 6791), True, 'import tensorflow as tf\n'), ((8279, 8290), 'time.time', 'time.time', ([], {}), '()\n', (8288, 8290), False, 'import time\n'), ((9412, 9477), 'numpy.save', 'np.save', (['"""../Cross-talk/Cross_talk_gcn_features128_FEGS.npy"""', 'emb'], {}), "('../Cross-talk/Cross_talk_gcn_features128_FEGS.npy', emb)\n", (9419, 9477), True, 'import numpy as np\n'), ((9667, 9715), 'evaluation.get_roc_score', 'get_roc_score', (['test_edges', 'test_edges_false', 'emb'], {}), '(test_edges, test_edges_false, emb)\n', (9680, 9715), False, 'from evaluation import get_roc_score, clustering_latent_space\n'), ((10650, 10668), 'numpy.mean', 'np.mean', (['mean_time'], {}), '(mean_time)\n', (10657, 10668), True, 'import numpy as np\n'), ((10710, 10727), 'numpy.std', 'np.std', (['mean_time'], {}), '(mean_time)\n', (10716, 10727), True, 'import numpy as np\n'), ((4506, 4533), 'kcore.compute_kcore', 'compute_kcore', (['adj', 'FLAGS.k'], {}), '(adj, FLAGS.k)\n', (4519, 4533), False, 'from kcore import compute_kcore, expand_embedding\n'), ((4762, 4773), 'time.time', 'time.time', ([], {}), '()\n', (4771, 4773), False, 'import time\n'), ((5135, 5160), 'scipy.sparse.identity', 'sp.identity', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (5146, 5160), True, 'import scipy.sparse as sp\n'), ((5393, 5426), 'tensorflow.sparse_placeholder', 'tf.sparse_placeholder', (['tf.float32'], {}), '(tf.float32)\n', (5414, 5426), True, 'import tensorflow as tf\n'), ((5444, 5477), 'tensorflow.sparse_placeholder', 'tf.sparse_placeholder', (['tf.float32'], {}), '(tf.float32)\n', (5465, 5477), True, 'import tensorflow as tf\n'), ((5500, 5533), 'tensorflow.sparse_placeholder', 'tf.sparse_placeholder', (['tf.float32'], {}), '(tf.float32)\n', (5521, 5533), True, 'import tensorflow as tf\n'), ((5555, 5597), 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['(0.0)'], {'shape': '()'}), '(0.0, shape=())\n', (5582, 5597), True, 'import tensorflow as tf\n'), ((6055, 6081), 'tensorflow.name_scope', 'tf.name_scope', (['"""optimizer"""'], {}), "('optimizer')\n", (6068, 6081), True, 'import tensorflow as tf\n'), ((6806, 6839), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (6837, 6839), True, 'import tensorflow as tf\n'), ((7027, 7038), 'time.time', 'time.time', ([], {}), '()\n', (7036, 7038), False, 'import time\n'), ((8768, 8833), 'kcore.expand_embedding', 'expand_embedding', (['adj_orig', 'emb', 'nodes_kcore', 'FLAGS.nb_iterations'], {}), '(adj_orig, emb, nodes_kcore, FLAGS.nb_iterations)\n', (8784, 8833), False, 'from kcore import compute_kcore, expand_embedding\n'), ((10134, 10151), 'numpy.mean', 'np.mean', (['mean_roc'], {}), '(mean_roc)\n', (10141, 10151), True, 'import numpy as np\n'), ((10189, 10205), 'numpy.std', 'np.std', (['mean_roc'], {}), '(mean_roc)\n', (10195, 10205), True, 'import numpy as np\n'), ((10283, 10299), 'numpy.mean', 'np.mean', (['mean_ap'], {}), '(mean_ap)\n', (10290, 10299), True, 'import numpy as np\n'), ((10336, 10351), 'numpy.std', 'np.std', (['mean_ap'], {}), '(mean_ap)\n', (10342, 10351), True, 'import numpy as np\n'), ((10463, 10488), 'numpy.mean', 'np.mean', (['mean_mutual_info'], {}), '(mean_mutual_info)\n', (10470, 10488), True, 'import numpy as np\n'), ((10534, 10558), 'numpy.std', 'np.std', (['mean_mutual_info'], {}), '(mean_mutual_info)\n', (10540, 10558), True, 'import numpy as np\n'), ((3865, 3882), 'scipy.sparse.triu', 'sp.triu', (['adj_init'], {}), '(adj_init)\n', (3872, 3882), True, 'import scipy.sparse as sp\n'), ((6714, 6734), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (6720, 6734), True, 'import scipy.sparse as sp\n'), ((9360, 9371), 'time.time', 'time.time', ([], {}), '()\n', (9369, 9371), False, 'import time\n'), ((8068, 8114), 'evaluation.get_roc_score', 'get_roc_score', (['val_edges', 'val_edges_false', 'emb'], {}), '(val_edges, val_edges_false, emb)\n', (8081, 8114), False, 'from evaluation import get_roc_score, clustering_latent_space\n'), ((8949, 8960), 'time.time', 'time.time', ([], {}), '()\n', (8958, 8960), False, 'import time\n'), ((6240, 6315), 'tensorflow.sparse_tensor_to_dense', 'tf.sparse_tensor_to_dense', (["placeholders['adj_orig']"], {'validate_indices': '(False)'}), "(placeholders['adj_orig'], validate_indices=False)\n", (6265, 6315), True, 'import tensorflow as tf\n'), ((7671, 7682), 'time.time', 'time.time', ([], {}), '()\n', (7680, 7682), False, 'import time\n')]
# -*- coding: utf-8 -*- # Copyright 2017-2019 ControlScan, Inc. # # This file is part of Cyphon Engine. # # Cyphon Engine 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, version 3 of the License. # # Cyphon Engine 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 Cyphon Engine. If not, see <http://www.gnu.org/licenses/>. """ Tests the Filter class. """ # third party from django.test import TestCase from django.core.exceptions import ValidationError from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User # local from aggregator.filters.models import Filter from target.followees.models import Followee from target.locations.models import Location from target.searchterms.models import SearchTerm from tests.fixture_manager import get_fixtures class FilterModelsTestCase(TestCase): """ Base class for testing Filter class and related classes. """ fixtures = get_fixtures(['followees', 'filters', 'reservoirs']) class FilterManagerTestCase(FilterModelsTestCase): """ Tests the FilterManager class. """ def test_enabled_filters_by_type(self): """ Tests the _find_enabled_filters_by_type method. """ followee_type = ContentType.objects.get_for_model(Followee) followees = Filter.objects._find_enabled_filters_by_type(followee_type) self.assertEqual(len(followees), 2) location_type = ContentType.objects.get_for_model(Location) locations = Filter.objects._find_enabled_filters_by_type(location_type) self.assertEqual(len(locations), 3) term_type = ContentType.objects.get_for_model(SearchTerm) terms = Filter.objects._find_enabled_filters_by_type(term_type) self.assertEqual(len(terms), 1) def test_get_oldest_time_last_used(self): """ Tests the _get_oldest_time_last_used method. """ oldest_time = Filter.objects._get_oldest_time_last_used() self.assertEqual(str(oldest_time), "2000-01-01 05:00:00+00:00") def test_create_timeframe(self): """ Tests the _get_timeframe method. """ timeframe = Filter.objects._create_timeframe() self.assertEqual(str(timeframe.start), "2000-01-01 05:00:00+00:00") def test_create_reservoir_query(self): """ Tests the create_reservoir_query method. """ query = Filter.objects.create_reservoir_query() self.assertEqual(len(query.accounts), 4) self.assertEqual(len(query.locations), 3) self.assertEqual(len(query.searchterms), 1) class FilterTestCase(FilterModelsTestCase): """ Tests the Filter class. """ def setUp(self): followee_type = ContentType.objects.get_for_model(Followee) location_type = ContentType.objects.get_for_model(Location) srchterm_type = ContentType.objects.get_for_model(SearchTerm) self.followee_filter = Filter( content_type=followee_type, object_id=1, last_used="2015-01-01T12:00:00+05:00" ) self.location_filter = Filter( content_type=location_type, object_id=1, last_used="2015-01-01T12:00:00+05:00" ) self.srchterm_filter = Filter( content_type=srchterm_type, object_id=1, last_used="2015-01-01T12:00:00+05:00" ) def test_str(self): """ Tests the __str__ method. """ actual = str(self.location_filter) expected = 'Point <Point> (location)' self.assertEqual(actual, expected) def test_filter_type(self): """ Tests the filter_type method. """ actual = self.followee_filter.filter_type expected = 'followee' self.assertEqual(actual, expected) def test_create_followee_filter(self): """ Test case for a Followee Filter. """ try: self.followee_filter.full_clean() except ValidationError: self.fail("Followee filter raised ValidationError unexpectedly") def test_create_location_filter(self): """ Test case for a Location Filter. """ try: self.location_filter.full_clean() except ValidationError: self.fail("Location filter raised ValidationError unexpectedly") def test_create_searchterm_filter(self): """ Test case for a SearchTerm Filter. """ try: self.srchterm_filter.full_clean() except ValidationError: self.fail("SearchTerm filter raised ValidationError unexpectedly") def test_create_invalid_filter(self): """ Test case for an invalid Filter. """ user_type = ContentType.objects.get_for_model(User) new_filter = Filter( content_type=user_type, object_id=1, last_used="2015-01-01T12:00:00+05:00" ) with self.assertRaises(ValidationError): new_filter.full_clean()
[ "aggregator.filters.models.Filter.objects._find_enabled_filters_by_type", "aggregator.filters.models.Filter", "django.contrib.contenttypes.models.ContentType.objects.get_for_model", "aggregator.filters.models.Filter.objects._create_timeframe", "tests.fixture_manager.get_fixtures", "aggregator.filters.models.Filter.objects._get_oldest_time_last_used", "aggregator.filters.models.Filter.objects.create_reservoir_query" ]
[((1299, 1351), 'tests.fixture_manager.get_fixtures', 'get_fixtures', (["['followees', 'filters', 'reservoirs']"], {}), "(['followees', 'filters', 'reservoirs'])\n", (1311, 1351), False, 'from tests.fixture_manager import get_fixtures\n'), ((1605, 1648), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['Followee'], {}), '(Followee)\n', (1638, 1648), False, 'from django.contrib.contenttypes.models import ContentType\n'), ((1669, 1728), 'aggregator.filters.models.Filter.objects._find_enabled_filters_by_type', 'Filter.objects._find_enabled_filters_by_type', (['followee_type'], {}), '(followee_type)\n', (1713, 1728), False, 'from aggregator.filters.models import Filter\n'), ((1798, 1841), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['Location'], {}), '(Location)\n', (1831, 1841), False, 'from django.contrib.contenttypes.models import ContentType\n'), ((1862, 1921), 'aggregator.filters.models.Filter.objects._find_enabled_filters_by_type', 'Filter.objects._find_enabled_filters_by_type', (['location_type'], {}), '(location_type)\n', (1906, 1921), False, 'from aggregator.filters.models import Filter\n'), ((1987, 2032), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['SearchTerm'], {}), '(SearchTerm)\n', (2020, 2032), False, 'from django.contrib.contenttypes.models import ContentType\n'), ((2049, 2104), 'aggregator.filters.models.Filter.objects._find_enabled_filters_by_type', 'Filter.objects._find_enabled_filters_by_type', (['term_type'], {}), '(term_type)\n', (2093, 2104), False, 'from aggregator.filters.models import Filter\n'), ((2291, 2334), 'aggregator.filters.models.Filter.objects._get_oldest_time_last_used', 'Filter.objects._get_oldest_time_last_used', ([], {}), '()\n', (2332, 2334), False, 'from aggregator.filters.models import Filter\n'), ((2530, 2564), 'aggregator.filters.models.Filter.objects._create_timeframe', 'Filter.objects._create_timeframe', ([], {}), '()\n', (2562, 2564), False, 'from aggregator.filters.models import Filter\n'), ((2774, 2813), 'aggregator.filters.models.Filter.objects.create_reservoir_query', 'Filter.objects.create_reservoir_query', ([], {}), '()\n', (2811, 2813), False, 'from aggregator.filters.models import Filter\n'), ((3101, 3144), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['Followee'], {}), '(Followee)\n', (3134, 3144), False, 'from django.contrib.contenttypes.models import ContentType\n'), ((3169, 3212), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['Location'], {}), '(Location)\n', (3202, 3212), False, 'from django.contrib.contenttypes.models import ContentType\n'), ((3237, 3282), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['SearchTerm'], {}), '(SearchTerm)\n', (3270, 3282), False, 'from django.contrib.contenttypes.models import ContentType\n'), ((3315, 3406), 'aggregator.filters.models.Filter', 'Filter', ([], {'content_type': 'followee_type', 'object_id': '(1)', 'last_used': '"""2015-01-01T12:00:00+05:00"""'}), "(content_type=followee_type, object_id=1, last_used=\n '2015-01-01T12:00:00+05:00')\n", (3321, 3406), False, 'from aggregator.filters.models import Filter\n'), ((3480, 3571), 'aggregator.filters.models.Filter', 'Filter', ([], {'content_type': 'location_type', 'object_id': '(1)', 'last_used': '"""2015-01-01T12:00:00+05:00"""'}), "(content_type=location_type, object_id=1, last_used=\n '2015-01-01T12:00:00+05:00')\n", (3486, 3571), False, 'from aggregator.filters.models import Filter\n'), ((3645, 3736), 'aggregator.filters.models.Filter', 'Filter', ([], {'content_type': 'srchterm_type', 'object_id': '(1)', 'last_used': '"""2015-01-01T12:00:00+05:00"""'}), "(content_type=srchterm_type, object_id=1, last_used=\n '2015-01-01T12:00:00+05:00')\n", (3651, 3736), False, 'from aggregator.filters.models import Filter\n'), ((5176, 5215), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['User'], {}), '(User)\n', (5209, 5215), False, 'from django.contrib.contenttypes.models import ContentType\n'), ((5237, 5324), 'aggregator.filters.models.Filter', 'Filter', ([], {'content_type': 'user_type', 'object_id': '(1)', 'last_used': '"""2015-01-01T12:00:00+05:00"""'}), "(content_type=user_type, object_id=1, last_used=\n '2015-01-01T12:00:00+05:00')\n", (5243, 5324), False, 'from aggregator.filters.models import Filter\n')]
#!/usr/bin/env python3 # This file reads in "HTML" from a call to # thrift --gen html .... # and does some post-processing to it. # 1. It wraps struct headers + div definitions # in a div. # 2. It reorders struct divs to be alphabetically # ordered. from bs4 import BeautifulSoup import fileinput import logging def make_nice_lines(): looking_for_tag = False have_ending_tag = False char_buff = [] logging.basicConfig() logger = logging.getLogger('make_nice_lines') logger.setLevel(logging.INFO) for line in fileinput.input(): logger.debug("original line: " + line) for char in line: if char == '<' and len(char_buff) > 0: yield ''.join(char_buff) char_buff = [] char_buff.append(char) if char == '<': looking_for_tag = True elif char == '/': if looking_for_tag: have_ending_tag = True elif char == '>': looking_for_tag = False if have_ending_tag: yield ''.join(char_buff) char_buff = [] have_ending_tag = False else: pass yield ''.join(char_buff) def add_divs(): added_html = [] main_pane = False in_h2 = False logging.basicConfig() logger = logging.getLogger('reorder_div') logger.setLevel(logging.INFO) for line in make_nice_lines(): logger.debug("getting line::" + line) stripped_line = line.strip() if stripped_line.startswith('<div class="container-fluid"'): logger.debug("finding main pane") main_pane = True added_html.append(line) continue if not main_pane: added_html.append(line) continue # otherwise, we're in the main pane if stripped_line.startswith('<h2 id'): logger.debug("Found h2: " + stripped_line) in_h2 = True h2_id = stripped_line.split('"')[1] added_html.append('<div id="' + h2_id +'_div">') added_html.append(line) continue if in_h2: if stripped_line.startswith('<hr'): in_h2 = False added_html.append('</div>') added_html.append(line) continue # elif stripped_line.startsWith('<h2'): else: added_html.append(line) else: added_html.append(line) return added_html def main(): doc_with_divs = add_divs() bs_doc = BeautifulSoup(''.join(doc_with_divs), 'html.parser') structs = bs_doc.select('#Structs_div .definition') sorted_structs = sorted(structs, key = lambda x : x.select('h3')[0].get_text().strip()) sd_dv = bs_doc.select('#Structs_div') if len(sd_dv) == 0: page = bs_doc.select('title') import sys print ("Generated page", page[0].get_text(), "has no struct definitions. This is probably okay, but you may want to verify.", file=sys.stderr) print (bs_doc.prettify()) return 0 div_children = sd_dv[0].contents if not(len(div_children) - 2 == len(sorted_structs)): raise Exception("length of div children (%s) != length of struct defs (%s)" % (len(div_children) - 2, len(sorted_structs))) for i in range(2, len(sorted_structs)+2): div_children[i] = sorted_structs[i-2] print (bs_doc.prettify()) return 0 if __name__ == '__main__': main()
[ "fileinput.input", "logging.getLogger", "logging.basicConfig" ]
[((425, 446), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (444, 446), False, 'import logging\n'), ((460, 496), 'logging.getLogger', 'logging.getLogger', (['"""make_nice_lines"""'], {}), "('make_nice_lines')\n", (477, 496), False, 'import logging\n'), ((547, 564), 'fileinput.input', 'fileinput.input', ([], {}), '()\n', (562, 564), False, 'import fileinput\n'), ((1353, 1374), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (1372, 1374), False, 'import logging\n'), ((1388, 1420), 'logging.getLogger', 'logging.getLogger', (['"""reorder_div"""'], {}), "('reorder_div')\n", (1405, 1420), False, 'import logging\n')]
import math def two_point_distance(x1, y1, x2, y2): """ Calculates distance between two given points. x1 - X Value of Point 1 y1 - Y Value of Point 1 x2 - X Value of Point 2 y2 - Y Value of Point 2 """ return math.fabs(math.hypot(x2 - x1, y2 - y1)) def get_closest_enemy(search_squads, my_loc, my_fac, max_range=0): to_return = None cur_dist = -1 for squad in search_squads: if squad.squad_faction is not my_fac: sqd_ld_loc = squad.squad_leader.get_xy() distance = two_point_distance(my_loc[0], my_loc[1], sqd_ld_loc[0], sqd_ld_loc[1]) if max_range == 0 or distance <= max_range: if cur_dist == -1 or distance < cur_dist: for soldier in squad.squad_members: if soldier.is_alive(): distance = two_point_distance(my_loc[0], my_loc[1], soldier.get_x(), soldier.get_y()) if (cur_dist == -1 or distance < cur_dist) and (max_range == 0 or distance <= max_range): to_return = soldier cur_dist = distance return to_return
[ "math.hypot" ]
[((255, 283), 'math.hypot', 'math.hypot', (['(x2 - x1)', '(y2 - y1)'], {}), '(x2 - x1, y2 - y1)\n', (265, 283), False, 'import math\n')]
from collections import Counter t = int(input()) for _ in range(t): s = input() firstOne = -1 lastOne = -1 for i in range(len(s)): if s[i] == '1': if firstOne == -1: firstOne = i else: lastOne = i if firstOne > -1 and lastOne > -1: print(Counter(s[firstOne:lastOne])['0']) else: print(0)
[ "collections.Counter" ]
[((330, 358), 'collections.Counter', 'Counter', (['s[firstOne:lastOne]'], {}), '(s[firstOne:lastOne])\n', (337, 358), False, 'from collections import Counter\n')]
import numpy as np import pandas as pd from dstk.preprocessing import (onehot_encode, mark_binary, nan_to_binary, num_to_str) # Create test data df = pd.DataFrame() df['numeric1'] = [0, 1, 0, 0, 1, 1] df['numeric2'] = [1.0, 3.4, 5.4, 2.3, 3.1, 4.1] df['numericNaN'] = [1, 2, 3, None, 3, None] df['cat1'] = ['a', 'a', 'b', 'c', 'c', 'a'] df['catNaN'] = ['A', 'B', None, None, 'B', 'C'] # Test for num_to_str function def test_numtostr(): # Test for converting column type to object test = num_to_str(df, ['numeric1']) assert test['numeric1'].dtype == 'O' def test_numtostr_inplace(): # Test for converting column to object in place df2 = df.copy() num_to_str(df2, ['numeric1'], inplace=True) assert df2['numeric1'].dtype == 'O' # Tests for nan_to_binary function def test_nantobinary_inplaceTrue(): # Test for converting dataframe in place df2 = df.copy() nan_to_binary(df2, ['numericNaN'], inplace=True) assert df2['binary#numericNaN'].tolist() == [0, 0, 0, 1, 0, 1] def test_nantobinary_featureselect(): # Test for converting specified features test = nan_to_binary(df, ['numericNaN']) assert test['binary#numericNaN'].tolist() == [0, 0, 0, 1, 0, 1] def test_nantobinary_auto(): # Test for auto converting columns with NaN > threshold test = nan_to_binary(df) assert test['binary#catNaN'].tolist() == [0, 0, 1, 1, 0, 0] def test_nantobinary_threshold(): # Test for auto converting columns with NaN > specified threshold test = nan_to_binary(df, threshold=0.5, inplace=False) assert test.loc[2, 'catNaN'] == None # Tests for markbinary function def test_markbinary_inplaceFalse(): # Test for not transforming df in place test = mark_binary(df, inplace=False) assert test.columns.tolist()[0] == 'binary#numeric1' def test_markbinary_inplaceTrue(): # Test for transforming df in place df2 = df.copy() mark_binary(df2, inplace=True) assert df2.columns.tolist()[0] == 'binary#numeric1' def test_markbinary_inplaceTrue_selectfeature(): # Test for selecting specific features to mark df2 = df.copy() mark_binary(df2, ['numeric1'], inplace=True) assert df2.columns.tolist()[0] == 'binary#numeric1' # Tests for onehotencode wrapper def test_onehot_checkprefix(): # Test whether prefixes are created correctly test = onehot_encode(df) assert test.columns.tolist() == ['numeric1', 'numeric2', 'numericNaN', 'binary#cat1_b', 'binary#cat1_c', 'binary#catNaN_B', 'binary#catNaN_C', 'binary#catNaN_nan'] def test_onehot_selectfeature(): # Test whether subselection of features is correct test = onehot_encode(df, features=['cat1']) assert test.columns.tolist() == ['numeric1', 'numeric2', 'numericNaN', 'catNaN', 'binary#cat1_b', 'binary#cat1_c'] def test_onehot_retainNaNs(): # Test whether nans are retained test = onehot_encode(df, impute='retain') assert np.isnan(test['binary#catNaN_B']).tolist() == [ False, False, True, True, False, False] def test_onehot_modeimputeNaNs(): # Test mode imputing NaNs test = onehot_encode(df, impute='mode') assert test['binary#catNaN_B'].tolist() == [0, 1, 1, 1, 1, 0] def test_onehot_trackNaNs(): # Test whether nans are tracked in separate column test = onehot_encode(df) assert test['binary#catNaN_nan'].tolist() == [0, 0, 1, 1, 0, 0] def test_onehot_drop_zerovar(): # Test whether zero variance columns are dropped df['cat2'] = ['a', 'a', 'a', 'a', 'a', 'a'] test = onehot_encode(df) assert test.columns.tolist() == ['numeric1', 'numeric2', 'numericNaN', 'binary#cat1_b', 'binary#cat1_c', 'binary#catNaN_B', 'binary#catNaN_C', 'binary#catNaN_nan']
[ "pandas.DataFrame", "dstk.preprocessing.nan_to_binary", "numpy.isnan", "dstk.preprocessing.onehot_encode", "dstk.preprocessing.num_to_str", "dstk.preprocessing.mark_binary" ]
[((248, 262), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (260, 262), True, 'import pandas as pd\n'), ((597, 625), 'dstk.preprocessing.num_to_str', 'num_to_str', (['df', "['numeric1']"], {}), "(df, ['numeric1'])\n", (607, 625), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((774, 817), 'dstk.preprocessing.num_to_str', 'num_to_str', (['df2', "['numeric1']"], {'inplace': '(True)'}), "(df2, ['numeric1'], inplace=True)\n", (784, 817), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((1001, 1049), 'dstk.preprocessing.nan_to_binary', 'nan_to_binary', (['df2', "['numericNaN']"], {'inplace': '(True)'}), "(df2, ['numericNaN'], inplace=True)\n", (1014, 1049), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((1213, 1246), 'dstk.preprocessing.nan_to_binary', 'nan_to_binary', (['df', "['numericNaN']"], {}), "(df, ['numericNaN'])\n", (1226, 1246), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((1417, 1434), 'dstk.preprocessing.nan_to_binary', 'nan_to_binary', (['df'], {}), '(df)\n', (1430, 1434), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((1616, 1663), 'dstk.preprocessing.nan_to_binary', 'nan_to_binary', (['df'], {'threshold': '(0.5)', 'inplace': '(False)'}), '(df, threshold=0.5, inplace=False)\n', (1629, 1663), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((1831, 1861), 'dstk.preprocessing.mark_binary', 'mark_binary', (['df'], {'inplace': '(False)'}), '(df, inplace=False)\n', (1842, 1861), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((2020, 2050), 'dstk.preprocessing.mark_binary', 'mark_binary', (['df2'], {'inplace': '(True)'}), '(df2, inplace=True)\n', (2031, 2050), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((2234, 2278), 'dstk.preprocessing.mark_binary', 'mark_binary', (['df2', "['numeric1']"], {'inplace': '(True)'}), "(df2, ['numeric1'], inplace=True)\n", (2245, 2278), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((2463, 2480), 'dstk.preprocessing.onehot_encode', 'onehot_encode', (['df'], {}), '(df)\n', (2476, 2480), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((3009, 3045), 'dstk.preprocessing.onehot_encode', 'onehot_encode', (['df'], {'features': "['cat1']"}), "(df, features=['cat1'])\n", (3022, 3045), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((3430, 3464), 'dstk.preprocessing.onehot_encode', 'onehot_encode', (['df'], {'impute': '"""retain"""'}), "(df, impute='retain')\n", (3443, 3464), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((3649, 3681), 'dstk.preprocessing.onehot_encode', 'onehot_encode', (['df'], {'impute': '"""mode"""'}), "(df, impute='mode')\n", (3662, 3681), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((3845, 3862), 'dstk.preprocessing.onehot_encode', 'onehot_encode', (['df'], {}), '(df)\n', (3858, 3862), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((4077, 4094), 'dstk.preprocessing.onehot_encode', 'onehot_encode', (['df'], {}), '(df)\n', (4090, 4094), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, num_to_str\n'), ((3476, 3509), 'numpy.isnan', 'np.isnan', (["test['binary#catNaN_B']"], {}), "(test['binary#catNaN_B'])\n", (3484, 3509), True, 'import numpy as np\n')]
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE from __future__ import absolute_import import pytest # noqa: F401 import numpy as np # noqa: F401 import awkward as ak # noqa: F401 def test(): for itype in ["i8", "u8", "i32", "u32", "i64"]: form = ak.forms.ListOffsetForm(itype, ak.forms.EmptyForm()) assert form.offsets == itype
[ "awkward.forms.EmptyForm" ]
[((337, 357), 'awkward.forms.EmptyForm', 'ak.forms.EmptyForm', ([], {}), '()\n', (355, 357), True, 'import awkward as ak\n')]
import logging import time from io import IOBase from typing import Callable from typing import Any from .base import Context from tftpy.states import Start logger = logging.getLogger('tftpy.context.server') class Server(Context): """The context for the server.""" def __init__(self, host: str, port: int, timeout: int, root: str, dyn_file_func: Callable[[str,str,int],Any] = None, upload_open: Callable[[str,Context],IOBase]=None, **kwargs) -> None: """Prepare the server context to process data from a client Args: host (str): The requesting clients IP port (int): The requesting clients Port timeout (int): stocket timeout root (str): server root path dyn_file_func (Callable[[str,str,int],Any], optional): A dynamic fucntion function to read from upload_open (Callable[[str,Context],IOBase], optional): A dynamic function to write data to """ super().__init__(host, port, timeout, **kwargs) # At this point we have no idea if this is a download or an upload. We # need to let the start state determine that. self.state = Start(self) self.root = root self.dyn_file_func = dyn_file_func self.upload_open = upload_open def start(self, buffer: bytes = None) -> None: """Start the state cycle. Note that the server context receives an initial packet in its start method. Also note that the server does not loop on cycle(), as it expects the TftpServer object to manage that. Args: buffer (bytes, optional): Buffer Data receivied from the client. Should be either a read or write request """ logger.debug("In tftpy.contex.server.start") self.metrics.start_time = self.last_update = time.time() pkt = self.factory.parse(buffer) logger.debug(f"tftpy.contex.server.start() - factory returned a {pkt}") # Call handle once with the initial packet. This should put us into # the download or the upload state. self.state = self.state.handle(pkt,self.host,self.port) def end(self, *args, **kwargs) -> None: """Finish up the context.""" super().end(*args, **kwargs) self.metrics.end_time = time.time() logger.debug(f"Set metrics.end_time to {self.metrics.end_time}") self.metrics.compute()
[ "tftpy.states.Start", "logging.getLogger", "time.time" ]
[((179, 220), 'logging.getLogger', 'logging.getLogger', (['"""tftpy.context.server"""'], {}), "('tftpy.context.server')\n", (196, 220), False, 'import logging\n'), ((1275, 1286), 'tftpy.states.Start', 'Start', (['self'], {}), '(self)\n', (1280, 1286), False, 'from tftpy.states import Start\n'), ((1980, 1991), 'time.time', 'time.time', ([], {}), '()\n', (1989, 1991), False, 'import time\n'), ((2474, 2485), 'time.time', 'time.time', ([], {}), '()\n', (2483, 2485), False, 'import time\n')]
from functools import partial from pyramid.view import view_defaults from pyramid.view import view_config from c2cgeoform.schema import GeoFormSchemaNode from c2cgeoform.views.abstract_views import ListField from deform.widget import FormWidget from c2cgeoportal_admin.schemas.treegroup import children_schema_node from c2cgeoportal_admin.schemas.metadata import metadatas_schema_node from c2cgeoportal_admin.schemas.treeitem import parent_id_node from c2cgeoportal_admin.views.treeitems import TreeItemViews from c2cgeoportal_commons.models.main import LayerGroup, TreeGroup _list_field = partial(ListField, LayerGroup) base_schema = GeoFormSchemaNode(LayerGroup, widget=FormWidget(fields_template='layer_group_fields')) base_schema.add(children_schema_node()) base_schema.add(metadatas_schema_node.clone()) base_schema.add_unique_validator(LayerGroup.name, LayerGroup.id) base_schema.add(parent_id_node(TreeGroup)) @view_defaults(match_param='table=layer_groups') class LayerGroupsViews(TreeItemViews): _list_fields = TreeItemViews._list_fields + \ [_list_field('is_expanded')] + \ TreeItemViews._extra_list_fields _id_field = 'id' _model = LayerGroup _base_schema = base_schema def _base_query(self, query=None): return super()._base_query( self._request.dbsession.query(LayerGroup).distinct()) @view_config(route_name='c2cgeoform_index', renderer='../templates/index.jinja2') def index(self): return super().index() @view_config(route_name='c2cgeoform_grid', renderer='fast_json') def grid(self): return super().grid() @view_config(route_name='c2cgeoform_item', request_method='GET', renderer='../templates/edit.jinja2') def view(self): return super().edit() @view_config(route_name='c2cgeoform_item', request_method='POST', renderer='../templates/edit.jinja2') def save(self): return super().save() @view_config(route_name='c2cgeoform_item', request_method='DELETE', renderer='fast_json') def delete(self): return super().delete() @view_config(route_name='c2cgeoform_item_duplicate', request_method='GET', renderer='../templates/edit.jinja2') def duplicate(self): return super().duplicate()
[ "functools.partial", "deform.widget.FormWidget", "c2cgeoportal_admin.schemas.treegroup.children_schema_node", "pyramid.view.view_config", "pyramid.view.view_defaults", "c2cgeoportal_admin.schemas.metadata.metadatas_schema_node.clone", "c2cgeoportal_admin.schemas.treeitem.parent_id_node" ]
[((594, 624), 'functools.partial', 'partial', (['ListField', 'LayerGroup'], {}), '(ListField, LayerGroup)\n', (601, 624), False, 'from functools import partial\n'), ((926, 973), 'pyramid.view.view_defaults', 'view_defaults', ([], {'match_param': '"""table=layer_groups"""'}), "(match_param='table=layer_groups')\n", (939, 973), False, 'from pyramid.view import view_defaults\n'), ((744, 766), 'c2cgeoportal_admin.schemas.treegroup.children_schema_node', 'children_schema_node', ([], {}), '()\n', (764, 766), False, 'from c2cgeoportal_admin.schemas.treegroup import children_schema_node\n'), ((784, 813), 'c2cgeoportal_admin.schemas.metadata.metadatas_schema_node.clone', 'metadatas_schema_node.clone', ([], {}), '()\n', (811, 813), False, 'from c2cgeoportal_admin.schemas.metadata import metadatas_schema_node\n'), ((896, 921), 'c2cgeoportal_admin.schemas.treeitem.parent_id_node', 'parent_id_node', (['TreeGroup'], {}), '(TreeGroup)\n', (910, 921), False, 'from c2cgeoportal_admin.schemas.treeitem import parent_id_node\n'), ((1371, 1456), 'pyramid.view.view_config', 'view_config', ([], {'route_name': '"""c2cgeoform_index"""', 'renderer': '"""../templates/index.jinja2"""'}), "(route_name='c2cgeoform_index', renderer='../templates/index.jinja2'\n )\n", (1382, 1456), False, 'from pyramid.view import view_config\n'), ((1527, 1590), 'pyramid.view.view_config', 'view_config', ([], {'route_name': '"""c2cgeoform_grid"""', 'renderer': '"""fast_json"""'}), "(route_name='c2cgeoform_grid', renderer='fast_json')\n", (1538, 1590), False, 'from pyramid.view import view_config\n'), ((1664, 1769), 'pyramid.view.view_config', 'view_config', ([], {'route_name': '"""c2cgeoform_item"""', 'request_method': '"""GET"""', 'renderer': '"""../templates/edit.jinja2"""'}), "(route_name='c2cgeoform_item', request_method='GET', renderer=\n '../templates/edit.jinja2')\n", (1675, 1769), False, 'from pyramid.view import view_config\n'), ((1855, 1961), 'pyramid.view.view_config', 'view_config', ([], {'route_name': '"""c2cgeoform_item"""', 'request_method': '"""POST"""', 'renderer': '"""../templates/edit.jinja2"""'}), "(route_name='c2cgeoform_item', request_method='POST', renderer=\n '../templates/edit.jinja2')\n", (1866, 1961), False, 'from pyramid.view import view_config\n'), ((2047, 2140), 'pyramid.view.view_config', 'view_config', ([], {'route_name': '"""c2cgeoform_item"""', 'request_method': '"""DELETE"""', 'renderer': '"""fast_json"""'}), "(route_name='c2cgeoform_item', request_method='DELETE', renderer\n ='fast_json')\n", (2058, 2140), False, 'from pyramid.view import view_config\n'), ((2230, 2344), 'pyramid.view.view_config', 'view_config', ([], {'route_name': '"""c2cgeoform_item_duplicate"""', 'request_method': '"""GET"""', 'renderer': '"""../templates/edit.jinja2"""'}), "(route_name='c2cgeoform_item_duplicate', request_method='GET',\n renderer='../templates/edit.jinja2')\n", (2241, 2344), False, 'from pyramid.view import view_config\n'), ((678, 726), 'deform.widget.FormWidget', 'FormWidget', ([], {'fields_template': '"""layer_group_fields"""'}), "(fields_template='layer_group_fields')\n", (688, 726), False, 'from deform.widget import FormWidget\n')]
import os import wave from io import BytesIO, BufferedIOBase from tempfile import NamedTemporaryFile import pytest from audoai.noise_removal import NoiseRemovalClient @pytest.fixture() def noise_removal() -> NoiseRemovalClient: api_key = os.environ['AUDO_API_KEY'] base_url = os.environ['AUDO_BASE_URL'] noise_removal = NoiseRemovalClient(api_key, base_url) return noise_removal @pytest.fixture() def silence_fileobject() -> BufferedIOBase: channels = 1 sample_rate = 44100 seconds = 4.0 wav_data = BytesIO(bytes()) with wave.open(wav_data, "wb") as wf: wf.setparams((1, channels, sample_rate, 0, "NONE", "not compressed")) wf.writeframes(b"\0" * int(sample_rate * seconds * channels)) wav_data.seek(0) return wav_data def test_process_fileobject( noise_removal: NoiseRemovalClient, silence_fileobject: BufferedIOBase ): output = noise_removal.process(silence_fileobject, "wav", output_extension="mp3") assert output.url with NamedTemporaryFile(suffix=".mp3") as temp: output.save(temp.name) # Invalid extension with pytest.raises(ValueError): with NamedTemporaryFile(suffix=".wav") as temp: output.save(temp.name) def test_process_filename( noise_removal: NoiseRemovalClient, silence_fileobject: BufferedIOBase ): with NamedTemporaryFile(suffix=".wav") as temp: temp.write(silence_fileobject.read()) output = noise_removal.process(temp.name) assert output.url def test_process_url( noise_removal: NoiseRemovalClient ): input_url = "http://dl5.webmfiles.org/big-buck-bunny_trailer.webm" output = noise_removal.process(input_url, output_extension="mp4") assert output.url def test_process_invalid( noise_removal: NoiseRemovalClient, silence_fileobject: BufferedIOBase ): with pytest.raises((OSError, TypeError)): noise_removal.process('invalid-arg')
[ "wave.open", "tempfile.NamedTemporaryFile", "pytest.fixture", "pytest.raises", "audoai.noise_removal.NoiseRemovalClient" ]
[((171, 187), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (185, 187), False, 'import pytest\n'), ((401, 417), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (415, 417), False, 'import pytest\n'), ((335, 372), 'audoai.noise_removal.NoiseRemovalClient', 'NoiseRemovalClient', (['api_key', 'base_url'], {}), '(api_key, base_url)\n', (353, 372), False, 'from audoai.noise_removal import NoiseRemovalClient\n'), ((562, 587), 'wave.open', 'wave.open', (['wav_data', '"""wb"""'], {}), "(wav_data, 'wb')\n", (571, 587), False, 'import wave\n'), ((1013, 1046), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'suffix': '""".mp3"""'}), "(suffix='.mp3')\n", (1031, 1046), False, 'from tempfile import NamedTemporaryFile\n'), ((1121, 1146), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1134, 1146), False, 'import pytest\n'), ((1358, 1391), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'suffix': '""".wav"""'}), "(suffix='.wav')\n", (1376, 1391), False, 'from tempfile import NamedTemporaryFile\n'), ((1865, 1900), 'pytest.raises', 'pytest.raises', (['(OSError, TypeError)'], {}), '((OSError, TypeError))\n', (1878, 1900), False, 'import pytest\n'), ((1161, 1194), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'suffix': '""".wav"""'}), "(suffix='.wav')\n", (1179, 1194), False, 'from tempfile import NamedTemporaryFile\n')]
import re from janome.tokenizer import Tokenizer # rules : {boolean function(word):label} # txt: str def rule_base_ner(rules,txt): tokenizer = Tokenizer() tokens = tokenizer.tokenize(txt) history = [] for t in tokens: word = t.surface for rule,label in rules.items(): if rule(word) and word not in history: tag1 = "<"+label+">" tag2 = "</"+label+">" txt = re.sub(word,tag1+word+tag2,txt) break history.append(word) return txt if __name__ == "__main__": rules = { lambda x: x=="男":"People", lambda x: x=="蟋蟀":"Organism", lambda x: x[-1]=="門":"Location", lambda x: x[-2:]=="大路":"Location", lambda x: x=="一" or x=="二" or x=="三":"Number",} txt = """広い門の下には、この男のほかに誰もいない。ただ、所々丹塗の剥はげた、大きな円柱に、蟋蟀が一匹とまっている。 羅生門が、朱雀大路にある以上は、この男のほかにも、雨やみをする市女笠や揉烏帽子が、 もう二三人はありそうなものである。それが、この男のほかには誰もいない""" result = rule_base_ner(rules,txt) print(txt) print(result)
[ "janome.tokenizer.Tokenizer", "re.sub" ]
[((148, 159), 'janome.tokenizer.Tokenizer', 'Tokenizer', ([], {}), '()\n', (157, 159), False, 'from janome.tokenizer import Tokenizer\n'), ((449, 486), 're.sub', 're.sub', (['word', '(tag1 + word + tag2)', 'txt'], {}), '(word, tag1 + word + tag2, txt)\n', (455, 486), False, 'import re\n')]
# Notes: # For fixing multi-press See: https://raspberrypi.stackexchange.com/questions/28955/unwanted-multiple-presses-when-using-gpio-button-press-detection # Supported file types: https://picamera.readthedocs.io/en/release-1.10/api_camera.html#picamera.camera.PiCamera.capture # 'jpeg' - Write a JPEG file # 'png' - Write a PNG file # 'gif' - Write a GIF file # 'bmp' - Write a Windows bitmap file # 'yuv' - Write the raw image data to a file in YUV420 format # 'rgb' - Write the raw image data to a file in 24-bit RGB format # 'rgba' - Write the raw image data to a file in 32-bit RGBA format # 'bgr' - Write the raw image data to a file in 24-bit BGR format # 'bgra' - Write the raw image data to a file in 32-bit BGRA format # 'raw' - Deprecated option for raw captures; the format is taken from the deprecated raw_format attribute # available_exposure_compensations = [-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25] # HQ Camera on-sensor defective pixel correction (DPC) # https://www.raspberrypi.org/forums/viewtopic.php?f=43&t=277768 # 0 - All DPC disabled. # 1 - Enable mapped on-sensor DPC. # 2 - Enable dynamic on-sensor DPC. # 3 - Enable mapped and dynamic on-sensor DPC. # The default is (3). It would be useful to get feedback from users who do astrophotography if disabling DPC actually makes a difference or not. # Note that this does not disable the ISP defective pixel correction that will still be active, so you will likely only see changes in the RAW image. # 8MP pi camera v2.1 # width = 3280 # height = 2464 # 12MP Pi HQ camera # width = 4056 # height = 3040 VERSION = "0.0.35" # Modules import document_handler import camera_handler ################################################################################ ## Config ## ################################################################################ config = { "colour_profile_path": "/home/pi/Colour_Profiles/imx477/Raspberry Pi High Quality Camera Lumariver 2860k-5960k Neutral Look.json", "dcim_path": 'home/pi/DCIM', "dcim_images_path_raw": '/home/pi/DCIM/images/raw', "dcim_original_images_path": '/home/pi/DCIM/images/original', "dcim_hdr_images_path": '/home/pi/DCIM/images/hdr', "dcim_videos_path": '/home/pi/DCIM/videos', "dcim_tmp_path": '/home/pi/DCIM/tmp', "filetype": '.dng', "bpp": 12, "format": 'jpeg', "video_format": 'h264', # mjpeg, h264 TODO: Make into an option "bayer": True, "delay_time": 0, "delay_times": [0, 1, 2, 5, 10], # in seconds "short_delay": False, "short_delay_time": 0.05, "min_fps": 0.005, # mode 3 for HQ cam is between 0.005 and 10 fps "max_fps": 40, # 40, # Possibly equal to screen_fps "screen_fps": 40, # 120 fps at 1012x760 "default_screen_fps": 60, "capture_timeout": 1000, # Must be greater than max exposure in seconds "screen_w": 1280, # 1024 # 1012 # 320 screen res # Needs to be 4:3 "screen_h": 960, # 768 #760 # 240 screen res # Needs to be 4:3 "overlay_w": 320, "overlay_h": 240, "width": 4056, # Image width "height": 3040, # Image height "video_width": 4056, "video_height": 3040, "annotate_text_size": 48, # 6 to 160, inclusive. The default is 32 "exposure_mode": 'auto', "default_exposure_mode": 'auto', "default_zoom": (0.0, 0.0, 1.0, 1.0), "set_zoom": '1x', "max_zoom": (0.4, 0.4, 0.2, 0.2), "max_zoom_2": (0.4499885557335775, 0.4499885557335775, 0.09999237048905166, 0.09999237048905166), "max_zoom_3": (0.5, 0.5, 0.05, 0.05), "available_exposure_modes": [ "auto", # default has to be first in the list "off", "verylong", "fixedfps", "antishake", "night", "nightpreview", "backlight", "spotlight", "sports", "snow", "beach", "fireworks" ], "available_isos": [0, 5, 10, 25, 50, 100, 200, 320, 400, 500, 640, 800, 1600], # 0 is auto / 3200, 6400 "iso": 5, #0, # 800 / should shift to 0 - auto "default_iso": 5, "available_shutter_speeds": [0, 100, 500, 1000, 1500, 2000, 4000, 8000, 3000, 16667, 33333, 66667, 125000, 250000, 500000, 1000000], # 1/10000, 1/2000, 1/1000, ... "available_long_shutter_speeds": [0, 1000000, 2000000, 3000000, 4000000, 5000000, 10000000, 15000000, 20000000, 25000000, 30000000, 35000000, 40000000, 200000000], "take_long_shutter_speed": False, "shutter_speed": 0, "long_shutter_speed": 0, "default_shutter_speed": 0, "available_awb_mode": ['auto', 'off', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon'], "awb_mode": 'auto', "default_awb_mode": 'auto', # "awb_gains": 0.0 - 8.0 (), "dpc": 0, # 0 - 3, default is 3 and 0 is disabled "default_dpc": 0, "raw_convert": True, "available_dpc_options": [0, 1, 2, 3], #https://www.raspberrypi.org/forums/viewtopic.php?f=43&t=277768 "current_menu_items": ["auto", "shutter_speed", "iso", "hdr2", "delay_time", "long_shutter_speed", "sub_menu"], "available_menu_items": ["auto", "shutter_speed", "iso", "hdr2", "delay_time", "long_shutter_speed", "sub_menu"], "available_sub_menu_items": ["sub_menu", "exposure_mode", "awb_mode", "hdr", "video", "resolution", "encoding", "dpc - star eater", "raw_convert", "fom"], "menu_item": "auto", "default_menu_item": "auto", "hdr": False, "preview": True, "fom": False, "default_fom": True, "fom_overlay_x_padding": 50, # in pixels "fom_overlay_y_padding": 50, # in pixels "hdr2": False, "preview_mode": "built-in", # "built-in" "continuous_shot" "default_preview_mode": 'built-in', "video": False, "recording": False, "encoding": False, # TODO "gpio": { "button_1": 27, "button_2": 23, "button_3": 22, "button_4": 17, "bouncetime": 450 } } document_handler.check_for_folders(config) ################################################################################ # Main Loop # ################################################################################ # Begin Camera start-up camera, overlay = camera_handler.start_camera(config) # Runs main camera loop message = input("Press enter to quit\n\n") # Run until someone presses enter print('Stop camera!') camera_handler.stop_camera(camera, overlay, config)
[ "camera_handler.stop_camera", "document_handler.check_for_folders", "camera_handler.start_camera" ]
[((5870, 5912), 'document_handler.check_for_folders', 'document_handler.check_for_folders', (['config'], {}), '(config)\n', (5904, 5912), False, 'import document_handler\n'), ((6207, 6242), 'camera_handler.start_camera', 'camera_handler.start_camera', (['config'], {}), '(config)\n', (6234, 6242), False, 'import camera_handler\n'), ((6371, 6422), 'camera_handler.stop_camera', 'camera_handler.stop_camera', (['camera', 'overlay', 'config'], {}), '(camera, overlay, config)\n', (6397, 6422), False, 'import camera_handler\n')]
import time from revscoring import Datasource, Feature, Model from revscoring.datasources.revision_oriented import revision from revscoring.scoring import ModelInfo from revscoring.scoring.statistics import Classification def process_last_two_in_rev_id(rev_id): last_two = str(rev_id)[-2:] if len(last_two) == 1: return "0" + last_two else: return last_two last_two_in_rev_id = Datasource( "revision.last_two_in_rev_id", process_last_two_in_rev_id, depends_on=[revision.id] ) def process_reversed_last_two_in_rev_id(last_two): return int("".join(reversed(last_two))) reversed_last_two_in_rev_id = Feature( "revision.reversed_last_two_in_rev_id", process_reversed_last_two_in_rev_id, returns=int, depends_on=[last_two_in_rev_id] ) def process_delay(): return 0.0 delay = Feature("delay", process_delay, returns=float) class RevIdScorer(Model): """ Implements a basic, testing scorer that predicts whether a revision ID's reversed last two digits are greater than 50. E.g. 974623 = 32 and 23754929 = 92 """ def __init__(self, version=None): super().__init__([reversed_last_two_in_rev_id, delay], version=version) self.info = ModelInfo() self.info['version'] = version self.info['type'] = "RevIDScorer" self.info['behavior'] = "Returns the last two digits in a rev_id " + \ "as a score." self.info['statistics'] = self.calculate_statistics() def score(self, feature_values): last_two_in_rev_id, delay = feature_values time.sleep(delay) probability = last_two_in_rev_id / 100 if probability > 0.5: prediction = True else: prediction = False return { 'prediction': prediction, 'probability': { True: probability, False: 1 - probability } } def calculate_statistics(self): "Jam some data through to generate statistics" rev_ids = range(0, 100, 1) feature_values = zip(rev_ids, [0] * 100) scores = [self.score(f) for f in feature_values] labels = [s['prediction'] for s in scores] statistics = Classification(labels, threshold_ndigits=1, decision_key='probability') score_labels = list(zip(scores, labels)) statistics.fit(score_labels) return statistics @classmethod def from_config(cls, config, name, section_key='scorer_models'): section = config[section_key][name] return cls(**{k: v for k, v in section.items() if k != "class"})
[ "revscoring.Feature", "revscoring.scoring.ModelInfo", "time.sleep", "revscoring.Datasource", "revscoring.scoring.statistics.Classification" ]
[((411, 510), 'revscoring.Datasource', 'Datasource', (['"""revision.last_two_in_rev_id"""', 'process_last_two_in_rev_id'], {'depends_on': '[revision.id]'}), "('revision.last_two_in_rev_id', process_last_two_in_rev_id,\n depends_on=[revision.id])\n", (421, 510), False, 'from revscoring import Datasource, Feature, Model\n'), ((650, 789), 'revscoring.Feature', 'Feature', (['"""revision.reversed_last_two_in_rev_id"""', 'process_reversed_last_two_in_rev_id'], {'returns': 'int', 'depends_on': '[last_two_in_rev_id]'}), "('revision.reversed_last_two_in_rev_id',\n process_reversed_last_two_in_rev_id, returns=int, depends_on=[\n last_two_in_rev_id])\n", (657, 789), False, 'from revscoring import Datasource, Feature, Model\n'), ((847, 893), 'revscoring.Feature', 'Feature', (['"""delay"""', 'process_delay'], {'returns': 'float'}), "('delay', process_delay, returns=float)\n", (854, 893), False, 'from revscoring import Datasource, Feature, Model\n'), ((1243, 1254), 'revscoring.scoring.ModelInfo', 'ModelInfo', ([], {}), '()\n', (1252, 1254), False, 'from revscoring.scoring import ModelInfo\n'), ((1620, 1637), 'time.sleep', 'time.sleep', (['delay'], {}), '(delay)\n', (1630, 1637), False, 'import time\n'), ((2279, 2350), 'revscoring.scoring.statistics.Classification', 'Classification', (['labels'], {'threshold_ndigits': '(1)', 'decision_key': '"""probability"""'}), "(labels, threshold_ndigits=1, decision_key='probability')\n", (2293, 2350), False, 'from revscoring.scoring.statistics import Classification\n')]
# -*- coding: utf-8 -*- # 创建信号 import datetime import dictdiffer from django.dispatch import Signal from django.apps import apps as django_apps import json def format_value(value): """格式化数据""" if isinstance(value, datetime.datetime): return value.strftime('%Y-%m-%d %H:%M:%S') return value def show_change(olddict, newdict): """比较两个字典 返回如 [{'field': 'data.sex', 'old': '\xe7\x94\xb7', 'new': '\xe5\xa5\xb3'}, {'field': 'template', 'old': '', 'new': '11'}] """ changelist = [] listchangedict = {} from dictdiffer.utils import dot_lookup for diff in list(dictdiffer.diff(olddict, newdict)): changedict = {} diff = list(diff) # print("Rawdifff", diff) # print(diff,"difffffffffffffff") if diff[0] == "change": # 这里重新格式化一下 changedict["field"] = diff[1] changedict["old"] = format_value(diff[2][0]) changedict["new"] = format_value(diff[2][1]) changelist.append(changedict) try: if isinstance(diff[1], list): changename = ".".join(diff[1][0:-1]) listchangedict[changename] = {"old": dot_lookup(olddict, changename), "new": dot_lookup(newdict, changename)} except Exception as e: print(e) if diff[0] == "remove" or diff[0] == "add": changename = diff[1] listchangedict[changename] = {"old": dot_lookup(olddict, changename), "new": dot_lookup(newdict, changename)} for key, value in listchangedict.items(): tmpdict = {"field": key, "old": value["old"], "new": value["new"]} if isinstance(value["new"], list) and isinstance(value["old"], list): if value["new"] and (isinstance(value["new"][0], dict) or isinstance(value["new"][0], list)): # 排除掉字典类的 continue if value["old"] and (isinstance(value["old"][0], dict) or isinstance(value["old"][0], list)): # 排除掉字典类的 continue changelist.append(tmpdict) # print("changelist", changelist) return changelist api_created = Signal() api_updated = Signal(providing_args=["old_data", "new_data", ]) def save_history(instance, user, action="--", field_name="--"): """保存到数据库""" HISmodel = django_apps.get_model(app_label='track_actions', model_name="History", require_ready=False) if HISmodel: try: history = HISmodel( table_name=str(instance._meta.db_table), user=user, instance_id=instance.id, action=action, field_name=field_name ) history.save() except ValueError as e: print(e) except Exception as e: print(e) def created(sender, **kwargs): print("create") print(sender, kwargs) def formate_bool(change): # 格式化日志布尔类型为中文显示 bool_list = {True: "是", False: "否"} new_data = bool_list.get(change.get("new"), change.get("new")) old_data = bool_list.get(change.get("old"), change.get("old")) change.update(**{"new": new_data, "old": old_data}) return change def formate_chioce(option, change): # 格式choice类型函数 new_data = option.get(change.get("new"), change.get("new")) old_data = option.get(change.get("old"), change.get("old")) change.update(**{"new": new_data, "old": old_data}) return change def formate_mutichioce(option, change): # 格式化多选类型函数 new_data = [] old_data = [] for ii in option: if ii['id'] in change.get("new", []): new_data.append(ii['name']) if ii['id'] in change.get("old", []): old_data.append(ii['name']) change.update(**{"new": ",".join(new_data), "old": ",".join(old_data)}) return change def loop_zh_name(ser, field_name, change={}): """循环ser获得中文名 选项名 键的类型""" from django.db.models import ManyToManyField, NullBooleanField, BooleanField try: if "." in field_name: # 这里只支持两层嵌套 不断循环 all_list = field_name.split('.') model1_str = all_list[0] field_name1 = all_list[1::] # 这里fieldname 应该是从头到 尾部 field_name1 = len(field_name) > 1 and ".".join(field_name1) or field_name1[0] ser1 = ser.__dict__["_fields"].get(model1_str) # 这里获取的不对 # 根据fieldname 判断还有没下一层 没有的话直接提取 有的话进入下一个循环 if "." in field_name1: res = [False, field_name1, ser1, field_name1] else: zh_name = ser1.Meta.model._meta.get_field(field_name1).verbose_name zh_name = u"%s-%s" % (ser1.Meta.model._meta.verbose_name, zh_name) # res = [True, zh_name, ser1, field_name1] # 根据不同的类型 格式化一下返回体 field = ser1.Meta.model._meta.get_field(field_name1) if hasattr(field, "choices") and field.choices != []: # 格式化单选 option = dict(field.choices) change = formate_chioce(option, change) elif isinstance(field, (NullBooleanField, BooleanField)): change = formate_bool(change) elif isinstance(field, (ManyToManyField,)): # 格式化多选 BaseMultiChoices = django_apps.get_model(app_label='chestpain', model_name="BaseMultiChoices", require_ready=False) option = BaseMultiChoices.objects.filter(choices_type=field.name).values("id", "name") change = formate_mutichioce(option, change) change.update(field=zh_name) res = [True, zh_name, change] return res else: zh_name = ser.Meta.model._meta.get_field(field_name).verbose_name return [True, zh_name, change] except Exception as e: print("error2", e) # 出错这个内容不保存 return [True, field_name, {}] def get_zh_name(ser, field_name, change={}): while True: res = loop_zh_name(ser, field_name, change) is_end = res[0] if is_end: return res[2] break else: ser = res[2] field_name = res[3] def map_nullfalse(str): if str in ["null", "", "Null", "NULL", "None", "none", None]: return "未填写" return str def updated(sender, **kwargs): old_data = kwargs.get("old_data") new_data = kwargs.get("new_data") instance = kwargs.get("instance") current_request = kwargs.get("current_request") change = show_change(old_data, new_data) # sender 是序列化器 尝试通过serializer获取fieldname 没有的话就用英文名 # print("changelist", change) wronglist = [] for index, item in enumerate(change): field_name = item['field'] # 这里有嵌套结构 嵌套接口单独分析 new_item = get_zh_name(sender, field_name, item) item.update(**new_item) if not new_item: wronglist.append(index) for num, i in enumerate(wronglist): change.pop(i - num) # 获取中文名 # print("change-----",change) # 获取单选项 # 获取多选项 # change = reform_change(change) try: # 如果建了历史记录的表 就进行记录的操作 if change: for i in change: # print("field", i["field"], isinstance(i["field"], list), type(i["field"])) if "last_modified" in i["field"] or u"最近更新时间" in i["field"] or isinstance(i["field"], list) or u"创建时间" in i[ "field"] or (not i['old'] and not i["new"]) or i['old'] == i['new'] or "id" in i["field"] or "ID" in \ i["field"]: continue changestr = u"由%s更新为%s" % (str(map_nullfalse(i["old"])), str(map_nullfalse(i["new"]))) save_history(instance, user=current_request.user, action=changestr, field_name=i["field"]) except Exception as e: print(e) api_created.connect(created) # 注册信号 api_updated.connect(updated) # 注册信号
[ "dictdiffer.diff", "dictdiffer.utils.dot_lookup", "django.dispatch.Signal", "django.apps.apps.get_model" ]
[((2227, 2235), 'django.dispatch.Signal', 'Signal', ([], {}), '()\n', (2233, 2235), False, 'from django.dispatch import Signal\n'), ((2251, 2298), 'django.dispatch.Signal', 'Signal', ([], {'providing_args': "['old_data', 'new_data']"}), "(providing_args=['old_data', 'new_data'])\n", (2257, 2298), False, 'from django.dispatch import Signal\n'), ((2399, 2494), 'django.apps.apps.get_model', 'django_apps.get_model', ([], {'app_label': '"""track_actions"""', 'model_name': '"""History"""', 'require_ready': '(False)'}), "(app_label='track_actions', model_name='History',\n require_ready=False)\n", (2420, 2494), True, 'from django.apps import apps as django_apps\n'), ((600, 633), 'dictdiffer.diff', 'dictdiffer.diff', (['olddict', 'newdict'], {}), '(olddict, newdict)\n', (615, 633), False, 'import dictdiffer\n'), ((1512, 1543), 'dictdiffer.utils.dot_lookup', 'dot_lookup', (['olddict', 'changename'], {}), '(olddict, changename)\n', (1522, 1543), False, 'from dictdiffer.utils import dot_lookup\n'), ((1594, 1625), 'dictdiffer.utils.dot_lookup', 'dot_lookup', (['newdict', 'changename'], {}), '(newdict, changename)\n', (1604, 1625), False, 'from dictdiffer.utils import dot_lookup\n'), ((1194, 1225), 'dictdiffer.utils.dot_lookup', 'dot_lookup', (['olddict', 'changename'], {}), '(olddict, changename)\n', (1204, 1225), False, 'from dictdiffer.utils import dot_lookup\n'), ((1284, 1315), 'dictdiffer.utils.dot_lookup', 'dot_lookup', (['newdict', 'changename'], {}), '(newdict, changename)\n', (1294, 1315), False, 'from dictdiffer.utils import dot_lookup\n'), ((5356, 5456), 'django.apps.apps.get_model', 'django_apps.get_model', ([], {'app_label': '"""chestpain"""', 'model_name': '"""BaseMultiChoices"""', 'require_ready': '(False)'}), "(app_label='chestpain', model_name='BaseMultiChoices',\n require_ready=False)\n", (5377, 5456), True, 'from django.apps import apps as django_apps\n')]
# 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 glob import os import docutils.core import testtools class TestTitles(testtools.TestCase): def _get_title(self, section_tree): section = { 'subtitles': [], } for node in section_tree: if node.tagname == 'title': section['name'] = node.rawsource elif node.tagname == 'section': subsection = self._get_title(node) section['subtitles'].append(subsection['name']) return section def _get_titles(self, spec): titles = {} for node in spec: if node.tagname == 'section': # Note subsection subtitles are thrown away section = self._get_title(node) titles[section['name']] = section['subtitles'] return titles def _check_titles(self, filename, expect, actual): missing_sections = [x for x in expect.keys() if x not in actual.keys()] extra_sections = [x for x in actual.keys() if x not in expect.keys()] msgs = [] if len(missing_sections) > 0: msgs.append("Missing sections: %s" % missing_sections) if len(extra_sections) > 0: msgs.append("Extra sections: %s" % extra_sections) for section in expect.keys(): missing_subsections = [x for x in expect[section] if x not in actual[section]] # extra subsections are allowed if len(missing_subsections) > 0: msgs.append("Section '%s' is missing subsections: %s" % (section, missing_subsections)) if len(msgs) > 0: self.fail("While checking '%s':\n %s" % (filename, "\n ".join(msgs))) def test_template(self): filenames = glob.glob("guidelines/*") for filename in filenames: if filename.endswith('~'): continue if os.path.isdir(filename): continue self.assertTrue( filename.endswith(".rst") or filename.endswith(".json"), "guideline file must use 'rst' or 'json'" "extension: {filename}".format(filename=filename)) with open(filename) as f: data = f.read() docutils.core.publish_doctree(data)
[ "os.path.isdir", "glob.glob" ]
[((2372, 2397), 'glob.glob', 'glob.glob', (['"""guidelines/*"""'], {}), "('guidelines/*')\n", (2381, 2397), False, 'import glob\n'), ((2512, 2535), 'os.path.isdir', 'os.path.isdir', (['filename'], {}), '(filename)\n', (2525, 2535), False, 'import os\n')]
from django.contrib import admin from . import models @admin.register(models.Lamp) class LampAdmin(admin.ModelAdmin): list_display = ('name', 'is_on', 'brightness') ordering = ('name',) @admin.register(models.WorkingPeriod) class WorkingPeriodAdmin(admin.ModelAdmin): list_display = ('lamp', 'brightness', 'start', 'end') ordering = ('-start',)
[ "django.contrib.admin.register" ]
[((58, 85), 'django.contrib.admin.register', 'admin.register', (['models.Lamp'], {}), '(models.Lamp)\n', (72, 85), False, 'from django.contrib import admin\n'), ((201, 237), 'django.contrib.admin.register', 'admin.register', (['models.WorkingPeriod'], {}), '(models.WorkingPeriod)\n', (215, 237), False, 'from django.contrib import admin\n')]
import json from typing import ( Any, Dict, List, Optional, ) import unittest from unittest import ( mock, ) import urllib.parse from more_itertools import ( one, ) import requests from app_test_case import ( LocalAppTestCase, ) from azul import ( cached_property, config, ) from azul.indexer import ( BundleFQID, ) from azul.indexer.document import ( null_str, ) from azul.indexer.index_service import ( IndexService, ) from azul.logging import ( configure_test_logging, ) from azul.service.hca_response_v5 import ( FileSearchResponse, KeywordSearchResponse, ) from azul.types import ( JSON, ) from service import ( WebServiceTestCase, ) from service.test_pagination import ( parse_url_qs, ) # noinspection PyPep8Naming def setUpModule(): configure_test_logging() class TestResponse(WebServiceTestCase): maxDiff = None @classmethod def bundles(cls) -> List[BundleFQID]: return super().bundles() + [ BundleFQID('fa5be5eb-2d64-49f5-8ed8-bd627ac9bc7a', '2019-02-14T192438.034764Z'), BundleFQID('d0e17014-9a58-4763-9e66-59894efbdaa8', '2018-10-03T144137.044509Z'), BundleFQID('e0ae8cfa-2b51-4419-9cde-34df44c6458a', '2018-12-05T230917.591044Z'), BundleFQID('411cd8d5-5990-43cd-84cc-6c7796b8a76d', '2018-10-18T204655.866661Z'), BundleFQID('412cd8d5-5990-43cd-84cc-6c7796b8a76d', '2018-10-18T204655.866661Z'), BundleFQID('ffac201f-4b1c-4455-bd58-19c1a9e863b4', '2019-10-09T170735.528600Z'), ] @classmethod def setUpClass(cls): super().setUpClass() cls._setup_indices() @classmethod def tearDownClass(cls): cls._teardown_indices() super().tearDownClass() def get_hits(self, entity_type: str, entity_id: str): """ Fetches hits from ES instance searching for a particular entity ID """ body = { "query": { "term": { "entity_id.keyword": entity_id } } } # Tests are assumed to only ever run with the azul dev index results = self.es_client.search(index=config.es_index_name(catalog=self.catalog, entity_type=entity_type, aggregate=True), body=body) return self._index_service.translate_fields(catalog=self.catalog, doc=[results['hits']['hits'][0]['_source']], forward=False) @cached_property def _index_service(self): return IndexService() def test_key_search_files_response(self): """ This method tests the KeywordSearchResponse object for the files entity type. It will make sure the functionality works as appropriate by asserting the apiResponse attribute is the same as expected. """ # Still need a way to test the response. keyword_response = KeywordSearchResponse( # the entity_id is hardcoded, but corresponds to the bundle above hits=self.get_hits('files', '0c5ac7c0-817e-40d4-b1b1-34c3d5cfecdb'), entity_type='files', catalog=self.catalog ).return_response().to_json() expected_response = { "hits": [ { "bundles": [ { "bundleUuid": "aaa96233-bf27-44c7-82df-b4dc15ad4d9d", "bundleVersion": "2018-11-02T113344.698028Z" } ], "cellLines": [ ], "cellSuspensions": [ { "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "selectedCellType": [None], "totalCells": 1 } ], "donorOrganisms": [ { "biologicalSex": ["female"], "disease": ['normal'], "developmentStage": [None], "genusSpecies": ["Australopithecus"], "id": ["DID_scRSq06"], "donorCount": 1, "organismAge": ["38"], "organismAgeUnit": ["year"], "organismAgeRange": [{"gte": 1198368000.0, "lte": 1198368000.0}] } ], "entryId": "0c5ac7c0-817e-40d4-b1b1-34c3d5cfecdb", "files": [ { "content_description": [None], "format": "fastq.gz", "name": "SRR3562915_1.fastq.gz", "sha256": "77337cb51b2e584b5ae1b99db6c163b988cbc5b894dda2f5d22424978c3bfc7a", "size": 195142097, "uuid": "7b07f99e-4a8a-4ad0-bd4f-db0d7a00c7bb", "version": "2018-11-02T113344.698028Z" } ], "organoids": [ ], "projects": [ { "laboratory": ["<NAME>"], "projectShortname": ["Single of human pancreas"], "projectTitle": ["Single cell transcriptome patterns."] } ], "protocols": [ { "libraryConstructionApproach": ["Smart-seq2"], "nucleicAcidSource": ["single cell"], }, { "instrumentManufacturerModel": ["Illumina NextSeq 500"], "pairedEnd": [True], } ], "samples": [ { "sampleEntityType": ["specimens"], "effectiveOrgan": ['pancreas'], "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism" ] } ], "specimens": [ { "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism" ] } ] } ] } self.assertElasticsearchResultsEqual(keyword_response, expected_response) def test_key_search_samples_response(self): """ KeywordSearchResponse for the specimens endpoint should return file type summaries instead of files """ keyword_response = KeywordSearchResponse( # the entity_id is hardcoded, but corresponds to the bundle above hits=self.get_hits('samples', 'a21dc760-a500-4236-bcff-da34a0e873d2'), entity_type='samples', catalog=self.catalog ).return_response().to_json() expected_response = { "hits": [ { "cellLines": [ ], "cellSuspensions": [ { "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "selectedCellType": [None], "totalCells": 1 } ], "donorOrganisms": [ { "biologicalSex": ["female"], "disease": ['normal'], "developmentStage": [None], "genusSpecies": ["Australopithecus"], "id": ["DID_scRSq06"], "donorCount": 1, "organismAge": ["38"], "organismAgeUnit": ["year"], "organismAgeRange": [{"gte": 1198368000.0, "lte": 1198368000.0}] } ], "entryId": "a21dc760-a500-4236-bcff-da34a0e873d2", "fileTypeSummaries": [ { "count": 2, "fileType": "fastq.gz", "totalSize": 385472253 } ], "organoids": [ ], "projects": [ { "laboratory": ["<NAME>"], "projectShortname": ["Single of human pancreas"], "projectTitle": ["Single cell transcriptome patterns."] } ], "protocols": [ { "instrumentManufacturerModel": ["Illumina NextSeq 500"], "pairedEnd": [True], }, { "libraryConstructionApproach": ["Smart-seq2"], "nucleicAcidSource": ["single cell"], } ], "samples": [ { "sampleEntityType": "specimens", "effectiveOrgan": "pancreas", "id": "DID_scRSq06_pancreas", "disease": ["normal"], "organ": "pancreas", "organPart": ["islet of Langerhans"], "preservationMethod": None, "source": "specimen_from_organism", } ], "specimens": [ { "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism", ] } ] } ] } self.assertElasticsearchResultsEqual(keyword_response, expected_response) path = "/index/files" query = "?size=5&search_after=cbb998ce-ddaf-34fa-e163-d14b399c6b34&search_after_uid=meta%2332" @property def paginations(self): return [ { "count": 2, "order": "desc", "pages": 1, "size": 5, "sort": "entryId", "total": 2 }, { "count": 2, "order": "desc", "pages": 1, "next": self.base_url + self.path + self.query, "size": 5, "sort": "entryId", "total": 2 } ] def test_file_search_response(self): """ n=0: Test the FileSearchResponse object, making sure the functionality works as appropriate by asserting the apiResponse attribute is the same as expected. n=1: Tests the FileSearchResponse object, using 'next' pagination. """ hits = [ { "bundles": [ { "bundleUuid": "aaa96233-bf27-44c7-82df-b4dc15ad4d9d", "bundleVersion": "2018-11-02T113344.698028Z" } ], "cellLines": [ ], "cellSuspensions": [ { "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "selectedCellType": [None], "totalCells": 1 } ], "donorOrganisms": [ { "biologicalSex": ["female"], "disease": ['normal'], "developmentStage": [None], "genusSpecies": ["Australopithecus"], "id": ["DID_scRSq06"], "donorCount": 1, "organismAge": ["38"], "organismAgeUnit": ["year"], "organismAgeRange": [{"gte": 1198368000.0, "lte": 1198368000.0}] } ], "entryId": "0c5ac7c0-817e-40d4-b1b1-34c3d5cfecdb", "files": [ { "content_description": [None], "format": "fastq.gz", "name": "SRR3562915_1.fastq.gz", "sha256": "77337cb51b2e584b5ae1b99db6c163b988cbc5b894dda2f5d22424978c3bfc7a", "size": 195142097, "uuid": "7b07f99e-4a8a-4ad0-bd4f-db0d7a00c7bb", "version": "2018-11-02T113344.698028Z" } ], "organoids": [ ], "projects": [ { "laboratory": ["<NAME>"], "projectShortname": ["Single of human pancreas"], "projectTitle": ["Single cell transcriptome patterns."] } ], "protocols": [ { "libraryConstructionApproach": ["Smart-seq2"], "nucleicAcidSource": ["single cell"], }, { "instrumentManufacturerModel": ["Illumina NextSeq 500"], "pairedEnd": [True], } ], "samples": [ { "sampleEntityType": ["specimens"], "effectiveOrgan": ['pancreas'], "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism", ] } ], "specimens": [ { "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism", ] } ] } ] responses = [ { "hits": hits, "pagination": { "count": 2, "order": "desc", "pages": 1, "next": None, "previous": None, "size": 5, "sort": "entryId", "total": 2 }, "termFacets": {} }, { "hits": hits, "pagination": { "count": 2, "order": "desc", "pages": 1, "next": self.base_url + self.path + self.query, "previous": None, "size": 5, "sort": "entryId", "total": 2 }, "termFacets": {} } ] for n in 0, 1: with self.subTest(n=n): filesearch_response = FileSearchResponse( hits=self.get_hits('files', '0c5ac7c0-817e-40d4-b1b1-34c3d5cfecdb'), pagination=self.paginations[n], facets={}, entity_type='files', catalog=self.catalog ).return_response().to_json() self.assertElasticsearchResultsEqual(filesearch_response, responses[n]) def test_file_search_response_file_summaries(self): """ Test non-'files' entity type passed to FileSearchResponse will give file summaries """ filesearch_response = FileSearchResponse( hits=self.get_hits('samples', 'a21dc760-a500-4236-bcff-da34a0e873d2'), pagination=self.paginations[0], facets={}, entity_type='samples', catalog=self.catalog ).return_response().to_json() for hit in filesearch_response['hits']: self.assertTrue('fileTypeSummaries' in hit) self.assertFalse('files' in hit) facets_populated = { "organ": { "doc_count": 21, "untagged": { "doc_count": 0 }, "myTerms": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "silver", "doc_count": 11 }, { "key": "teal", "doc_count": 10 } ] } }, "disease": { "doc_count": 21, "untagged": { "doc_count": 12 }, "myTerms": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "silver", "doc_count": 9 } ] } } } def test_file_search_response_add_facets(self): """ Test adding facets to FileSearchResponse with missing values in one facet and no missing values in the other null term should not appear if there are no missing values """ facets = FileSearchResponse.add_facets(self.facets_populated) expected_output = { "organ": { "terms": [ { "term": "silver", "count": 11 }, { "term": "teal", "count": 10 } ], "total": 21, "type": "terms" }, "disease": { "terms": [ { "term": "silver", "count": 9 }, { "term": None, "count": 12 } ], "total": 21, "type": "terms" } } self.assertElasticsearchResultsEqual(facets, expected_output) def _params(self, filters: Optional[JSON] = None, **params: Any) -> Dict[str, Any]: return { **({} if filters is None else {'filters': json.dumps(filters)}), 'catalog': self.catalog, **params } def test_sorting_details(self): for entity_type in 'files', 'samples', 'projects', 'bundles': with self.subTest(entity_type=entity_type): base_url = self.base_url url = base_url + "/index/" + entity_type response = requests.get(url, params=self._params()) response.raise_for_status() response_json = response.json() # Verify default sort field is set correctly self.assertEqual(response_json['pagination']["sort"], self.app_module.sort_defaults[entity_type][0]) # Verify all fields in the response that are lists of primitives are sorted for hit in response_json['hits']: self._verify_sorted_lists(hit) def test_transform_request_with_file_url(self): base_url = self.base_url for entity_type in ('files', 'bundles'): with self.subTest(entity_type=entity_type): url = base_url + f"/index/{entity_type}" response = requests.get(url, params=self._params()) response.raise_for_status() response_json = response.json() for hit in response_json['hits']: if entity_type == 'files': self.assertEqual(len(hit['files']), 1) else: self.assertGreater(len(hit['files']), 0) for file in hit['files']: self.assertIn('url', file.keys()) actual_url = urllib.parse.urlparse(file['url']) actual_query_vars = {k: one(v) for k, v in urllib.parse.parse_qs(actual_url.query).items()} expected_base_url = urllib.parse.urlparse(base_url) self.assertEqual(expected_base_url.netloc, actual_url.netloc) self.assertEqual(expected_base_url.scheme, actual_url.scheme) self.assertIsNotNone(actual_url.path) self.assertEqual(self.catalog, actual_query_vars['catalog']) self.assertIsNotNone(actual_query_vars['version']) def test_projects_key_search_response(self): """ Test building response for projects Response should include project detail fields that do not appear for other entity type responses """ keyword_response = KeywordSearchResponse( hits=self.get_hits('projects', 'e8642221-4c2c-4fd7-b926-a68bce363c88'), entity_type='projects', catalog=self.catalog ).return_response().to_json() expected_response = { "hits": [ { "cellLines": [ ], "cellSuspensions": [ { "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "selectedCellType": [None], "totalCells": 1 } ], "donorOrganisms": [ { "biologicalSex": ["female"], "disease": ['normal'], "developmentStage": [None], "genusSpecies": ["Australopithecus"], "id": ["DID_scRSq06"], "donorCount": 1, "organismAge": ["38"], "organismAgeUnit": ["year"], "organismAgeRange": [{"gte": 1198368000.0, "lte": 1198368000.0}] } ], "entryId": "e8642221-4c2c-4fd7-b926-a68bce363c88", "fileTypeSummaries": [ { "count": 2, "fileType": "fastq.gz", "totalSize": 385472253 } ], "organoids": [ ], "projects": [ { "arrayExpressAccessions": [None], "geoSeriesAccessions": [None], "insdcProjectAccessions": [None], "insdcStudyAccessions": [None], "contributors": [ { "contactName": "<NAME>", "correspondingContributor": None, "email": "<EMAIL>", "institution": "University", "laboratory": None, "projectRole": None }, { "contactName": "Matthew,,Green", "correspondingContributor": False, "email": "<EMAIL>", "institution": "Farmers Trucks", "laboratory": "<NAME>", "projectRole": "Human Cell Atlas wrangler" }, { "contactName": "Laura,,Huerta", "correspondingContributor": False, "email": "<EMAIL>", "institution": "Farmers Trucks", "laboratory": "<NAME>", "projectRole": "external curator" } ], "laboratory": ["<NAME>"], "projectDescription": "As organisms age, cells accumulate genetic and epigenetic changes " "that eventually lead to impaired organ function or catastrophic " "failure such as cancer. Here we describe a single-cell " "transcriptome analysis of 2544 human pancreas cells from donors, " "spanning six decades of life. We find that islet cells from older " "donors have increased levels of disorder as measured both by noise " "in the transcriptome and by the number of cells which display " "inappropriate hormone expression, revealing a transcriptional " "instability associated with aging. By analyzing the spectrum of " "somatic mutations in single cells from previously-healthy donors, " "we find a specific age-dependent mutational signature " "characterized by C to A and C to G transversions, indicators of " "oxidative stress, which is absent in single cells from human brain " "tissue or in a tumor cell line. Cells carrying a high load of such " "mutations also express higher levels of stress and senescence " "markers, including FOS, JUN, and the cytoplasmic superoxide " "dismutase SOD1, markers previously linked to pancreatic diseases " "with substantial age-dependent risk, such as type 2 diabetes " "mellitus and adenocarcinoma. Thus, our single-cell approach " "unveils gene expression changes and somatic mutations acquired in " "aging human tissue, and identifies molecular pathways induced by " "these genetic changes that could influence human disease. Also, " "our results demonstrate the feasibility of using single-cell " "RNA-seq data from primary cells to derive meaningful insights into " "the genetic processes that operate on aging human tissue and to " "determine which molecular mechanisms are coordinated with these " "processes. Examination of single cells from primary human pancreas " "tissue", "projectShortname": "Single of human pancreas", "projectTitle": "Single cell transcriptome patterns.", "publications": [ { "publicationTitle": "Single-Cell Analysis of Human Pancreas Reveals " "Transcriptional Signatures of Aging and Somatic Mutation " "Patterns.", "publicationUrl": "https://www.ncbi.nlm.nih.gov/pubmed/28965763" } ], "supplementaryLinks": [ "https://www.ebi.ac.uk/gxa/sc/experiments/E-GEOD-81547/Results" ], "matrices": {}, "contributorMatrices": {} } ], "protocols": [ { "libraryConstructionApproach": ["Smart-seq2"], "nucleicAcidSource": ["single cell"], }, { "instrumentManufacturerModel": ["Illumina NextSeq 500"], "pairedEnd": [True], } ], "samples": [ { "sampleEntityType": ["specimens"], "effectiveOrgan": ["pancreas"], "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism" ] } ], "specimens": [ { "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism" ] } ] } ] } self.assertElasticsearchResultsEqual(keyword_response, expected_response) def test_projects_file_search_response(self): """ Test building response for projects Response should include project detail fields that do not appear for other entity type responses """ keyword_response = FileSearchResponse( hits=self.get_hits('projects', 'e8642221-4c2c-4fd7-b926-a68bce363c88'), pagination=self.paginations[0], facets=self.facets_populated, entity_type='projects', catalog=self.catalog ).return_response().to_json() expected_response = { "hits": [ { "cellLines": [ ], "cellSuspensions": [ { "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "selectedCellType": [None], "totalCells": 1 } ], "donorOrganisms": [ { "biologicalSex": ["female"], "disease": ['normal'], "developmentStage": [None], "genusSpecies": ["Australopithecus"], "id": ["DID_scRSq06"], "donorCount": 1, "organismAge": ["38"], "organismAgeUnit": ["year"], "organismAgeRange": [{"gte": 1198368000.0, "lte": 1198368000.0}] } ], "entryId": "e8642221-4c2c-4fd7-b926-a68bce363c88", "fileTypeSummaries": [ { "count": 2, "fileType": "fastq.gz", "totalSize": 385472253 } ], "organoids": [ ], "projects": [ { "arrayExpressAccessions": [None], "geoSeriesAccessions": [None], "insdcProjectAccessions": [None], "insdcStudyAccessions": [None], "contributors": [ { "contactName": "Matthew,,Green", "correspondingContributor": False, "email": "<EMAIL>", "institution": "Farmers Trucks", "laboratory": "John Dear", "projectRole": "Human Cell Atlas wrangler" }, { "contactName": "<NAME>", "correspondingContributor": None, "email": "<EMAIL>", "institution": "University", "laboratory": None, "projectRole": None }, { "contactName": "Laura,,Huerta", "correspondingContributor": False, "email": "<EMAIL>", "institution": "Farmers Trucks", "laboratory": "John Dear", "projectRole": "external curator" } ], "laboratory": ["John Dear"], "projectDescription": "As organisms age, cells accumulate genetic and epigenetic changes " "that eventually lead to impaired organ function or catastrophic " "failure such as cancer. Here we describe a single-cell " "transcriptome analysis of 2544 human pancreas cells from donors, " "spanning six decades of life. We find that islet cells from older " "donors have increased levels of disorder as measured both by noise " "in the transcriptome and by the number of cells which display " "inappropriate hormone expression, revealing a transcriptional " "instability associated with aging. By analyzing the spectrum of " "somatic mutations in single cells from previously-healthy donors, " "we find a specific age-dependent mutational signature " "characterized by C to A and C to G transversions, indicators of " "oxidative stress, which is absent in single cells from human brain " "tissue or in a tumor cell line. Cells carrying a high load of such " "mutations also express higher levels of stress and senescence " "markers, including FOS, JUN, and the cytoplasmic superoxide " "dismutase SOD1, markers previously linked to pancreatic diseases " "with substantial age-dependent risk, such as type 2 diabetes " "mellitus and adenocarcinoma. Thus, our single-cell approach " "unveils gene expression changes and somatic mutations acquired in " "aging human tissue, and identifies molecular pathways induced by " "these genetic changes that could influence human disease. Also, " "our results demonstrate the feasibility of using single-cell " "RNA-seq data from primary cells to derive meaningful insights into " "the genetic processes that operate on aging human tissue and to " "determine which molecular mechanisms are coordinated with these " "processes. Examination of single cells from primary human pancreas " "tissue", "projectShortname": "Single of human pancreas", "projectTitle": "Single cell transcriptome patterns.", "publications": [ { "publicationTitle": "Single-Cell Analysis of Human Pancreas Reveals " "Transcriptional Signatures of Aging and Somatic Mutation " "Patterns.", "publicationUrl": "https://www.ncbi.nlm.nih.gov/pubmed/28965763" } ], "supplementaryLinks": [ 'https://www.ebi.ac.uk/gxa/sc/experiments/E-GEOD-81547/Results' ], "matrices": {}, "contributorMatrices": {} } ], "protocols": [ { "libraryConstructionApproach": ["Smart-seq2"], "nucleicAcidSource": ["single cell"], }, { "instrumentManufacturerModel": ["Illumina NextSeq 500"], "pairedEnd": [True], } ], "samples": [ { "sampleEntityType": ["specimens"], "effectiveOrgan": ["pancreas"], "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism" ] } ], "specimens": [ { "disease": ["normal"], "id": ["DID_scRSq06_pancreas"], "organ": ["pancreas"], "organPart": ["islet of Langerhans"], "preservationMethod": [None], "source": [ "specimen_from_organism" ] } ] } ], "pagination": { "count": 2, "order": "desc", "pages": 1, "next": None, "previous": None, "size": 5, "sort": "entryId", "total": 2 }, "termFacets": { "disease": { "terms": [ { "count": 9, "term": "silver" }, { "count": 12, "term": None } ], "total": 21, "type": "terms" }, "organ": { "terms": [ { "count": 11, "term": "silver" }, { "count": 10, "term": "teal" } ], "total": 21, "type": "terms" } } } self.assertElasticsearchResultsEqual(keyword_response, expected_response) def test_project_accessions_response(self): """ This method tests the KeywordSearchResponse object for the projects entity type, specifically making sure the accessions fields are present in the response. """ keyword_response = KeywordSearchResponse( hits=self.get_hits('projects', '627cb0ba-b8a1-405a-b58f-0add82c3d635'), entity_type='projects', catalog=self.catalog ).return_response().to_json() expected_response = { "hits": [ { "cellLines": [ ], "cellSuspensions": [ { "organ": ["brain"], "organPart": ["amygdala"], "selectedCellType": [None], "totalCells": 10000 } ], "donorOrganisms": [ { "biologicalSex": ["male"], "disease": ['H syndrome'], "developmentStage": ["human adult stage"], "genusSpecies": ["Homo sapiens"], "id": ["donor_ID_1"], "donorCount": 1, "organismAge": ["20"], "organismAgeUnit": ["year"], "organismAgeRange": [{"gte": 630720000.0, "lte": 630720000.0}] } ], "entryId": "627cb0ba-b8a1-405a-b58f-0add82c3d635", "fileTypeSummaries": [ { "count": 1, "fileType": "bai", "totalSize": 2395616 }, { "count": 1, "fileType": "bam", "totalSize": 55840108 }, { "count": 1, "fileType": "csv", "totalSize": 665 }, { "count": 1, "fileType": "unknown", "totalSize": 2645006 }, { "count": 2, "fileType": "mtx", "totalSize": 6561141 }, { "count": 3, "fileType": "fastq.gz", "totalSize": 44668092 }, { "count": 3, "fileType": "h5", "totalSize": 5573714 }, { "count": 4, "fileType": "tsv", "totalSize": 15872628 } ], "organoids": [ ], "projects": [ { "contributors": [ { "contactName": "John,D,Doe. ", "correspondingContributor": False, "email": "<EMAIL>", "institution": "EMBL-EBI", "laboratory": "Department of Biology", "projectRole": "principal investigator" } ], "arrayExpressAccessions": ["E-AAAA-00"], "geoSeriesAccessions": ["GSE00000"], "insdcProjectAccessions": ["SRP000000"], "insdcStudyAccessions": ["PRJNA000000"], "laboratory": ["Department of Biology"], "projectDescription": "Contains a small file set from the dataset: 4k PBMCs from a " "Healthy Donor, a Single Cell Gene Expression Dataset by Cell " "Ranger 2.1.0. Peripheral blood mononuclear cells (PBMCs) were " "taken from a healthy donor (same donor as pbmc8k). PBMCs are " "primary cells with relatively small amounts of RNA (~1pg " "RNA/cell). Data/Analysis can be found here " "https://support.10xgenomics.com/single-cell-gene-expression/datasets" "/2.1.0/pbmc4k and all data is licensed under the creative commons " "attribution license (https://creativecommons.org/licenses/by/4.0/). " "This test also contains extensive metadata for browser testing. " "Metadata is fabricated.", "projectShortname": "staging/10x/2019-02-14T18:29:38Z", "projectTitle": "10x 1 Run Integration Test", "publications": [ { "publicationTitle": "A title of a publication goes here.", "publicationUrl": "https://europepmc.org" } ], "supplementaryLinks": [None], "matrices": {}, "contributorMatrices": {} } ], "protocols": [ { "workflow": ['cellranger_v1.0.2'] }, { "libraryConstructionApproach": ["10X v2 sequencing"], "nucleicAcidSource": [None], }, { "instrumentManufacturerModel": ["Illumina HiSeq 2500"], "pairedEnd": [False], } ], "samples": [ { "sampleEntityType": ["specimens"], "effectiveOrgan": ["brain"], "disease": ["H syndrome"], "id": ["specimen_ID_1"], "organ": ["brain"], "organPart": ["amygdala"], "preservationMethod": [None], "source": [ "specimen_from_organism" ] } ], "specimens": [ { "disease": ["H syndrome"], "id": ["specimen_ID_1"], "organ": ["brain"], "organPart": ["amygdala"], "preservationMethod": [None], "source": [ "specimen_from_organism" ] } ] } ] } self.assertElasticsearchResultsEqual(keyword_response, expected_response) def test_cell_suspension_response(self): """ Test KeywordSearchResponse contains the correct selectedCellType value """ keyword_response = KeywordSearchResponse( hits=self.get_hits('projects', '250aef61-a15b-4d97-b8b4-54bb997c1d7d'), entity_type='projects', catalog=self.catalog ).return_response().to_json() cell_suspension = one(keyword_response['hits'][0]['cellSuspensions']) self.assertEqual(["Plasma cells"], cell_suspension['selectedCellType']) def test_cell_line_response(self): """ Test KeywordSearchResponse contains the correct cell_line and sample field values """ keyword_response = KeywordSearchResponse( hits=self.get_hits('projects', 'c765e3f9-7cfc-4501-8832-79e5f7abd321'), entity_type='projects', catalog=self.catalog ).return_response().to_json() expected_cell_lines = { 'id': ['cell_line_Day7_hiPSC-CM_BioRep2', 'cell_line_GM18517'], 'cellLineType': ['primary', 'stem cell-derived'], 'modelOrgan': ['blood (parent_cell_line)', 'blood (child_cell_line)'], } cell_lines = one(one(keyword_response['hits'])['cellLines']) self.assertElasticsearchResultsEqual(cell_lines, expected_cell_lines) expected_samples = { 'sampleEntityType': ['cellLines'], 'effectiveOrgan': ['blood (child_cell_line)'], 'id': ['cell_line_Day7_hiPSC-CM_BioRep2'], 'cellLineType': ['stem cell-derived'], 'modelOrgan': ['blood (child_cell_line)'], } samples = one(one(keyword_response['hits'])['samples']) self.assertElasticsearchResultsEqual(samples, expected_samples) def test_file_response(self): """ Test KeywordSearchResponse contains the correct file field values """ keyword_response = KeywordSearchResponse( hits=self.get_hits('files', '4015da8b-18d8-4f3c-b2b0-54f0b77ae80a'), entity_type='files', catalog=self.catalog ).return_response().to_json() expected_file = { 'content_description': ['RNA sequence'], 'format': 'fastq.gz', 'name': 'Cortex2.CCJ15ANXX.SM2_052318p4_D8.unmapped.1.fastq.gz', 'sha256': '709fede4736213f0f71ae4d76719fd51fa402a9112582a4c52983973cb7d7e47', 'size': 22819025, 'uuid': 'a8b8479d-cfa9-4f74-909f-49552439e698', 'version': '2019-10-09T172251.560099Z' } file = one(one(keyword_response['hits'])['files']) self.assertElasticsearchResultsEqual(file, expected_file) def test_filter_with_none(self): """ Test response when using a filter with a None value """ test_data_values = [["year"], [None], ["year", None]] for test_data in test_data_values: with self.subTest(test_data=test_data): url = self.base_url + "/index/samples" params = self._params(size=10, filters={'organismAgeUnit': {'is': test_data}}) response = requests.get(url, params=params) response.raise_for_status() response_json = response.json() organism_age_units = { oau for hit in response_json['hits'] for donor in hit['donorOrganisms'] for oau in donor['organismAgeUnit'] } # Assert that the organismAgeUnits values found in the response only match what was filtered for self.assertEqual(organism_age_units, set(test_data)) def test_filter_by_projectId(self): """ Test response when using a projectId filter """ test_data_sets = [ { 'id': '627cb0ba-b8a1-405a-b58f-0add82c3d635', 'title': '10x 1 Run Integration Test' }, { 'id': '250aef61-a15b-4d97-b8b4-54bb997c1d7d', 'title': 'Bone marrow plasma cells from hip replacement surgeries' } ] for test_data in test_data_sets: for entity_type in 'files', 'samples', 'projects', 'bundles': with self.subTest(entity_type=entity_type): url = self.base_url + "/index/" + entity_type params = self._params(size=2, filters={'projectId': {'is': [test_data['id']]}}) response = requests.get(url, params=params) response.raise_for_status() response_json = response.json() for hit in response_json['hits']: for project in hit['projects']: if entity_type == 'projects': self.assertEqual(test_data['title'], project['projectTitle']) else: self.assertIn(test_data['title'], project['projectTitle']) for term in response_json['termFacets']['project']['terms']: self.assertEqual(term['projectId'], [test_data['id']]) def test_translated_facets(self): """ Test that response facets values are correctly translated back to the correct data types and that the translated None value is not present. """ url = self.base_url + "/index/samples" params = self._params(size=10, filters={}) response = requests.get(url, params=params) response.raise_for_status() response_json = response.json() facets = response_json['termFacets'] paired_end_terms = {term['term'] for term in facets['pairedEnd']['terms']} self.assertEqual(paired_end_terms, {'true', 'false'}) preservation_method_terms = {term['term'] for term in facets['preservationMethod']['terms']} self.assertEqual(preservation_method_terms, {None}) model_organ_part_terms = {term['term'] for term in facets['modelOrganPart']['terms']} self.assertEqual(model_organ_part_terms, {None}) for facet in facets.values(): for term in facet['terms']: self.assertNotEqual(term['term'], null_str.to_index(None)) def test_sample(self): """ Test that sample(s) in the response contain values matching values in the source cellLine/organoid/specimen """ for entity_type in 'projects', 'samples', 'files', 'bundles': with self.subTest(entity_type=entity_type): url = self.base_url + "/index/" + entity_type response = requests.get(url, params=self._params()) response.raise_for_status() response_json = response.json() if entity_type == 'samples': for hit in response_json['hits']: for sample in hit['samples']: sample_entity_type = sample['sampleEntityType'] for key, val in sample.items(): if key not in ['sampleEntityType', 'effectiveOrgan']: if isinstance(val, list): for one_val in val: self.assertIn(one_val, hit[sample_entity_type][0][key]) else: self.assertIn(val, hit[sample_entity_type][0][key]) def test_bundles_outer_entity(self): entity_type = 'bundles' url = self.base_url + "/index/" + entity_type response = requests.get(url, params=self._params()) response.raise_for_status() response = response.json() indexed_uuids = set(self.bundles()) self.assertEqual(len(self.bundles()), len(indexed_uuids)) hits_uuids = { (one(hit['bundles'])['bundleUuid'], one(hit['bundles'])['bundleVersion']) for hit in response['hits'] } self.assertEqual(len(response['hits']), len(hits_uuids)) self.assertSetEqual(indexed_uuids, hits_uuids) def test_ranged_values(self): test_hits = [ [ { "biologicalSex": [ "male", "female" ], "developmentStage": [None], "disease": ['normal'], "genusSpecies": [ "Homo sapiens" ], "id": [ "HPSI0314i-hoik", "HPSI0214i-wibj", "HPSI0314i-sojd", "HPSI0214i-kucg" ], "donorCount": 4, "organismAge": [ "45-49", "65-69" ], "organismAgeRange": [ { "gte": 2049840000.0, "lte": 2175984000.0 }, { "gte": 1419120000.0, "lte": 1545264000.0 } ], "organismAgeUnit": [ "year" ] } ], [ { "biologicalSex": [ "male", "female" ], "developmentStage": [None], "disease": ['normal'], "genusSpecies": [ "Homo sapiens" ], "id": [ "HPSI0314i-hoik", "HPSI0214i-wibj", "HPSI0314i-sojd", "HPSI0214i-kucg" ], "donorCount": 4, "organismAge": [ "40-44", "55-59" ], "organismAgeRange": [ { "gte": 1734480000.0, "lte": 1860624000.0 }, { "gte": 1261440000.0, "lte": 1387584000.0 } ], "organismAgeUnit": [ "year" ] } ] ] url = self.base_url + '/index/projects' for relation, range_value, expected_hits in [('contains', (1419130000, 1545263000), test_hits[:1]), ('within', (1261430000, 1545265000), test_hits), ('intersects', (1860623000, 1900000000), test_hits[1:]), ('contains', (1860624000, 2049641000), []), ('within', (1734490000, 1860623000), []), ('intersects', (1860624100, 2049641000), [])]: with self.subTest(relation=relation, value=range_value): params = self._params(filters={'organismAgeRange': {relation: [range_value]}}, order='desc', sort='entryId') response = requests.get(url, params=params) actual_value = [hit['donorOrganisms'] for hit in response.json()['hits']] self.assertElasticsearchResultsEqual(expected_hits, actual_value) def test_ordering(self): sort_fields = [ ('cellCount', lambda hit: hit['cellSuspensions'][0]['totalCells']), ('donorCount', lambda hit: hit['donorOrganisms'][0]['donorCount']) ] url = self.base_url + '/index/projects' for sort_field, accessor in sort_fields: responses = { order: requests.get(url, params=self._params(filters={}, order=order, sort=sort_field)) for order in ['asc', 'desc'] } hit_sort_values = {} for order, response in responses.items(): response.raise_for_status() hit_sort_values[order] = [accessor(hit) for hit in response.json()['hits']] self.assertEqual(hit_sort_values['asc'], sorted(hit_sort_values['asc'])) self.assertEqual(hit_sort_values['desc'], sorted(hit_sort_values['desc'], reverse=True)) def test_missing_field_sorting(self): """ Test that sorting by a field that doesn't exist in all hits produces results with the hits missing the field placed at the end of a ascending sort and the beginning of a descending sort. """ ascending_values = [ ['induced pluripotent'], ['induced pluripotent'], ['primary', 'stem cell-derived'], None, # The last 4 hits don't have any 'cellLines' inner entities None, # so for purposes of this test we use None to represent None, # that there is a hit however it has no 'cellLineType'. None ] def extract_cell_line_types(response_json): # For each hit yield the 'cellLineType' value or None if not present for hit in response_json['hits']: if hit['cellLines']: yield one(hit['cellLines'])['cellLineType'] else: yield None for ascending in (True, False): with self.subTest(ascending=ascending): url = self.base_url + '/index/projects' params = self._params(size=15, filters={}, sort='cellLineType', order='asc' if ascending else 'desc') response = requests.get(url, params=params) response.raise_for_status() response_json = response.json() actual_values = list(extract_cell_line_types(response_json)) expected = ascending_values if ascending else list(reversed(ascending_values)) self.assertEqual(actual_values, expected) def test_multivalued_field_sorting(self): """ Test that sorting by a multi-valued field responds with hits that are correctly sorted based on the first value from each multi-valued field, and that each multi-valued field itself is sorted low to high regardless of the search sort """ for order, reverse in (('asc', False), ('desc', True)): with self.subTest(order=order, reverse=reverse): url = self.base_url + "/index/projects" params = self._params(size=15, filters={}, sort='laboratory', order=order) response = requests.get(url, params=params) response.raise_for_status() response_json = response.json() laboratories = [] for hit in response_json['hits']: laboratory = one(hit['projects'])['laboratory'] self.assertEqual(laboratory, sorted(laboratory)) laboratories.append(laboratory[0]) self.assertGreater(len(laboratories), 1) self.assertEqual(laboratories, sorted(laboratories, reverse=reverse)) def test_disease_facet(self): """ Verify the values of the different types of disease facets """ url = self.base_url + "/index/projects" test_data = { # disease specified in donor, specimen, and sample (the specimen) '627cb0ba-b8a1-405a-b58f-0add82c3d635': { 'sampleDisease': [{'term': 'H syndrome', 'count': 1}], 'donorDisease': [{'term': 'H syndrome', 'count': 1}], 'specimenDisease': [{'term': 'H syndrome', 'count': 1}], }, # disease specified in donor only '250aef61-a15b-4d97-b8b4-54bb997c1d7d': { 'sampleDisease': [{'term': None, 'count': 1}], 'donorDisease': [{'term': 'isolated hip osteoarthritis', 'count': 1}], 'specimenDisease': [{'term': None, 'count': 1}], }, # disease specified in donor and specimen, not in sample (the cell line) 'c765e3f9-7cfc-4501-8832-79e5f7abd321': { 'sampleDisease': [{'term': None, 'count': 1}], 'donorDisease': [{'term': 'normal', 'count': 1}], 'specimenDisease': [{'term': 'normal', 'count': 1}] } } self._assert_term_facets(test_data, url) def _assert_term_facets(self, project_term_facets: JSON, url: str) -> None: for project_id, term_facets in project_term_facets.items(): with self.subTest(project_id=project_id): params = self._params(filters={'projectId': {'is': [project_id]}}) response = requests.get(url, params=params) response.raise_for_status() response_json = response.json() actual_term_facets = response_json['termFacets'] for facet, terms in term_facets.items(): self.assertEqual(actual_term_facets[facet]['terms'], terms) def test_organism_age_facet(self): """ Verify the terms of the organism age facet """ url = self.base_url + "/index/projects" test_data = { # This project has one donor organism '627cb0ba-b8a1-405a-b58f-0add82c3d635': { 'organismAge': [ { 'term': { 'value': '20', 'unit': 'year' }, 'count': 1 } ], 'organismAgeUnit': [ { 'term': 'year', 'count': 1 } ], 'organismAgeValue': [ { 'term': '20', 'count': 1 } ], }, # This project has multiple donor organisms '2c4724a4-7252-409e-b008-ff5c127c7e89': { 'organismAge': [ { 'term': { 'value': '40-44', 'unit': 'year' }, 'count': 1 }, { 'term': { 'value': '55-59', 'unit': 'year' }, 'count': 1 } ], 'organismAgeUnit': [ { 'term': 'year', 'count': 1 } ], 'organismAgeValue': [ { 'term': '40-44', 'count': 1 }, { 'term': '55-59', 'count': 1 } ] }, # This project has one donor but donor has no age 'c765e3f9-7cfc-4501-8832-79e5f7abd321': { 'organismAge': [ { 'term': None, 'count': 1 } ], 'organismAgeUnit': [ { 'term': None, 'count': 1 } ], 'organismAgeValue': [ { 'term': None, 'count': 1 } ], } } self._assert_term_facets(test_data, url) def test_organism_age_facet_search(self): """ Verify filtering by organism age """ url = self.base_url + "/index/projects" test_cases = [ ( '627cb0ba-b8a1-405a-b58f-0add82c3d635', { 'is': [ { 'value': '20', 'unit': 'year' } ] } ), ( 'c765e3f9-7cfc-4501-8832-79e5f7abd321', { 'is': [ None ] } ), ( None, { 'is': [ {} ] } ), ( None, { 'is': [ { 'value': None, 'unit': 'weeks' } ] } ) ] for project_id, filters in test_cases: with self.subTest(filters=filters): response = requests.get(url, params=dict(catalog=self.catalog, filters=json.dumps({'organismAge': filters}))) if project_id is None: self.assertTrue(response.status_code, 400) else: response.raise_for_status() response = response.json() hit = one(response['hits']) self.assertEqual(hit['entryId'], project_id) donor_organism = one(hit['donorOrganisms']) age = one(one(filters.values())) self.assertEqual(donor_organism['organismAge'], [None if age is None else age['value']]) self.assertEqual(donor_organism['organismAgeUnit'], [None if age is None else age['unit']]) def test_pagination_search_after_search_before(self): """ Test search_after and search_before values when using sorting on a field containing None values """ url = self.base_url + "/index/samples" params = self._params(size=3, filters={}, sort='workflow', order='asc') response = requests.get(url + '?' + urllib.parse.urlencode(params)) response.raise_for_status() response_json = response.json() first_page_next = parse_url_qs(response_json['pagination']['next']) expected_entry_ids = [ '58c60e15-e07c-4875-ac34-f026d6912f1c', '195b2621-ec05-4618-9063-c56048de97d1', '2d8282f0-6cbb-4d5a-822c-4b01718b4d0d', ] self.assertEqual(expected_entry_ids, [h['entryId'] for h in response_json['hits']]) # NOTE: The sort field `workflow` is an `analysis_protocol` field and # does not exist in all bundles. This is why the `search_after` field # has the value `null` (JSON representation of `None`) because the last # row in this page of results does not have an `analysis_protocol` or # `workflow` field. If the last row did have a `workflow` field with a # value `None`, `search_after` would be a translated `None` (`"~null"`) self.assertIsNotNone(response_json['pagination']['next']) self.assertIsNone(response_json['pagination']['previous']) self.assertEqual(first_page_next['search_after'], 'null') self.assertEqual(first_page_next['search_after_uid'], 'doc#2d8282f0-6cbb-4d5a-822c-4b01718b4d0d') response = requests.get(response_json['pagination']['next']) response.raise_for_status() response_json = response.json() second_page_next = parse_url_qs(response_json['pagination']['next']) second_page_previous = parse_url_qs(response_json['pagination']['previous']) expected_entry_ids = [ '308eea51-d14b-4036-8cd1-cfd81d7532c3', '73f10dad-afc5-4d1d-a71c-4a8b6fff9172', '79682426-b813-4f69-8c9c-2764ffac5dc1', ] self.assertEqual(expected_entry_ids, [h['entryId'] for h in response_json['hits']]) self.assertEqual(second_page_next['search_after'], 'null') self.assertEqual(second_page_next['search_after_uid'], 'doc#79682426-b813-4f69-8c9c-2764ffac5dc1') self.assertEqual(second_page_previous['search_before'], 'null') self.assertEqual(second_page_previous['search_before_uid'], 'doc#308eea51-d14b-4036-8cd1-cfd81d7532c3') class TestSortAndFilterByCellCount(WebServiceTestCase): maxDiff = None @classmethod def bundles(cls) -> List[BundleFQID]: return super().bundles() + [ # 2 bundles from 1 project with 7738 total cells across 2 cell suspensions BundleFQID('97f0cc83-f0ac-417a-8a29-221c77debde8', '2019-10-14T195415.397406Z'), BundleFQID('8c90d4fe-9a5d-4e3d-ada2-0414b666b880', '2019-10-14T195415.397546Z'), # other bundles BundleFQID('fa5be5eb-2d64-49f5-8ed8-bd627ac9bc7a', '2019-02-14T192438.034764Z'), BundleFQID('411cd8d5-5990-43cd-84cc-6c7796b8a76d', '2018-10-18T204655.866661Z'), BundleFQID('ffac201f-4b1c-4455-bd58-19c1a9e863b4', '2019-10-09T170735.528600Z'), ] @classmethod def setUpClass(cls): super().setUpClass() cls._setup_indices() @classmethod def tearDownClass(cls): cls._teardown_indices() super().tearDownClass() def _count_total_cells(self, response_json): """ Return the number of cell suspension inner entities and total cell count per hit. """ return [ ( len(hit['cellSuspensions']), sum([cs['totalCells'] for cs in hit['cellSuspensions']]) ) for hit in response_json['hits'] ] def test_sorting_by_cell_count(self): """ Verify sorting by 'cellCount' sorts the documents based on the total number of cells in each document, using the sum of total cells when a document contains more than one cell suspension inner entity. """ ascending_results = [ (1, 1), (1, 349), (1, 6210), (2, 7738), (1, 10000) ] for ascending in (True, False): with self.subTest(ascending=ascending): url = self.base_url + '/index/projects' params = { 'catalog': self.catalog, 'sort': 'cellCount', 'order': 'asc' if ascending else 'desc' } response = requests.get(url, params=params) response.raise_for_status() response_json = response.json() actual_results = self._count_total_cells(response_json) expected = ascending_results if ascending else list(reversed(ascending_results)) self.assertEqual(actual_results, expected) def test_filter_by_cell_count(self): """ Verify filtering by 'cellCount' filters the documents based on the total number of cells in each document, using the sum of total cells when a document contains more than one cell suspension inner entity. """ url = self.base_url + "/index/projects" params = { 'catalog': self.catalog, 'filters': json.dumps({ 'cellCount': { 'within': [ [ 6000, 9000 ] ] } }) } response = requests.get(url, params=params) response.raise_for_status() response_json = response.json() actual_results = self._count_total_cells(response_json) expected_results = [ (1, 6210), (2, 7738) ] self.assertEqual(actual_results, expected_results) class TestProjectMatrices(WebServiceTestCase): maxDiff = None @classmethod def bundles(cls) -> List[BundleFQID]: return super().bundles() + [ # An analysis bundle that has two files with a 'dcp2' submitter_id BundleFQID('f0731ab4-6b80-4eed-97c9-4984de81a47c', '2019-07-23T062120.663434Z'), # A contributor-generated matrix bundle for the same project BundleFQID('1ec111a0-7481-571f-b35a-5a0e8fca890a', '2020-10-07T11:11:17.095956Z') ] @classmethod def setUpClass(cls): super().setUpClass() cls._setup_indices() @classmethod def tearDownClass(cls): cls._teardown_indices() super().tearDownClass() @property def params(self): return { 'filters': json.dumps({'projectId': {'is': ['091cf39b-01bc-42e5-9437-f419a66c8a45']}}), 'catalog': self.catalog, 'size': 20 } def test_contributor_matrix_files(self): """ Verify the files endpoint returns all the files from both the analysis and CGM bundles. """ url = self.base_url + '/index/files' response = requests.get(url, params=self.params) response.raise_for_status() response_json = response.json() expected_files = [ # files from the analysis bundle '13eab62e-0038-4997-aeab-aa3192cc090e.zarr/.zattrs', 'BoneMarrow_CD34_2_IGO_07861_2_S2_L001_R1_001.fastq.gz', 'BoneMarrow_CD34_2_IGO_07861_2_S2_L001_R2_001.fastq.gz', 'empty_drops_result.csv', 'merged-cell-metrics.csv.gz', 'merged-gene-metrics.csv.gz', 'merged.bam', 'sparse_counts.npz', 'sparse_counts_col_index.npy', 'sparse_counts_row_index.npy', "matrix.csv.zip", # files from the contributor-generated matrices bundle '4d6f6c96-2a83-43d8-8fe1-0f53bffd4674.BaderLiverLandscape-10x_cell_type_2020-03-10.csv', '4d6f6c96-2a83-43d8-8fe1-0f53bffd4674.HumanLiver.zip', ] self.assertEqual(len(expected_files), len(response_json['hits'])) actual_files = [one(hit['files'])['name'] for hit in response_json['hits']] self.assertEqual(sorted(expected_files), sorted(actual_files)) def test_matrices_tree(self): """ Verify the projects endpoint includes a valid 'matrices' and 'contributorMatrices' tree inside the projects inner-entity. """ url = self.base_url + '/index/projects' response = requests.get(url, params=self.params) response.raise_for_status() response_json = response.json() hit = one(response_json['hits']) self.assertEqual('091cf39b-01bc-42e5-9437-f419a66c8a45', hit['entryId']) matrices = { 'genusSpecies': { 'Homo sapiens': { 'developmentStage': { 'human adult stage': { 'libraryConstructionApproach': { '10X v2 sequencing': { 'organ': { 'blood': [ { 'name': 'matrix.csv.zip', 'url': self.base_url + '/fetch/dss/files/' '535d7a99-9e4f-406e-a478-32afdf78a522' '?version=2019-07-23T064742.317855Z' '&catalog=test' } ], 'hematopoietic system': [ { 'name': 'sparse_counts.npz', 'url': self.base_url + '/fetch/dss/files/' '787084e4-f61e-4a15-b6b9-56c87fb31410' '?version=2019-07-23T064557.057500Z' '&catalog=test' }, { 'name': 'merged-cell-metrics.csv.gz', 'url': self.base_url + '/fetch/dss/files/' '9689a1ab-02c3-48a1-ac8c-c1e097445ed8' '?version=2019-07-23T064556.193221Z' '&catalog=test' } ] } } } } } } } } self.assertEqual(matrices, one(hit['projects'])['matrices']) contributor_matrices = { 'organ': { 'liver': { 'genusSpecies': { 'Homo sapiens': { 'developmentStage': { 'human adult stage': { 'library': { '10X v2 sequencing': [ { 'name': '4d6f6c96-2a83-43d8-8fe1-0f53bffd4674.' 'BaderLiverLandscape-10x_cell_type_2020-03-10.csv', 'url': self.base_url + '/fetch/dss/files/' '0d8607e9-0540-5144-bbe6-674d233a900e' '?version=2020-10-20T15%3A53%3A50.322559Z' '&catalog=test' } ], 'Smart-seq2': [ { 'name': '4d6f6c96-2a83-43d8-8fe1-0f53bffd4674.' 'BaderLiverLandscape-10x_cell_type_2020-03-10.csv', 'url': self.base_url + '/fetch/dss/files/' '0d8607e9-0540-5144-bbe6-674d233a900e' '?version=2020-10-20T15%3A53%3A50.322559Z' '&catalog=test' } ] } } } }, 'Mus musculus': { 'developmentStage': { 'adult': { 'library': { '10X v2 sequencing': [ { 'name': '4d6f6c96-2a83-43d8-8fe1-0f53bffd4674.HumanLiver.zip', 'url': self.base_url + '/fetch/dss/files/' '7c3ad02f-2a7a-5229-bebd-0e729a6ac6e5' '?version=2020-10-20T15%3A53%3A50.322559Z' '&catalog=test' } ] } } } } } } } } self.assertEqual(contributor_matrices, one(hit['projects'])['contributorMatrices']) class TestResponseSummary(WebServiceTestCase): maxDiff = None @classmethod def bundles(cls) -> List[BundleFQID]: return super().bundles() + [ BundleFQID('dcccb551-4766-4210-966c-f9ee25d19190', '2018-10-18T204655.866661Z'), BundleFQID('94f2ba52-30c8-4de0-a78e-f95a3f8deb9c', '2019-04-03T103426.471000Z') # an imaging bundle ] @classmethod def setUpClass(cls): super().setUpClass() cls._setup_indices() @classmethod def tearDownClass(cls): cls._teardown_indices() super().tearDownClass() def test_summary_response(self): """ Verify the /index/summary response with two sequencing bundles and one imaging bundle that has no cell suspension. - bundle=aaa96233…, fileCount=2, donorCount=1, totalCellCount=1.0, organType=pancreas, labCount=1 - bundle=dcccb551…, fileCount=19, donorCount=4, totalCellCount=6210.0, organType=Brain, labCount=1 - bundle=94f2ba52…, fileCount=227, donorCount=1, totalCellCount=0, organType=brain, labCount=(None counts as 1) """ url = self.base_url + "/index/summary" response = requests.get(url, params=dict(catalog=self.catalog)) response.raise_for_status() summary_object = response.json() self.assertEqual(summary_object['fileCount'], 2 + 19 + 227) self.assertEqual(summary_object['labCount'], 1 + 1 + 1) self.assertEqual(summary_object['donorCount'], 1 + 4 + 1) self.assertEqual(summary_object['totalCellCount'], 1.0 + 6210.0 + 0) file_counts_expected = { 'tiff': 221, 'json': 6, 'fastq.gz': 5, 'tsv': 4, 'h5': 3, 'pdf': 3, 'mtx': 2, 'bai': 1, 'bam': 1, 'csv': 1, 'unknown': 1 } file_counts_actual = {summary['fileType']: summary['count'] for summary in summary_object['fileTypeSummaries']} self.assertEqual(file_counts_actual, file_counts_expected) self.assertEqual(set(summary_object['organTypes']), {'Brain', 'brain', 'pancreas'}) self.assertEqual(summary_object['cellCountSummaries'], [ # 'brain' from the imaging bundle is not represented in cellCountSummaries as these values are tallied # from the cell suspensions and the imaging bundle does not have any cell suspensions {'organType': ['Brain'], 'countOfDocsWithOrganType': 1, 'totalCellCountByOrgan': 6210.0}, {'organType': ['pancreas'], 'countOfDocsWithOrganType': 1, 'totalCellCountByOrgan': 1.0}, ]) def test_summary_filter_none(self): for use_filter, labCount in [(False, 3), (True, 2)]: with self.subTest(use_filter=use_filter, labCount=labCount): url = self.base_url + '/index/summary' params = dict(catalog=self.catalog) if use_filter: params['filters'] = json.dumps({"organPart": {"is": [None]}}) response = requests.get(url, params=params) response.raise_for_status() summary_object = response.json() self.assertEqual(summary_object['labCount'], labCount) class TestUnpopulatedIndexResponse(WebServiceTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.index_service.create_indices(cls.catalog) @classmethod def tearDownClass(cls): cls.index_service.delete_indices(cls.catalog) super().tearDownClass() def test_empty_response(self): url = self.base_url + "/index/projects" response = requests.get(url) response.raise_for_status() response = response.json() self.assertEqual([], response['hits']) self.assertEqual({None}, set(response['pagination'].values())) self.assertEqual({}, response['termFacets']) class TestPortalIntegrationResponse(LocalAppTestCase): @classmethod def lambda_name(cls) -> str: return "service" maxDiff = None # Mocked DB content for the tests _portal_integrations_db = [ { "portal_id": "9852dece-443d-42e8-869c-17b9a86d447e", "integrations": [ { "integration_id": "b87b7f30-2e60-4ca5-9a6f-00ebfcd35f35", "integration_type": "get_manifest", "entity_type": "file", "manifest_type": "full", }, { "integration_id": "977854a0-2eea-4fec-9459-d4807fe79f0c", "integration_type": "get", "entity_type": "project", "entity_ids": ["c4077b3c-5c98-4d26-a614-246d12c2e5d7"] } ] }, { "portal_id": "f58bdc5e-98cd-4df4-80a4-7372dc035e87", "integrations": [ { "integration_id": "e8b3ca4f-bcf5-42eb-b58c-de6d7e0fe138", "integration_type": "get", "entity_type": "project", "entity_ids": ["c4077b3c-5c98-4d26-a614-246d12c2e5d7"] }, { "integration_id": "dbfe9394-a326-4574-9632-fbadb51a7b1a", "integration_type": "get", "entity_type": "project", "entity_ids": ["90bd6933-40c0-48d4-8d76-778c103bf545"] }, { "integration_id": "f13ddf2d-d913-492b-9ea8-2de4b1881c26", "integration_type": "get", "entity_type": "project", "entity_ids": ["cddab57b-6868-4be4-806f-395ed9dd635a"] }, { "integration_id": "224b1d42-b939-4d10-8a8f-2b2ac304b813", "integration_type": "get", "entity_type": "project", # NO entity_ids field } ] } ] def _mock_portal_crud(self, operation): operation(self._portal_integrations_db) def _get_integrations(self, params: dict) -> dict: url = self.base_url + '/integrations' response = requests.get(url, params=params) response.raise_for_status() return response.json() @classmethod def _extract_integration_ids(cls, response_json): return [ integration['integration_id'] for portal in response_json for integration in portal['integrations'] ] @mock.patch('azul.portal_service.PortalService._crud') def test_integrations(self, portal_crud): """ Verify requests specifying `integration_type` and `entity_type` only return integrations matching those types """ test_cases = [ ('get_manifest', 'file', ['b87b7f30-2e60-4ca5-9a6f-00ebfcd35f35']), ('get', 'bundle', []), ( 'get', 'project', [ '977854a0-2eea-4fec-9459-d4807fe79f0c', 'e8b3ca4f-bcf5-42eb-b58c-de6d7e0fe138', 'dbfe9394-a326-4574-9632-fbadb51a7b1a', 'f13ddf2d-d913-492b-9ea8-2de4b1881c26', '224b1d42-b939-4d10-8a8f-2b2ac304b813' ] ) ] portal_crud.side_effect = self._mock_portal_crud with mock.patch.object(type(config), 'dss_deployment_stage', 'prod'): for integration_type, entity_type, expected_integration_ids in test_cases: params = dict(integration_type=integration_type, entity_type=entity_type) with self.subTest(**params): response_json = self._get_integrations(params) found_integration_ids = self._extract_integration_ids(response_json) self.assertEqual(len(expected_integration_ids), len(found_integration_ids)) self.assertEqual(set(expected_integration_ids), set(found_integration_ids)) self.assertTrue(all(isinstance(integration.get('entity_ids', []), list) for portal in response_json for integration in portal['integrations'])) @mock.patch('azul.portal_service.PortalService._crud') def test_integrations_by_entity_ids(self, portal_crud): """ Verify requests specifying `entity_ids` only return integrations matching those entity_ids """ # 224b1d42-b939-4d10-8a8f-2b2ac304b813 must appear in every test since it lacks the entity_ids field test_cases = [ # One project entity id specified by one integration ( 'cddab57b-6868-4be4-806f-395ed9dd635a', [ 'f13ddf2d-d913-492b-9ea8-2de4b1881c26', '224b1d42-b939-4d10-8a8f-2b2ac304b813' ] ), # Two project entity ids specified by two different integrations ( 'cddab57b-6868-4be4-806f-395ed9dd635a, 90bd6933-40c0-48d4-8d76-778c103bf545', [ 'f13ddf2d-d913-492b-9ea8-2de4b1881c26', 'dbfe9394-a326-4574-9632-fbadb51a7b1a', '224b1d42-b939-4d10-8a8f-2b2ac304b813' ] ), # One project entity id specified by two different integrations ( 'c4077b3c-5c98-4d26-a614-246d12c2e5d7', [ '977854a0-2eea-4fec-9459-d4807fe79f0c', 'e8b3ca4f-bcf5-42eb-b58c-de6d7e0fe138', '224b1d42-b939-4d10-8a8f-2b2ac304b813' ] ), # Blank entity id, to match integrations lacking the entity_id field ( '', [ '224b1d42-b939-4d10-8a8f-2b2ac304b813' ] ), # No entity id, accepting all integrations ( None, [ 'f13ddf2d-d913-492b-9ea8-2de4b1881c26', 'dbfe9394-a326-4574-9632-fbadb51a7b1a', '977854a0-2eea-4fec-9459-d4807fe79f0c', 'e8b3ca4f-bcf5-42eb-b58c-de6d7e0fe138', '224b1d42-b939-4d10-8a8f-2b2ac304b813' ] ) ] portal_crud.side_effect = self._mock_portal_crud with mock.patch.object(type(config), 'dss_deployment_stage', 'prod'): for entity_ids, integration_ids in test_cases: params = dict(integration_type='get', entity_type='project') if entity_ids is not None: params['entity_ids'] = entity_ids with self.subTest(**params): response_json = self._get_integrations(params) found_integration_ids = self._extract_integration_ids(response_json) self.assertEqual(set(integration_ids), set(found_integration_ids)) if __name__ == '__main__': unittest.main()
[ "unittest.main", "azul.service.hca_response_v5.FileSearchResponse.add_facets", "more_itertools.one", "service.test_pagination.parse_url_qs", "json.dumps", "azul.indexer.BundleFQID", "unittest.mock.patch", "azul.config.es_index_name", "azul.logging.configure_test_logging", "requests.get", "azul.indexer.document.null_str.to_index", "azul.indexer.index_service.IndexService" ]
[((820, 844), 'azul.logging.configure_test_logging', 'configure_test_logging', ([], {}), '()\n', (842, 844), False, 'from azul.logging import configure_test_logging\n'), ((95908, 95961), 'unittest.mock.patch', 'mock.patch', (['"""azul.portal_service.PortalService._crud"""'], {}), "('azul.portal_service.PortalService._crud')\n", (95918, 95961), False, 'from unittest import mock\n'), ((97666, 97719), 'unittest.mock.patch', 'mock.patch', (['"""azul.portal_service.PortalService._crud"""'], {}), "('azul.portal_service.PortalService._crud')\n", (97676, 97719), False, 'from unittest import mock\n'), ((100497, 100512), 'unittest.main', 'unittest.main', ([], {}), '()\n', (100510, 100512), False, 'import unittest\n'), ((2789, 2803), 'azul.indexer.index_service.IndexService', 'IndexService', ([], {}), '()\n', (2801, 2803), False, 'from azul.indexer.index_service import IndexService\n'), ((19527, 19579), 'azul.service.hca_response_v5.FileSearchResponse.add_facets', 'FileSearchResponse.add_facets', (['self.facets_populated'], {}), '(self.facets_populated)\n', (19556, 19579), False, 'from azul.service.hca_response_v5 import FileSearchResponse, KeywordSearchResponse\n'), ((52046, 52097), 'more_itertools.one', 'one', (["keyword_response['hits'][0]['cellSuspensions']"], {}), "(keyword_response['hits'][0]['cellSuspensions'])\n", (52049, 52097), False, 'from more_itertools import one\n'), ((57297, 57329), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (57309, 57329), False, 'import requests\n'), ((75076, 75125), 'service.test_pagination.parse_url_qs', 'parse_url_qs', (["response_json['pagination']['next']"], {}), "(response_json['pagination']['next'])\n", (75088, 75125), False, 'from service.test_pagination import parse_url_qs\n'), ((76215, 76264), 'requests.get', 'requests.get', (["response_json['pagination']['next']"], {}), "(response_json['pagination']['next'])\n", (76227, 76264), False, 'import requests\n'), ((76368, 76417), 'service.test_pagination.parse_url_qs', 'parse_url_qs', (["response_json['pagination']['next']"], {}), "(response_json['pagination']['next'])\n", (76380, 76417), False, 'from service.test_pagination import parse_url_qs\n'), ((76449, 76502), 'service.test_pagination.parse_url_qs', 'parse_url_qs', (["response_json['pagination']['previous']"], {}), "(response_json['pagination']['previous'])\n", (76461, 76502), False, 'from service.test_pagination import parse_url_qs\n'), ((80380, 80412), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (80392, 80412), False, 'import requests\n'), ((81883, 81920), 'requests.get', 'requests.get', (['url'], {'params': 'self.params'}), '(url, params=self.params)\n', (81895, 81920), False, 'import requests\n'), ((83307, 83344), 'requests.get', 'requests.get', (['url'], {'params': 'self.params'}), '(url, params=self.params)\n', (83319, 83344), False, 'import requests\n'), ((83435, 83461), 'more_itertools.one', 'one', (["response_json['hits']"], {}), "(response_json['hits'])\n", (83438, 83461), False, 'from more_itertools import one\n'), ((92965, 92982), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (92977, 92982), False, 'import requests\n'), ((95567, 95599), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (95579, 95599), False, 'import requests\n'), ((80101, 80154), 'json.dumps', 'json.dumps', (["{'cellCount': {'within': [[6000, 9000]]}}"], {}), "({'cellCount': {'within': [[6000, 9000]]}})\n", (80111, 80154), False, 'import json\n'), ((81498, 81573), 'json.dumps', 'json.dumps', (["{'projectId': {'is': ['091cf39b-01bc-42e5-9437-f419a66c8a45']}}"], {}), "({'projectId': {'is': ['091cf39b-01bc-42e5-9437-f419a66c8a45']}})\n", (81508, 81573), False, 'import json\n'), ((1015, 1094), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""fa5be5eb-2d64-49f5-8ed8-bd627ac9bc7a"""', '"""2019-02-14T192438.034764Z"""'], {}), "('fa5be5eb-2d64-49f5-8ed8-bd627ac9bc7a', '2019-02-14T192438.034764Z')\n", (1025, 1094), False, 'from azul.indexer import BundleFQID\n'), ((1108, 1187), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""d0e17014-9a58-4763-9e66-59894efbdaa8"""', '"""2018-10-03T144137.044509Z"""'], {}), "('d0e17014-9a58-4763-9e66-59894efbdaa8', '2018-10-03T144137.044509Z')\n", (1118, 1187), False, 'from azul.indexer import BundleFQID\n'), ((1201, 1280), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""e0ae8cfa-2b51-4419-9cde-34df44c6458a"""', '"""2018-12-05T230917.591044Z"""'], {}), "('e0ae8cfa-2b51-4419-9cde-34df44c6458a', '2018-12-05T230917.591044Z')\n", (1211, 1280), False, 'from azul.indexer import BundleFQID\n'), ((1294, 1373), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""411cd8d5-5990-43cd-84cc-6c7796b8a76d"""', '"""2018-10-18T204655.866661Z"""'], {}), "('411cd8d5-5990-43cd-84cc-6c7796b8a76d', '2018-10-18T204655.866661Z')\n", (1304, 1373), False, 'from azul.indexer import BundleFQID\n'), ((1387, 1466), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""412cd8d5-5990-43cd-84cc-6c7796b8a76d"""', '"""2018-10-18T204655.866661Z"""'], {}), "('412cd8d5-5990-43cd-84cc-6c7796b8a76d', '2018-10-18T204655.866661Z')\n", (1397, 1466), False, 'from azul.indexer import BundleFQID\n'), ((1480, 1559), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""ffac201f-4b1c-4455-bd58-19c1a9e863b4"""', '"""2019-10-09T170735.528600Z"""'], {}), "('ffac201f-4b1c-4455-bd58-19c1a9e863b4', '2019-10-09T170735.528600Z')\n", (1490, 1559), False, 'from azul.indexer import BundleFQID\n'), ((2214, 2301), 'azul.config.es_index_name', 'config.es_index_name', ([], {'catalog': 'self.catalog', 'entity_type': 'entity_type', 'aggregate': '(True)'}), '(catalog=self.catalog, entity_type=entity_type,\n aggregate=True)\n', (2234, 2301), False, 'from azul import cached_property, config\n'), ((52861, 52890), 'more_itertools.one', 'one', (["keyword_response['hits']"], {}), "(keyword_response['hits'])\n", (52864, 52890), False, 'from more_itertools import one\n'), ((53311, 53340), 'more_itertools.one', 'one', (["keyword_response['hits']"], {}), "(keyword_response['hits'])\n", (53314, 53340), False, 'from more_itertools import one\n'), ((54243, 54272), 'more_itertools.one', 'one', (["keyword_response['hits']"], {}), "(keyword_response['hits'])\n", (54246, 54272), False, 'from more_itertools import one\n'), ((54843, 54875), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (54855, 54875), False, 'import requests\n'), ((63426, 63458), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (63438, 63458), False, 'import requests\n'), ((66098, 66130), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (66110, 66130), False, 'import requests\n'), ((67195, 67227), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (67207, 67227), False, 'import requests\n'), ((69348, 69380), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (69360, 69380), False, 'import requests\n'), ((77425, 77504), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""97f0cc83-f0ac-417a-8a29-221c77debde8"""', '"""2019-10-14T195415.397406Z"""'], {}), "('97f0cc83-f0ac-417a-8a29-221c77debde8', '2019-10-14T195415.397406Z')\n", (77435, 77504), False, 'from azul.indexer import BundleFQID\n'), ((77518, 77597), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""8c90d4fe-9a5d-4e3d-ada2-0414b666b880"""', '"""2019-10-14T195415.397546Z"""'], {}), "('8c90d4fe-9a5d-4e3d-ada2-0414b666b880', '2019-10-14T195415.397546Z')\n", (77528, 77597), False, 'from azul.indexer import BundleFQID\n'), ((77639, 77718), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""fa5be5eb-2d64-49f5-8ed8-bd627ac9bc7a"""', '"""2019-02-14T192438.034764Z"""'], {}), "('fa5be5eb-2d64-49f5-8ed8-bd627ac9bc7a', '2019-02-14T192438.034764Z')\n", (77649, 77718), False, 'from azul.indexer import BundleFQID\n'), ((77732, 77811), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""411cd8d5-5990-43cd-84cc-6c7796b8a76d"""', '"""2018-10-18T204655.866661Z"""'], {}), "('411cd8d5-5990-43cd-84cc-6c7796b8a76d', '2018-10-18T204655.866661Z')\n", (77742, 77811), False, 'from azul.indexer import BundleFQID\n'), ((77825, 77904), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""ffac201f-4b1c-4455-bd58-19c1a9e863b4"""', '"""2019-10-09T170735.528600Z"""'], {}), "('ffac201f-4b1c-4455-bd58-19c1a9e863b4', '2019-10-09T170735.528600Z')\n", (77835, 77904), False, 'from azul.indexer import BundleFQID\n'), ((79326, 79358), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (79338, 79358), False, 'import requests\n'), ((80952, 81031), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""f0731ab4-6b80-4eed-97c9-4984de81a47c"""', '"""2019-07-23T062120.663434Z"""'], {}), "('f0731ab4-6b80-4eed-97c9-4984de81a47c', '2019-07-23T062120.663434Z')\n", (80962, 81031), False, 'from azul.indexer import BundleFQID\n'), ((81118, 81203), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""1ec111a0-7481-571f-b35a-5a0e8fca890a"""', '"""2020-10-07T11:11:17.095956Z"""'], {}), "('1ec111a0-7481-571f-b35a-5a0e8fca890a',\n '2020-10-07T11:11:17.095956Z')\n", (81128, 81203), False, 'from azul.indexer import BundleFQID\n'), ((82912, 82929), 'more_itertools.one', 'one', (["hit['files']"], {}), "(hit['files'])\n", (82915, 82929), False, 'from more_itertools import one\n'), ((86011, 86031), 'more_itertools.one', 'one', (["hit['projects']"], {}), "(hit['projects'])\n", (86014, 86031), False, 'from more_itertools import one\n'), ((89224, 89244), 'more_itertools.one', 'one', (["hit['projects']"], {}), "(hit['projects'])\n", (89227, 89244), False, 'from more_itertools import one\n'), ((89446, 89525), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""dcccb551-4766-4210-966c-f9ee25d19190"""', '"""2018-10-18T204655.866661Z"""'], {}), "('dcccb551-4766-4210-966c-f9ee25d19190', '2018-10-18T204655.866661Z')\n", (89456, 89525), False, 'from azul.indexer import BundleFQID\n'), ((89539, 89618), 'azul.indexer.BundleFQID', 'BundleFQID', (['"""94f2ba52-30c8-4de0-a78e-f95a3f8deb9c"""', '"""2019-04-03T103426.471000Z"""'], {}), "('94f2ba52-30c8-4de0-a78e-f95a3f8deb9c', '2019-04-03T103426.471000Z')\n", (89549, 89618), False, 'from azul.indexer import BundleFQID\n'), ((92349, 92381), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (92361, 92381), False, 'import requests\n'), ((20622, 20641), 'json.dumps', 'json.dumps', (['filters'], {}), '(filters)\n', (20632, 20641), False, 'import json\n'), ((56281, 56313), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (56293, 56313), False, 'import requests\n'), ((58040, 58063), 'azul.indexer.document.null_str.to_index', 'null_str.to_index', (['None'], {}), '(None)\n', (58057, 58063), False, 'from azul.indexer.document import null_str\n'), ((59717, 59736), 'more_itertools.one', 'one', (["hit['bundles']"], {}), "(hit['bundles'])\n", (59720, 59736), False, 'from more_itertools import one\n'), ((59752, 59771), 'more_itertools.one', 'one', (["hit['bundles']"], {}), "(hit['bundles'])\n", (59755, 59771), False, 'from more_itertools import one\n'), ((74084, 74105), 'more_itertools.one', 'one', (["response['hits']"], {}), "(response['hits'])\n", (74087, 74105), False, 'from more_itertools import one\n'), ((74208, 74234), 'more_itertools.one', 'one', (["hit['donorOrganisms']"], {}), "(hit['donorOrganisms'])\n", (74211, 74234), False, 'from more_itertools import one\n'), ((92280, 92321), 'json.dumps', 'json.dumps', (["{'organPart': {'is': [None]}}"], {}), "({'organPart': {'is': [None]}})\n", (92290, 92321), False, 'import json\n'), ((67437, 67457), 'more_itertools.one', 'one', (["hit['projects']"], {}), "(hit['projects'])\n", (67440, 67457), False, 'from more_itertools import one\n'), ((22388, 22394), 'more_itertools.one', 'one', (['v'], {}), '(v)\n', (22391, 22394), False, 'from more_itertools import one\n'), ((65599, 65620), 'more_itertools.one', 'one', (["hit['cellLines']"], {}), "(hit['cellLines'])\n", (65602, 65620), False, 'from more_itertools import one\n'), ((73800, 73836), 'json.dumps', 'json.dumps', (["{'organismAge': filters}"], {}), "({'organismAge': filters})\n", (73810, 73836), False, 'import json\n')]
#! /usr/bin/env python3 import os import sys def error(msg): print(msg) print(f"Usage: {sys.argv[0]} FILE.gitp8") print(" Converts FILE.gitp8 in merge-friendly format to FILE.p8 in pico-8 format.") sys.exit(1) if len(sys.argv) < 2 or len(sys.argv) > 2: error("Exactly 1 argument required.") if not os.path.exists(sys.argv[1]): error(f"{sys.argv[1]} does not exist.") if not sys.argv[1].endswith(".gitp8"): error(f"{sys.argv[1]} does not have extension .gitp8") fname=sys.argv[1] base=fname.split(".gitp8")[0] with open(fname, "r") as f: lines=f.read().splitlines() labels = ["__lua__", "__gfx__", "__gff__", "__label__", "__map__", "__sfx__", "__music__"] def get_segment(lines, label): segment=[] reading=False for line in lines: if line == label: reading=True elif line in labels: reading=False if reading: segment.append(line) return segment def reserialize(lines, w, h, L): if not lines: return lines lbl = lines[0] lines = lines[1:] CW = L CH = len(lines)*w*h//L serialized = [['z' for _ in range(CW)] for __ in range(CH)] BW = CW // w BH = CH // h for i in range(len(lines)): bx = i % BW by = i // BW for dx in range(w): for dy in range(h): serialized[by*h+dy][bx*w+dx] = lines[i][dy*w+dx] serialized = ["".join(l) for l in serialized] return [lbl] + serialized hdr = lines[:2] lua = get_segment(lines, "__lua__") gfx = get_segment(lines, "__gfx__") gff = get_segment(lines, "__gff__") lbl = get_segment(lines, "__label__") map = get_segment(lines, "__map__") sfx = get_segment(lines, "__sfx__") msc = get_segment(lines, "__music__") gfx = reserialize(gfx, 8, 8, 128) gff = reserialize(gff, 2, 1, 256) map = reserialize(map, 2, 1, 256) if os.path.exists(base+".p8"): if input(f"{base}.p8 exists. Overwrite? (y/n) ") not in ["y", "Y"]: print("Aborted.") sys.exit(1) with open(base+".p8", "w") as f: for lines in [hdr, lua, gfx, gff, lbl, map, sfx, msc]: if lines: f.write("\n".join(lines)) f.write("\n")
[ "os.path.exists", "sys.exit" ]
[((1872, 1900), 'os.path.exists', 'os.path.exists', (["(base + '.p8')"], {}), "(base + '.p8')\n", (1886, 1900), False, 'import os\n'), ((217, 228), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (225, 228), False, 'import sys\n'), ((323, 350), 'os.path.exists', 'os.path.exists', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (337, 350), False, 'import os\n'), ((2006, 2017), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2014, 2017), False, 'import sys\n')]
"""Utilities for multiprocessing.""" from contextlib import contextmanager import logging import time from dask.distributed import Client, LocalCluster, progress from dask_jobqueue import PBSCluster import numpy as np _logger = logging.getLogger(__name__) def map_function(function, function_args, pbs=False, **cluster_kwargs): """Parallize `function` over `function_args` across available CPUs. Utilizes dask.distributed.Client.map which follows the implementation of built-in `map`. See https://docs.python.org/3/library/functions.html#map and https://distributed.dask.org/en/latest/client.html. Examples -------- ``` def add(x, y): return x + y xs = [1, 2, 3, 4] ys = [11, 12, 13, 14] map_function(add, [xs, ys]) => [12, 14, 16, 18] ``` Parameters ---------- function : function | method function_args : list If `function` takes multiple args, follow implementation of `map`. Namely, if f(x1, x2) => y, then `function_args` should be `[all_x1, all_x2]`. pbs : bool, optional Whether or not to create a PBS job over whose cluster to parallize, by default False. Returns ------- list """ _logger.info( "Running %s in parallel with args of shape %s", function.__name__, np.shape(function_args), ) with dask_client(pbs=pbs, **cluster_kwargs) as client: if len(np.shape(function_args)) == 1: function_args = [function_args] futures = client.map(function, *function_args) progress(futures) return_values = client.gather(futures) return return_values @contextmanager def dask_client(pbs=False, **cluster_kwargs): """Context manager surrounding a dask client. Handles closing upon completion. Examples -------- ``` with dask_client() as client: client.do_something() ``` Parameters ---------- pbs: bool, optional Whether or not dask should submit a PBS job over whose cluster to operate. **cluster_kwargs: Arguments to either `PBSCluster` or `LocalCluster` which are pretty much the same. Some usefule arguments include: - n_workers - cores - interface - memory - walltime """ if pbs: cluster = PBSCluster(**cluster_kwargs) if "n_workers" not in cluster_kwargs: cluster.scale(1) else: cluster = LocalCluster(processes=False, **cluster_kwargs) client = Client(cluster) client.wait_for_workers(n_workers=1) time.sleep(5) try: _logger.info("Dask Cluster: %s\nDask Client: %s", cluster, client) yield client finally: client.close() cluster.close() _logger.info("Closed client and cluster") def flatten_array(arr): """Flatten an array by 1 dimension.""" shape = np.array(arr).shape if len(shape) == 1: return arr return [item for list_1d in arr for item in list_1d]
[ "dask.distributed.Client", "dask.distributed.LocalCluster", "time.sleep", "numpy.shape", "dask.distributed.progress", "numpy.array", "dask_jobqueue.PBSCluster", "logging.getLogger" ]
[((230, 257), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (247, 257), False, 'import logging\n'), ((2557, 2572), 'dask.distributed.Client', 'Client', (['cluster'], {}), '(cluster)\n', (2563, 2572), False, 'from dask.distributed import Client, LocalCluster, progress\n'), ((2619, 2632), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (2629, 2632), False, 'import time\n'), ((1333, 1356), 'numpy.shape', 'np.shape', (['function_args'], {}), '(function_args)\n', (1341, 1356), True, 'import numpy as np\n'), ((1577, 1594), 'dask.distributed.progress', 'progress', (['futures'], {}), '(futures)\n', (1585, 1594), False, 'from dask.distributed import Client, LocalCluster, progress\n'), ((2363, 2391), 'dask_jobqueue.PBSCluster', 'PBSCluster', ([], {}), '(**cluster_kwargs)\n', (2373, 2391), False, 'from dask_jobqueue import PBSCluster\n'), ((2495, 2542), 'dask.distributed.LocalCluster', 'LocalCluster', ([], {'processes': '(False)'}), '(processes=False, **cluster_kwargs)\n', (2507, 2542), False, 'from dask.distributed import Client, LocalCluster, progress\n'), ((2930, 2943), 'numpy.array', 'np.array', (['arr'], {}), '(arr)\n', (2938, 2943), True, 'import numpy as np\n'), ((1438, 1461), 'numpy.shape', 'np.shape', (['function_args'], {}), '(function_args)\n', (1446, 1461), True, 'import numpy as np\n')]
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # CloudWatch Custom Widget sample: call any read-only AWS API and return raw results in JSON import boto3 import json import os import re DOCS = """ ## Make an AWS Call Calls any (read-only) AWS API and displays the result as JSON. ### Widget parameters Param | Description ---|--- **service** | The name of the AWS service to call, e.g. **EC2** or **CloudWatch** **api** | The API name to call **params** | The parameters to pass to the API ### Example parameters ``` yaml service: EC2 api: describeInstances params: Filters: - Name: instance-state-name Values: - running ```""" def lambda_handler(event, context): if 'describe' in event: return DOCS service = event.get('service', 'cloudwatch').lower() apiRaw = event.get('api', 'list_dashboards') api = re.sub(r'(?<!^)(?=[A-Z])', '_', apiRaw).lower() # Convert to snakecase in case it's in CamelCase region = event.get('region', os.environ['AWS_REGION']) params = event.get('params', {}) client = boto3.client(service) try: apiFunc = getattr(client, api) result = apiFunc(**params) return json.dumps(result, sort_keys=True, default=str) except AttributeError: return f"api '{api}' not found for service '{service}'"
[ "re.sub", "boto3.client", "json.dumps" ]
[((1108, 1129), 'boto3.client', 'boto3.client', (['service'], {}), '(service)\n', (1120, 1129), False, 'import boto3\n'), ((1233, 1280), 'json.dumps', 'json.dumps', (['result'], {'sort_keys': '(True)', 'default': 'str'}), '(result, sort_keys=True, default=str)\n', (1243, 1280), False, 'import json\n'), ((901, 939), 're.sub', 're.sub', (['"""(?<!^)(?=[A-Z])"""', '"""_"""', 'apiRaw'], {}), "('(?<!^)(?=[A-Z])', '_', apiRaw)\n", (907, 939), False, 'import re\n')]
import time from testtools import TestResult from logging import ( Formatter, Logger, INFO, ) from six import b from mimeparse import parse_mime_type from testtools import TestCase from testlogging import SubunitHandler from testlogging.testing import StreamResultDouble class SubunitHandlerTest(TestCase): def setUp(self): super(SubunitHandlerTest, self).setUp() self.result = StreamResultDouble() self.handler = SubunitHandler() self.handler.setResult(self.result) self.logger = Logger("test") self.logger.addHandler(self.handler) self.logger.setLevel(INFO) def test_default(self): """The handler has sane defaults.""" self.logger.info("hello") event = self.result.getEvent(0) self.assertEqual("status", event.name) self.assertIsNone(event.test_id) self.assertEqual("test.log", event.file_name) self.assertEqual(b("hello\n"), event.file_bytes) _, _, parameters = parse_mime_type(event.mime_type) self.assertEqual("python", parameters["language"]) self.assertEqual("default", parameters["format"]) self.assertAlmostEqual( time.time(), time.mktime(event.timestamp.timetuple()), delta=5) def test_decorated(self): self.addCleanup(self.handler.setResult, self.result) self.handler.setResult(TestResult()) error = self.assertRaises(RuntimeError, self.logger.info, "hello") self.assertEqual("Not a stream result", str(error)) def test_format(self): """A custom formatter and format name can be specified.""" formatter = Formatter("[%(name)s:%(levelname)s] %(message)s") self.handler.setFormatter(formatter, "myformat") self.logger.info("hello") event = self.result.getEvent(0) self.assertEqual(b("[test:INFO] hello\n"), event.file_bytes) _, _, parameters = parse_mime_type(event.mime_type) self.assertEqual("python", parameters["language"]) self.assertEqual("myformat", parameters["format"]) def test_file_name(self): """A custom file name can be specified.""" self.handler.setFileName("my.log") self.logger.info("hello") event = self.result.getEvent(0) self.assertEqual("my.log", event.file_name) def test_test_id(self): """A custom test ID can be specified.""" self.handler.setTestId("my.test") self.logger.info("hello") event = self.result.getEvent(0) self.assertEqual("my.test", event.test_id) def test_close(self): """ When the handler is closed, an EOF packet is written. """ self.handler.close() event = self.result.getEvent(0) self.assertEqual(b(""), event.file_bytes) self.assertTrue(event.eof)
[ "testtools.TestResult", "testlogging.testing.StreamResultDouble", "testlogging.SubunitHandler", "logging.Logger", "logging.Formatter", "mimeparse.parse_mime_type", "time.time", "six.b" ]
[((419, 439), 'testlogging.testing.StreamResultDouble', 'StreamResultDouble', ([], {}), '()\n', (437, 439), False, 'from testlogging.testing import StreamResultDouble\n'), ((463, 479), 'testlogging.SubunitHandler', 'SubunitHandler', ([], {}), '()\n', (477, 479), False, 'from testlogging import SubunitHandler\n'), ((546, 560), 'logging.Logger', 'Logger', (['"""test"""'], {}), "('test')\n", (552, 560), False, 'from logging import Formatter, Logger, INFO\n'), ((1016, 1048), 'mimeparse.parse_mime_type', 'parse_mime_type', (['event.mime_type'], {}), '(event.mime_type)\n', (1031, 1048), False, 'from mimeparse import parse_mime_type\n'), ((1661, 1710), 'logging.Formatter', 'Formatter', (['"""[%(name)s:%(levelname)s] %(message)s"""'], {}), "('[%(name)s:%(levelname)s] %(message)s')\n", (1670, 1710), False, 'from logging import Formatter, Logger, INFO\n'), ((1940, 1972), 'mimeparse.parse_mime_type', 'parse_mime_type', (['event.mime_type'], {}), '(event.mime_type)\n', (1955, 1972), False, 'from mimeparse import parse_mime_type\n'), ((957, 969), 'six.b', 'b', (['"""hello\n"""'], {}), "('hello\\n')\n", (958, 969), False, 'from six import b\n'), ((1210, 1221), 'time.time', 'time.time', ([], {}), '()\n', (1219, 1221), False, 'import time\n'), ((1397, 1409), 'testtools.TestResult', 'TestResult', ([], {}), '()\n', (1407, 1409), False, 'from testtools import TestResult\n'), ((1869, 1893), 'six.b', 'b', (['"""[test:INFO] hello\n"""'], {}), "('[test:INFO] hello\\n')\n", (1870, 1893), False, 'from six import b\n'), ((2798, 2803), 'six.b', 'b', (['""""""'], {}), "('')\n", (2799, 2803), False, 'from six import b\n')]
import numpy as np import gym import gym_carsim from gym import spaces from keras.models import Sequential from keras.layers import Dense, Activation, Flatten from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.policy import BoltzmannQPolicy from rl.memory import SequentialMemory ENV_NAME = 'carsim-v0' class WrapThreeFrames(gym.Wrapper): def __init__(self, env): gym.ObservationWrapper.__init__(self, env) self.observation_space = spaces.Box(low=0.0, high=1.0, shape=(9,)) self.past_obs = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] def shift_past_obs(self, new_obs): self.past_obs = self.past_obs[3:]+new_obs return self.past_obs def reset(self): obs = self.env.reset() return self.shift_past_obs(obs) def step(self, action): obs, reward, done, info = self.env.step(action) return self.shift_past_obs(obs), reward, done, info # Get the environment and extract the number of actions. env = gym.make(ENV_NAME) env = WrapThreeFrames(env) np.random.seed(98283476) env.seed(87518645) nb_actions = env.action_space.n # Next, we build a very simple model regardless of the dueling architecture # if you enable dueling network in DQN , DQN will build a dueling network base on your model automatically # Also, you can build a dueling network by yourself and turn off the dueling network in DQN. model = Sequential() model.add(Flatten(input_shape=(1,) + env.observation_space.shape)) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(nb_actions, activation='sigmoid')) print(model.summary()) # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and # even the metrics! memory = SequentialMemory(limit=50000, window_length=1) policy = BoltzmannQPolicy() # enable the dueling network # you can specify the dueling_type to one of {'avg','max','naive'} dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=100, enable_dueling_network=True, dueling_type='avg', target_model_update=1e-2, policy=policy) dqn.compile(Adam(lr=1e-3), metrics=['mae']) # Okay, now it's time to learn something! We visualize the training here for show, but this # slows down training quite a lot. You can always safely abort the training prematurely using # Ctrl + C. dqn.fit(env, nb_steps=50000, visualize=False, verbose=2) # After training is done, we save the final weights. dqn.save_weights('duel_dqn_{}_weights.h5f'.format(ENV_NAME), overwrite=True) #dqn.load_weights('duel_dqn_{}_weights.h5f'.format(ENV_NAME)) # Finally, evaluate our algorithm for 5 episodes. print(dqn.test(env, nb_episodes=5, nb_max_episode_steps=10000, visualize=True))
[ "rl.memory.SequentialMemory", "rl.agents.dqn.DQNAgent", "numpy.random.seed", "gym.make", "keras.layers.Activation", "keras.layers.Flatten", "rl.policy.BoltzmannQPolicy", "keras.optimizers.Adam", "gym.ObservationWrapper.__init__", "keras.layers.Dense", "gym.spaces.Box", "keras.models.Sequential" ]
[((1015, 1033), 'gym.make', 'gym.make', (['ENV_NAME'], {}), '(ENV_NAME)\n', (1023, 1033), False, 'import gym\n'), ((1061, 1085), 'numpy.random.seed', 'np.random.seed', (['(98283476)'], {}), '(98283476)\n', (1075, 1085), True, 'import numpy as np\n'), ((1422, 1434), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1432, 1434), False, 'from keras.models import Sequential\n'), ((1802, 1848), 'rl.memory.SequentialMemory', 'SequentialMemory', ([], {'limit': '(50000)', 'window_length': '(1)'}), '(limit=50000, window_length=1)\n', (1818, 1848), False, 'from rl.memory import SequentialMemory\n'), ((1858, 1876), 'rl.policy.BoltzmannQPolicy', 'BoltzmannQPolicy', ([], {}), '()\n', (1874, 1876), False, 'from rl.policy import BoltzmannQPolicy\n'), ((1979, 2158), 'rl.agents.dqn.DQNAgent', 'DQNAgent', ([], {'model': 'model', 'nb_actions': 'nb_actions', 'memory': 'memory', 'nb_steps_warmup': '(100)', 'enable_dueling_network': '(True)', 'dueling_type': '"""avg"""', 'target_model_update': '(0.01)', 'policy': 'policy'}), "(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup\n =100, enable_dueling_network=True, dueling_type='avg',\n target_model_update=0.01, policy=policy)\n", (1987, 2158), False, 'from rl.agents.dqn import DQNAgent\n'), ((1445, 1500), 'keras.layers.Flatten', 'Flatten', ([], {'input_shape': '((1,) + env.observation_space.shape)'}), '(input_shape=(1,) + env.observation_space.shape)\n', (1452, 1500), False, 'from keras.layers import Dense, Activation, Flatten\n'), ((1512, 1521), 'keras.layers.Dense', 'Dense', (['(16)'], {}), '(16)\n', (1517, 1521), False, 'from keras.layers import Dense, Activation, Flatten\n'), ((1533, 1551), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (1543, 1551), False, 'from keras.layers import Dense, Activation, Flatten\n'), ((1563, 1572), 'keras.layers.Dense', 'Dense', (['(16)'], {}), '(16)\n', (1568, 1572), False, 'from keras.layers import Dense, Activation, Flatten\n'), ((1584, 1602), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (1594, 1602), False, 'from keras.layers import Dense, Activation, Flatten\n'), ((1614, 1653), 'keras.layers.Dense', 'Dense', (['nb_actions'], {'activation': '"""sigmoid"""'}), "(nb_actions, activation='sigmoid')\n", (1619, 1653), False, 'from keras.layers import Dense, Activation, Flatten\n'), ((2177, 2191), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (2181, 2191), False, 'from keras.optimizers import Adam\n'), ((406, 448), 'gym.ObservationWrapper.__init__', 'gym.ObservationWrapper.__init__', (['self', 'env'], {}), '(self, env)\n', (437, 448), False, 'import gym\n'), ((482, 523), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(0.0)', 'high': '(1.0)', 'shape': '(9,)'}), '(low=0.0, high=1.0, shape=(9,))\n', (492, 523), False, 'from gym import spaces\n')]
#!/usr/bin/env python # encoding: utf-8 """ pytimeNSW ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2017 by <NAME> <<EMAIL>> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BaseParser.main dp = BaseParser.parse_diff def parse(value): return bp(value) def count(value1, value2): _val1, _val2 = parse(value1), parse(value2) if type(_val1) == type(_val2): return _val1 - _val2 else: _val1 = _val1 if isinstance(_val1, datetime.datetime) else midnight(_val1) _val2 = _val2 if isinstance(_val2, datetime.datetime) else midnight(_val2) return _val1 - _val2 # max, min _date = datetime.date.today() _datetime = datetime.datetime.now() _year = _date.year _month = _date.month _day = _date.day _SEVEN_DAYS = datetime.timedelta(days=7) _ONE_DAY = datetime.timedelta(days=1) def today(year=None): """this day, last year""" return datetime.date(int(year), _date.month, _date.day) if year else _date def tomorrow(date=None): """tomorrow is another day""" if not date: return _date + datetime.timedelta(days=1) else: current_date = parse(date) return current_date + datetime.timedelta(days=1) def yesterday(date=None): """yesterday once more""" if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1) ######################## # function method ######################## def daysrange(first=None, second=None, wipe=False): """ get all days between first and second :param first: datetime, date or string :param second: datetime, date or string :return: list """ _first, _second = parse(first), parse(second) (_start, _end) = (_second, _first) if _first > _second else (_first, _second) days_between = (_end - _start).days date_list = [_end - datetime.timedelta(days=x) for x in range(0, days_between + 1)] if wipe and len(date_list) >= 2: date_list = date_list[1:-1] return date_list def lastday(year=_year, month=_month): """ get the current month's last day :param year: default to current year :param month: default to current month :return: month's last day """ last_day = calendar.monthrange(year, month)[1] return datetime.date(year=year, month=month, day=last_day) def midnight(arg=None): """ convert date to datetime as midnight or get current day's midnight :param arg: string or date/datetime :return: datetime at 00:00:00 """ if arg: _arg = parse(arg) if isinstance(_arg, datetime.date): return datetime.datetime.combine(_arg, datetime.datetime.min.time()) elif isinstance(_arg, datetime.datetime): return datetime.datetime.combine(_arg.date(), datetime.datetime.min.time()) else: return datetime.datetime.combine(_date, datetime.datetime.min.time()) def before(base=_datetime, diff=None): """ count datetime before `base` time :param base: minuend -> str/datetime/date :param diff: str :return: datetime """ _base = parse(base) if isinstance(_base, datetime.date): _base = midnight(_base) if not diff: return _base result_dict = dp(diff) # weeks already convert to days in diff_parse function(dp) for unit in result_dict: _val = result_dict[unit] if not _val: continue if unit == 'years': _base = _base.replace(year=(_base.year - _val)) elif unit == 'months': if _base.month <= _val: _month_diff = 12 - (_val - _base.month) _base = _base.replace(year=_base.year - 1).replace(month=_month_diff) else: _base = _base.replace(month=_base.month - _val) elif unit in ['days', 'hours', 'minutes', 'seconds']: _base = _base - datetime.timedelta(**{unit: _val}) return _base def after(base=_datetime, diff=None): """ count datetime after diff args :param base: str/datetime/date :param diff: str :return: datetime """ _base = parse(base) if isinstance(_base, datetime.date): _base = midnight(_base) result_dict = dp(diff) for unit in result_dict: _val = result_dict[unit] if not _val: continue if unit == 'years': _base = _base.replace(year=(_base.year + _val)) elif unit == 'months': if _base.month + _val <= 12: _base = _base.replace(month=_base.month + _val) else: _month_diff = (_base.month + _val) - 12 _base = _base.replace(year=_base.year + 1).replace(month=_month_diff) elif unit in ['days', 'hours', 'minutes', 'seconds']: _base = _base + datetime.timedelta(**{unit: _val}) return _base def _datetime_to_date(arg): """ convert datetime/str to date :param arg: :return: """ _arg = parse(arg) if isinstance(_arg, datetime.datetime): _arg = _arg.date() return _arg # Monday to Monday -> 00:00:00 to 00:00:00 month 1st - next month 1st def this_week(arg=_date, clean=False): _arg = _datetime_to_date(arg) return _arg - datetime.timedelta(days=_arg.weekday()), _arg + datetime.timedelta( days=6 - _arg.weekday()) if clean else _arg + datetime.timedelta(days=6 - _arg.weekday()) + _ONE_DAY def last_week(arg=_date, clean=False): this_week_tuple = this_week(arg) return this_week_tuple[0] - _SEVEN_DAYS, this_week_tuple[1] - _SEVEN_DAYS if clean \ else this_week_tuple[1] - _SEVEN_DAYS + _ONE_DAY def next_week(arg=_date, clean=False): this_week_tuple = this_week(arg) return this_week_tuple[0] + _SEVEN_DAYS, this_week_tuple[1] + _SEVEN_DAYS if clean \ else this_week_tuple[1] + _SEVEN_DAYS + _ONE_DAY def this_month(arg=_date, clean=False): _arg = _datetime_to_date(arg) return datetime.date(_arg.year, _arg.month, 1), lastday(_arg.year, _arg.month) if clean \ else lastday(_arg.year, _arg.month) + _ONE_DAY def last_month(arg=_date, clean=False): _arg = _datetime_to_date(arg) this_month_first_day = datetime.date(_arg.year, _arg.month, 1) last_month_last_day = this_month_first_day - _ONE_DAY last_month_first_day = datetime.date(last_month_last_day.year, last_month_last_day.month, 1) return last_month_first_day, last_month_last_day if clean else this_month_first_day def next_month(arg=_date, clean=False): _arg = _datetime_to_date(arg) this_month_last_day = lastday(_arg.year, _arg.month) next_month_first_day = this_month_last_day + _ONE_DAY next_month_last_day = lastday(next_month_first_day.year, next_month_first_day.month) return next_month_first_day, next_month_last_day if clean else next_month_last_day + _ONE_DAY ###################### # festival ###################### def newyear(year=None): january_first = datetime.date(int(year), 1, 1) if year else datetime.date(_year, 1, 1) weekday_seq = january_first.weekday() if is_weekend(january_first): return datetime.date(january_first.year, 1, (8 - weekday_seq)%7) else: return january_first def valentine(year=None): return datetime.date(int(year), 2, 14) if year else datetime.date(_year, 2, 14) def fool(year=None): return datetime.date(int(year), 4, 1) if year else datetime.date(_year, 4, 1) def christmas(year=None): december_25 = datetime.date(int(year), 12, 25) if year else datetime.date(_year, 12, 25) weekday_seq = december_25.weekday() if is_weekend(december_25): return datetime.date(december_25.year, 12, 27) else: return december_25 def boxing(year=None): return datetime.date(int(year), 12, 26) if year else datetime.date(_year, 12, 26) def mother(year=None): """ the 2nd Sunday in May :param year: int :return: Mother's day """ may_first = datetime.date(_year, 5, 1) if not year else datetime.date(int(year), 5, 1) weekday_seq = may_first.weekday() return datetime.date(may_first.year, 5, (14 - weekday_seq)) def father(year=None): """ the 1st Sunday in September :param year: int :return: Father's day """ september_first = datetime.date(_year, 9, 1) if not year else datetime.date(int(year), 9, 1) weekday_seq = september_first.weekday() return datetime.date(september_first.year, 9, (7 - weekday_seq)) def halloween(year=None): return lastday(month=10) if not year else lastday(year, 10) def goodfri(year=None): return yesterday(eastersat(year)) def eastersat(year=None): return yesterday(eastersun(year)) def eastersun(year=None): """ 1900 - 2099 limit :param year: int :return: Easter day """ y = int(year) if year else _year n = y - 1900 a = n % 19 q = n // 4 b = (7 * a + 1) // 19 m = (11 * a + 4 - b) % 29 w = (n + q + 31 - m) % 7 d = 25 - m - w if d > 0: return datetime.date(y, 4, d) else: return datetime.date(y, 3, (31 + d)) def eastermon(year=None): return tomorrow(eastersun(year)) def easter(year=None): return goodfri(year), eastersat(year), eastersun(year), eastermon(year) def anzac(year=None): return datetime.date(int(year), 4, 25) if year else datetime.date(_year, 4, 25) def australia(year=None): return datetime.date(int(year), 1, 26) if year else datetime.date(_year, 1, 26) def queen(year=None): #check later """ the 2nd Monday in June :param year: int :return: Queen's birthday """ june_eight = datetime.date(_year, 6, 8) if not year else datetime.date(int(year), 6, 8) weekday_seq = june_eight.weekday() return datetime.date(june_eight.year, 6, 7 + (8 - weekday_seq)%7) def labour(year=None): """ the 1st Monday in October :param year: int :return: Labour day """ october_first = datetime.date(_year, 10, 1) if not year else datetime.date(int(year), 10, 1) weekday_seq = october_first.weekday() return datetime.date(october_first.year, 10, (8 - weekday_seq)%7) def family(year=None): year = year if year else _year family_day = {2011: datetime.date(2011,10,10), 2012: datetime.date(2012,10,8), 2013: datetime.date(2013,9,30), 2014: datetime.date(2014,9,29), 2015: datetime.date(2015,9,28), 2016: datetime.date(2016,9,26), 2017: datetime.date(2017,9,25), 2018: datetime.date(2018,10,8), 2019: datetime.date(2019,9,30) } return family_day.get(year) def canberra(year=None): """ the 2nd monday of March :param year: int :return: Canberra day """ march_eight = datetime.date(year, 3, 8) if not year else datetime.date(int(year), 3, 8) weekday_seq = march_eight.weekday() return datetime.date(march_eight.year, 3, 7 + (8 - weekday_seq)%7) def public_holidays(year): """ returns a list of datetime objects that correspond to NSW public holidays :param year: int :return: list of datetime objects """ year = year if year else _year return [i for i in easter(year)] + [newyear(year), australia(year),anzac(year), queen(year), labour(year), christmas(year), boxing(year)] def public_holidays_can(year): """ returns a list of datetime objects that correspond to NSW public holidays :param year: int :return: list of datetime objects """ year = year if year else _year return [i for i in easter(year)] + [newyear(year), australia(year),anzac(year), queen(year), labour(year), christmas(year), boxing(year), family(year), canberra(year)] def is_public(date_): """ """ if type(date_) == datetime.date: pass elif type(date_) == datetime.datetime: date_ = date_.date() else: date_ = parse(date_) year = date_.year return (date_ in public_holidays(year)) def is_public_can(date_): if type(date_) == datetime.date: pass elif type(date_) == datetime.datetime: date_ = date_.date() else: date_ = parse(date_) year = date_.year return (date_ in public_holidays_can(year)) def is_weekend(date_): if type(date_) == datetime.date: pass elif type(date_) == datetime.datetime: date_ = date_.date() else: date_ = parse(date_) return (date_.weekday() >=5 ) if __name__ == '__main__': # _time_filter('2015-01-03') # print(calendar.monthrange(2015, 10)) print(bp('2015-01-03'))
[ "datetime.date", "datetime.date.today", "datetime.timedelta", "datetime.datetime.min.time", "calendar.monthrange", "datetime.datetime.now" ]
[((762, 783), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (781, 783), False, 'import datetime\n'), ((796, 819), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (817, 819), False, 'import datetime\n'), ((892, 918), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), '(days=7)\n', (910, 918), False, 'import datetime\n'), ((930, 956), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (948, 956), False, 'import datetime\n'), ((2461, 2512), 'datetime.date', 'datetime.date', ([], {'year': 'year', 'month': 'month', 'day': 'last_day'}), '(year=year, month=month, day=last_day)\n', (2474, 2512), False, 'import datetime\n'), ((6384, 6423), 'datetime.date', 'datetime.date', (['_arg.year', '_arg.month', '(1)'], {}), '(_arg.year, _arg.month, 1)\n', (6397, 6423), False, 'import datetime\n'), ((6509, 6578), 'datetime.date', 'datetime.date', (['last_month_last_day.year', 'last_month_last_day.month', '(1)'], {}), '(last_month_last_day.year, last_month_last_day.month, 1)\n', (6522, 6578), False, 'import datetime\n'), ((8279, 8329), 'datetime.date', 'datetime.date', (['may_first.year', '(5)', '(14 - weekday_seq)'], {}), '(may_first.year, 5, 14 - weekday_seq)\n', (8292, 8329), False, 'import datetime\n'), ((8604, 8659), 'datetime.date', 'datetime.date', (['september_first.year', '(9)', '(7 - weekday_seq)'], {}), '(september_first.year, 9, 7 - weekday_seq)\n', (8617, 8659), False, 'import datetime\n'), ((9939, 9999), 'datetime.date', 'datetime.date', (['june_eight.year', '(6)', '(7 + (8 - weekday_seq) % 7)'], {}), '(june_eight.year, 6, 7 + (8 - weekday_seq) % 7)\n', (9952, 9999), False, 'import datetime\n'), ((10263, 10323), 'datetime.date', 'datetime.date', (['october_first.year', '(10)', '((8 - weekday_seq) % 7)'], {}), '(october_first.year, 10, (8 - weekday_seq) % 7)\n', (10276, 10323), False, 'import datetime\n'), ((11019, 11080), 'datetime.date', 'datetime.date', (['march_eight.year', '(3)', '(7 + (8 - weekday_seq) % 7)'], {}), '(march_eight.year, 3, 7 + (8 - weekday_seq) % 7)\n', (11032, 11080), False, 'import datetime\n'), ((2414, 2446), 'calendar.monthrange', 'calendar.monthrange', (['year', 'month'], {}), '(year, month)\n', (2433, 2446), False, 'import calendar\n'), ((6143, 6182), 'datetime.date', 'datetime.date', (['_arg.year', '_arg.month', '(1)'], {}), '(_arg.year, _arg.month, 1)\n', (6156, 6182), False, 'import datetime\n'), ((7195, 7221), 'datetime.date', 'datetime.date', (['_year', '(1)', '(1)'], {}), '(_year, 1, 1)\n', (7208, 7221), False, 'import datetime\n'), ((7314, 7373), 'datetime.date', 'datetime.date', (['january_first.year', '(1)', '((8 - weekday_seq) % 7)'], {}), '(january_first.year, 1, (8 - weekday_seq) % 7)\n', (7327, 7373), False, 'import datetime\n'), ((7495, 7522), 'datetime.date', 'datetime.date', (['_year', '(2)', '(14)'], {}), '(_year, 2, 14)\n', (7508, 7522), False, 'import datetime\n'), ((7601, 7627), 'datetime.date', 'datetime.date', (['_year', '(4)', '(1)'], {}), '(_year, 4, 1)\n', (7614, 7627), False, 'import datetime\n'), ((7720, 7748), 'datetime.date', 'datetime.date', (['_year', '(12)', '(25)'], {}), '(_year, 12, 25)\n', (7733, 7748), False, 'import datetime\n'), ((7837, 7876), 'datetime.date', 'datetime.date', (['december_25.year', '(12)', '(27)'], {}), '(december_25.year, 12, 27)\n', (7850, 7876), False, 'import datetime\n'), ((7996, 8024), 'datetime.date', 'datetime.date', (['_year', '(12)', '(26)'], {}), '(_year, 12, 26)\n', (8009, 8024), False, 'import datetime\n'), ((8155, 8181), 'datetime.date', 'datetime.date', (['_year', '(5)', '(1)'], {}), '(_year, 5, 1)\n', (8168, 8181), False, 'import datetime\n'), ((8474, 8500), 'datetime.date', 'datetime.date', (['_year', '(9)', '(1)'], {}), '(_year, 9, 1)\n', (8487, 8500), False, 'import datetime\n'), ((9209, 9231), 'datetime.date', 'datetime.date', (['y', '(4)', 'd'], {}), '(y, 4, d)\n', (9222, 9231), False, 'import datetime\n'), ((9257, 9284), 'datetime.date', 'datetime.date', (['y', '(3)', '(31 + d)'], {}), '(y, 3, 31 + d)\n', (9270, 9284), False, 'import datetime\n'), ((9527, 9554), 'datetime.date', 'datetime.date', (['_year', '(4)', '(25)'], {}), '(_year, 4, 25)\n', (9540, 9554), False, 'import datetime\n'), ((9638, 9665), 'datetime.date', 'datetime.date', (['_year', '(1)', '(26)'], {}), '(_year, 1, 26)\n', (9651, 9665), False, 'import datetime\n'), ((9814, 9840), 'datetime.date', 'datetime.date', (['_year', '(6)', '(8)'], {}), '(_year, 6, 8)\n', (9827, 9840), False, 'import datetime\n'), ((10133, 10160), 'datetime.date', 'datetime.date', (['_year', '(10)', '(1)'], {}), '(_year, 10, 1)\n', (10146, 10160), False, 'import datetime\n'), ((10405, 10432), 'datetime.date', 'datetime.date', (['(2011)', '(10)', '(10)'], {}), '(2011, 10, 10)\n', (10418, 10432), False, 'import datetime\n'), ((10438, 10464), 'datetime.date', 'datetime.date', (['(2012)', '(10)', '(8)'], {}), '(2012, 10, 8)\n', (10451, 10464), False, 'import datetime\n'), ((10470, 10496), 'datetime.date', 'datetime.date', (['(2013)', '(9)', '(30)'], {}), '(2013, 9, 30)\n', (10483, 10496), False, 'import datetime\n'), ((10521, 10547), 'datetime.date', 'datetime.date', (['(2014)', '(9)', '(29)'], {}), '(2014, 9, 29)\n', (10534, 10547), False, 'import datetime\n'), ((10553, 10579), 'datetime.date', 'datetime.date', (['(2015)', '(9)', '(28)'], {}), '(2015, 9, 28)\n', (10566, 10579), False, 'import datetime\n'), ((10585, 10611), 'datetime.date', 'datetime.date', (['(2016)', '(9)', '(26)'], {}), '(2016, 9, 26)\n', (10598, 10611), False, 'import datetime\n'), ((10636, 10662), 'datetime.date', 'datetime.date', (['(2017)', '(9)', '(25)'], {}), '(2017, 9, 25)\n', (10649, 10662), False, 'import datetime\n'), ((10668, 10694), 'datetime.date', 'datetime.date', (['(2018)', '(10)', '(8)'], {}), '(2018, 10, 8)\n', (10681, 10694), False, 'import datetime\n'), ((10700, 10726), 'datetime.date', 'datetime.date', (['(2019)', '(9)', '(30)'], {}), '(2019, 9, 30)\n', (10713, 10726), False, 'import datetime\n'), ((10894, 10919), 'datetime.date', 'datetime.date', (['year', '(3)', '(8)'], {}), '(year, 3, 8)\n', (10907, 10919), False, 'import datetime\n'), ((1191, 1217), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (1209, 1217), False, 'import datetime\n'), ((1293, 1319), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (1311, 1319), False, 'import datetime\n'), ((1418, 1444), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (1436, 1444), False, 'import datetime\n'), ((1520, 1546), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (1538, 1546), False, 'import datetime\n'), ((2031, 2057), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'x'}), '(days=x)\n', (2049, 2057), False, 'import datetime\n'), ((3059, 3087), 'datetime.datetime.min.time', 'datetime.datetime.min.time', ([], {}), '()\n', (3085, 3087), False, 'import datetime\n'), ((2833, 2861), 'datetime.datetime.min.time', 'datetime.datetime.min.time', ([], {}), '()\n', (2859, 2861), False, 'import datetime\n'), ((2971, 2999), 'datetime.datetime.min.time', 'datetime.datetime.min.time', ([], {}), '()\n', (2997, 2999), False, 'import datetime\n'), ((4073, 4107), 'datetime.timedelta', 'datetime.timedelta', ([], {}), '(**{unit: _val})\n', (4091, 4107), False, 'import datetime\n'), ((4996, 5030), 'datetime.timedelta', 'datetime.timedelta', ([], {}), '(**{unit: _val})\n', (5014, 5030), False, 'import datetime\n')]
from pyml.tree.regression import DecisionTreeRegressor from pyml.metrics.pairwise import euclidean_distance import numpy as np # TODO: 使用平方误差,还是绝对值误差,还是Huber Loss class GradientBoostingRegression(): def __init__(self, learning_rate=0.1, base_estimator=DecisionTreeRegressor, n_estimators=500, random_state=None ): self.estimators = [] self.n_estimators = n_estimators self.base_estimator = base_estimator self.learning_rate = learning_rate self.parameters = { 'f' : [], 'lr' : [] } # key='f' : a list of estimator # key='lr' : a list of learning_rate def optimizer(self, X, Y, watch=False): """ 训练一次 """ cur_Y_pred = self.predict(X) # print('cur_Y_pred : ', cur_Y_pred) # 计算cost cost = euclidean_distance(cur_Y_pred, Y) # 计算残差 or 计算梯度 d_fx = cur_Y_pred - Y # print('d_fx : ', d_fx) # 梯度取负数 d_fx = - d_fx # 计算学习率,这里默认为初始化参数 lr = self.learning_rate # 创建一个新回归器,去拟合梯度 new_estimator = self.base_estimator() new_estimator.fit(X,d_fx) self.parameters['f'].append(new_estimator) self.parameters['lr'].append(lr) return cost def fit(self, X, Y, watch=False): init_estimator = self.base_estimator() init_estimator.fit(X,Y) self.parameters['f'].append(init_estimator) self.parameters['lr'].append(1) for i in range(self.n_estimators): cost = self.optimizer(X,Y) if i % 10 == 0: print('train {}/{} current cost : {}'.format(i,self.n_estimators,cost)) def predict(self, X_pred): """ Parameters ------------- X_pred : 2d array-like shape(n_samples, n_feature) Returns -------------- pre_Y : 1d array-like shape(n_samples,) """ # the number of features should be consistent. total_num = X_pred.shape[0] Y_pred = np.zeros((total_num)) for cur_estimator, lr in zip(self.parameters['f'], self.parameters['lr']): Y_pred += cur_estimator.predict(X_pred) * lr return Y_pred if __name__ == '__main__': mini_train_X = np.array([ [1,2,3,4,5,6,7,8], [2,3,4,5,6,7,8,9], [3,4,5,6,7,8,9,10], [4,5,6,7,8,9,10,11], [5,6,7,8,9,10,11,12], [6,7,8,9,10,11,12,13], [7,8,9,10,11,12,13,14] ]) mini_train_Y = np.array([ 1.5,2.5,3.5,4.5,5.5,6.5,7.5 ]) mini_test_X = np.array([ [2,3,4,5,6,7.5,8,9], [4,5,6,7.5,8,9,10,11] ]) mini_standard_out_Y = np.array([ 2.5,4.5 ]) rgs = GradientBoostingRegression() rgs.fit(mini_train_X,mini_train_Y) print(rgs.predict(mini_test_X))
[ "numpy.zeros", "pyml.metrics.pairwise.euclidean_distance", "numpy.array" ]
[((2317, 2533), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 9], [3, 4, 5, 6, 7, 8, 9, \n 10], [4, 5, 6, 7, 8, 9, 10, 11], [5, 6, 7, 8, 9, 10, 11, 12], [6, 7, 8,\n 9, 10, 11, 12, 13], [7, 8, 9, 10, 11, 12, 13, 14]]'], {}), '([[1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 9], [3, 4, 5, 6, \n 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10, 11], [5, 6, 7, 8, 9, 10, 11, 12],\n [6, 7, 8, 9, 10, 11, 12, 13], [7, 8, 9, 10, 11, 12, 13, 14]])\n', (2325, 2533), True, 'import numpy as np\n'), ((2557, 2602), 'numpy.array', 'np.array', (['[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]'], {}), '([1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5])\n', (2565, 2602), True, 'import numpy as np\n'), ((2629, 2697), 'numpy.array', 'np.array', (['[[2, 3, 4, 5, 6, 7.5, 8, 9], [4, 5, 6, 7.5, 8, 9, 10, 11]]'], {}), '([[2, 3, 4, 5, 6, 7.5, 8, 9], [4, 5, 6, 7.5, 8, 9, 10, 11]])\n', (2637, 2697), True, 'import numpy as np\n'), ((2732, 2752), 'numpy.array', 'np.array', (['[2.5, 4.5]'], {}), '([2.5, 4.5])\n', (2740, 2752), True, 'import numpy as np\n'), ((877, 910), 'pyml.metrics.pairwise.euclidean_distance', 'euclidean_distance', (['cur_Y_pred', 'Y'], {}), '(cur_Y_pred, Y)\n', (895, 910), False, 'from pyml.metrics.pairwise import euclidean_distance\n'), ((2086, 2105), 'numpy.zeros', 'np.zeros', (['total_num'], {}), '(total_num)\n', (2094, 2105), True, 'import numpy as np\n')]
class TestSet5: def test_challenge33(self): from cryptopals.set5.challenge33 import challenge33 assert challenge33(), "The result does not match the expected value" def test_challenge34(self): from cryptopals.set5.challenge34 import challenge34 assert challenge34(), "The result does not match the expected value" def test_challenge35(self): from cryptopals.set5.challenge35 import challenge35 assert challenge35(), "The result does not match the expected value"
[ "cryptopals.set5.challenge34.challenge34", "cryptopals.set5.challenge33.challenge33", "cryptopals.set5.challenge35.challenge35" ]
[((124, 137), 'cryptopals.set5.challenge33.challenge33', 'challenge33', ([], {}), '()\n', (135, 137), False, 'from cryptopals.set5.challenge33 import challenge33\n'), ((295, 308), 'cryptopals.set5.challenge34.challenge34', 'challenge34', ([], {}), '()\n', (306, 308), False, 'from cryptopals.set5.challenge34 import challenge34\n'), ((466, 479), 'cryptopals.set5.challenge35.challenge35', 'challenge35', ([], {}), '()\n', (477, 479), False, 'from cryptopals.set5.challenge35 import challenge35\n')]
from pymarkauth import MarkDown with MarkDown('../README.md') as doc: sec = doc.section("PyMarkAuth") sec.paragraphs( 'With PyMarkAuth you can author markdown code simply from python code.' ' To view the source code that generated this readme, take a look at the examples directory!', ) subsec = sec.section("Here's a list of features") subsec.unordered_list([ 'lines and paragraphs', 'nested sections', 'text styling', 'links and images', 'nested ordered lists and unordered lists', 'code blocks', doc.italics('future features:'), doc.ordered_list([ 'Tables', 'List of emojies (github specific)', 'programming language enum' ]) ]) sec.text('Heres some code:') sec.code( 'for x in range(10):', ' print(f"Hello, World! {x}")', language='python' ) subsec = sec.section('You can also add images and links') subsec.image(source='logo/logo.svg') subsec.newline() subsec.text('You can go to python.org from ') subsec.link(target='https://python.org', display_text='here.')
[ "pymarkauth.MarkDown" ]
[((38, 62), 'pymarkauth.MarkDown', 'MarkDown', (['"""../README.md"""'], {}), "('../README.md')\n", (46, 62), False, 'from pymarkauth import MarkDown\n')]
#!/usr/bin/python3 # -*- coding: utf-8 -*- ############################################################################# # Copyright (c): 2021, Huawei Tech. Co., Ltd. # FileName : agent_collect.py # Version : # Date : 2021-4-7 # Description : Receives and stores agent data. ############################################################################# try: import sys import os from flask import request, Response from flask_restful import Resource sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../")) from common.logger import CreateLogger from service.datafactory.storage.insert_data_to_database import SaveData except ImportError as err: sys.exit("agent_collect.py: Failed to import module: %s." % str(err)) LOGGER = CreateLogger("debug", "server.log").create_log() class ResponseTuple: """ This class is used for generating a response tuple. """ @staticmethod def success(result=None): if result is None: return {"status": "success"}, 200 return {"status": "success", "result": result} @staticmethod def error(msg="", status_code=400): return {"status": "error", "msg": msg}, status_code class Source(Resource): """ This class is used for acquiring metric data from agent and save data in sqlite database. """ def __init__(self): pass @staticmethod def post(): content = request.json client_ip = request.remote_addr LOGGER.info("Successfully received request from: %s." % client_ip) try: insert_db = SaveData(LOGGER) insert_db.run(content) return ResponseTuple.success() except Exception as e: return ResponseTuple.error(msg=str(e), status_code=Response.status_code) @staticmethod def get(): return ResponseTuple.success(result="Server service is normal.") @staticmethod def delete(): return ResponseTuple.error(status_code=400)
[ "common.logger.CreateLogger", "os.path.dirname", "service.datafactory.storage.insert_data_to_database.SaveData" ]
[((794, 829), 'common.logger.CreateLogger', 'CreateLogger', (['"""debug"""', '"""server.log"""'], {}), "('debug', 'server.log')\n", (806, 829), False, 'from common.logger import CreateLogger\n'), ((522, 547), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (537, 547), False, 'import os\n'), ((1631, 1647), 'service.datafactory.storage.insert_data_to_database.SaveData', 'SaveData', (['LOGGER'], {}), '(LOGGER)\n', (1639, 1647), False, 'from service.datafactory.storage.insert_data_to_database import SaveData\n')]
from selenium import webdriver from realtimekeyword import getNaverRealtimekeyword import time from bs4 import BeautifulSoup class TistoryPostingBot: def __init__(self,driver, dir, id,password): self.id = id self.dir =dir self.password = password self.driver = driver return def login(self): dir = self.dir + '/manage' driver = self.driver driver.get(dir) driver.find_element_by_id("loginId").send_keys(self.id) driver.find_element_by_id("loginPw").send_keys(self.password) driver.find_element_by_class_name("btn_login").click() return True def writePost(self, title, text ,istag =False): dir = self.dir + '/admin/entry/post/' driver = self.driver driver.get(dir) driver.find_element_by_id("titleBox").send_keys(title) if istag == False: driver.switch_to_frame(driver.find_element_by_id("tx_canvas_wysiwyg")) driver.find_element_by_class_name("tx-content-container").send_keys((text)) driver.switch_to_default_content() else: driver.find_element_by_id("tx_switchertoggle").click() for t in text: driver.find_element_by_id("tx_canvas_source").send_keys((t)) time.sleep(2) #post btn driver.find_element_by_xpath("//*[@id=\"tistoryFoot\"]/div/button[3]").click() #popup close window_after = driver.window_handles[1] driver.switch_to_window(window_after) driver.find_element_by_id("btnSubmit").click()
[ "time.sleep" ]
[((1323, 1336), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1333, 1336), False, 'import time\n')]
#form.py from flask_wtf import FlaskForm from wtforms import StringField , PasswordField , SubmitField , BooleanField #導入用途是為了建立表單 from wtforms.validators import DataRequired, Length , Email , EqualTo , ValidationError #導入用途是為了建立表單 ValidationError是檢視重複輸入 from app.models import User class RegisterForm(FlaskForm): username = StringField('Username', validators = [DataRequired(), Length(min = 6 , max = 20)])#監控用長度監控 password = PasswordField('Password', validators = [DataRequired(), Length(min = 8 , max = 20)])#監控用長度監控 confirm = PasswordField('Repeat Password', validators = [DataRequired(), EqualTo('password')])#監控相等於密碼監控 email = StringField('E-MAIL', validators = [DataRequired(), Email()])#監控用EMAIL submit = SubmitField('Register') def validate_username(self, username): #導入用途是為了建立表單 ValidationError是檢視重複輸入 user = User.query.filter_by(username = username.data).first() if user: raise ValidationError('Username already token') def validate_email(self, email): mail = User.query.filter_by(email = email.data).first() if mail: raise ValidationError('email already token') class LoginForm(FlaskForm): username = StringField('Username', validators = [DataRequired(), Length(min = 6 , max = 20)])#監控用長度監控 password = PasswordField('Password', validators = [DataRequired(), Length(min = 8 , max = 20)])#監控用長度監控 remember = BooleanField('Remember') submit = SubmitField('sign in') class PasswordResetRequestForm(FlaskForm): email = StringField('E-MAIL', validators = [DataRequired(), Email()]) submit = SubmitField('sent') def validate_email(self, email): mail = User.query.filter_by(email = email.data).first() if not email: raise ValidationError('email does not exsit')
[ "wtforms.validators.Length", "wtforms.validators.Email", "wtforms.BooleanField", "wtforms.SubmitField", "app.models.User.query.filter_by", "wtforms.validators.EqualTo", "wtforms.validators.DataRequired", "wtforms.validators.ValidationError" ]
[((755, 778), 'wtforms.SubmitField', 'SubmitField', (['"""Register"""'], {}), "('Register')\n", (766, 778), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1465, 1489), 'wtforms.BooleanField', 'BooleanField', (['"""Remember"""'], {}), "('Remember')\n", (1477, 1489), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1504, 1526), 'wtforms.SubmitField', 'SubmitField', (['"""sign in"""'], {}), "('sign in')\n", (1515, 1526), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1668, 1687), 'wtforms.SubmitField', 'SubmitField', (['"""sent"""'], {}), "('sent')\n", (1679, 1687), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((971, 1012), 'wtforms.validators.ValidationError', 'ValidationError', (['"""Username already token"""'], {}), "('Username already token')\n", (986, 1012), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((1157, 1195), 'wtforms.validators.ValidationError', 'ValidationError', (['"""email already token"""'], {}), "('email already token')\n", (1172, 1195), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((1833, 1872), 'wtforms.validators.ValidationError', 'ValidationError', (['"""email does not exsit"""'], {}), "('email does not exsit')\n", (1848, 1872), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((385, 399), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (397, 399), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((401, 422), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(20)'}), '(min=6, max=20)\n', (407, 422), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((494, 508), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (506, 508), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((510, 531), 'wtforms.validators.Length', 'Length', ([], {'min': '(8)', 'max': '(20)'}), '(min=8, max=20)\n', (516, 531), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((609, 623), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (621, 623), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((625, 644), 'wtforms.validators.EqualTo', 'EqualTo', (['"""password"""'], {}), "('password')\n", (632, 644), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((706, 720), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (718, 720), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((722, 729), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (727, 729), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((879, 923), 'app.models.User.query.filter_by', 'User.query.filter_by', ([], {'username': 'username.data'}), '(username=username.data)\n', (899, 923), False, 'from app.models import User\n'), ((1071, 1109), 'app.models.User.query.filter_by', 'User.query.filter_by', ([], {'email': 'email.data'}), '(email=email.data)\n', (1091, 1109), False, 'from app.models import User\n'), ((1287, 1301), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1299, 1301), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((1303, 1324), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(20)'}), '(min=6, max=20)\n', (1309, 1324), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((1396, 1410), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1408, 1410), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((1412, 1433), 'wtforms.validators.Length', 'Length', ([], {'min': '(8)', 'max': '(20)'}), '(min=8, max=20)\n', (1418, 1433), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((1628, 1642), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1640, 1642), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((1644, 1651), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (1649, 1651), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError\n'), ((1742, 1780), 'app.models.User.query.filter_by', 'User.query.filter_by', ([], {'email': 'email.data'}), '(email=email.data)\n', (1762, 1780), False, 'from app.models import User\n')]
# was stanza.models.pos.model import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence, pack_sequence, PackedSequence from biaffine import BiaffineScorer from hlstm import HighwayLSTM from dropout import WordDropout from char_model import CharacterModel class Tagger(nn.Module): def __init__(self, args, vocab, emb_matrix=None): super().__init__() self.vocab = vocab self.args = args self.use_pretrained = emb_matrix is not None self.use_char = args['char_emb_dim'] > 0 self.use_word = args['word_emb_dim'] > 0 self.share_hid = args['pos_emb_dim'] < 1 self.unsaved_modules = [] def add_unsaved_module(name, module): self.unsaved_modules += [name] setattr(self, name, module) # input layers input_size = 0 if self.use_word: # frequent word embeddings self.word_emb = nn.Embedding(len(vocab['word']), self.args['word_emb_dim'], padding_idx=0) input_size += self.args['word_emb_dim'] if not self.share_hid: # pos embeddings self.pos_emb = nn.Embedding(len(vocab['pos']), self.args['pos_emb_dim'], padding_idx=0) if self.use_char: self.charmodel = CharacterModel(args, vocab, bidirectional=args['char_bidir']) self.trans_char = nn.Linear(self.charmodel.num_dir * self.args['char_hidden_dim'], self.args['transformed_dim'], bias=False) input_size += self.args['transformed_dim'] if self.use_pretrained: # pretrained embeddings, by default this won't be saved into model file add_unsaved_module('pretrained_emb', nn.Embedding.from_pretrained(torch.from_numpy(emb_matrix), freeze=True)) self.trans_pretrained = nn.Linear(emb_matrix.shape[1], self.args['transformed_dim'], bias=False) input_size += self.args['transformed_dim'] # recurrent layers self.taggerlstm = HighwayLSTM(input_size, self.args['tag_hidden_dim'], self.args['tag_num_layers'], batch_first=True, bidirectional=True, dropout=self.args['dropout'], rec_dropout=self.args['tag_rec_dropout'], highway_func=torch.tanh) self.drop_replacement = nn.Parameter(torch.randn(input_size) / np.sqrt(input_size)) self.taggerlstm_h_init = nn.Parameter(torch.zeros(2 * self.args['tag_num_layers'], 1, self.args['tag_hidden_dim'])) self.taggerlstm_c_init = nn.Parameter(torch.zeros(2 * self.args['tag_num_layers'], 1, self.args['tag_hidden_dim'])) # classifiers self.pos_hid = nn.Linear(self.args['tag_hidden_dim'] * 2, self.args['deep_biaff_hidden_dim']) self.pos_clf = nn.Linear(self.args['deep_biaff_hidden_dim'], len(vocab['pos'])) self.pos_clf.weight.data.zero_() self.pos_clf.bias.data.zero_() if self.share_hid: clf_constructor = lambda insize, outsize: nn.Linear(insize, outsize) else: self.feats_hid = nn.Linear(self.args['tag_hidden_dim'] * 2, self.args['composite_deep_biaff_hidden_dim']) clf_constructor = lambda insize, outsize: BiaffineScorer(insize, self.args['pos_emb_dim'], outsize) self.feats_clf = nn.ModuleList() for l in vocab['feats'].lens(): if self.share_hid: self.feats_clf.append(clf_constructor(self.args['deep_biaff_hidden_dim'], l)) self.feats_clf[-1].weight.data.zero_() self.feats_clf[-1].bias.data.zero_() else: self.feats_clf.append(clf_constructor(self.args['composite_deep_biaff_hidden_dim'], l)) # criterion self.crit = nn.CrossEntropyLoss(ignore_index=0) # ignore padding self.drop = nn.Dropout(args['dropout']) self.worddrop = WordDropout(args['word_dropout']) def forward(self, word, word_mask, wordchars, wordchars_mask, pos, feats, pretrained, word_orig_idx, sentlens, wordlens): def pack(x): return pack_padded_sequence(x, sentlens, batch_first=True) def get_batch_sizes(sentlens): b = [] for i in range(max(sentlens)): c = len([x for x in sentlens if x > i]) b.append(c) return torch.tensor(b) def pad(x): return pad_packed_sequence(PackedSequence(x, batch_sizes), batch_first=True)[0] inputs = [] if self.use_word: word_emb = self.word_emb(word) word_emb = pack(word_emb) inputs += [word_emb] batch_sizes = word_emb.batch_sizes else: batch_sizes = get_batch_sizes(sentlens) if self.use_pretrained: pretrained_emb = self.pretrained_emb(pretrained) pretrained_emb = self.trans_pretrained(pretrained_emb) pretrained_emb = pack(pretrained_emb) inputs += [pretrained_emb] if self.use_char: char_reps = self.charmodel(wordchars, wordchars_mask, word_orig_idx, sentlens, wordlens) char_reps = PackedSequence(self.trans_char(self.drop(char_reps.data)), char_reps.batch_sizes) inputs += [char_reps] lstm_inputs = torch.cat([x.data for x in inputs], 1) lstm_inputs = self.worddrop(lstm_inputs, self.drop_replacement) lstm_inputs = self.drop(lstm_inputs) lstm_inputs = PackedSequence(lstm_inputs, inputs[0].batch_sizes) lstm_outputs, _ = self.taggerlstm(lstm_inputs, sentlens, hx=(self.taggerlstm_h_init.expand(2 * self.args['tag_num_layers'], word.size(0), self.args['tag_hidden_dim']).contiguous(), self.taggerlstm_c_init.expand(2 * self.args['tag_num_layers'], word.size(0), self.args['tag_hidden_dim']).contiguous())) lstm_outputs = lstm_outputs.data pos_hid = F.relu(self.pos_hid(self.drop(lstm_outputs))) pos_pred = self.pos_clf(self.drop(pos_hid)) preds = [pad(pos_pred).max(2)[1]] pos = pack(pos).data loss = self.crit(pos_pred.view(-1, pos_pred.size(-1)), pos.view(-1)) if self.share_hid: feats_hid = pos_hid clffunc = lambda clf, hid: clf(self.drop(hid)) else: feats_hid = F.relu(self.feats_hid(self.drop(lstm_outputs))) # TODO: self.training is never set, but check if this is a bug #if self.training: pos_emb = self.pos_emb(pos) else: pos_emb = self.pos_emb(pos_pred.max(1)[1]) clffunc = lambda clf, hid: clf(self.drop(hid), self.drop(pos_emb)) feats_preds = [] feats = pack(feats).data for i in range(len(self.vocab['feats'])): feats_pred = clffunc(self.feats_clf[i], feats_hid) loss += self.crit(feats_pred.view(-1, feats_pred.size(-1)), feats[:, i].view(-1)) feats_preds.append(pad(feats_pred).max(2, keepdim=True)[1]) preds.append(torch.cat(feats_preds, 2)) return loss, preds if __name__ == "__main__": print("This file cannot be used on its own.") print("To launch the tagger, use tagger.py instead of model.py")
[ "torch.nn.Dropout", "torch.nn.utils.rnn.pack_padded_sequence", "torch.from_numpy", "biaffine.BiaffineScorer", "torch.nn.ModuleList", "dropout.WordDropout", "torch.nn.CrossEntropyLoss", "torch.cat", "torch.nn.utils.rnn.PackedSequence", "torch.zeros", "torch.randn", "torch.nn.Linear", "hlstm.HighwayLSTM", "numpy.sqrt", "torch.tensor", "char_model.CharacterModel" ]
[((2077, 2308), 'hlstm.HighwayLSTM', 'HighwayLSTM', (['input_size', "self.args['tag_hidden_dim']", "self.args['tag_num_layers']"], {'batch_first': '(True)', 'bidirectional': '(True)', 'dropout': "self.args['dropout']", 'rec_dropout': "self.args['tag_rec_dropout']", 'highway_func': 'torch.tanh'}), "(input_size, self.args['tag_hidden_dim'], self.args[\n 'tag_num_layers'], batch_first=True, bidirectional=True, dropout=self.\n args['dropout'], rec_dropout=self.args['tag_rec_dropout'], highway_func\n =torch.tanh)\n", (2088, 2308), False, 'from hlstm import HighwayLSTM\n'), ((2680, 2758), 'torch.nn.Linear', 'nn.Linear', (["(self.args['tag_hidden_dim'] * 2)", "self.args['deep_biaff_hidden_dim']"], {}), "(self.args['tag_hidden_dim'] * 2, self.args['deep_biaff_hidden_dim'])\n", (2689, 2758), True, 'import torch.nn as nn\n'), ((3306, 3321), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (3319, 3321), True, 'import torch.nn as nn\n'), ((3758, 3793), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'ignore_index': '(0)'}), '(ignore_index=0)\n', (3777, 3793), True, 'import torch.nn as nn\n'), ((3831, 3858), 'torch.nn.Dropout', 'nn.Dropout', (["args['dropout']"], {}), "(args['dropout'])\n", (3841, 3858), True, 'import torch.nn as nn\n'), ((3883, 3916), 'dropout.WordDropout', 'WordDropout', (["args['word_dropout']"], {}), "(args['word_dropout'])\n", (3894, 3916), False, 'from dropout import WordDropout\n'), ((5286, 5324), 'torch.cat', 'torch.cat', (['[x.data for x in inputs]', '(1)'], {}), '([x.data for x in inputs], 1)\n', (5295, 5324), False, 'import torch\n'), ((5464, 5514), 'torch.nn.utils.rnn.PackedSequence', 'PackedSequence', (['lstm_inputs', 'inputs[0].batch_sizes'], {}), '(lstm_inputs, inputs[0].batch_sizes)\n', (5478, 5514), False, 'from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence, pack_sequence, PackedSequence\n'), ((1366, 1427), 'char_model.CharacterModel', 'CharacterModel', (['args', 'vocab'], {'bidirectional': "args['char_bidir']"}), "(args, vocab, bidirectional=args['char_bidir'])\n", (1380, 1427), False, 'from char_model import CharacterModel\n'), ((1458, 1569), 'torch.nn.Linear', 'nn.Linear', (["(self.charmodel.num_dir * self.args['char_hidden_dim'])", "self.args['transformed_dim']"], {'bias': '(False)'}), "(self.charmodel.num_dir * self.args['char_hidden_dim'], self.args[\n 'transformed_dim'], bias=False)\n", (1467, 1569), True, 'import torch.nn as nn\n'), ((1895, 1967), 'torch.nn.Linear', 'nn.Linear', (['emb_matrix.shape[1]', "self.args['transformed_dim']"], {'bias': '(False)'}), "(emb_matrix.shape[1], self.args['transformed_dim'], bias=False)\n", (1904, 1967), True, 'import torch.nn as nn\n'), ((2432, 2508), 'torch.zeros', 'torch.zeros', (["(2 * self.args['tag_num_layers'])", '(1)', "self.args['tag_hidden_dim']"], {}), "(2 * self.args['tag_num_layers'], 1, self.args['tag_hidden_dim'])\n", (2443, 2508), False, 'import torch\n'), ((2556, 2632), 'torch.zeros', 'torch.zeros', (["(2 * self.args['tag_num_layers'])", '(1)', "self.args['tag_hidden_dim']"], {}), "(2 * self.args['tag_num_layers'], 1, self.args['tag_hidden_dim'])\n", (2567, 2632), False, 'import torch\n'), ((3079, 3172), 'torch.nn.Linear', 'nn.Linear', (["(self.args['tag_hidden_dim'] * 2)", "self.args['composite_deep_biaff_hidden_dim']"], {}), "(self.args['tag_hidden_dim'] * 2, self.args[\n 'composite_deep_biaff_hidden_dim'])\n", (3088, 3172), True, 'import torch.nn as nn\n'), ((4085, 4136), 'torch.nn.utils.rnn.pack_padded_sequence', 'pack_padded_sequence', (['x', 'sentlens'], {'batch_first': '(True)'}), '(x, sentlens, batch_first=True)\n', (4105, 4136), False, 'from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence, pack_sequence, PackedSequence\n'), ((4342, 4357), 'torch.tensor', 'torch.tensor', (['b'], {}), '(b)\n', (4354, 4357), False, 'import torch\n'), ((6972, 6997), 'torch.cat', 'torch.cat', (['feats_preds', '(2)'], {}), '(feats_preds, 2)\n', (6981, 6997), False, 'import torch\n'), ((2339, 2362), 'torch.randn', 'torch.randn', (['input_size'], {}), '(input_size)\n', (2350, 2362), False, 'import torch\n'), ((2365, 2384), 'numpy.sqrt', 'np.sqrt', (['input_size'], {}), '(input_size)\n', (2372, 2384), True, 'import numpy as np\n'), ((3009, 3035), 'torch.nn.Linear', 'nn.Linear', (['insize', 'outsize'], {}), '(insize, outsize)\n', (3018, 3035), True, 'import torch.nn as nn\n'), ((3222, 3279), 'biaffine.BiaffineScorer', 'BiaffineScorer', (['insize', "self.args['pos_emb_dim']", 'outsize'], {}), "(insize, self.args['pos_emb_dim'], outsize)\n", (3236, 3279), False, 'from biaffine import BiaffineScorer\n'), ((1815, 1843), 'torch.from_numpy', 'torch.from_numpy', (['emb_matrix'], {}), '(emb_matrix)\n', (1831, 1843), False, 'import torch\n'), ((4418, 4448), 'torch.nn.utils.rnn.PackedSequence', 'PackedSequence', (['x', 'batch_sizes'], {}), '(x, batch_sizes)\n', (4432, 4448), False, 'from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence, pack_sequence, PackedSequence\n')]
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from heat.common import exception from heat.common.i18n import _ from heat.engine import attributes from heat.engine import constraints from heat.engine import properties from heat.engine import resource from heat.engine import support class Order(resource.Resource): support_status = support.SupportStatus(version='2014.2') default_client_name = 'barbican' entity = 'orders' PROPERTIES = ( NAME, PAYLOAD_CONTENT_TYPE, MODE, EXPIRATION, ALGORITHM, BIT_LENGTH, TYPE, REQUEST_TYPE, SUBJECT_DN, SOURCE_CONTAINER_REF, CA_ID, PROFILE, REQUEST_DATA, PASS_PHRASE ) = ( 'name', 'payload_content_type', 'mode', 'expiration', 'algorithm', 'bit_length', 'type', 'request_type', 'subject_dn', 'source_container_ref', 'ca_id', 'profile', 'request_data', 'pass_phrase' ) ATTRIBUTES = ( STATUS, ORDER_REF, SECRET_REF, PUBLIC_KEY, PRIVATE_KEY, CERTIFICATE, INTERMEDIATES, CONTAINER_REF ) = ( 'status', 'order_ref', 'secret_ref', 'public_key', 'private_key', 'certificate', 'intermediates', 'container_ref' ) properties_schema = { NAME: properties.Schema( properties.Schema.STRING, _('Human readable name for the secret.'), ), PAYLOAD_CONTENT_TYPE: properties.Schema( properties.Schema.STRING, _('The type/format the secret data is provided in.'), ), EXPIRATION: properties.Schema( properties.Schema.STRING, _('The expiration date for the secret in ISO-8601 format.'), constraints=[ constraints.CustomConstraint('iso_8601'), ], ), ALGORITHM: properties.Schema( properties.Schema.STRING, _('The algorithm type used to generate the secret.'), ), BIT_LENGTH: properties.Schema( properties.Schema.INTEGER, _('The bit-length of the secret.'), ), MODE: properties.Schema( properties.Schema.STRING, _('The type/mode of the algorithm associated with the secret ' 'information.'), ), TYPE: properties.Schema( properties.Schema.STRING, _('The type of the order.'), constraints=[ constraints.AllowedValues([ 'key', 'asymmetric', 'certificate' ]), ], required=True, support_status=support.SupportStatus(version='5.0.0'), ), REQUEST_TYPE: properties.Schema( properties.Schema.STRING, _('The type of the certificate request.'), support_status=support.SupportStatus(version='5.0.0'), ), SUBJECT_DN: properties.Schema( properties.Schema.STRING, _('The subject of the certificate request.'), support_status=support.SupportStatus(version='5.0.0'), ), SOURCE_CONTAINER_REF: properties.Schema( properties.Schema.STRING, _('The source of certificate request.'), support_status=support.SupportStatus(version='5.0.0'), ), CA_ID: properties.Schema( properties.Schema.STRING, _('The identifier of the CA to use.'), support_status=support.SupportStatus(version='5.0.0'), ), PROFILE: properties.Schema( properties.Schema.STRING, _('The profile of certificate to use.'), support_status=support.SupportStatus(version='5.0.0'), ), REQUEST_DATA: properties.Schema( properties.Schema.STRING, _('The content of the CSR.'), support_status=support.SupportStatus(version='5.0.0'), ), PASS_PHRASE: properties.Schema( properties.Schema.STRING, _('The passphrase the created key.'), support_status=support.SupportStatus(version='5.0.0'), ), } attributes_schema = { STATUS: attributes.Schema( _('The status of the order.'), type=attributes.Schema.STRING ), ORDER_REF: attributes.Schema( _('The URI to the order.'), type=attributes.Schema.STRING ), SECRET_REF: attributes.Schema( _('The URI to the created secret.'), type=attributes.Schema.STRING ), CONTAINER_REF: attributes.Schema( _('The URI to the created container.'), support_status=support.SupportStatus(version='5.0.0'), type=attributes.Schema.STRING ), PUBLIC_KEY: attributes.Schema( _('The payload of the created public key, if available.'), support_status=support.SupportStatus(version='5.0.0'), type=attributes.Schema.STRING ), PRIVATE_KEY: attributes.Schema( _('The payload of the created private key, if available.'), support_status=support.SupportStatus(version='5.0.0'), type=attributes.Schema.STRING ), CERTIFICATE: attributes.Schema( _('The payload of the created certificate, if available.'), support_status=support.SupportStatus(version='5.0.0'), type=attributes.Schema.STRING ), INTERMEDIATES: attributes.Schema( _('The payload of the created intermediates, if available.'), support_status=support.SupportStatus(version='5.0.0'), type=attributes.Schema.STRING ), } def handle_create(self): info = dict((k, v) for k, v in self.properties.items() if v is not None) order = self.client().orders.create(**info) order_ref = order.submit() self.resource_id_set(order_ref) # NOTE(pshchelo): order_ref is HATEOAS reference, i.e a string # need not to be fixed re LP bug #1393268 return order_ref def check_create_complete(self, order_href): order = self.client().orders.get(order_href) if order.status == 'ERROR': reason = order.error_reason code = order.error_status_code msg = (_("Order '%(name)s' failed: %(code)s - %(reason)s") % {'name': self.name, 'code': code, 'reason': reason}) raise exception.Error(msg) return order.status == 'ACTIVE' def _resolve_attribute(self, name): client = self.client() order = client.orders.get(self.resource_id) if name in ( self.PUBLIC_KEY, self.PRIVATE_KEY, self.CERTIFICATE, self.INTERMEDIATES): container = client.containers.get(order.container_ref) secret = getattr(container, name) return secret.payload return getattr(order, name) # TODO(ochuprykov): remove this method when bug #1485619 will be fixed def _show_resource(self): order = self.client().orders.get(self.resource_id) info = order._get_formatted_entity() return dict(zip(info[0], info[1])) def resource_mapping(): return { 'OS::Barbican::Order': Order, }
[ "heat.engine.constraints.AllowedValues", "heat.engine.constraints.CustomConstraint", "heat.engine.support.SupportStatus", "heat.common.i18n._", "heat.common.exception.Error" ]
[((867, 906), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""2014.2"""'}), "(version='2014.2')\n", (888, 906), False, 'from heat.engine import support\n'), ((1816, 1856), 'heat.common.i18n._', '_', (['"""Human readable name for the secret."""'], {}), "('Human readable name for the secret.')\n", (1817, 1856), False, 'from heat.common.i18n import _\n'), ((1968, 2020), 'heat.common.i18n._', '_', (['"""The type/format the secret data is provided in."""'], {}), "('The type/format the secret data is provided in.')\n", (1969, 2020), False, 'from heat.common.i18n import _\n'), ((2122, 2181), 'heat.common.i18n._', '_', (['"""The expiration date for the secret in ISO-8601 format."""'], {}), "('The expiration date for the secret in ISO-8601 format.')\n", (2123, 2181), False, 'from heat.common.i18n import _\n'), ((2381, 2433), 'heat.common.i18n._', '_', (['"""The algorithm type used to generate the secret."""'], {}), "('The algorithm type used to generate the secret.')\n", (2382, 2433), False, 'from heat.common.i18n import _\n'), ((2536, 2570), 'heat.common.i18n._', '_', (['"""The bit-length of the secret."""'], {}), "('The bit-length of the secret.')\n", (2537, 2570), False, 'from heat.common.i18n import _\n'), ((2666, 2741), 'heat.common.i18n._', '_', (['"""The type/mode of the algorithm associated with the secret information."""'], {}), "('The type/mode of the algorithm associated with the secret information.')\n", (2667, 2741), False, 'from heat.common.i18n import _\n'), ((2854, 2881), 'heat.common.i18n._', '_', (['"""The type of the order."""'], {}), "('The type of the order.')\n", (2855, 2881), False, 'from heat.common.i18n import _\n'), ((3239, 3280), 'heat.common.i18n._', '_', (['"""The type of the certificate request."""'], {}), "('The type of the certificate request.')\n", (3240, 3280), False, 'from heat.common.i18n import _\n'), ((3449, 3493), 'heat.common.i18n._', '_', (['"""The subject of the certificate request."""'], {}), "('The subject of the certificate request.')\n", (3450, 3493), False, 'from heat.common.i18n import _\n'), ((3672, 3711), 'heat.common.i18n._', '_', (['"""The source of certificate request."""'], {}), "('The source of certificate request.')\n", (3673, 3711), False, 'from heat.common.i18n import _\n'), ((3875, 3912), 'heat.common.i18n._', '_', (['"""The identifier of the CA to use."""'], {}), "('The identifier of the CA to use.')\n", (3876, 3912), False, 'from heat.common.i18n import _\n'), ((4078, 4117), 'heat.common.i18n._', '_', (['"""The profile of certificate to use."""'], {}), "('The profile of certificate to use.')\n", (4079, 4117), False, 'from heat.common.i18n import _\n'), ((4288, 4316), 'heat.common.i18n._', '_', (['"""The content of the CSR."""'], {}), "('The content of the CSR.')\n", (4289, 4316), False, 'from heat.common.i18n import _\n'), ((4486, 4522), 'heat.common.i18n._', '_', (['"""The passphrase the created key."""'], {}), "('The passphrase the created key.')\n", (4487, 4522), False, 'from heat.common.i18n import _\n'), ((4682, 4711), 'heat.common.i18n._', '_', (['"""The status of the order."""'], {}), "('The status of the order.')\n", (4683, 4711), False, 'from heat.common.i18n import _\n'), ((4816, 4842), 'heat.common.i18n._', '_', (['"""The URI to the order."""'], {}), "('The URI to the order.')\n", (4817, 4842), False, 'from heat.common.i18n import _\n'), ((4948, 4983), 'heat.common.i18n._', '_', (['"""The URI to the created secret."""'], {}), "('The URI to the created secret.')\n", (4949, 4983), False, 'from heat.common.i18n import _\n'), ((5092, 5130), 'heat.common.i18n._', '_', (['"""The URI to the created container."""'], {}), "('The URI to the created container.')\n", (5093, 5130), False, 'from heat.common.i18n import _\n'), ((5303, 5360), 'heat.common.i18n._', '_', (['"""The payload of the created public key, if available."""'], {}), "('The payload of the created public key, if available.')\n", (5304, 5360), False, 'from heat.common.i18n import _\n'), ((5534, 5592), 'heat.common.i18n._', '_', (['"""The payload of the created private key, if available."""'], {}), "('The payload of the created private key, if available.')\n", (5535, 5592), False, 'from heat.common.i18n import _\n'), ((5766, 5824), 'heat.common.i18n._', '_', (['"""The payload of the created certificate, if available."""'], {}), "('The payload of the created certificate, if available.')\n", (5767, 5824), False, 'from heat.common.i18n import _\n'), ((6000, 6060), 'heat.common.i18n._', '_', (['"""The payload of the created intermediates, if available."""'], {}), "('The payload of the created intermediates, if available.')\n", (6001, 6060), False, 'from heat.common.i18n import _\n'), ((6978, 6998), 'heat.common.exception.Error', 'exception.Error', (['msg'], {}), '(msg)\n', (6993, 6998), False, 'from heat.common import exception\n'), ((3097, 3135), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (3118, 3135), False, 'from heat.engine import support\n'), ((3309, 3347), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (3330, 3347), False, 'from heat.engine import support\n'), ((3522, 3560), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (3543, 3560), False, 'from heat.engine import support\n'), ((3740, 3778), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (3761, 3778), False, 'from heat.engine import support\n'), ((3941, 3979), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (3962, 3979), False, 'from heat.engine import support\n'), ((4146, 4184), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (4167, 4184), False, 'from heat.engine import support\n'), ((4345, 4383), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (4366, 4383), False, 'from heat.engine import support\n'), ((4551, 4589), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (4572, 4589), False, 'from heat.engine import support\n'), ((5159, 5197), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (5180, 5197), False, 'from heat.engine import support\n'), ((5389, 5427), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (5410, 5427), False, 'from heat.engine import support\n'), ((5621, 5659), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (5642, 5659), False, 'from heat.engine import support\n'), ((5853, 5891), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (5874, 5891), False, 'from heat.engine import support\n'), ((6089, 6127), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""5.0.0"""'}), "(version='5.0.0')\n", (6110, 6127), False, 'from heat.engine import support\n'), ((6834, 6885), 'heat.common.i18n._', '_', (['"""Order \'%(name)s\' failed: %(code)s - %(reason)s"""'], {}), '("Order \'%(name)s\' failed: %(code)s - %(reason)s")\n', (6835, 6885), False, 'from heat.common.i18n import _\n'), ((2225, 2265), 'heat.engine.constraints.CustomConstraint', 'constraints.CustomConstraint', (['"""iso_8601"""'], {}), "('iso_8601')\n", (2253, 2265), False, 'from heat.engine import constraints\n'), ((2925, 2988), 'heat.engine.constraints.AllowedValues', 'constraints.AllowedValues', (["['key', 'asymmetric', 'certificate']"], {}), "(['key', 'asymmetric', 'certificate'])\n", (2950, 2988), False, 'from heat.engine import constraints\n')]
import os import torch from zero.common.utils import CONFIG, get_gpu_memory_mb, print_log from torch.distributed import init_process_group def init_w_ps(builder): from patrickstar.runtime import initialize_engine config = CONFIG.copy() rank = int(os.environ['RANK']) world_size = int(os.environ['WORLD_SIZE']) host = os.environ['MASTER_ADDR'] port = int(os.environ['MASTER_PORT']) init_process_group(rank=rank, world_size=world_size, init_method=f'tcp://{host}:{port}', backend='nccl') torch.cuda.set_device(rank) if CONFIG.get('gpu_mem_fraction', None) is not None: torch.cuda.set_per_process_memory_fraction(CONFIG['gpu_mem_fraction']) print_log(f'Set max GPU mem: {get_gpu_memory_mb() * CONFIG["gpu_mem_fraction"]:.2f} MB') build_data, build_model, build_loss, _, build_scheduler = builder() train_data, test_data = build_data() criterion = build_loss() model, optimizer = initialize_engine(model_func=build_model, local_rank=rank, config=config) lr_scheduler = build_scheduler(len(train_data), optimizer) return model, train_data, test_data, criterion, optimizer, None, lr_scheduler
[ "zero.common.utils.CONFIG.get", "torch.cuda.set_per_process_memory_fraction", "torch.distributed.init_process_group", "patrickstar.runtime.initialize_engine", "torch.cuda.set_device", "zero.common.utils.get_gpu_memory_mb", "zero.common.utils.CONFIG.copy" ]
[((234, 247), 'zero.common.utils.CONFIG.copy', 'CONFIG.copy', ([], {}), '()\n', (245, 247), False, 'from zero.common.utils import CONFIG, get_gpu_memory_mb, print_log\n'), ((414, 523), 'torch.distributed.init_process_group', 'init_process_group', ([], {'rank': 'rank', 'world_size': 'world_size', 'init_method': 'f"""tcp://{host}:{port}"""', 'backend': '"""nccl"""'}), "(rank=rank, world_size=world_size, init_method=\n f'tcp://{host}:{port}', backend='nccl')\n", (432, 523), False, 'from torch.distributed import init_process_group\n'), ((524, 551), 'torch.cuda.set_device', 'torch.cuda.set_device', (['rank'], {}), '(rank)\n', (545, 551), False, 'import torch\n'), ((954, 1027), 'patrickstar.runtime.initialize_engine', 'initialize_engine', ([], {'model_func': 'build_model', 'local_rank': 'rank', 'config': 'config'}), '(model_func=build_model, local_rank=rank, config=config)\n', (971, 1027), False, 'from patrickstar.runtime import initialize_engine\n'), ((559, 595), 'zero.common.utils.CONFIG.get', 'CONFIG.get', (['"""gpu_mem_fraction"""', 'None'], {}), "('gpu_mem_fraction', None)\n", (569, 595), False, 'from zero.common.utils import CONFIG, get_gpu_memory_mb, print_log\n'), ((617, 687), 'torch.cuda.set_per_process_memory_fraction', 'torch.cuda.set_per_process_memory_fraction', (["CONFIG['gpu_mem_fraction']"], {}), "(CONFIG['gpu_mem_fraction'])\n", (659, 687), False, 'import torch\n'), ((726, 745), 'zero.common.utils.get_gpu_memory_mb', 'get_gpu_memory_mb', ([], {}), '()\n', (743, 745), False, 'from zero.common.utils import CONFIG, get_gpu_memory_mb, print_log\n')]
#!/usr/bin/env python import rospy import random import time import os from gazebo_msgs.srv import SpawnModel, DeleteModel from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Pose import pdb; class Respawn(): def __init__(self): self.modelPath = os.path.dirname(os.path.realpath(__file__)) + "/goal_square/goal_box/model.sdf" self.f = open(self.modelPath, 'r') self.model = self.f.read() self.stage = 2 self.goal_position = Pose() self.init_goal_x = 0.6 self.init_goal_y = 0.0 self.goal_position.position.x = self.init_goal_x self.goal_position.position.y = self.init_goal_y self.modelName = 'goal' self.obstacle_1 = -1.0, -1.0 self.obstacle_2 = -1.0, 1.0 self.obstacle_3 = 1.0, -1.0 self.obstacle_4 = 1.0, 1.0 self.human_1 = 1.74723, -1.88126 self.human_2 = -2.21807, 2.24004 self.last_goal_x = self.init_goal_x self.last_goal_y = self.init_goal_y self.last_index = 0 self.sub_model = rospy.Subscriber('gazebo/model_states', ModelStates, self.checkModel) self.check_model = False self.index = 0 def checkModel(self, model): self.check_model = False for i in range(len(model.name)): if model.name[i] == "goal": self.check_model = True def respawnModel(self): while True: if not self.check_model: rospy.wait_for_service('gazebo/spawn_sdf_model') spawn_model_prox = rospy.ServiceProxy('gazebo/spawn_sdf_model', SpawnModel) spawn_model_prox(self.modelName, self.model, 'robotos_name_space', self.goal_position, "world") rospy.loginfo("Goal position : %.1f, %.1f", self.goal_position.position.x, self.goal_position.position.y) break else: #print("Goal Model did not spawn") pass def deleteModel(self): while True: if self.check_model: rospy.wait_for_service('gazebo/delete_model') del_model_prox = rospy.ServiceProxy('gazebo/delete_model', DeleteModel) del_model_prox(self.modelName) break else: pass def getPosition(self, position_check=False, delete=False): if delete: self.deleteModel() while position_check: goal_x = random.randrange(-26, 27) / 10.0 # (-12, 13) goal_y = random.randrange(-26, 27) / 10.0 # (-12, 13) if abs(goal_x - self.obstacle_1[0]) <= 0.4 and abs(goal_y - self.obstacle_1[1]) <= 0.4: position_check = True elif abs(goal_x - self.obstacle_2[0]) <= 0.4 and abs(goal_y - self.obstacle_2[1]) <= 0.4: position_check = True elif abs(goal_x - self.obstacle_3[0]) <= 0.4 and abs(goal_y - self.obstacle_3[1]) <= 0.4: position_check = True elif abs(goal_x - self.obstacle_4[0]) <= 0.4 and abs(goal_y - self.obstacle_4[1]) <= 0.4: position_check = True elif abs(goal_x - self.human_1[0]) <= 0.4 and abs(goal_y - self.human_1[1]) <= 0.4: position_check = True elif abs(goal_x - self.human_2[0]) <= 0.4 and abs(goal_y - self.human_2[1]) <= 0.4: position_check = True elif abs(goal_x - 0.0) <= 0.4 and abs(goal_y - 0.0) <= 0.4: position_check = True else: position_check = False if abs(goal_x - self.last_goal_x) < 1 and abs(goal_y - self.last_goal_y) < 1: position_check = True self.goal_position.position.x = goal_x self.goal_position.position.y = goal_y time.sleep(0.5) self.respawnModel() # Setting up the last goal position self.last_goal_x = self.goal_position.position.x self.last_goal_y = self.goal_position.position.y return self.goal_position.position.x, self.goal_position.position.y
[ "rospy.Subscriber", "os.path.realpath", "rospy.ServiceProxy", "time.sleep", "rospy.loginfo", "random.randrange", "rospy.wait_for_service", "geometry_msgs.msg.Pose" ]
[((488, 494), 'geometry_msgs.msg.Pose', 'Pose', ([], {}), '()\n', (492, 494), False, 'from geometry_msgs.msg import Pose\n'), ((1072, 1141), 'rospy.Subscriber', 'rospy.Subscriber', (['"""gazebo/model_states"""', 'ModelStates', 'self.checkModel'], {}), "('gazebo/model_states', ModelStates, self.checkModel)\n", (1088, 1141), False, 'import rospy\n'), ((3858, 3873), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (3868, 3873), False, 'import time\n'), ((293, 319), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (309, 319), False, 'import os\n'), ((1488, 1536), 'rospy.wait_for_service', 'rospy.wait_for_service', (['"""gazebo/spawn_sdf_model"""'], {}), "('gazebo/spawn_sdf_model')\n", (1510, 1536), False, 'import rospy\n'), ((1572, 1628), 'rospy.ServiceProxy', 'rospy.ServiceProxy', (['"""gazebo/spawn_sdf_model"""', 'SpawnModel'], {}), "('gazebo/spawn_sdf_model', SpawnModel)\n", (1590, 1628), False, 'import rospy\n'), ((1757, 1866), 'rospy.loginfo', 'rospy.loginfo', (['"""Goal position : %.1f, %.1f"""', 'self.goal_position.position.x', 'self.goal_position.position.y'], {}), "('Goal position : %.1f, %.1f', self.goal_position.position.x,\n self.goal_position.position.y)\n", (1770, 1866), False, 'import rospy\n'), ((2102, 2147), 'rospy.wait_for_service', 'rospy.wait_for_service', (['"""gazebo/delete_model"""'], {}), "('gazebo/delete_model')\n", (2124, 2147), False, 'import rospy\n'), ((2181, 2235), 'rospy.ServiceProxy', 'rospy.ServiceProxy', (['"""gazebo/delete_model"""', 'DeleteModel'], {}), "('gazebo/delete_model', DeleteModel)\n", (2199, 2235), False, 'import rospy\n'), ((2511, 2536), 'random.randrange', 'random.randrange', (['(-26)', '(27)'], {}), '(-26, 27)\n', (2527, 2536), False, 'import random\n'), ((2578, 2603), 'random.randrange', 'random.randrange', (['(-26)', '(27)'], {}), '(-26, 27)\n', (2594, 2603), False, 'import random\n')]
"""Unit tests for orbitpy.util module. """ import unittest import numpy as np from numpy.core.numeric import tensordot from instrupy.util import Orientation from instrupy import Instrument from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft import orbitpy.util import propcov from util.spacecrafts import spc1_json, spc2_json, spc3_json class TestOrbitState(unittest.TestCase): def test_date_from_dict(self): x = OrbitState.date_from_dict({"@type":"JULIAN_DATE_UT1", "jd":2459270.75}) self.assertIsInstance(x, propcov.AbsoluteDate) y = OrbitState.date_from_dict({"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}) self.assertIsInstance(y, propcov.AbsoluteDate) self.assertEqual(x, y) def test_state_from_dict(self): x = OrbitState.state_from_dict({"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6867, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}) self.assertIsInstance(x, propcov.OrbitState) cart_state = x.GetCartesianState().GetRealArray() y = OrbitState.state_from_dict({"@type": "CARTESIAN_EARTH_CENTERED_INERTIAL", "x": cart_state[0], "y": cart_state[1], "z": cart_state[2], "vx": cart_state[3], "vy": cart_state[4], "vz": cart_state[5]}) self.assertIsInstance(y, propcov.OrbitState) self.assertEqual(x, y) def test_date_to_dict(self): #@TODO pass def test_state_to_dict(self): #@TODO pass def test_get_julian_date(self): #@TODO pass def test_get_cartesian_earth_centered_inertial_state(self): #@TODO pass def test_get_keplerian_earth_centered_inertial_state(self): #@TODO pass def test_from_dict(self): # Julian date, Cartesian state o = OrbitState.from_dict({"date":{"@type":"JULIAN_DATE_UT1", "jd":2459270.75}, "state":{"@type": "CARTESIAN_EARTH_CENTERED_INERTIAL", "x": 6878.137, "y": 0, "z": 0, "vx": 0, "vy": 7.6126, "vz": 0}, "@id": 123}) self.assertIsInstance(o, OrbitState) self.assertEqual(o._id, 123) self.assertEqual(o.date, propcov.AbsoluteDate.fromJulianDate(2459270.75)) self.assertEqual(o.state, propcov.OrbitState.fromCartesianState(propcov.Rvector6([6878.137,0,0,0,7.6126,0]))) # Gregorian date, Keplerian state o = OrbitState.from_dict({"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}, }) self.assertIsInstance(o, OrbitState) self.assertIsNone(o._id) self.assertEqual(o.date, propcov.AbsoluteDate.fromGregorianDate(2021, 2, 25, 6 ,0, 0)) self.assertEqual(o.state, propcov.OrbitState.fromKeplerianState(6878.137, 0.001, np.deg2rad(45), np.deg2rad(35), np.deg2rad(145), np.deg2rad(-25))) def test_to_dict(self): #@TODO test Keplerian state output # Input: Julian date, Cartesian state o = OrbitState.from_dict({"date":{"@type":"JULIAN_DATE_UT1", "jd":2459270.75}, "state":{"@type": "CARTESIAN_EARTH_CENTERED_INERTIAL", "x": 6878.137, "y": 0, "z": 0, "vx": 0, "vy": 7.6126, "vz": 0}, }) d = o.to_dict() self.assertEqual(d["date"]["@type"], "JULIAN_DATE_UT1") self.assertEqual(d["date"]["jd"], 2459270.75) self.assertEqual(d["state"]["@type"], "CARTESIAN_EARTH_CENTERED_INERTIAL") self.assertAlmostEqual(d["state"]["x"], 6878.137) self.assertEqual(d["state"]["y"], 0) self.assertEqual(d["state"]["z"], 0) self.assertEqual(d["state"]["vx"], 0) self.assertEqual(d["state"]["vy"], 7.6126) self.assertEqual(d["state"]["vz"], 0) self.assertIsNone(d["@id"]) # Input: Gregorian date, Keplerian state o = OrbitState.from_dict({"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}, "@id": "123"}) d = o.to_dict() date = o.get_julian_date() state = o.get_cartesian_earth_centered_inertial_state() self.assertEqual(d["date"]["@type"], "JULIAN_DATE_UT1") self.assertEqual(d["date"]["jd"], date) self.assertEqual(d["state"]["@type"], "CARTESIAN_EARTH_CENTERED_INERTIAL") self.assertAlmostEqual(d["state"]["x"], state[0]) self.assertEqual(d["state"]["y"], state[1]) self.assertEqual(d["state"]["z"], state[2]) self.assertEqual(d["state"]["vx"], state[3]) self.assertEqual(d["state"]["vy"], state[4]) self.assertEqual(d["state"]["vz"], state[5]) self.assertEqual(d["@id"], "123") class TestSpacecraftBus(unittest.TestCase): def test_from_json(self): # typical case o = SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", \ "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}') self.assertEqual(o.name, "BlueCanyon") self.assertEqual(o.mass, 20) self.assertEqual(o.volume, 0.5) self.assertEqual(o.orientation, Orientation.from_dict({"referenceFrame":"Nadir_pointing", "convention": "REF_FRAME_ALIGNED", "@id": "abc"})) self.assertIsNone(o.solarPanelConfig) self.assertEqual(o._id, 123) # check default orientation o = SpacecraftBus.from_json('{"name": "Microsat", "mass": 100, "volume": 1}') self.assertEqual(o.name, "Microsat") self.assertEqual(o.mass, 100) self.assertEqual(o.volume, 1) self.assertEqual(o.orientation, Orientation.from_dict({"referenceFrame":"Nadir_pointing", "convention": "REF_FRAME_ALIGNED"})) self.assertIsNone(o.solarPanelConfig) self.assertIsNone(o._id) # side look orientation o = SpacecraftBus.from_json('{"orientation":{"referenceFrame": "NADIR_POINTING", "convention": "SIDE_LOOK", "sideLookAngle":-10}, "@id":123}') self.assertIsNone(o.name) self.assertIsNone(o.mass) self.assertIsNone(o.volume) self.assertEqual(o.orientation, Orientation.from_dict({"referenceFrame":"Nadir_pointing", "convention": "SIDE_LOOK", "sideLookAngle":-10})) self.assertIsNone(o.solarPanelConfig) self.assertEqual(o._id, 123) # Euler rotation specification, ECI frame o = SpacecraftBus.from_json('{"orientation":{"referenceFrame": "EARTH_CENTERED_INERTIAL", "convention": "XYZ","xRotation":10,"yRotation":-10.4,"zRotation":20.78}}') self.assertIsNone(o.name) self.assertIsNone(o.mass) self.assertIsNone(o.volume) self.assertEqual(o.orientation, Orientation.from_dict({"referenceFrame":"EARTH_CENTERED_INERTIAL", "convention": "XYZ","xRotation":10,"yRotation":-10.4,"zRotation":20.78})) self.assertIsNone(o.solarPanelConfig) self.assertIsNone(o._id) def test_to_dict(self): # typical case o = SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", \ "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}') o_dict = o.to_dict() self.assertEqual(o_dict['name'], 'BlueCanyon') self.assertEqual(o_dict['mass'], 20) self.assertEqual(o_dict['volume'], 0.5) self.assertIsNone(o_dict['solarPanelConfig']) self.assertEqual(o_dict['orientation']['eulerAngle1'], 0) self.assertEqual(o_dict['orientation']['eulerAngle2'], 0) self.assertEqual(o_dict['orientation']['eulerAngle3'], 0) self.assertEqual(o_dict['orientation']['eulerSeq1'], 1) self.assertEqual(o_dict['orientation']['eulerSeq2'], 2) self.assertEqual(o_dict['orientation']['eulerSeq3'], 3) self.assertEqual(o_dict['orientation']['@id'], 'abc') self.assertEqual(o_dict['@id'], 123) def test___eq_(self): # typical case, note that "@id" can be different. o1 = SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", \ "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}') o2 = SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", \ "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":"abc"}') self.assertEqual(o1, o2) o2 = SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 10, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", \ "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}') self.assertNotEqual(o1, o2) # Equivalent orientation specifications in different input format o1 = SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", \ "convention": "REF_FRAME_ALIGNED"}, "@id":123}') o2 = SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", \ "convention": "XYZ","xRotation":0,"yRotation":0,"zRotation":0}, "@id":123}') self.assertEqual(o1, o2) class TestSpacecraft(unittest.TestCase): def test_from_json(self): spc1 = Spacecraft.from_json(spc1_json) spc2 = Spacecraft.from_json(spc2_json) spc3 = Spacecraft.from_json(spc3_json) # typical case 1 instrument self.assertEqual(spc1.name, "Mars") self.assertEqual(spc1.spacecraftBus, SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} \ }')) self.assertEqual(spc1.instrument, [Instrument.from_json('{"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, \ "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, \ "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}')]) self.assertEqual(spc1.orbitState, OrbitState.from_json('{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}')) self.assertEqual(spc1._id, "sp1") # no instruments self.assertEqual(spc2.name, "Jupyter") self.assertEqual(spc2.spacecraftBus, SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} \ }')) self.assertIsNone(spc2.instrument) self.assertEqual(spc2.orbitState, OrbitState.from_json('{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}')) self.assertEqual(spc2._id, 12) # 3 instruments with multiple modes, no spacecraft id assignment self.assertEqual(spc3.name, "Saturn") self.assertEqual(spc3.spacecraftBus, SpacecraftBus.from_json('{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} \ }')) self.assertEqual(len(spc3.instrument), 3) # 1st instrument self.assertEqual(spc3.instrument[0].get_id(), 'bs1') self.assertEqual(spc3.instrument[0].get_mode_id()[0], '0') # 2nd instrument self.assertIsNotNone(spc3.instrument[1].get_id()) self.assertIsNotNone(spc3.instrument[1].get_mode_id()[0], '0') # 3rd instrument self.assertEqual(spc3.instrument[2].get_id(), 'bs3') self.assertEqual(spc3.instrument[2].get_mode_id()[0], 0) self.assertEqual(spc3.instrument[2].get_mode_id()[1], 1) self.assertIsNotNone(spc3.instrument[2].get_mode_id()[2]) self.assertEqual(spc3.orbitState, OrbitState.from_json('{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}')) self.assertIsNotNone(spc3._id) def test_get_instrument(self): spc1 = Spacecraft.from_json(spc1_json) spc2 = Spacecraft.from_json(spc2_json) spc3 = Spacecraft.from_json(spc3_json) # spc1 has 1 instrument with id 'bs1' self.assertEqual(spc1.get_instrument(sensor_id='bs1'), spc1.instrument[0]) self.assertEqual(spc1.get_instrument(), spc1.instrument[0]) # no sensor_id specification self.assertIsNone(spc1.get_instrument('bs2')) # wrong sensor_id # spc2 has no instruments self.assertIsNone(spc2.get_instrument()) # spc3 has three instruments self.assertEqual(spc3.get_instrument(sensor_id='bs1'), spc3.instrument[0]) self.assertEqual(spc3.get_instrument(), spc3.instrument[0]) self.assertEqual(spc3.get_instrument(sensor_id='bs3'), spc3.instrument[2]) def test_add_instrument(self): #TODO pass def test_add_to_list(self): #TODO pass def test_get_id(self): #TODO pass def test_to_dict(self): #TODO pass ''' def test___eq__(self): o1 = Spacecraft.from_json('{"@id": "sp1", "name": "Spock", \ "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} \ }, \ "instrument": {"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, \ "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, \ "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}, \ "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} \ } \ }') o2 = Spacecraft.from_json('{"@id": "sp1", "name": "Spock", \ "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} \ }, \ "instrument": {"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, \ "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, \ "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}, \ "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} \ } \ }') self.assertEqual(o1, o2) # spacecraft bus different (orientation) o2 = Spacecraft.from_json('{"@id": "sp1", "name": "Spock", \ "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame":"Nadir_pointing", "convention": "SIDE_LOOK", "sideLookAngle":-1} \ }, \ "instrument": {"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, \ "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, \ "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}, \ "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} \ } \ }') self.assertNotEqual(o1, o2) # instrument different (fieldOfViewGeometry) o2 = Spacecraft.from_json('{"@id": "sp1", "name": "Spock", \ "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame":"Nadir_pointing", "convention": "SIDE_LOOK", "sideLookAngle":-1} \ }, \ "instrument": {"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":15 }, \ "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, \ "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}, \ "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} \ } \ }') self.assertNotEqual(o1, o2) # orbitState different (date) o2 = Spacecraft.from_json('{"@id": "sp1", "name": "Spock", \ "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame":"Nadir_pointing", "convention": "SIDE_LOOK", "sideLookAngle":-1} \ }, \ "instrument": {"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":15 }, \ "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, \ "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}, \ "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":3, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} \ } \ }') self.assertNotEqual(o1, o2) ''' class TestUtilModuleFunction(unittest.TestCase): def test_helper_extract_spacecraft_params(self): # 1 instrument, 1 mode o1 = Spacecraft.from_json('{"@id": "sp1", "name": "Mars", \ "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} \ }, \ "instrument": {"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, \ "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, \ "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}, \ "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} \ } \ }') # no instruments o2 = Spacecraft.from_json('{"@id": 12, "name": "Jupyter", \ "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} \ }, \ "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} \ } \ }') # 3 instruments with multiple modes, no spacecraft id assignment o3 = Spacecraft.from_json('{"name": "Saturn", \ "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, \ "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} \ }, \ "instrument": [ \ { "name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, \ "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, \ "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor" \ }, \ { "name": "Beta", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, \ "maneuver":{"maneuverType": "SINGLE_ROLL_ONLY", "A_rollMin":10, "A_rollMax":15}, \ "mode": [{"@id":101, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}} \ ], \ "numberDetectorRows":5, "numberDetectorCols":10, "@type":"Basic Sensor" \ }, \ { "name": "Gamma", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, \ "fieldOfViewGeometry": {"shape": "RECTANGULAR", "angleHeight":5, "angleWidth":10 }, \ "maneuver":{"maneuverType": "Double_Roll_Only", "A_rollMin":10, "A_rollMax":15, "B_rollMin":-15, "B_rollMax":-10}, \ "mode": [{"@id":0, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}}, \ {"@id":1, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "SIDE_LOOK", "sideLookAngle": 25}}, \ { "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "SIDE_LOOK", "sideLookAngle": -25}} \ ], \ "numberDetectorRows":5, "numberDetectorCols":10, "@id": "bs3", "@type":"Basic Sensor" \ } \ ], \ "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, \ "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} \ } \ }') # single sc tests x = orbitpy.util.helper_extract_spacecraft_params([o1]) self.assertEqual(len(x), 1) self.assertEqual(x[0].sc_id, 'sp1') self.assertEqual(x[0].instru_id,'bs1') self.assertEqual(x[0].mode_id, '0') self.assertAlmostEqual(x[0].sma, 6878.136999999998) self.assertAlmostEqual(x[0].fov_height, 5.0) self.assertAlmostEqual(x[0]. fov_width, 5.0) self.assertAlmostEqual(x[0].for_height, 15.0) self.assertAlmostEqual(x[0].for_width, 15.0) # spacecraft with no instruments x = orbitpy.util.helper_extract_spacecraft_params([o2]) self.assertEqual(len(x), 1) self.assertEqual(x[0].sc_id, 12) self.assertIsNone(x[0].instru_id) self.assertIsNone(x[0].mode_id) self.assertAlmostEqual(x[0].sma, 6878.136999999998) self.assertIsNone(x[0].fov_height) self.assertIsNone(x[0]. fov_width) self.assertIsNone(x[0].for_height) self.assertIsNone(x[0].for_width) x = orbitpy.util.helper_extract_spacecraft_params([o3]) self.assertEqual(len(x), 8) self.assertIsNotNone(x[0].sc_id) self.assertIsNotNone(x[1].sc_id) self.assertIsNotNone(x[2].sc_id) self.assertIsNotNone(x[3].sc_id) self.assertIsNotNone(x[4].sc_id) self.assertIsNotNone(x[5].sc_id) self.assertIsNotNone(x[6].sc_id) self.assertIsNotNone(x[7].sc_id) self.assertEqual(x[0].instru_id,'bs1') self.assertIsNotNone(x[1].instru_id) self.assertEqual(x[2].instru_id,'bs3') self.assertEqual(x[3].instru_id,'bs3') self.assertEqual(x[4].instru_id,'bs3') self.assertEqual(x[5].instru_id,'bs3') self.assertEqual(x[6].instru_id,'bs3') self.assertEqual(x[7].instru_id,'bs3') self.assertEqual(x[0].mode_id, '0') self.assertEqual(x[1].mode_id, 101) self.assertEqual(x[2].mode_id, 0) self.assertEqual(x[3].mode_id, 0) self.assertEqual(x[4].mode_id, 1) self.assertEqual(x[5].mode_id, 1) self.assertIsNotNone(x[6].mode_id) self.assertIsNotNone(x[7].mode_id) self.assertAlmostEqual(x[0].sma, 6878.136999999998) self.assertAlmostEqual(x[1].sma, 6878.136999999998) self.assertAlmostEqual(x[2].sma, 6878.136999999998) self.assertAlmostEqual(x[3].sma, 6878.136999999998) self.assertAlmostEqual(x[4].sma, 6878.136999999998) self.assertAlmostEqual(x[5].sma, 6878.136999999998) self.assertAlmostEqual(x[6].sma, 6878.136999999998) self.assertAlmostEqual(x[7].sma, 6878.136999999998) self.assertAlmostEqual(x[0].fov_height, 5.0) self.assertAlmostEqual(x[1].fov_height, 5.0) self.assertAlmostEqual(x[2].fov_height, 5.0) self.assertAlmostEqual(x[3].fov_height, 5.0) self.assertAlmostEqual(x[4].fov_height, 5.0) self.assertAlmostEqual(x[5].fov_height, 5.0) self.assertAlmostEqual(x[6].fov_height, 5.0) self.assertAlmostEqual(x[0]. fov_width, 5) self.assertAlmostEqual(x[1]. fov_width, 5) self.assertAlmostEqual(x[2]. fov_width, 10.0) self.assertAlmostEqual(x[3]. fov_width, 10.0) self.assertAlmostEqual(x[4]. fov_width, 10.0) self.assertAlmostEqual(x[5]. fov_width, 10.0) self.assertAlmostEqual(x[6]. fov_width, 10.0) self.assertAlmostEqual(x[7]. fov_width, 10.0) self.assertAlmostEqual(x[0].for_height, 15.0) self.assertAlmostEqual(x[1].for_height, 5.0) self.assertAlmostEqual(x[2].for_height, 5.0) self.assertAlmostEqual(x[3].for_height, 5.0) self.assertAlmostEqual(x[4].for_height, 5.0) self.assertAlmostEqual(x[5].for_height, 5.0) self.assertAlmostEqual(x[6].for_height, 5.0) self.assertAlmostEqual(x[7].for_height, 5.0) self.assertAlmostEqual(x[0].for_width, 15.0) self.assertAlmostEqual(x[1].for_width, 10.0) self.assertAlmostEqual(x[2].for_width, 15.0) self.assertAlmostEqual(x[3].for_width, 15.0) self.assertAlmostEqual(x[4].for_width, 15.0) self.assertAlmostEqual(x[5].for_width, 15.0) self.assertAlmostEqual(x[6].for_width, 15.0) self.assertAlmostEqual(x[7].for_width, 15.0) # test multiple spacecraft list, test first and last element of the resultant list x = orbitpy.util.helper_extract_spacecraft_params([o1, o2, o3]) self.assertEqual(len(x), 10) self.assertEqual(x[0].sc_id, 'sp1') self.assertEqual(x[0].instru_id,'bs1') self.assertEqual(x[0].mode_id, '0') self.assertAlmostEqual(x[0].sma, 6878.136999999998) self.assertAlmostEqual(x[0].fov_height, 5.0) self.assertAlmostEqual(x[0]. fov_width, 5.0) self.assertAlmostEqual(x[0].for_height, 15.0) self.assertAlmostEqual(x[0].for_width, 15.0) self.assertEqual(x[1].sc_id, 12) self.assertIsNotNone(x[2].sc_id) self.assertEqual(x[3].sc_id, x[2].sc_id) self.assertEqual(x[4].sc_id, x[2].sc_id) self.assertEqual(x[5].sc_id, x[2].sc_id) self.assertEqual(x[6].sc_id, x[2].sc_id) self.assertEqual(x[7].sc_id, x[2].sc_id) self.assertEqual(x[8].sc_id, x[2].sc_id) self.assertEqual(x[9].sc_id, x[2].sc_id) self.assertEqual(x[9].instru_id,'bs3') self.assertIsNotNone(x[9].mode_id) self.assertAlmostEqual(x[9].sma, 6878.136999999998) self.assertAlmostEqual(x[9].fov_height, 5.0) self.assertAlmostEqual(x[9]. fov_width, 10.0) self.assertAlmostEqual(x[9].for_height, 5.0) self.assertAlmostEqual(x[9].for_width, 15.0) def test_extract_auxillary_info_from_state_file(self): # TODO pass class TestGroundStation(unittest.TestCase): #TODO pass class TestUtilFunctions(unittest.TestCase): def test_dictionary_list_to_object_list(self): #TODO pass def test_object_list_to_dictionary_list(self): #TODO pass def test_initialize_object_list(self): #TODO pass def test_add_to_list(self): #TODO pass class TestOutputInfoUtility(unittest.TestCase): #TODO pass
[ "orbitpy.util.OrbitState.from_json", "orbitpy.util.OrbitState.state_from_dict", "propcov.Rvector6", "numpy.deg2rad", "orbitpy.util.SpacecraftBus.from_json", "propcov.AbsoluteDate.fromJulianDate", "instrupy.Instrument.from_json", "orbitpy.util.OrbitState.date_from_dict", "orbitpy.util.Spacecraft.from_json", "instrupy.util.Orientation.from_dict", "orbitpy.util.OrbitState.from_dict", "propcov.AbsoluteDate.fromGregorianDate" ]
[((442, 515), 'orbitpy.util.OrbitState.date_from_dict', 'OrbitState.date_from_dict', (["{'@type': 'JULIAN_DATE_UT1', 'jd': 2459270.75}"], {}), "({'@type': 'JULIAN_DATE_UT1', 'jd': 2459270.75})\n", (467, 515), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((582, 713), 'orbitpy.util.OrbitState.date_from_dict', 'OrbitState.date_from_dict', (["{'@type': 'GREGORIAN_UTC', 'year': 2021, 'month': 2, 'day': 25, 'hour': 6,\n 'minute': 0, 'second': 0}"], {}), "({'@type': 'GREGORIAN_UTC', 'year': 2021, 'month':\n 2, 'day': 25, 'hour': 6, 'minute': 0, 'second': 0})\n", (607, 713), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((839, 990), 'orbitpy.util.OrbitState.state_from_dict', 'OrbitState.state_from_dict', (["{'@type': 'KEPLERIAN_EARTH_CENTERED_INERTIAL', 'sma': 6867, 'ecc': 0.001,\n 'inc': 45, 'raan': 35, 'aop': 145, 'ta': -25}"], {}), "({'@type': 'KEPLERIAN_EARTH_CENTERED_INERTIAL',\n 'sma': 6867, 'ecc': 0.001, 'inc': 45, 'raan': 35, 'aop': 145, 'ta': -25})\n", (865, 990), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((1112, 1317), 'orbitpy.util.OrbitState.state_from_dict', 'OrbitState.state_from_dict', (["{'@type': 'CARTESIAN_EARTH_CENTERED_INERTIAL', 'x': cart_state[0], 'y':\n cart_state[1], 'z': cart_state[2], 'vx': cart_state[3], 'vy':\n cart_state[4], 'vz': cart_state[5]}"], {}), "({'@type': 'CARTESIAN_EARTH_CENTERED_INERTIAL',\n 'x': cart_state[0], 'y': cart_state[1], 'z': cart_state[2], 'vx':\n cart_state[3], 'vy': cart_state[4], 'vz': cart_state[5]})\n", (1138, 1317), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((1822, 2042), 'orbitpy.util.OrbitState.from_dict', 'OrbitState.from_dict', (["{'date': {'@type': 'JULIAN_DATE_UT1', 'jd': 2459270.75}, 'state': {'@type':\n 'CARTESIAN_EARTH_CENTERED_INERTIAL', 'x': 6878.137, 'y': 0, 'z': 0,\n 'vx': 0, 'vy': 7.6126, 'vz': 0}, '@id': 123}"], {}), "({'date': {'@type': 'JULIAN_DATE_UT1', 'jd': 2459270.75\n }, 'state': {'@type': 'CARTESIAN_EARTH_CENTERED_INERTIAL', 'x': \n 6878.137, 'y': 0, 'z': 0, 'vx': 0, 'vy': 7.6126, 'vz': 0}, '@id': 123})\n", (1842, 2042), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((2435, 2715), 'orbitpy.util.OrbitState.from_dict', 'OrbitState.from_dict', (["{'date': {'@type': 'GREGORIAN_UTC', 'year': 2021, 'month': 2, 'day': 25,\n 'hour': 6, 'minute': 0, 'second': 0}, 'state': {'@type':\n 'KEPLERIAN_EARTH_CENTERED_INERTIAL', 'sma': 6878.137, 'ecc': 0.001,\n 'inc': 45, 'raan': 35, 'aop': 145, 'ta': -25}}"], {}), "({'date': {'@type': 'GREGORIAN_UTC', 'year': 2021,\n 'month': 2, 'day': 25, 'hour': 6, 'minute': 0, 'second': 0}, 'state': {\n '@type': 'KEPLERIAN_EARTH_CENTERED_INERTIAL', 'sma': 6878.137, 'ecc': \n 0.001, 'inc': 45, 'raan': 35, 'aop': 145, 'ta': -25}})\n", (2455, 2715), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((3219, 3427), 'orbitpy.util.OrbitState.from_dict', 'OrbitState.from_dict', (["{'date': {'@type': 'JULIAN_DATE_UT1', 'jd': 2459270.75}, 'state': {'@type':\n 'CARTESIAN_EARTH_CENTERED_INERTIAL', 'x': 6878.137, 'y': 0, 'z': 0,\n 'vx': 0, 'vy': 7.6126, 'vz': 0}}"], {}), "({'date': {'@type': 'JULIAN_DATE_UT1', 'jd': 2459270.75\n }, 'state': {'@type': 'CARTESIAN_EARTH_CENTERED_INERTIAL', 'x': \n 6878.137, 'y': 0, 'z': 0, 'vx': 0, 'vy': 7.6126, 'vz': 0}})\n", (3239, 3427), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((4098, 4392), 'orbitpy.util.OrbitState.from_dict', 'OrbitState.from_dict', (["{'date': {'@type': 'GREGORIAN_UTC', 'year': 2021, 'month': 2, 'day': 25,\n 'hour': 6, 'minute': 0, 'second': 0}, 'state': {'@type':\n 'KEPLERIAN_EARTH_CENTERED_INERTIAL', 'sma': 6878.137, 'ecc': 0.001,\n 'inc': 45, 'raan': 35, 'aop': 145, 'ta': -25}, '@id': '123'}"], {}), "({'date': {'@type': 'GREGORIAN_UTC', 'year': 2021,\n 'month': 2, 'day': 25, 'hour': 6, 'minute': 0, 'second': 0}, 'state': {\n '@type': 'KEPLERIAN_EARTH_CENTERED_INERTIAL', 'sma': 6878.137, 'ecc': \n 0.001, 'inc': 45, 'raan': 35, 'aop': 145, 'ta': -25}, '@id': '123'})\n", (4118, 4392), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((5231, 5467), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}\'\n )\n', (5254, 5467), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((5865, 5938), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "Microsat", "mass": 100, "volume": 1}"""'], {}), '(\'{"name": "Microsat", "mass": 100, "volume": 1}\')\n', (5888, 5938), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((6319, 6467), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"orientation":{"referenceFrame": "NADIR_POINTING", "convention": "SIDE_LOOK", "sideLookAngle":-10}, "@id":123}"""'], {}), '(\n \'{"orientation":{"referenceFrame": "NADIR_POINTING", "convention": "SIDE_LOOK", "sideLookAngle":-10}, "@id":123}\'\n )\n', (6342, 6467), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((6856, 7026), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"orientation":{"referenceFrame": "EARTH_CENTERED_INERTIAL", "convention": "XYZ","xRotation":10,"yRotation":-10.4,"zRotation":20.78}}"""'], {}), '(\n \'{"orientation":{"referenceFrame": "EARTH_CENTERED_INERTIAL", "convention": "XYZ","xRotation":10,"yRotation":-10.4,"zRotation":20.78}}\'\n )\n', (6879, 7026), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((7445, 7681), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}\'\n )\n', (7468, 7681), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((8500, 8736), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}\'\n )\n', (8523, 8736), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((8742, 8980), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":"abc"}"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":"abc"}\'\n )\n', (8765, 8980), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((9019, 9255), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 10, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 10, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED", "@id": "abc"}, "@id":123}\'\n )\n', (9042, 9255), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((9373, 9595), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"}, "@id":123}"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"}, "@id":123}\'\n )\n', (9396, 9595), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((9601, 9851), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "XYZ","xRotation":0,"yRotation":0,"zRotation":0}, "@id":123}"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "XYZ","xRotation":0,"yRotation":0,"zRotation":0}, "@id":123}\'\n )\n', (9624, 9851), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((9965, 9996), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['spc1_json'], {}), '(spc1_json)\n', (9985, 9996), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((10014, 10045), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['spc2_json'], {}), '(spc2_json)\n', (10034, 10045), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((10063, 10094), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['spc3_json'], {}), '(spc3_json)\n', (10083, 10094), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((13966, 13997), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['spc1_json'], {}), '(spc1_json)\n', (13986, 13997), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((14015, 14046), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['spc2_json'], {}), '(spc2_json)\n', (14035, 14046), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((14064, 14095), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['spc3_json'], {}), '(spc3_json)\n', (14084, 14095), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((22706, 24121), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['"""{"@id": "sp1", "name": "Mars", "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }, "instrument": {"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}, "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} } }"""'], {}), '(\n \'{"@id": "sp1", "name": "Mars", "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }, "instrument": {"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}, "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} } }\'\n )\n', (22726, 24121), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((24174, 24956), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['"""{"@id": 12, "name": "Jupyter", "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }, "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} } }"""'], {}), '(\n \'{"@id": 12, "name": "Jupyter", "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }, "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} } }\'\n )\n', (24194, 24956), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((25047, 28682), 'orbitpy.util.Spacecraft.from_json', 'Spacecraft.from_json', (['"""{"name": "Saturn", "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }, "instrument": [ { "name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor" }, { "name": "Beta", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, "maneuver":{"maneuverType": "SINGLE_ROLL_ONLY", "A_rollMin":10, "A_rollMax":15}, "mode": [{"@id":101, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}} ], "numberDetectorRows":5, "numberDetectorCols":10, "@type":"Basic Sensor" }, { "name": "Gamma", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "fieldOfViewGeometry": {"shape": "RECTANGULAR", "angleHeight":5, "angleWidth":10 }, "maneuver":{"maneuverType": "Double_Roll_Only", "A_rollMin":10, "A_rollMax":15, "B_rollMin":-15, "B_rollMax":-10}, "mode": [{"@id":0, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}}, {"@id":1, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "SIDE_LOOK", "sideLookAngle": 25}}, { "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "SIDE_LOOK", "sideLookAngle": -25}} ], "numberDetectorRows":5, "numberDetectorCols":10, "@id": "bs3", "@type":"Basic Sensor" } ], "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} } }"""'], {}), '(\n \'{"name": "Saturn", "spacecraftBus":{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }, "instrument": [ { "name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor" }, { "name": "Beta", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, "maneuver":{"maneuverType": "SINGLE_ROLL_ONLY", "A_rollMin":10, "A_rollMax":15}, "mode": [{"@id":101, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}} ], "numberDetectorRows":5, "numberDetectorCols":10, "@type":"Basic Sensor" }, { "name": "Gamma", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "fieldOfViewGeometry": {"shape": "RECTANGULAR", "angleHeight":5, "angleWidth":10 }, "maneuver":{"maneuverType": "Double_Roll_Only", "A_rollMin":10, "A_rollMax":15, "B_rollMin":-15, "B_rollMax":-10}, "mode": [{"@id":0, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}}, {"@id":1, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "SIDE_LOOK", "sideLookAngle": 25}}, { "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "SIDE_LOOK", "sideLookAngle": -25}} ], "numberDetectorRows":5, "numberDetectorCols":10, "@id": "bs3", "@type":"Basic Sensor" } ], "orbitState": {"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25} } }\'\n )\n', (25067, 28682), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((2213, 2260), 'propcov.AbsoluteDate.fromJulianDate', 'propcov.AbsoluteDate.fromJulianDate', (['(2459270.75)'], {}), '(2459270.75)\n', (2248, 2260), False, 'import propcov\n'), ((2875, 2935), 'propcov.AbsoluteDate.fromGregorianDate', 'propcov.AbsoluteDate.fromGregorianDate', (['(2021)', '(2)', '(25)', '(6)', '(0)', '(0)'], {}), '(2021, 2, 25, 6, 0, 0)\n', (2913, 2935), False, 'import propcov\n'), ((5624, 5736), 'instrupy.util.Orientation.from_dict', 'Orientation.from_dict', (["{'referenceFrame': 'Nadir_pointing', 'convention': 'REF_FRAME_ALIGNED',\n '@id': 'abc'}"], {}), "({'referenceFrame': 'Nadir_pointing', 'convention':\n 'REF_FRAME_ALIGNED', '@id': 'abc'})\n", (5645, 5736), False, 'from instrupy.util import Orientation\n'), ((6100, 6198), 'instrupy.util.Orientation.from_dict', 'Orientation.from_dict', (["{'referenceFrame': 'Nadir_pointing', 'convention': 'REF_FRAME_ALIGNED'}"], {}), "({'referenceFrame': 'Nadir_pointing', 'convention':\n 'REF_FRAME_ALIGNED'})\n", (6121, 6198), False, 'from instrupy.util import Orientation\n'), ((6602, 6714), 'instrupy.util.Orientation.from_dict', 'Orientation.from_dict', (["{'referenceFrame': 'Nadir_pointing', 'convention': 'SIDE_LOOK',\n 'sideLookAngle': -10}"], {}), "({'referenceFrame': 'Nadir_pointing', 'convention':\n 'SIDE_LOOK', 'sideLookAngle': -10})\n", (6623, 6714), False, 'from instrupy.util import Orientation\n'), ((7161, 7316), 'instrupy.util.Orientation.from_dict', 'Orientation.from_dict', (["{'referenceFrame': 'EARTH_CENTERED_INERTIAL', 'convention': 'XYZ',\n 'xRotation': 10, 'yRotation': -10.4, 'zRotation': 20.78}"], {}), "({'referenceFrame': 'EARTH_CENTERED_INERTIAL',\n 'convention': 'XYZ', 'xRotation': 10, 'yRotation': -10.4, 'zRotation': \n 20.78})\n", (7182, 7316), False, 'from instrupy.util import Orientation\n'), ((10229, 10506), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }\'\n )\n', (10252, 10506), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((11204, 11535), 'orbitpy.util.OrbitState.from_json', 'OrbitState.from_json', (['"""{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}"""'], {}), '(\n \'{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}\'\n )\n', (11224, 11535), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((11697, 11974), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }\'\n )\n', (11720, 11974), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((12055, 12386), 'orbitpy.util.OrbitState.from_json', 'OrbitState.from_json', (['"""{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}"""'], {}), '(\n \'{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}\'\n )\n', (12075, 12386), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((12592, 12869), 'orbitpy.util.SpacecraftBus.from_json', 'SpacecraftBus.from_json', (['"""{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }"""'], {}), '(\n \'{"name": "BlueCanyon", "mass": 20, "volume": 0.5, "orientation":{"referenceFrame": "NADIR_POINTING", "convention": "REF_FRAME_ALIGNED"} }\'\n )\n', (12615, 12869), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((13546, 13877), 'orbitpy.util.OrbitState.from_json', 'OrbitState.from_json', (['"""{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}"""'], {}), '(\n \'{"date":{"@type":"GREGORIAN_UTC", "year":2021, "month":2, "day":25, "hour":6, "minute":0, "second":0}, "state":{"@type": "KEPLERIAN_EARTH_CENTERED_INERTIAL", "sma": 6878.137, "ecc": 0.001, "inc": 45, "raan": 35, "aop": 145, "ta": -25}}\'\n )\n', (13566, 13877), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((2334, 2382), 'propcov.Rvector6', 'propcov.Rvector6', (['[6878.137, 0, 0, 0, 7.6126, 0]'], {}), '([6878.137, 0, 0, 0, 7.6126, 0])\n', (2350, 2382), False, 'import propcov\n'), ((3026, 3040), 'numpy.deg2rad', 'np.deg2rad', (['(45)'], {}), '(45)\n', (3036, 3040), True, 'import numpy as np\n'), ((3042, 3056), 'numpy.deg2rad', 'np.deg2rad', (['(35)'], {}), '(35)\n', (3052, 3056), True, 'import numpy as np\n'), ((3058, 3073), 'numpy.deg2rad', 'np.deg2rad', (['(145)'], {}), '(145)\n', (3068, 3073), True, 'import numpy as np\n'), ((3075, 3090), 'numpy.deg2rad', 'np.deg2rad', (['(-25)'], {}), '(-25)\n', (3085, 3090), True, 'import numpy as np\n'), ((10545, 11161), 'instrupy.Instrument.from_json', 'Instrument.from_json', (['"""{"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}"""'], {}), '(\n \'{"name": "Alpha", "mass":10, "volume":12.45, "dataRate": 40, "bitsPerPixel": 8, "power": 12, "orientation": {"referenceFrame": "SC_BODY_FIXED", "convention": "REF_FRAME_ALIGNED"}, "fieldOfViewGeometry": {"shape": "CIRCULAR", "diameter":5 }, "maneuver":{"maneuverType": "CIRCULAR", "diameter":10}, "numberDetectorRows":5, "numberDetectorCols":10, "@id":"bs1", "@type":"Basic Sensor"}\'\n )\n', (10565, 11161), False, 'from instrupy import Instrument\n')]